// screens-binder.jsx — The Binder: your collection + card viewer

// completion ring
function Ring({ pct, size = 44, sw = 5, color = 'var(--accent)' }) {
  const r = (size - sw) / 2;
  const c = 2 * Math.PI * r;
  return (
    <svg width={size} height={size} className="ring">
      <circle cx={size / 2} cy={size / 2} r={r} stroke="var(--line-2)" strokeWidth={sw} />
      <circle cx={size / 2} cy={size / 2} r={r} stroke={color} strokeWidth={sw}
              strokeDasharray={c} strokeDashoffset={c * (1 - pct)} style={{ transition: 'stroke-dashoffset .6s cubic-bezier(.2,.7,.2,1)' }} />
    </svg>
  );
}

function flavorFor(card) {
  const set = card.set || setById(card.setId);
  const lines = {
    common: `A familiar face from ${set.name}. Trades easy at the lunch table.`,
    uncommon: `Steady pull. ${card.name} shows up just often enough to be loved.`,
    rare: `${card.name} — a clean rare. The kind that anchors a binder page.`,
    holo: `Holo foil. Tilt it in the light and ${card.name} comes alive.`,
    chase: `The chase. Pulling ${card.name} is the whole reason you open packs.`,
  };
  return lines[card.rarity];
}

