// Individual token page — chart, curve progress, live buy/sell against the curve

const pedbyAgo = (s) => {
  if (s == null) return 'now';
  if (s < 60) return Math.round(s) + 's ago';
  if (s < 3600) return Math.round(s / 60) + 'm ago';
  if (s < 86400) return Math.round(s / 3600) + 'h ago';
  return Math.round(s / 86400) + 'd ago';
};

const pedbyFmtTok = (n) => {
  if (n == null) return '';
  if (n >= 1e6) return (n / 1e6).toFixed(1).replace(/\.0$/, '') + 'M';
  if (n >= 1e3) return (n / 1e3).toFixed(1).replace(/\.0$/, '') + 'K';
  return Math.round(n).toLocaleString();
};

// Share: native sheet on mobile, copy-link + X / Telegram intents elsewhere
function PedbyShare({ token }) {
  const [copied, setCopied] = React.useState(false);
  const url = window.location.origin + window.location.pathname + '#/token/' + token.id;
  const text = `$${token.ticker} — ${token.name} · live on the curve at pedby`;

  const share = async () => {
    if (navigator.share) {
      try { await navigator.share({ title: '$' + token.ticker + ' on pedby', text, url }); return; } catch (e) { /* dismissed */ }
    }
    try { await navigator.clipboard.writeText(url); setCopied(true); setTimeout(() => setCopied(false), 1800); }
    catch (e) { window.prompt('Copy the link:', url); }
  };

  const iconBtn = {
    height: 32, padding: '0 11px', borderRadius: 999, border: '1px solid #E6EAE6', background: '#fff',
    fontFamily: 'inherit', fontSize: 12, fontWeight: 700, color: '#3B453F', cursor: 'pointer',
    display: 'inline-flex', alignItems: 'center', gap: 6, textDecoration: 'none',
  };
  return (
    <div style={{ display: 'flex', gap: 6, flexShrink: 0 }}>
      <button onClick={share} style={{ ...iconBtn, background: copied ? '#E7F4EC' : '#fff', color: copied ? '#0F4E27' : '#3B453F' }}>
        <SfIcon name="out" size={13} stroke="currentColor" />{copied ? 'Copied ✓' : 'Share'}
      </button>
      <a href={'https://twitter.com/intent/tweet?text=' + encodeURIComponent(text) + '&url=' + encodeURIComponent(url)}
        target="_blank" rel="noreferrer" style={iconBtn} title="Share on X">𝕏</a>
      <a href={'https://t.me/share/url?url=' + encodeURIComponent(url) + '&text=' + encodeURIComponent(text)}
        target="_blank" rel="noreferrer" style={iconBtn} title="Share on Telegram">TG</a>
    </div>
  );
}

