// components.jsx — shared UI components
const { useState, useEffect, useRef, useMemo } = React;

// ---------- icons (inline svg) ----------
const Icon = {
  search: (p) => <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><circle cx="11" cy="11" r="7"/><path d="m20 20-3-3"/></svg>,
  copy: (p) => <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><rect x="9" y="9" width="11" height="11" rx="2"/><path d="M5 15V5a2 2 0 0 1 2-2h10"/></svg>,
  chev: (p) => <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><path d="m6 9 6 6 6-6"/></svg>,
  ext:  (p) => <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><path d="M7 17 17 7M9 7h8v8"/></svg>,
  tg:   (p) => <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" {...p}><path d="M12 0C5.4 0 0 5.4 0 12s5.4 12 12 12 12-5.4 12-12S18.6 0 12 0zm5.7 8-1.9 9c-.1.6-.5.7-1 .5l-2.9-2.1-1.4 1.3c-.2.2-.3.3-.6.3l.2-2.9 5.2-4.7c.2-.2-.05-.3-.3-.1l-6.4 4-2.8-.9c-.6-.2-.6-.6.1-.9l11-4.2c.5-.2.9.1.7.9z"/></svg>,
  x:    (p) => <svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor" {...p}><path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"/></svg>,
  web:  (p) => <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><circle cx="12" cy="12" r="10"/><path d="M2 12h20M12 2a15 15 0 0 1 0 20M12 2a15 15 0 0 0 0 20"/></svg>,
  upload:(p)=> <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}><path d="M12 16V4m0 0L8 8m4-4 4 4M4 20h16"/></svg>,
  back: (p) => <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><path d="m15 18-6-6 6-6"/></svg>,
  flame:(p) => <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" {...p}><path d="M12 2s4 6 4 10a4 4 0 0 1-8 0c0-1.5 1-3 1-3s-3 1-3 5a6 6 0 0 0 12 0c0-5-6-12-6-12z"/></svg>,
};

// ---------- arrow ----------
function ChangeArrow({ v }) {
  const up = v >= 0;
  return (
    <span className={up ? 'up' : 'down'} style={{ fontFamily: 'var(--font-mono)', fontSize: 13 }}>
      {up ? '▲' : '▼'} {Math.abs(v).toFixed(1)}%
    </span>
  );
}

