// ============================================================
// screens/Collection.jsx
// ============================================================
const { useState: useState_C, useMemo: useMemo_C } = React;

function CollectionScreen({ collection, onPickCard, selectedCardId }) {
  const [filter, setFilter] = useState_C({ pos: 'ALL', type: 'ALL', rarity: 'ALL', sort: 'ovr' });
  const [query, setQuery] = useState_C('');

  const cards = useMemo_C(() => {
    let list = collection.map(id => window.CARDS.find(c => c.id === id)).filter(Boolean);
    if (filter.pos !== 'ALL')   list = list.filter(c => c.pos === filter.pos);
    if (filter.type !== 'ALL')  list = list.filter(c => c.type === filter.type);
    if (filter.rarity !== 'ALL')list = list.filter(c => c.rarity === filter.rarity);
    if (query) list = list.filter(c => c.name.toLowerCase().includes(query.toLowerCase()));
    if (filter.sort === 'ovr')  list.sort((a,b) => b.ovr - a.ovr);
    if (filter.sort === 'rarity') {
      const order = ['legendary','epic','rare','uncommon','common'];
      list.sort((a,b) => order.indexOf(a.rarity) - order.indexOf(b.rarity));
    }
    if (filter.sort === 'name') list.sort((a,b) => a.name.localeCompare(b.name));
    return list;
  }, [collection, filter, query]);

  const layout = window.__layout || 'classic';

  return (
    <div style={{ padding: '28px 40px 80px', maxWidth: 1400, margin: '0 auto' }}>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 24, marginBottom: 24 }}>
        <h1 style={{
          fontFamily: 'var(--font-display)', fontSize: 42, margin: 0, color: '#fff', fontWeight: 600,
        }}>Collection</h1>
        <div style={{ color: '#6a7380', fontSize: 13, letterSpacing: '0.08em', textTransform: 'uppercase' }}>
          {cards.length} of {collection.length} cards
        </div>
        <div style={{ flex: 1 }} />
        <RarityLegend />
      </div>

      {/* filters */}
      <div style={{
        display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center',
        marginBottom: 28, paddingBottom: 20, borderBottom: '1px solid #1a1f26',
      }}>
        <SearchBox value={query} onChange={setQuery} />
        <FilterGroup label="Position" value={filter.pos} onChange={v=>setFilter({...filter,pos:v})}
          opts={[['ALL','All'],['GK','GK'],['DEF','DEF'],['MID','MID'],['FWD','FWD']]} />
        <FilterGroup label="Type" value={filter.type} onChange={v=>setFilter({...filter,type:v})}
          opts={[['ALL','All'],...Object.entries(window.TYPES).map(([k,t])=>[k,t.name])]} />
        <FilterGroup label="Rarity" value={filter.rarity} onChange={v=>setFilter({...filter,rarity:v})}
          opts={[['ALL','All'],...Object.entries(window.RARITIES).map(([k,r])=>[k,r.name])]} />
        <div style={{ flex: 1 }} />
        <FilterGroup label="Sort" value={filter.sort} onChange={v=>setFilter({...filter,sort:v})}
          opts={[['ovr','Overall'],['rarity','Rarity'],['name','Name']]} />
      </div>

      {/* grid */}
      <div style={{
        display: 'grid',
        gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))',
        gap: 20,
      }}>
        {cards.map(c => (
          <div key={c.id} style={{ display: 'flex', justifyContent: 'center' }}>
            <window.PlayerCard
              cardId={c.id}
              size="sm"
              layout={layout}
              selected={c.id === selectedCardId}
              onClick={() => onPickCard && onPickCard(c.id)}
            />
          </div>
        ))}
        {cards.length === 0 && (
          <div style={{
            gridColumn: '1 / -1', padding: 60, textAlign: 'center',
            color: '#6a7380', fontSize: 14, border: '1px dashed #1e2329', borderRadius: 12,
          }}>No cards match those filters.</div>
        )}
      </div>
    </div>
  );
}

function SearchBox({ value, onChange }) {
  return (
    <div style={{ position: 'relative' }}>
      <input
        value={value}
        onChange={e => onChange(e.target.value)}
        placeholder="Search name…"
        style={{
          background: '#0e1114', border: '1px solid #1e2329', borderRadius: 6,
          color: '#e6e8eb', padding: '8px 12px 8px 32px', fontSize: 13, width: 200,
          fontFamily: 'var(--font-sans)', outline: 'none',
        }}
      />
      <div style={{ position: 'absolute', left: 10, top: 8, color: '#5a6169', fontSize: 14 }}>⌕</div>
    </div>
  );
}

function FilterGroup({ label, value, onChange, opts }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
      <span style={{
        fontSize: 10, color: '#5a6169', textTransform: 'uppercase',
        letterSpacing: '0.1em', fontWeight: 600,
      }}>{label}</span>
      <div style={{ display: 'flex', background: '#0e1114', borderRadius: 6, padding: 2, border: '1px solid #1e2329' }}>
        {opts.map(([k,l]) => (
          <button key={k} onClick={() => onChange(k)} style={{
            background: value === k ? '#1e2329' : 'transparent',
            border: 'none', color: value === k ? '#fff' : '#8a9099',
            padding: '5px 10px', fontSize: 11, borderRadius: 4,
            cursor: 'pointer', fontFamily: 'inherit', fontWeight: 600,
            letterSpacing: '0.04em',
          }}>{l}</button>
        ))}
      </div>
    </div>
  );
}

function RarityLegend() {
  return (
    <div style={{ display: 'flex', gap: 14, fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.1em' }}>
      {Object.entries(window.RARITIES).map(([k,r]) => (
        <div key={k} style={{ display: 'flex', alignItems: 'center', gap: 5, color: r.color, fontWeight: 600 }}>
          <span style={{
            width: 8, height: 8, borderRadius: '50%', background: r.color,
            boxShadow: `0 0 8px ${r.glow}`,
          }}/>
          {r.name}
        </div>
      ))}
    </div>
  );
}

window.CollectionScreen = CollectionScreen;
