// wci26/buy-drawer.jsx - slide-in buy drawer backed by live Sepolia pool data.

const WCI_BUY_ETH_PRESETS = [0.1, 0.25, 0.5, 1];

const wciBuyFmtEth = (value, digits = 4) => {
  const number = Number(value || 0);
  if (!Number.isFinite(number) || number <= 0) return '0 ETH';
  return `${number.toFixed(digits).replace(/\.?0+$/, '')} ETH`;
};

const wciBuyFmtWeth = (value, digits = 4) => {
  const number = Number(value || 0);
  if (!Number.isFinite(number) || number <= 0) return '0 WETH';
  return `${number.toFixed(digits).replace(/\.?0+$/, '')} WETH`;
};

const wciBuyFmtTokens = (value) => {
  const number = Number(value || 0);
  if (!Number.isFinite(number) || number <= 0) return '0';
  if (number >= 1_000_000) return `${(number / 1_000_000).toFixed(2).replace(/\.?0+$/, '')}M`;
  if (number >= 1_000) return `${(number / 1_000).toFixed(1).replace(/\.?0+$/, '')}K`;
  return number.toLocaleString(undefined, { maximumFractionDigits: 2 });
};

const wciBuyFmtMarketCap = (country) => (
  typeof wciFormatCountryMarketCap === 'function'
    ? wciFormatCountryMarketCap(country)
    : (typeof fmtMcap === 'function' ? fmtMcap(country?.mcap || 0) : '$--')
);

const wciBuyFmtVolume = (country) => (
  typeof wciFormatCountryVolume === 'function'
    ? wciFormatCountryVolume(country)
    : (typeof fmtVol === 'function' ? fmtVol(country?.volume24h || 0) : '$0')
);

const wciBuyFmtPrice = (country) => (
  typeof wciFormatCountryPrice === 'function'
    ? wciFormatCountryPrice(country, { fallback: '$--' })
    : '$--'
);

const BuyMetric = ({ label, value, color }) => (
  <div style={{
    padding: '10px 9px',
    borderRadius: 11,
    background: 'rgba(255,255,255,0.04)',
    border: '1px solid rgba(255,255,255,0.07)',
    minWidth: 0,
  }}>
    <div className="label" style={{ fontSize: 8 }}>{label}</div>
    <div className="mono" style={{
      marginTop: 5,
      fontSize: 11,
      color: color || '#fff',
      fontWeight: 800,
      overflow: 'hidden',
      textOverflow: 'ellipsis',
      whiteSpace: 'nowrap',
    }}>{value}</div>
  </div>
);