/* ───────────── BINDER (collection) ───────────── */
function BinderScreen({ t, owned, viewCard }) {
  const ownedCount = SETS.reduce((s, set) => s + (owned[set.id]?.length || 0), 0);
  const total = SETS.length * CARDS_PER_SET;
  const hits = SETS.reduce((s, set) => s + (owned[set.id] || []).filter(i => RARITY[cardRarity(i)].stars >= 4).length, 0);
  const setsDone = SETS.filter(set => (owned[set.id]?.length || 0) === CARDS_PER_SET).length;

  return (
    <div className="fade-up" style={{ paddingBottom: 18 }}>
      <div style={{ padding: 'var(--top-pad) 20px 10px' }}>
        <div className="kicker" style={{ marginBottom: 8 }}>Your collection</div>
        <div className="t-display" style={{ fontSize: 32 }}>The Binder</div>
        <div className="muted" style={{ fontSize: 13, marginTop: 8, lineHeight: 1.35 }}>Pulled a card? Tap its empty slot to add it.</div>
      </div>

      {/* stats */}
      <div style={{ padding: '16px 20px 6px' }}>
        <div className="card" style={{ padding: 16, display: 'flex', alignItems: 'center', gap: 16 }}>
          <div style={{ position: 'relative', width: 64, height: 64, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Ring pct={ownedCount / total} size={64} sw={6} color="var(--accent)" />
            <div style={{ position: 'absolute', textAlign: 'center' }}>
              <div className="t-display" style={{ fontSize: 17, lineHeight: 1 }}>{Math.round((ownedCount / total) * 100)}%</div>
            </div>
          </div>
          <div style={{ flex: 1, display: 'flex', justifyContent: 'space-between' }}>
            {[[ownedCount + '/' + total, 'Cards'], [hits, 'Hits'], [setsDone + '/' + SETS.length, 'Sets done']].map(([v, k], i) => (
              <div key={i} style={{ textAlign: 'center' }}>
                <div className="t-display" style={{ fontSize: 20 }}>{v}</div>
                <div className="kicker" style={{ fontSize: 9, marginTop: 3 }}>{k}</div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* per-set pages */}
      <div style={{ padding: '12px 20px 0', display: 'flex', flexDirection: 'column', gap: 16 }}>
        {SETS.map(set => {
          const own = owned[set.id] || [];
          const pct = own.length / CARDS_PER_SET;
          return (
            <div key={set.id}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 10 }}>
                <div style={{ position: 'relative', width: 38, height: 38, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                  <Ring pct={pct} size={38} sw={4} color={pct === 1 ? 'var(--good)' : 'var(--accent)'} />
                  <div style={{ position: 'absolute', width: 22, height: 22, borderRadius: 7, background: `linear-gradient(150deg, ${set.c1}, ${set.c2})`, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    <Icon name={set.icon === 'flame' ? 'flame' : set.icon === 'wave' ? 'wave' : set.icon === 'leaf' ? 'leaf' : set.icon === 'bolt' ? 'bolt' : set.icon === 'snow' ? 'snow' : 'star'} size={12} color="#fff" />
                  </div>
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontFamily: 'var(--ff-display)', fontWeight: 800, fontSize: 16 }}>{set.name}</div>
                  <div style={{ fontFamily: 'var(--ff-mono)', fontSize: 10.5, color: 'var(--ink-3)' }}>{own.length} / {CARDS_PER_SET} collected{pct === 1 ? ' · complete' : ''}</div>
                </div>
                {pct === 1 && <span className="badge badge-good"><Icon name="check" size={11} color="var(--good)" sw={3} />Done</span>}
              </div>
              <div className="binder-grid" style={{ gridTemplateColumns: 'repeat(6,1fr)' }}>
                {Array.from({ length: CARDS_PER_SET }).map((_, i) => {
                  const has = own.includes(i);
                  const card = makeCard(set.id, i);
                  // Slots are buttons, not divs: tapping an empty one is the
                  // only way a card enters the binder, so it has to be
                  // reachable by keyboard and announce itself.
                  const label = '#' + String(i + 1).padStart(3, '0') + ' ' + set.name + ' · ' + (has ? card.name : 'empty slot, tap to add');
                  return has ? (
                    <button key={i} type="button" className="slot" aria-label={label} onClick={() => viewCard(card, true)}><CardFace card={card} w={48} /></button>
                  ) : (
                    <button key={i} type="button" className="slot locked" aria-label={label} onClick={() => viewCard(card, true)}><span className="q">?</span></button>
                  );
                })}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

/* ───────────── CARD VIEWER (overlay) ───────────── */
function CardViewer({ card, onClose, onPost, canPost = false, onAdd, canAdd = false, owned = true }) {
  const r = RARITY[card.rarity];
  const set = card.set || setById(card.setId);
  const [posted, setPosted] = React.useState(false);
  function post() { if (!posted) { onPost(card); setPosted(true); } }
  return (
    <div className="screen-push" style={{ background: 'radial-gradient(120% 80% at 50% 20%, color-mix(in oklab, ' + set.c1 + ' 26%, #14110c), #14110c 64%)', color: '#F3EDE0', zIndex: 70, display: 'flex', flexDirection: 'column', animation: 'fadeUp .3s ease both' }}>
      <div style={{ padding: 'var(--top-pad) 18px 4px' }}>
        <button onClick={onClose} style={{ width: 38, height: 38, borderRadius: 9999, border: 'none', background: 'rgba(255,255,255,0.12)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer' }}>
          <Icon name="chevL" size={20} sw={2.4} color="#fff" />
        </button>
      </div>
      <div className="scroll" style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', padding: '10px 28px 30px' }}>
        <div style={{ position: 'relative', marginTop: 14, marginBottom: 22 }}>
          {owned && r.stars >= 4 && <div className="hit-glow" style={{ '--hit-glow': r.tint, width: '120%' }} />}
          {/* a card you don't have yet reads as a preview, not as part of the collection */}
          <div style={{ position: 'relative', filter: owned ? 'drop-shadow(0 20px 36px rgba(0,0,0,0.5))' : 'grayscale(0.85) brightness(0.72)', opacity: owned ? 1 : 0.72 }}>
            <CardFace card={card} w={236} />
          </div>
        </div>
        <span className="badge" style={{ background: owned ? r.color : 'rgba(255,255,255,0.14)', color: '#fff', fontSize: 11.5, marginBottom: 10 }}>
          <RarityStars rarity={card.rarity} size={11} color="#fff" /> {r.label}{owned ? '' : ' · not collected'}
        </span>
        <h2 className="t-display" style={{ fontSize: 26, color: '#fff', margin: '4px 0 4px', textAlign: 'center' }}>{card.name}</h2>
        <div style={{ fontFamily: 'var(--ff-mono)', fontSize: 12, opacity: 0.65, marginBottom: 18 }}>{set.name} · #{String(card.idx + 1).padStart(3, '0')} · {card.hp} HP</div>
        <p style={{ fontSize: 14.5, lineHeight: 1.5, textAlign: 'center', opacity: 0.85, maxWidth: 280, margin: 0 }}>{flavorFor(card)}</p>
        {/* the way cards enter the binder: you pulled one, you say so */}
        {!owned && canAdd && (
          <button className="btn btn-accent" onClick={() => onAdd(card)} style={{ marginTop: 22, padding: '14px 24px' }}>
            <Icon name="check" size={18} color="var(--on-accent)" sw={2.6} /> I pulled this — add it
          </button>
        )}
        {/* posting a card you actually own — the Wall runs on real pulls */}
        {owned && canPost && (
          <button className="btn" onClick={post} disabled={posted}
                  style={{ marginTop: 22, padding: '14px 24px', background: posted ? 'rgba(255,255,255,0.12)' : 'var(--gold)', color: posted ? '#fff' : '#2a2208', opacity: posted ? 0.8 : 1 }}>
            {posted
              ? <><Icon name="check" size={18} color="#fff" sw={2.6} /> Posted to the Wall</>
              : <><Icon name="users" size={18} color="#2a2208" /> Show it off on the Wall</>}
          </button>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { Ring, BinderScreen, CardViewer, flavorFor });
