/* ============================================================
   basket.fun — Basket Details screen
   ============================================================ */

function xProfileUrl(handle) {
  const h = String(handle || '').replace('@', '').trim();
  return h ? `https://x.com/${encodeURIComponent(h)}` : 'https://x.com/';
}

function useFollowedKol(handle) {
  const key = 'basket.followedKols';
  const clean = String(handle || '').replace('@', '').trim();
  const [following, setFollowing] = useState(false);
  useEffect(() => {
    try {
      const stored = JSON.parse(localStorage.getItem(key) || '[]');
      setFollowing(stored.includes(clean));
    } catch (e) {
      setFollowing(false);
    }
  }, [clean]);
  const toggle = () => {
    setFollowing((current) => {
      let stored = [];
      try { stored = JSON.parse(localStorage.getItem(key) || '[]'); } catch (e) { stored = []; }
      const next = current ? stored.filter(item => item !== clean) : Array.from(new Set([...stored, clean]));
      try { localStorage.setItem(key, JSON.stringify(next)); } catch (e) {}
      return !current;
    });
  };
  return [following, toggle];
}

function TF({ value, onChange }) {
  const opts = ['7D', '30D', 'All'];
  return (
    <div style={{ display: 'inline-flex', background: 'var(--surface-2)', borderRadius: 10, padding: 3, border: '1px solid var(--line)' }}>
      {opts.map(o => (
        <button key={o} onClick={() => onChange(o)} style={{
          padding: '6px 14px', borderRadius: 8, border: 'none', cursor: 'pointer', fontFamily: 'var(--font)',
          fontSize: 13, fontWeight: 600, background: value === o ? 'var(--text)' : 'transparent',
          color: value === o ? 'var(--bg)' : 'var(--text-2)', transition: 'all .15s',
        }}>{o}</button>
      ))}
    </div>
  );
}

function TokenRow({ t, i, expanded, onToggle }) {
  const [h, setH] = useState(false);
  return (
    <div style={{ borderBottom: '1px solid var(--line)' }}>
      <div onClick={onToggle} onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
        style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr 1.4fr auto', alignItems: 'center', gap: 12, padding: '14px 4px', cursor: 'pointer', background: h ? 'var(--surface-2)' : 'transparent', borderRadius: 10, transition: 'background .15s' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 11 }}>
          <TokenDot color={t.color} sym={t.sym} logoUrl={t.logo_url || t.logoUrl} logoSources={t.logo_sources || t.logoSources} size={34} />
          <div>
            <div style={{ fontWeight: 700, fontSize: 14.5, display: 'flex', alignItems: 'center', gap: 7 }}>
              {t.sym}
              <ChainBadge chain={t.chain} size="sm" />
            </div>
            <div style={{ fontSize: 12, color: 'var(--text-3)' }}>{t.name}</div>
          </div>
        </div>
        <div className="data" style={{ fontWeight: 700, fontSize: 15 }}>{t.weight}%</div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <div style={{ flex: 1, height: 6, borderRadius: 99, background: 'var(--surface-2)', overflow: 'hidden' }}>
            <div style={{ width: `${t.weight}%`, height: '100%', borderRadius: 99, background: t.color, transformOrigin: 'left', animation: `barGrow .8s cubic-bezier(.22,.61,.36,1) ${0.05 + i * 0.06}s forwards`, boxShadow: `0 0 8px ${t.color}66` }} />
          </div>
        </div>
        <Icon name={expanded ? 'arrowUp' : 'arrowDn'} size={16} color="var(--text-3)" />
      </div>
      {expanded && (
        <div style={{ padding: '0 4px 16px 49px', animation: 'fadeIn .25s ease .06s forwards' }}>
          <div style={{ background: 'var(--surface-2)', borderRadius: 12, padding: '12px 14px', borderLeft: '2px solid ' + t.color }}>
            <div style={{ fontSize: 11, fontFamily: 'var(--mono)', textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--text-3)', marginBottom: 4 }}>KOL thesis · {t.sym}</div>
            <div style={{ fontSize: 13.5, color: 'var(--text)', lineHeight: 1.5 }}>{t.thesis}</div>
          </div>
        </div>
      )}
    </div>
  );
}

function HistoryTimeline({ history }) {
  return (
    <div style={{ position: 'relative', paddingLeft: 22 }}>
      <div style={{ position: 'absolute', left: 5, top: 6, bottom: 6, width: 2, background: 'var(--line)' }} />
      {history.map((h, i) => (
        <div key={i} style={{ position: 'relative', paddingBottom: i === history.length - 1 ? 0 : 18 }}>
          <span style={{ position: 'absolute', left: -22, top: 3, width: 12, height: 12, borderRadius: 99, background: h.kind === 'rebalance' ? 'var(--accent)' : 'var(--blue)', border: '3px solid var(--bg)', boxShadow: i === 0 ? '0 0 8px var(--accent-glow)' : 'none' }} />
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 2 }}>
            <span style={{ fontWeight: 700, fontSize: 13 }}>{h.action}</span>
            <span style={{ fontSize: 11, color: 'var(--text-3)' }}>· v{h.v} · {h.when}</span>
          </div>
          <div style={{ fontSize: 12.5, color: 'var(--text-2)', lineHeight: 1.45 }}>{h.note}</div>
        </div>
      ))}
    </div>
  );
}

