// ── Paints — manage your colour collections ──────────────────────
// A collection is a named subset of the catalogue (PAINTS). Create, rename,
// add/remove paints, delete. These preselect paints in the generator.

function Paints({ navigate, user, credits, onSignOut }) {
  const [collections, setCollections] = useState([]);
  const [loading, setLoading] = useState(true);
  const [selectedId, setSelectedId] = useState(null); // collection id | 'new' | null
  const [draftName, setDraftName] = useState('');
  const [draftIds, setDraftIds] = useState([]);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState(null);

  const [brand, setBrand] = useState('all');
  const [family, setFamily] = useState('all');
  const [query, setQuery] = useState('');

  useEffect(() => {
    let cancelled = false;
    Api.listCollections()
      .then(r => { if (!cancelled) setCollections(r.collections || []); })
      .catch(err => { if (!cancelled) setError(err.message); })
      .finally(() => { if (!cancelled) setLoading(false); });
    return () => { cancelled = true; };
  }, []);

  const stored = collections.find(c => c.id === selectedId) || null;
  const editing = selectedId === 'new' || !!stored;
  const dirty = editing && (
    selectedId === 'new' ||
    draftName !== (stored?.name || '') ||
    draftIds.length !== (stored?.paintIds?.length || 0) ||
    draftIds.some(id => !stored?.paintIds?.includes(id))
  );

  const filtered = useMemo(() => {
    let p = PAINTS;
    if (family !== 'all') p = p.filter(x => x.family === family);
    if (brand !== 'all') p = p.filter(x => x.brand === brand);
    if (query) {
      const q = query.toLowerCase();
      p = p.filter(x => x.name.toLowerCase().includes(q) || x.code.toLowerCase().includes(q) || x.brand.toLowerCase().includes(q));
    }
    return p;
  }, [family, brand, query]);

  const draftPaints = draftIds.map(id => PAINTS.find(p => p.id === id)).filter(Boolean);

  function selectCollection(c) {
    setSelectedId(c.id); setDraftName(c.name); setDraftIds(c.paintIds || []); setError(null);
  }
  function newCollection() {
    setSelectedId('new'); setDraftName('New collection'); setDraftIds([]); setError(null);
  }
  function toggle(id) {
    setDraftIds(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]);
  }

  async function save() {
    if (!draftName.trim()) { setError('Give your collection a name.'); return; }
    setSaving(true); setError(null);
    try {
      if (selectedId === 'new') {
        const created = await Api.createCollection(draftName.trim(), draftIds);
        setCollections(prev => [created, ...prev]);
        setSelectedId(created.id);
      } else {
        const updated = await Api.updateCollection(selectedId, { name: draftName.trim(), paintIds: draftIds });
        setCollections(prev => prev.map(c => c.id === selectedId ? updated : c));
      }
    } catch (err) {
      setError(err.message || 'Could not save');
    } finally {
      setSaving(false);
    }
  }

  async function remove(id, e) {
    e && e.stopPropagation();
    if (!window.confirm('Delete this collection? Your paints stay in the catalogue.')) return;
    try {
      await Api.deleteCollection(id);
      setCollections(prev => prev.filter(c => c.id !== id));
      if (selectedId === id) { setSelectedId(null); }
    } catch (err) {
      setError(err.message || 'Could not delete');
    }
  }

  return (
    <div data-screen-label="paints" className="pm-shell">
      <PMSidebar navigate={navigate} active="paints" user={user} credits={credits} onSignOut={onSignOut} />
      <div className="pm-content">
        <div className="pm-topbar">
          <div>
            <div className="pm-h1">Paints &amp; Collections</div>
            <div className="pm-eyebrow" style={{ marginTop: 3 }}>
              {collections.length} COLLECTION{collections.length === 1 ? '' : 'S'} · {PAINTS.length} PAINTS CATALOGUED
            </div>
          </div>
          <div style={{ flex: 1 }} />
          <button className="btn btn-gold btn-sm" onClick={newCollection}>New collection +</button>
        </div>

        <div className="pm-paints-panes">
          {/* Left: collections list */}
          <div className="pm-paints-list" style={{ borderRight: '1px solid var(--line)', padding: 20, overflowY: 'auto' }}>
            <div className="mono" style={{ fontSize: 10, letterSpacing: '0.12em', color: 'var(--ink-3)', marginBottom: 12 }}>YOUR COLLECTIONS</div>
            {loading ? (
              <div style={{ color: 'var(--ink-3)', fontSize: 13 }}>Loading…</div>
            ) : collections.length === 0 ? (
              <div style={{ padding: '16px', borderRadius: 10, background: 'var(--surface-2)', border: '1px dashed var(--line-2)', fontSize: 12.5, color: 'var(--ink-3)', lineHeight: 1.5 }}>
                No collections yet. Hit <strong style={{ color: 'var(--ink-2)' }}>New collection</strong> to group the paints you own or love — they'll preselect in the generator.
              </div>
            ) : (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {collections.map(c => {
                  const on = selectedId === c.id;
                  const preview = (c.paintIds || []).map(id => PAINTS.find(p => p.id === id)).filter(Boolean).slice(0, 6);
                  return (
                    <button key={c.id} onClick={() => selectCollection(c)} style={{
                      textAlign: 'left', padding: '12px 13px', borderRadius: 10,
                      background: on ? 'var(--brand-soft)' : 'var(--surface)',
                      border: `1.5px solid ${on ? 'var(--brand)' : 'var(--line-2)'}`,
                    }}>
                      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
                        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7, fontFamily: 'var(--serif)', fontSize: 17, fontWeight: 600 }}><PMIcon name="paints" size={15} />{c.name}</span>
                        <span onClick={(e) => remove(c.id, e)} title="Delete" style={{ color: 'var(--ink-4)', fontSize: 15, lineHeight: 1, padding: '0 2px' }}>×</span>
                      </div>
                      <div className="mono" style={{ fontSize: 9.5, color: 'var(--ink-3)', margin: '4px 0 8px', letterSpacing: '0.06em' }}>{(c.paintIds?.length || 0)} PAINTS</div>
                      <div style={{ display: 'flex', gap: 3 }}>
                        {preview.map(p => <span key={p.id} style={{ width: 18, height: 18, borderRadius: 4, background: p.hex, boxShadow: 'inset 0 0 0 1px rgba(0,0,0,.12)' }}/>)}
                        {preview.length === 0 && <span style={{ fontSize: 11, color: 'var(--ink-4)' }}>Empty</span>}
                      </div>
                    </button>
                  );
                })}
              </div>
            )}
          </div>

          {/* Right: editor */}
          <div className="pm-paints-editor" style={{ padding: 24, overflowY: 'auto' }}>
            {!editing ? (
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'flex-start', textAlign: 'center', color: 'var(--ink-3)', gap: 10, paddingTop: 'clamp(20px, 6vh, 72px)' }}>
                <div style={{ width: 46, height: 46, borderRadius: 12, background: 'var(--brand-soft)', border: '1px solid var(--brand)', display: 'grid', placeItems: 'center', color: 'var(--brand-deep)' }}><PMIcon name="paints" size={22} /></div>
                <div style={{ fontFamily: 'var(--serif)', fontSize: 22, color: 'var(--ink)' }}>Pick a collection to edit</div>
                <div style={{ fontSize: 13, maxWidth: 360, lineHeight: 1.5 }}>Select one on the left, or create a new collection and choose paints from the catalogue below.</div>
                <button className="btn btn-gold" style={{ marginTop: 6 }} onClick={newCollection}>New collection +</button>
              </div>
            ) : (
              <>
                <div style={{ display: 'flex', alignItems: 'flex-end', gap: 14, marginBottom: 18 }}>
                  <div style={{ flex: 1 }}>
                    <div className="mono" style={{ fontSize: 9, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--ink-3)', marginBottom: 6 }}>Collection name</div>
                    <input className="input" value={draftName} onChange={e => setDraftName(e.target.value)} style={{ height: 44, fontFamily: 'var(--serif)', fontSize: 20, fontWeight: 600 }} />
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    <div className="mono" style={{ fontSize: 9.5, color: 'var(--ink-3)', marginBottom: 6 }}>{draftPaints.length} PAINTS</div>
                    <button className={dirty && !saving ? 'btn btn-gold' : 'btn btn-ghost'} disabled={!dirty || saving} onClick={save}
                      style={{ height: 44, opacity: dirty || saving ? 1 : 0.5 }}>
                      {saving ? 'Saving…' : dirty ? (selectedId === 'new' ? 'Create collection' : 'Save changes') : 'Saved'}
                    </button>
                  </div>
                </div>

                {error && (
                  <div style={{ marginBottom: 14, padding: '9px 12px', borderRadius: 8, background: 'rgba(154,27,31,.08)', border: '1px solid rgba(154,27,31,.28)', color: 'var(--crimson)', fontSize: 12.5 }}>{error}</div>
                )}

                {/* selected strip */}
                <div style={{ marginBottom: 16, padding: 14, borderRadius: 10, background: 'var(--surface-2)', border: '1px solid var(--line)' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: draftPaints.length ? 10 : 0 }}>
                    <span className="mono" style={{ fontSize: 9.5, letterSpacing: '0.1em', color: 'var(--ink-3)' }}>IN THIS COLLECTION · {draftPaints.length}</span>
                    {draftPaints.length > 0 && <button onClick={() => setDraftIds([])} style={{ fontSize: 11, color: 'var(--ink-3)' }}>Clear all</button>}
                  </div>
                  {draftPaints.length === 0 ? (
                    <div style={{ fontSize: 12, color: 'var(--ink-4)' }}>Tap paints in the catalogue below to add them.</div>
                  ) : (
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                      {draftPaints.map(p => (
                        <button key={p.id} onClick={() => toggle(p.id)} title={`Remove ${p.name}`} style={{
                          display: 'inline-flex', alignItems: 'center', gap: 6, padding: '5px 9px 5px 5px',
                          background: 'var(--surface)', borderRadius: 100, fontSize: 11.5, border: '1px solid var(--line-2)',
                        }}>
                          <span style={{ width: 16, height: 16, borderRadius: 4, background: p.hex, boxShadow: 'inset 0 0 0 1px rgba(0,0,0,.15)' }}/>
                          {p.name}
                          <span style={{ color: 'var(--ink-4)', fontSize: 14, lineHeight: 1 }}>×</span>
                        </button>
                      ))}
                    </div>
                  )}
                </div>

                {/* catalogue */}
                <div className="pm-section-head"><h2>Catalogue</h2><span className="rule" /></div>
                <div style={{ position: 'relative', marginBottom: 10 }}>
                  <input className="input" placeholder="Search name, code, or brand" value={query} onChange={e => setQuery(e.target.value)} style={{ height: 40 }} />
                </div>
                <div style={{ display: 'flex', gap: 6, marginBottom: 8, flexWrap: 'wrap' }}>
                  {[{ id: 'all', label: 'All' }, { id: 'Citadel', label: 'Citadel' }, { id: 'Vallejo', label: 'Vallejo' }, { id: 'Scale75', label: 'Scale75' }, { id: 'Custom', label: 'Custom' }].map(b => (
                    <button key={b.id} onClick={() => setBrand(b.id)} style={{
                      padding: '5px 11px', borderRadius: 100,
                      background: brand === b.id ? 'var(--brand-soft)' : 'transparent',
                      color: brand === b.id ? 'var(--brand-deep)' : 'var(--ink-3)',
                      border: `1px solid ${brand === b.id ? 'var(--brand)' : 'var(--line)'}`,
                      fontSize: 10.5, fontFamily: 'var(--mono)', letterSpacing: '0.05em',
                    }}>{b.label}</button>
                  ))}
                </div>
                <div style={{ display: 'flex', gap: 6, marginBottom: 14, flexWrap: 'wrap' }}>
                  {FAMILIES.map(f => (
                    <button key={f.id} onClick={() => setFamily(f.id)} style={{
                      padding: '5px 11px', borderRadius: 100,
                      background: family === f.id ? 'var(--ink)' : 'var(--surface-2)',
                      color: family === f.id ? 'var(--paper)' : 'var(--ink-2)',
                      border: '1px solid var(--line-2)', fontSize: 11,
                    }}>{f.label}</button>
                  ))}
                </div>

                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(180px, 1fr))', gap: 7 }}>
                  {filtered.map(p => {
                    const on = draftIds.includes(p.id);
                    return (
                      <button key={p.id} onClick={() => toggle(p.id)} style={{
                        display: 'flex', alignItems: 'center', gap: 9, padding: '8px 10px', borderRadius: 8,
                        border: `1.5px solid ${on ? 'var(--brand)' : 'var(--line)'}`,
                        background: on ? 'var(--brand-soft)' : 'var(--surface)', textAlign: 'left', minWidth: 0,
                      }}>
                        <span style={{ width: 24, height: 24, borderRadius: 5, background: p.hex, flexShrink: 0, boxShadow: 'inset 0 0 0 1px rgba(0,0,0,.12)' }}/>
                        <span style={{ minWidth: 0, flex: 1 }}>
                          <div style={{ fontSize: 12, fontWeight: 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{p.name}</div>
                          <div className="mono" style={{ fontSize: 8.5, color: 'var(--ink-4)', letterSpacing: '0.06em' }}>{p.brand.toUpperCase()} · {p.code}</div>
                        </span>
                        <span style={{ width: 18, height: 18, borderRadius: '50%', flexShrink: 0, display: 'grid', placeItems: 'center', fontSize: 11, fontWeight: 700,
                          background: on ? 'var(--brand)' : 'transparent', color: '#242424',
                          border: on ? 'none' : '1.5px solid var(--line-2)' }}>{on ? '✓' : ''}</span>
                      </button>
                    );
                  })}
                  {filtered.length === 0 && (
                    <div style={{ gridColumn: '1/-1', padding: 24, textAlign: 'center', color: 'var(--ink-3)', fontSize: 13 }}>No paints match — try another filter.</div>
                  )}
                </div>
              </>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Paints });