const BuyDrawer = ({ open, country, countries = [], buybackPool = 0, onClose, onConfirm }) => {
  const [amountEth, setAmountEth] = React.useState(0.25);
  React.useEffect(() => { if (open) setAmountEth(0.25); }, [open, country?.code]);

  React.useEffect(() => {
    if (!open) return;
    const h = (e) => e.key === 'Escape' && onClose();
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, [open, onClose]);

  if (!country && !open) return null;
  const c = country;
  const tokenLabel = c && typeof wciCountryDollarTicker === 'function' ? wciCountryDollarTicker(c) : `$${c?.code || ''}26`;
  const tradeUrl = c && typeof WCI_TRADE_LINKS !== 'undefined'
    ? WCI_TRADE_LINKS.buildUniswapSwapUrl(c, { amountEth })
    : '#';
  const tradeTokenAddress = c && typeof WCI_TRADE_LINKS !== 'undefined'
    ? WCI_TRADE_LINKS.resolveCountryTokenAddress(c)
    : '';
  const estimatedTokens = c?.priceWETH > 0 ? amountEth / c.priceWETH : 0;
  const marketCapLabel = wciBuyFmtMarketCap(c);
  const volumeLabel = wciBuyFmtVolume(c);

  return (
    <>
      <div className="buy-backdrop" style={{
        position: 'fixed', inset: 0, zIndex: 80,
        background: 'rgba(10,6,21,0.65)',
        backdropFilter: 'blur(6px)',
        opacity: open ? 1 : 0,
        pointerEvents: open ? 'auto' : 'none',
        transition: 'opacity 280ms var(--ease)',
      }} onClick={onClose} />

      <div className="buy-drawer" style={{
        position: 'fixed', top: 0, right: 0, bottom: 0, zIndex: 81,
        width: 440, padding: 28, overflow: 'auto',
        background: `
          radial-gradient(ellipse 80% 30% at 50% 0%, ${c?.color || '#F5D020'}22, transparent 70%),
          linear-gradient(180deg, #1a1340 0%, #0a0615 100%)`,
        borderLeft: `1px solid ${c?.color || 'var(--hair-strong)'}33`,
        boxShadow: `-30px 0 80px -20px rgba(0,0,0,0.8), -10px 0 0 ${c?.color || 'var(--gold)'}22`,
        transform: open ? 'translateX(0)' : 'translateX(100%)',
        transition: 'transform 320ms var(--ease)',
      }}>
        {c && (<>
          <button onClick={onClose} aria-label="Close buy drawer" style={{
            position: 'absolute', top: 18, right: 18, width: 36, height: 36, borderRadius: 10,
            background: 'rgba(255,255,255,0.06)', border: '1px solid var(--hair)',
            color: 'var(--t2)', cursor: 'pointer', fontSize: 18,
          }}>x</button>

          <div className="label" style={{ color: c.color, marginBottom: 4 }}>BUY COUNTRY TOKEN</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 20 }}>
            <FlagRect code={c.code} w={56} h={38} />
            <div>
              <div className="display" style={{ fontSize: 32, lineHeight: 1 }}>
                {tokenLabel}
              </div>
              <div style={{ fontSize: 12, color: 'var(--t3)', marginTop: 2 }}>{c.name} - Group {c.group}</div>
            </div>
          </div>

          <div style={{
            padding: '16px 18px', borderRadius: 14,
            background: 'rgba(255,255,255,0.03)',
            border: `1px solid ${c.color}33`,
            marginBottom: 18,
          }}>
            <div style={{ display: 'flex', alignItems: 'flex-end', gap: 12 }}>
              <div className="mono" style={{ fontSize: 25, fontWeight: 700, color: '#fff', lineHeight: 1 }}>
                {wciBuyFmtPrice(c)}
              </div>
              <div className="mono" style={{ fontSize: 12, fontWeight: 800, paddingBottom: 3, color: 'var(--gold)' }}>
                per token
              </div>
            </div>
            <div style={{
              display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10, marginTop: 12,
              paddingTop: 12, borderTop: '1px solid rgba(255,255,255,0.05)',
            }}>
              <BuyMetric label="RANK" value={`#${c.rank}`} />
              <BuyMetric label="MARKET CAP" value={marketCapLabel} />
              <BuyMetric label="VOLUME" value={volumeLabel} />
            </div>
          </div>

          <div style={{ marginBottom: 16 }}>
            <div className="label" style={{ marginBottom: 8 }}>AMOUNT (ETH)</div>
            <div style={{
              padding: '14px 18px', borderRadius: 12,
              background: 'rgba(255,255,255,0.04)',
              border: '1.5px solid ' + c.color + '44',
              display: 'flex', alignItems: 'center', gap: 10,
            }}>
              <input type="number" min="0" step="0.01" value={amountEth}
                onChange={e => setAmountEth(Math.max(0, parseFloat(e.target.value) || 0))}
                aria-label="ETH amount"
                style={{
                  flex: 1, background: 'transparent', border: 0, color: '#fff',
                  fontSize: 24, fontWeight: 700, fontFamily: 'JetBrains Mono', outline: 'none',
                  minWidth: 0,
                }} />
              <span style={{ fontSize: 12, color: 'var(--t3)', fontWeight: 800 }}>ETH</span>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 6, marginTop: 10 }}>
              {WCI_BUY_ETH_PRESETS.map(p => (
                <button key={p} onClick={() => setAmountEth(p)} style={{
                  padding: '8px 0', borderRadius: 8,
                  background: amountEth === p ? c.color + '22' : 'rgba(255,255,255,0.04)',
                  border: '1px solid ' + (amountEth === p ? c.color : 'var(--hair)'),
                  color: amountEth === p ? c.color : 'var(--t2)',
                  fontSize: 12, fontWeight: 800, cursor: 'pointer',
                  fontFamily: 'JetBrains Mono',
                }}>{wciBuyFmtEth(p, 2)}</button>
              ))}
            </div>
          </div>

          <div style={{
            padding: 14, borderRadius: 12,
            background: `linear-gradient(180deg, ${c.color}12, rgba(0,0,0,0.26))`,
            border: `1px solid ${c.color}44`,
            marginBottom: 18,
          }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>
              <div>
                <div className="label" style={{ color: c.color }}>LIVE POOL DATA</div>
                <div style={{ marginTop: 4, fontSize: 11, color: 'var(--t3)' }}>
                  Market cap and volume from the live Sepolia country token pair.
                </div>
              </div>
              <div style={{ textAlign: 'right' }}>
                <div className="label" style={{ fontSize: 8 }}>Market cap</div>
                <div className="mono" style={{ fontSize: 14, color: 'var(--lime)', fontWeight: 800 }}>{marketCapLabel}</div>
              </div>
            </div>

            <div style={{ marginTop: 12, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
              <BuyMetric label="MARKET CAP" value={marketCapLabel} />
              <BuyMetric label="VOLUME" value={volumeLabel} />
            </div>
          </div>

          <div style={{
            padding: 14, borderRadius: 12,
            background: 'rgba(0,0,0,0.3)',
            border: '1px solid var(--hair)',
            marginBottom: 18,
            display: 'flex', flexDirection: 'column', gap: 8,
          }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 10 }}>
              <span className="label">EST. OUTPUT</span>
              <span className="mono" style={{ fontSize: 16, fontWeight: 800, color: c.color, textAlign: 'right' }}>
                {estimatedTokens ? wciBuyFmtTokens(estimatedTokens) : 'Quoted on Uniswap'}<span style={{ fontSize: 11, color: 'var(--t3)', marginLeft: 6 }}>{tokenLabel}</span>
              </span>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', gap: 10, fontSize: 11, color: 'var(--t3)' }}>
              <span>Country token transfer tax</span>
              <span className="mono">0%</span>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', gap: 10, fontSize: 11, color: 'var(--t3)' }}>
              <span>Destination</span>
              <span className="mono">Uniswap / Sepolia</span>
            </div>
          </div>

          <a href={tradeUrl}
            target="_blank"
            rel="noopener noreferrer"
            data-token-address={tradeTokenAddress}
            data-pool-address={c.poolAddress || c.v3PoolAddress || ''}
            data-amount-eth={amountEth}
            onClick={(event) => {
              if (!tradeTokenAddress) event.preventDefault();
            }}
            className="btn-3d uniswap-buy-link"
            style={{
              display: 'block',
              width: '100%', padding: '18px',
              background: `linear-gradient(180deg, ${c.color}, ${c.secondary})`,
              boxShadow: `
                inset 0 2px 0 0 rgba(255,255,255,0.45),
                inset 0 -2px 0 0 rgba(0,0,0,0.2),
                0 4px 0 0 rgba(0,0,0,0.4),
                0 8px 0 0 rgba(0,0,0,0.3),
                0 12px 24px -4px rgba(0,0,0,0.6),
                0 0 32px -8px ${c.color}
              `,
              color: '#fff',
              fontSize: 16,
              fontWeight: 900,
              textAlign: 'center',
              textDecoration: 'none',
              textShadow: '0 1px 0 rgba(0,0,0,0.3)',
              cursor: tradeTokenAddress ? 'pointer' : 'not-allowed',
            }}>
            BUY ON UNISWAP - {wciBuyFmtEth(amountEth, 2)} - {tokenLabel}
          </a>

          <div style={{ marginTop: 18 }}>
            <div className="label" style={{ marginBottom: 8 }}>SEPOLIA FEED - {c.code}</div>
            <div style={{
              display: 'flex', alignItems: 'center', gap: 10,
              padding: '10px 0', borderBottom: '1px solid rgba(255,255,255,0.04)',
              fontSize: 11,
            }}>
              <span style={{ width: 8, height: 8, borderRadius: '50%', background: c.color, boxShadow: `0 0 8px ${c.color}` }} />
              <span style={{ color: 'var(--t3)' }}>Awaiting indexed wallet-level buys</span>
            </div>
          </div>
        </>)}
      </div>
    </>
  );
};

window.BuyDrawer = BuyDrawer;