function PedbyTokenDetail({ token, onNav, wallet, onTrade, trades = [], activityReady = true }) {
  const [side, setSide] = React.useState('buy'); // buy | sell
  const [ethAmt, setEthAmt] = React.useState(0.05);
  const [tokAmt, setTokAmt] = React.useState(0);

  if (!token) {
    return <div style={{ padding: 96, textAlign: 'center', color: '#9AA39E' }}>Token not found. <a href="#" onClick={() => onNav('marketplace')}>Back to marketplace</a></div>;
  }

  const curve = token.curve;
  const price = PEDBY_CURVE.price(curve);
  const priceUsd = price * PEDBY_CURVE.ETH_USD;
  const mcap = PEDBY_CURVE.marketCapUsd(curve);
  const progress = token.graduated ? 1 : PEDBY_CURVE.progress(curve);

  const preview = side === 'buy'
    ? PEDBY_CURVE.buy(curve, ethAmt)
    : PEDBY_CURVE.sell(curve, tokAmt);
  const previewOut = side === 'buy' ? preview.tokensOut : preview.ethOut;
  const newPrice = PEDBY_CURVE.price(preview.curve);
  const impactPct = ((newPrice - price) / price * 100);

  const holderBal = wallet.holdings[token.id] || 0;

  const doTrade = () => {
    onTrade(token.id, side, side === 'buy' ? ethAmt : tokAmt);
  };

  return (
    <div className="pedby-page-pad" style={{ maxWidth: 1120, margin: '0 auto', padding: '28px 28px 96px' }}>
      <button onClick={() => onNav('marketplace')} style={{ background: 'none', border: 'none', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6, color: '#6B7570', fontFamily: 'inherit', fontSize: 12.5, marginBottom: 18, padding: 0 }}>
        <SfIcon name="arrowL" size={14} /> Marketplace
      </button>

      <div className="pedby-detail-grid" style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 24 }}>
        <div>
          {/* Header */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 22 }}>
            <TokenGlyph ticker={token.ticker} graduated={token.graduated} size={54} image={token.image} />
            <div style={{ flex: 1 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <div style={{ fontSize: 24, fontWeight: 800, letterSpacing: -0.5 }}>{token.name}</div>
                <span style={{ fontFamily: 'JetBrains Mono', fontSize: 13, color: '#9AA39E' }}>${token.ticker}</span>
                <StatusDot t={token} />
              </div>
              <div style={{ fontSize: 13, color: '#6B7570', marginTop: 3 }}>{token.tag}</div>
            </div>
            <PedbyShare token={token} />
          </div>

          {/* Price */}
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 14, marginBottom: 4 }}>
            <div className="sf-serif sf-num" style={{ fontStyle: 'italic', fontSize: 44, letterSpacing: -1, lineHeight: 1 }}>{PEDBY_CURVE.fmtUsd(priceUsd, false)}</div>
            <div className="sf-num" style={{ fontSize: 13, color: '#6B7570' }}>{PEDBY_CURVE.fmtEth(price)} / token</div>
          </div>
          <div style={{ fontSize: 13, color: '#6B7570', marginBottom: 20 }}>Market cap <span className="sf-num" style={{ fontWeight: 600, color: '#16201A' }}>{PEDBY_CURVE.fmtUsd(mcap)}</span></div>

          {/* Chart */}
          <Card pad={18} style={{ marginBottom: 20 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 10 }}>
              <span style={{ fontFamily: 'JetBrains Mono', fontSize: 11, color: '#6B7570', textTransform: 'uppercase', letterSpacing: 0.6 }}>Price history</span>
              <span style={{ fontFamily: 'JetBrains Mono', fontSize: 11, color: '#6B7570' }}>
                {!activityReady ? 'syncing…' : token.trades && token.trades.length >= 2 ? 'on-chain trades' : 'bonding curve'}
              </span>
            </div>
            {!activityReady && (!token.trades || token.trades.length < 2) ? (
              <div style={{ height: 180, borderRadius: 12, background: '#F3FAF5', display: 'flex', alignItems: 'center', justifyContent: 'center', animation: 'pedby-shimmer 1.4s ease-in-out infinite' }}>
                <span style={{ fontFamily: 'JetBrains Mono', fontSize: 10.5, letterSpacing: 1.2, color: '#6B7570' }}>SYNCING PRICE HISTORY…</span>
              </div>
            ) : token.trades && token.trades.length >= 2
              ? <CandleChart trades={token.trades} />
              : <Sparkline data={token.spark} w={520} h={140} />}
          </Card>

          {/* Curve progress */}
          <Card pad={18} style={{ marginBottom: 20 }}>
            <CurveProgress curve={curve} graduated={token.graduated} />
            <div style={{ fontSize: 12, color: '#6B7570', marginTop: 10, lineHeight: 1.5 }}>
              {token.graduated
                ? 'Curve filled — liquidity is locked in a Base DEX pool. Trading now happens off-curve.'
                : `${PEDBY_CURVE.fmtEth(curve.realEth)} of ${PEDBY_CURVE.fmtEth(PEDBY_CURVE.GRADUATION_ETH)} raised toward graduation.`}
            </div>
          </Card>

          {/* Recent trades */}
          {(() => {
            const mine = trades.filter(tr => tr.tokenId === token.id).slice(0, 10);
            if (!mine.length && !activityReady) {
              return (
                <Card pad={18} style={{ marginBottom: 20 }}>
                  <div style={{ fontFamily: 'JetBrains Mono', fontSize: 11, color: '#6B7570', textTransform: 'uppercase', letterSpacing: 0.6, marginBottom: 12 }}>Latest trades</div>
                  {[85, 60, 74].map((w, i) => (
                    <div key={i} style={{ height: 11, width: w + '%', borderRadius: 6, background: '#EFF2EE', margin: '9px 0', animation: `pedby-shimmer 1.3s ease-in-out ${i * 0.18}s infinite` }} />
                  ))}
                </Card>
              );
            }
            if (!mine.length) return null;
            return (
              <Card pad={18} style={{ marginBottom: 20 }}>
                <div style={{ fontFamily: 'JetBrains Mono', fontSize: 11, color: '#6B7570', textTransform: 'uppercase', letterSpacing: 0.6, marginBottom: 12 }}>
                  Latest trades
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
                  {mine.map(tr => {
                    const isBuy = tr.side === 'buy';
                    return (
                      <div key={tr.key} style={{ display: 'flex', alignItems: 'baseline', gap: 10, fontSize: 12, fontFamily: 'JetBrains Mono', flexWrap: 'wrap' }}>
                        <span style={{ color: isBuy ? '#1E8C45' : '#C0392B', fontWeight: 700, flex: '0 0 52px' }}>{isBuy ? '▲ BUY' : '▼ SELL'}</span>
                        <span className="sf-num" style={{ color: '#16201A', fontWeight: 600 }}>{tr.ethAmt.toFixed(4)} ETH</span>
                        {tr.tokAmt != null && <span style={{ color: '#9AA39E' }}>{isBuy ? '→' : '←'} {pedbyFmtTok(tr.tokAmt)} {token.ticker}</span>}
                        <span style={{ marginLeft: 'auto', color: '#9AA39E', display: 'flex', gap: 10 }}>
                          {tr.trader && (
                            tr.traderAddress
                              ? <a href={PEDBY_CHAIN.explorerAddr(tr.traderAddress)} target="_blank" rel="noreferrer" style={{ color: '#6B7570' }}>{tr.trader}</a>
                              : <span>{tr.trader}</span>
                          )}
                          <span>{pedbyAgo(tr.agoSec)}</span>
                        </span>
                      </div>
                    );
                  })}
                </div>
              </Card>
            );
          })()}

          {/* About */}
          <Card pad={18}>
            <div style={{ fontFamily: 'JetBrains Mono', fontSize: 11, color: '#6B7570', textTransform: 'uppercase', letterSpacing: 0.6, marginBottom: 8 }}>About</div>
            <div style={{ fontSize: 13.5, color: '#3B453F', lineHeight: 1.6, marginBottom: 12 }}>{token.description}</div>
            <div style={{ marginBottom: 12 }}>
              <SocialLinks links={token.links} />
            </div>
            <div style={{ display: 'flex', gap: 18, fontSize: 12, color: '#6B7570' }}>
              <span>Created by <span className="sf-num" style={{ color: '#16201A' }}>{token.creator}</span></span>
              <span>{token.createdAgo}</span>
            </div>
          </Card>
        </div>

        {/* Trade panel */}
        <div className="pedby-detail-trade">
          <Card pad={18} style={{ position: 'sticky', top: 84 }}>
            {(
              <React.Fragment>
                {token.graduated && (
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 14 }}>
                    <Pill tone="blue" dot>Graduated</Pill>
                    <span style={{ fontSize: 11.5, color: '#6B7570' }}>trading on the locked liquidity pool</span>
                  </div>
                )}
                <div style={{ display: 'flex', gap: 6, marginBottom: 16 }}>
                  <button onClick={() => setSide('buy')} style={tabStyle(side === 'buy', '#1E8C45', '#E7F4EC', '#0F4E27')}>Buy</button>
                  <button onClick={() => setSide('sell')} style={tabStyle(side === 'sell', '#C0392B', '#FBE3E0', '#7A1E15')}>Sell</button>
                </div>

                {side === 'buy' ? (
                  <label style={{ display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 14 }}>
                    <span style={{ fontSize: 11.5, color: '#6B7570' }}>You pay (ETH)</span>
                    <input type="number" min="0" step="0.01" value={ethAmt} onChange={e => setEthAmt(Math.max(0, +e.target.value))} style={inputStyle} />
                    <div style={{ display: 'flex', gap: 6 }}>
                      {[0.05, 0.1, 0.5, 1].map(v => (
                        <button key={v} onClick={() => setEthAmt(v)} style={quickBtn}>{v} ETH</button>
                      ))}
                    </div>
                  </label>
                ) : (
                  <label style={{ display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 14 }}>
                    <span style={{ fontSize: 11.5, color: '#6B7570' }}>You sell ({token.ticker}) · holding {holderBal.toLocaleString()}</span>
                    <input type="number" min="0" value={tokAmt} onChange={e => setTokAmt(Math.max(0, +e.target.value))} style={inputStyle} />
                    <input type="range" min="0" max={holderBal || 0} value={Math.min(tokAmt, holderBal)} onChange={e => setTokAmt(+e.target.value)} style={{ width: '100%' }} />
                  </label>
                )}

                <div style={{ border: '1px solid #E6EAE6', borderRadius: 10, padding: 12, marginBottom: 14, fontSize: 12.5 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
                    <span style={{ color: '#6B7570' }}>You receive</span>
                    <span className="sf-num" style={{ fontWeight: 600 }}>
                      {side === 'buy' ? Math.round(previewOut).toLocaleString() + ' ' + token.ticker : PEDBY_CURVE.fmtEth(previewOut)}
                    </span>
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <span style={{ color: '#6B7570' }}>Price impact</span>
                    <span className="sf-num" style={{ fontWeight: 600, color: impactPct >= 0 ? '#0F4E27' : '#7A1E15' }}>{impactPct >= 0 ? '+' : ''}{impactPct.toFixed(2)}%</span>
                  </div>
                </div>

                <Btn kind={side === 'buy' ? 'primary' : 'dark'} style={{ width: '100%', justifyContent: 'center' }} onClick={doTrade}>
                  {side === 'buy' ? `Buy $${token.ticker}` : `Sell $${token.ticker}`}
                </Btn>
                <div style={{ fontSize: 11, color: '#9AA39E', textAlign: 'center', marginTop: 10 }}>
                  {window.PEDBY_LIVE
                    ? 'Trades settle on-chain on Base · 1% ' + (token.graduated ? 'pool' : 'curve') + ' fee'
                    : 'Simulated trade — no real funds move.'}
                </div>
              </React.Fragment>
            )}
          </Card>
        </div>
      </div>
    </div>
  );
}

const tabStyle = (active, fg, bg, fgActive) => ({
  flex: 1, height: 36, borderRadius: 10, border: 'none', cursor: 'pointer', fontFamily: 'inherit',
  fontSize: 13, fontWeight: 700, background: active ? bg : '#EFF2EE', color: active ? fgActive : '#6B7570',
});

const inputStyle = {
  height: 40, borderRadius: 10, border: '1px solid #E6EAE6', padding: '0 12px',
  fontSize: 15, fontFamily: 'JetBrains Mono', outline: 'none', background: '#fff',
};

const quickBtn = {
  flex: 1, height: 28, borderRadius: 8, border: '1px solid #E6EAE6', background: '#fff',
  fontFamily: 'inherit', fontSize: 11, cursor: 'pointer', color: '#3B453F',
};

window.PedbyTokenDetail = PedbyTokenDetail;