// ---------- token card ----------
function TokenCard({ tok, lang, onClick }) {
  const t = I18N[lang];
  return (
    <div className="tok-card" onClick={onClick}>
      <div className="tok-card-head">
        <div className="tok-avatar">{tok.glyph}</div>
        <div style={{ minWidth: 0, flex: 1 }}>
          <div className="tok-name" style={{ overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{tok.name[lang]}</div>
          <div className="tok-sym">${tok.sym}</div>
        </div>
        <ChangeArrow v={tok.ch24} />
      </div>
      <div className="tok-card-stats">
        <div>
          <label>{t.mcap}</label>
          <b>{fmtMcap(tok.mcap)} <span style={{ color:'var(--text-faint)', fontSize:10 }}>TON</span></b>
        </div>
        <div>
          <label>{t.vol_24h}</label>
          <b>{fmtMcap(tok.vol24)} <span style={{ color:'var(--text-faint)', fontSize:10 }}>TON</span></b>
        </div>
      </div>
      <div className="tok-progress">
        <div className="tok-progress-fill" style={{ width: tok.progress + '%' }}></div>
      </div>
      <div className="tok-progress-row">
        <span>{t.progress}</span>
        <span style={{ color: 'var(--accent)' }}>{tok.progress.toFixed(1)}%</span>
      </div>
    </div>
  );
}

// ---------- live ticker ----------
function makeTrade(seed) {
  const r = mulberry32(seed);
  const tok = TOKENS[Math.floor(r() * TOKENS.length)];
  const side = r() > 0.45 ? 'b' : 's';
  const amount = (r() * 50 + 0.1);
  const addr = FAKE_ADDRS[Math.floor(r() * FAKE_ADDRS.length)];
  return { id: seed, tok, side, amount, addr, when: 0 };
}

function LiveTicker({ lang }) {
  const t = I18N[lang];
  const [trades, setTrades] = useState(() =>
    Array.from({ length: 14 }, (_, i) => ({ ...makeTrade(Date.now() + i * 7919), when: i * 5 + 2 }))
  );
  useEffect(() => {
    const id = setInterval(() => {
      setTrades((prev) => {
        const next = [{ ...makeTrade(Date.now() + Math.random() * 99991), when: 0 }, ...prev];
        return next.slice(0, 18).map((tr, i) => ({ ...tr, when: i === 0 ? 0 : tr.when + 2 }));
      });
    }, 2400);
    return () => clearInterval(id);
  }, []);
  return (
    <div className="card ticker">
      <div className="card-head">
        <h3>{t.live_trades}</h3>
        <span className="tag live">{t.live}</span>
      </div>
      <div className="ticker-list">
        {trades.map((tr) => (
          <div key={tr.id} className="ticker-item">
            <span className={'ticker-side ' + tr.side}>{tr.side === 'b' ? t.buy.toUpperCase().slice(0,3) : t.sell.toUpperCase().slice(0,3)}</span>
            <div className="ticker-mid">
              <div className="ticker-amt"><b>{tr.amount.toFixed(2)}</b> TON · ${tr.tok.sym}</div>
              <div className="ticker-addr">{tr.addr}</div>
            </div>
            <span className="ticker-time">{tr.when < 1 ? 'now' : tr.when + 's'}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

// ---------- wallet button + modal ----------
function WalletButton({ lang, wallet, onConnect, onAction }) {
  const t = I18N[lang];
  const [open, setOpen] = useState(false);
  const ref = useRef();
  useEffect(() => {
    const h = (e) => { if (!ref.current?.contains(e.target)) setOpen(false); };
    document.addEventListener('click', h);
    return () => document.removeEventListener('click', h);
  }, []);
  if (!wallet.connected) {
    return <button className="btn btn-primary" onClick={onConnect}>{t.connect_wallet}</button>;
  }
  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <button className="wallet-btn" onClick={(e) => { e.stopPropagation(); setOpen((o) => !o); }}>
        <span className="dot"></span>
        <span>{wallet.addr}</span>
        <span style={{ width: 1, height: 14, background: 'var(--line-2)' }}></span>
        <span className="bal">{wallet.bal.toFixed(2)} TON</span>
        <Icon.chev style={{ opacity: 0.5 }} />
      </button>
      {open && (
        <div className="dropdown">
          <div className="dropdown-item" onClick={() => { setOpen(false); onAction('profile'); }}>👤 {t.view_profile}</div>
          <div className="dropdown-item" onClick={() => { setOpen(false); onAction('pnl'); }}>📊 {t.view_pnl}</div>
          <div className="dropdown-item danger" onClick={() => { setOpen(false); onAction('disconnect'); }}>⏻ {t.disconnect}</div>
        </div>
      )}
    </div>
  );
}

function WalletModal({ lang, onClose, onSelect }) {
  const t = I18N[lang];
  const [agreed, setAgreed] = useState(false);
  const wallets = [
    { id: 'tonkeeper', name: 'Tonkeeper', icon: '🔑', desc: 'tonkeeper.com', rec: true },
    { id: 'tg', name: 'Telegram Wallet', icon: '✈️', desc: 'wallet.tg' },
    { id: 'mtw', name: 'MyTonWallet', icon: '💎', desc: 'mytonwallet.io' },
  ];
  return (
    <div className="modal-back" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <div className="modal-head">
          <h3 className="modal-title">{t.wallet_select_title}</h3>
          <button className="modal-close" onClick={onClose}>✕</button>
        </div>
        <div className="modal-body">
          {wallets.map((w) => (
            <div key={w.id} className="wallet-opt" onClick={() => agreed && onSelect(w)} style={{ opacity: agreed ? 1 : 0.55 }}>
              <div className="wallet-opt-icon">{w.icon}</div>
              <div style={{ flex: 1 }}>
                <div className="wallet-opt-name">{w.name} {w.rec && <span className="tag" style={{ background:'color-mix(in oklab, var(--accent) 18%, transparent)', borderColor:'transparent', color:'var(--accent)' }}>{t.wallet_recommended}</span>}</div>
                <div className="wallet-opt-desc">{w.desc}</div>
              </div>
              <Icon.chev style={{ transform: 'rotate(-90deg)', color: 'var(--text-faint)' }} />
            </div>
          ))}
          <div className="chk" onClick={() => setAgreed((a) => !a)}>
            <div className={'chk-box ' + (agreed ? 'on' : '')}>{agreed && '✓'}</div>
            <span>{t.wallet_agree}</span>
          </div>
          <div style={{ borderTop: '1px solid var(--line)', marginTop: 8, paddingTop: 14, textAlign: 'center', fontSize: 12 }}>
            <a style={{ color: 'var(--accent)', textDecoration: 'none' }}>{t.wallet_guide} →</a>
          </div>
        </div>
      </div>
    </div>
  );
}

function SignModal({ lang, title, sub, gas = 0.005 }) {
  const t = I18N[lang];
  return (
    <div className="modal-back">
      <div className="modal" style={{ width: 380 }}>
        <div className="modal-body" style={{ padding: '32px 28px', textAlign: 'center' }}>
          <div className="signing-anim"></div>
          <h3 className="modal-title" style={{ marginBottom: 8 }}>{title || t.tx_signing}</h3>
          <p style={{ color: 'var(--text-dim)', fontSize: 13, lineHeight: 1.5, margin: '0 0 20px' }}>{sub || t.tx_signing_sub}</p>
          <div style={{ background: 'var(--surface-2)', border: '1px solid var(--line)', borderRadius: 8, padding: '10px 14px', display: 'flex', justifyContent: 'space-between', fontSize: 12, fontFamily: 'var(--font-mono)' }}>
            <span style={{ color: 'var(--text-dim)' }}>{t.est_gas}</span>
            <span>~{gas.toFixed(3)} TON</span>
          </div>
        </div>
      </div>
    </div>
  );
}

// ---------- toast ----------
function Toast({ msg }) {
  if (!msg) return null;
  return (
    <div style={{ position: 'fixed', bottom: 28, left: '50%', transform: 'translateX(-50%)', zIndex: 200, background: 'var(--surface)', border: '1px solid var(--accent)', boxShadow: '0 0 20px var(--accent-2)', padding: '12px 20px', borderRadius: 10, fontFamily: 'var(--font-mono)', fontSize: 13, animation: 'modalIn 0.2s ease' }}>
      ✓ {msg}
    </div>
  );
}

// expose globally
Object.assign(window, {
  Icon, ChangeArrow, TokenCard, LiveTicker, WalletButton, WalletModal, SignModal, Toast, makeTrade,
});