function BasketDetail({ basketId, onBack, onCopy, order = [], onNavigate, onOpenKol }) {
  const { baskets } = window.DB;
  const b = baskets.find(x => x.id === basketId) || baskets[0];
  const isMobile = useIsMobile();
  const [tf, setTf] = useState('30D');
  const [exp, setExp] = useState(null);
  const [slide, setSlide] = useState(0); // transient slide-in offset for swipe feedback
  const [following, toggleFollow] = useFollowedKol(b.kol.handle);
  const history = b.history && b.history.length ? b.history : window.DB.history;
  const idx = order.indexOf(b.id);
  const prevId = idx > 0 ? order[idx - 1] : null;
  const nextId = idx >= 0 && idx < order.length - 1 ? order[idx + 1] : null;

  const goPrev = () => { if (prevId && onNavigate) { setSlide(1); onNavigate(prevId); } };
  const goNext = () => { if (nextId && onNavigate) { setSlide(-1); onNavigate(nextId); } };
  useEffect(() => { if (slide) { const t = setTimeout(() => setSlide(0), 30); return () => clearTimeout(t); } }, [b.id]);
  const swipe = useSwipe({ onLeft: goNext, onRight: goPrev });

  const perf = tf === '7D' ? b.perf7d : tf === '30D' ? b.perf30d : b.perfAll;
  // build a longer series for the chart
  const series = useMemo(() => window.DB.spark(b.name.length * 7 + 3, tf === '7D' ? 24 : tf === '30D' ? 40 : 80, perf > 0 ? 0.012 : -0.004), [tf, b.id]);

  return (
    <div className="page" {...(isMobile ? swipe : {})} style={{ padding: '24px 32px 64px', maxWidth: 1280, margin: '0 auto', animation: 'fadeIn .35s ease .06s forwards' }}>
      {/* breadcrumb */}
      <button onClick={onBack} style={{ display: 'inline-flex', alignItems: 'center', gap: 7, background: 'none', border: 'none', color: 'var(--text-2)', cursor: 'pointer', fontFamily: 'var(--font)', fontSize: 14, fontWeight: 600, marginBottom: 20, padding: 0 }}>
        <Icon name="arrowR" size={16} color="var(--text-2)" style={{ transform: 'rotate(180deg)' }} /> Explore
      </button>

      {/* mobile basket pager — swipe or tap to move between baskets */}
      {isMobile && order.length > 1 && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 16 }}>
          <button onClick={goPrev} disabled={!prevId} style={{ width: 40, height: 40, flexShrink: 0, borderRadius: 11, border: '1px solid var(--line-2)', background: 'var(--surface)', cursor: prevId ? 'pointer' : 'not-allowed', opacity: prevId ? 1 : 0.4, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon name="arrowR" size={18} color="var(--text)" style={{ transform: 'rotate(180deg)' }} />
          </button>
          <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
            <div style={{ fontSize: 12, color: 'var(--text-3)', fontWeight: 600 }}>Basket {idx + 1} of {order.length} · swipe to browse</div>
            <div style={{ display: 'flex', gap: 6 }}>
              {order.map((id, i) => (
                <span key={id} style={{ width: i === idx ? 18 : 6, height: 6, borderRadius: 99, background: i === idx ? 'var(--accent)' : 'var(--line-strong)', transition: 'all .3s cubic-bezier(.22,.61,.36,1)' }} />
              ))}
            </div>
          </div>
          <button onClick={goNext} disabled={!nextId} style={{ width: 40, height: 40, flexShrink: 0, borderRadius: 11, border: '1px solid var(--line-2)', background: 'var(--surface)', cursor: nextId ? 'pointer' : 'not-allowed', opacity: nextId ? 1 : 0.4, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon name="arrowR" size={18} color="var(--text)" />
          </button>
        </div>
      )}

      <div key={b.id} style={isMobile ? { animation: `${slide < 0 ? 'slideFromRight' : slide > 0 ? 'slideFromLeft' : 'fadeIn'} .32s cubic-bezier(.22,.61,.36,1) .05s forwards` } : {}}>

      {/* header */}
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 24, marginBottom: 14, flexWrap: 'wrap' }}>
        <div style={{ display: 'flex', gap: 18, alignItems: 'flex-start' }}>
          <KolAvatar kol={b.kol} size={58} />
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
              <h1 className="display" style={{ margin: 0, fontSize: 'clamp(28px, 3vw, 40px)', fontWeight: 900, lineHeight: 1.04 }}>{b.name}</h1>
              <span className="data" style={{ fontSize: 12, fontWeight: 700, padding: '4px 9px', borderRadius: 7, background: 'var(--surface-2)', border: '1px solid var(--line-2)', color: 'var(--text-2)' }}>v{b.version}</span>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 8, color: 'var(--text-2)', fontSize: 13.5, flexWrap: 'wrap' }}>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>by <button onClick={() => onOpenKol && onOpenKol(b.kol.handle)} style={{ background: 'none', border: 'none', padding: 0, cursor: 'pointer', color: 'var(--text)', fontWeight: 700, fontFamily: 'var(--font)', fontSize: 13.5, textDecoration: 'underline', textDecorationColor: 'var(--line-strong)', textUnderlineOffset: 3 }}>{b.kol.x}</button></span>
              <span style={{ color: 'var(--text-3)' }}>·</span>
              <span className="data">{b.kol.followers} followers</span>
              <span style={{ color: 'var(--text-3)' }}>·</span>
              <span className="data">{b.ageDays}d old</span>
              {b.chainSplit.base > 0 ? <ChainBadge chain="base" size="sm" /> : <ChainBadge chain="sol" size="sm" />}
            </div>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 10 }}>
          <Btn variant={following ? 'soft' : 'ghost'} icon={following ? 'check' : 'bell'} onClick={toggleFollow}>{following ? 'Following' : 'Follow'}</Btn>
          <Magnetic><Btn icon="copy" size="md" onClick={() => onCopy(b.id)}>Copy basket</Btn></Magnetic>
        </div>
      </div>
      <p style={{ margin: '0 0 26px', fontSize: 15.5, color: 'var(--text-2)', maxWidth: 600, lineHeight: 1.5 }}>{b.tagline}</p>

      <div className="detail-grid" style={{ display: 'grid', gridTemplateColumns: '1fr 360px', gap: 24, alignItems: 'start' }}>
        {/* main column */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
          {/* performance card */}
          <Card pad={24} spot hover>
            <SectionLabel n="01" right={<TF value={tf} onChange={setTf} />}>Performance</SectionLabel>
            <div style={{ display: 'flex', alignItems: 'flex-end', gap: 14, marginBottom: 4 }}>
              <div className="data" style={{ fontSize: 52, fontWeight: 700, lineHeight: 0.85, letterSpacing: '-0.04em', color: perf >= 0 ? 'var(--accent-ink)' : 'var(--danger)' }}>
                {sign(perf)}{Math.abs(perf).toFixed(1)}%
              </div>
              <span className="eyebrow" style={{ paddingBottom: 6 }}>{tf} · indexed NAV</span>
            </div>
            <div style={{ marginTop: 16 }}>
              <AreaChart key={tf} data={series} h={260} color={perf >= 0 ? 'var(--accent-ink)' : 'var(--danger)'} />
            </div>
            <div className="g4" style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 16, marginTop: 22, paddingTop: 20, borderTop: '1px solid var(--line)' }}>
              <Stat label="AUM" value={fmtCompact(b.aum)} />
              <Stat label="Copiers" value={b.copiers.toLocaleString()} />
              <Stat label="Buy / sell fee" value={b.buyFee + '%'} sub="to KOL" />
              <Stat label="Tokens" value={b.tokens.length} sub={b.chainSplit.base > 0 ? 'Solana + Base' : 'Solana'} />
            </div>
          </Card>

          {/* thesis */}
          <Card pad={24}>
            <SectionLabel n="02">Basket thesis</SectionLabel>
            <p style={{ margin: 0, fontSize: 15.5, lineHeight: 1.62, color: 'var(--text)' }}>{b.thesis}</p>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 18, paddingTop: 16, borderTop: '1px solid var(--line)' }}>
              <KolAvatar kol={b.kol} size={32} />
              <div style={{ fontSize: 13 }}>
                <strong>{b.kol.name}</strong> <button onClick={() => onOpenKol && onOpenKol(b.kol.handle)} style={{ background: 'none', border: 'none', padding: 0, cursor: 'pointer', color: 'var(--text-3)', fontFamily: 'var(--mono)', fontSize: 12 }}>{b.kol.x}</button>
              </div>
              <a href={xProfileUrl(b.kol.handle)} target="_blank" rel="noreferrer" style={{ marginLeft: 'auto', fontSize: 13, color: 'var(--blue)', textDecoration: 'none', display: 'inline-flex', alignItems: 'center', gap: 4, fontWeight: 600 }}>View on X <Icon name="ext" size={13} color="var(--blue)" /></a>
            </div>
          </Card>

          {/* composition table */}
          <Card pad={24}>
            <SectionLabel n="03" right={<span className="eyebrow">tap row for thesis</span>}>Composition</SectionLabel>
            <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr 1.4fr auto', gap: 12, padding: '4px 4px 10px', borderBottom: '1px solid var(--line)' }} className="eyebrow">
              <div>Token</div><div>Weight</div><div>Allocation</div><div />
            </div>
            {b.tokens.map((t, i) => (
              <TokenRow key={t.sym} t={t} i={i} expanded={exp === t.sym} onToggle={() => setExp(exp === t.sym ? null : t.sym)} />
            ))}
          </Card>
        </div>

        {/* right column (sticky) */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 20, position: 'sticky', top: 92 }}>
          {/* copy panel */}
          <Card pad={22} style={{ background: 'linear-gradient(165deg, var(--surface), var(--bg-2))', borderColor: 'var(--line-2)' }}>
            <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 18 }}>
              <WeightRing tokens={b.tokens} size={172} thickness={20} centerLabel={b.tokens.length} centerSub="tokens" />
            </div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7, justifyContent: 'center', marginBottom: 20 }}>
              {b.tokens.map(t => (
                <span key={t.sym} style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 11.5, color: 'var(--text-2)', background: 'var(--surface-2)', padding: '3px 8px', borderRadius: 99 }}>
                  <span style={{ width: 7, height: 7, borderRadius: 99, background: t.color }} />{t.sym} {t.weight}%
                </span>
              ))}
            </div>
            <Btn full size="lg" icon="copy" onClick={() => onCopy(b.id)}>Copy basket</Btn>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6, marginTop: 12, fontSize: 12, color: 'var(--text-3)' }}>
              <Icon name="shield" size={13} color="var(--text-3)" /> Custodial vaults · auto-follow rebalances
            </div>
          </Card>

          {/* chain split */}
          <Card pad={20}>
            <h4 style={{ margin: '0 0 14px', fontSize: 14, fontWeight: 700 }}>Chain split</h4>
            <div style={{ display: 'flex', height: 10, borderRadius: 99, overflow: 'hidden', marginBottom: 12 }}>
              <div style={{ width: b.chainSplit.sol + '%', background: '#9945FF' }} />
              {b.chainSplit.base > 0 && <div style={{ width: b.chainSplit.base + '%', background: '#4C6FFF' }} />}
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13 }}>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><span style={{ width: 8, height: 8, borderRadius: 99, background: '#9945FF' }} />Solana <strong>{b.chainSplit.sol}%</strong></span>
              {b.chainSplit.base > 0 && <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><span style={{ width: 8, height: 8, borderRadius: 99, background: '#4C6FFF' }} />Base <strong>{b.chainSplit.base}%</strong></span>}
            </div>
            {b.chainSplit.base > 0 && (
              <div style={{ marginTop: 12, fontSize: 11.5, color: 'var(--text-3)', display: 'flex', gap: 6, alignItems: 'flex-start' }}>
                <Icon name="swap2" size={13} color="var(--text-3)" style={{ marginTop: 1, flexShrink: 0 }} />Cross-chain legs settle via CCTP. Expect added bridge time on copy.
              </div>
            )}
          </Card>

          {/* history */}
          <Card pad={20}>
            <h4 style={{ margin: '0 0 16px', fontSize: 14, fontWeight: 700 }}>Version history</h4>
            <HistoryTimeline history={history} />
          </Card>
        </div>
      </div>
      </div>
    </div>
  );
}

Object.assign(window, { BasketDetail });
