// wci26_pwa/m-sheets.jsx - native iOS-style bottom sheets.

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

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

const mBuyFmtWeth = (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 mBuyFmtTokens = (value) => {
  const number = Number(value || 0);
  if (!Number.isFinite(number) || number <= 0) return 'Quoted on Uniswap';
  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 mBuyFmtMarketCap = (country) => (
  typeof wciFormatCountryMarketCap === 'function'
    ? wciFormatCountryMarketCap(country)
    : (typeof fmtMcap === 'function' ? fmtMcap(country?.mcap || 0) : '$--')
);

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

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

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

  if (!open || !country) return null;
  const tokenLabel = typeof wciCountryDollarTicker === 'function'
    ? wciCountryDollarTicker(country)
    : (country.tokenSymbol || `$${country.code}26`);
  const tokenName = tokenLabel.replace(/^\$/, '');
  const estimatedTokens = country.priceWETH > 0 ? amountEth / country.priceWETH : 0;
  const tradeUrl = typeof WCI_TRADE_LINKS !== 'undefined'
    ? WCI_TRADE_LINKS.buildUniswapSwapUrl(country, { amountEth })
    : '#';
  const tradeTokenAddress = typeof WCI_TRADE_LINKS !== 'undefined'
    ? WCI_TRADE_LINKS.resolveCountryTokenAddress(country)
    : '';
  const marketCapLabel = mBuyFmtMarketCap(country);
  const volumeLabel = mBuyFmtVolume(country);

  return (
    <>
      <div className="sheet-backdrop" onClick={onClose} />
      <div className="sheet-panel">
        <div className="sheet-grab" />
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '4px 4px 18px' }}>
          <FlagRect code={country.code} w={44} h={30} style={{ borderRadius: 5, boxShadow: '0 4px 14px rgba(0,0,0,0.4)' }} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="sfd" style={{ fontSize: 22, fontWeight: 700 }}>{country.name}</div>
            <div className="mono" style={{ fontSize: 12, color: 'rgba(235,235,245,0.55)' }}>
              {mBuyFmtPrice(country)} per token
            </div>
          </div>
          <button onClick={onClose} className="press" aria-label="Close buy sheet" style={{
            width: 32, height: 32, borderRadius: 999,
            background: 'linear-gradient(180deg, rgba(255,255,255,0.10), rgba(255,255,255,0.02))',
            border: '0.5px solid rgba(255,255,255,0.14)',
            color: 'rgba(235,235,245,0.85)',
            display: 'grid', placeItems: 'center', cursor: 'pointer', fontSize: 14,
            boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.15)',
          }}>x</button>
        </div>

        <div style={{
          padding: 14, borderRadius: 14,
          background: 'linear-gradient(180deg, rgba(255,255,255,0.04), rgba(255,255,255,0.01))',
          border: '0.5px solid rgba(255,255,255,0.06)',
          boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.05)',
          marginBottom: 14,
        }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
            <div>
              <div style={{ fontSize: 10, fontWeight: 700, color: 'rgba(235,235,245,0.5)', letterSpacing: 0.1 + 'em', textTransform: 'uppercase' }}>Market cap</div>
              <div className="mono" style={{ marginTop: 4, fontSize: 13, fontWeight: 800 }}>{marketCapLabel}</div>
            </div>
            <div>
              <div style={{ fontSize: 10, fontWeight: 700, color: 'rgba(235,235,245,0.5)', letterSpacing: 0.1 + 'em', textTransform: 'uppercase' }}>Volume</div>
              <div className="mono" style={{ marginTop: 4, fontSize: 13, fontWeight: 800 }}>{volumeLabel}</div>
            </div>
          </div>
        </div>

        <div style={{ textAlign: 'center', padding: '6px 0' }}>
          <div className="bgd tnum" style={{ fontSize: 50, color: '#fff', lineHeight: 1 }}>
            {mBuyFmtEth(amountEth, 2)}
          </div>
          <div className="mono" style={{ fontSize: 13, color: 'rgba(235,235,245,0.6)', marginTop: 4 }}>
            {mBuyFmtTokens(estimatedTokens)} {tokenName}
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8, marginTop: 14 }}>
          {WCI_MOBILE_BUY_ETH_PRESETS.map(p => (
            <button key={p} onClick={() => setAmountEth(p)} className="press" style={{
              padding: '13px 0', borderRadius: 14,
              background: amountEth === p
                ? `linear-gradient(180deg, ${country.color}50, ${country.color}1c)`
                : 'linear-gradient(180deg, rgba(255,255,255,0.06), rgba(255,255,255,0.02))',
              border: '0.5px solid ' + (amountEth === p ? country.color : 'rgba(255,255,255,0.08)'),
              color: amountEth === p ? '#fff' : 'rgba(235,235,245,0.85)',
              fontSize: 13, fontWeight: 700, cursor: 'pointer',
              fontFamily: 'inherit',
              boxShadow: amountEth === p
                ? `inset 0 1px 0 rgba(255,255,255,0.20), inset 0 -1px 0 rgba(0,0,0,0.2), 0 4px 14px -4px ${country.color}aa`
                : 'inset 0 1px 0 rgba(255,255,255,0.05)',
            }}>
              {mBuyFmtEth(p, 2)}
            </button>
          ))}
        </div>

        <a href={tradeUrl}
          target="_blank"
          rel="noopener noreferrer"
          data-token-address={tradeTokenAddress}
          data-pool-address={country.poolAddress || country.v3PoolAddress || ''}
          data-amount-eth={amountEth}
          onClick={(event) => {
            if (!tradeTokenAddress) event.preventDefault();
          }}
          className="press btn-3d uniswap-buy-link" style={{
          marginTop: 16, width: '100%', borderRadius: 18,
          display: 'block', textAlign: 'center', textDecoration: 'none',
          cursor: tradeTokenAddress ? 'pointer' : 'not-allowed',
        }}>
          Buy {tokenLabel} with {mBuyFmtEth(amountEth, 2)}
        </a>

        <div style={{ textAlign: 'center', fontSize: 11, color: 'rgba(235,235,245,0.4)', marginTop: 10 }}>
          Opens Uniswap Mainnet with ETH to {tokenName}
        </div>
      </div>
    </>
  );
};

const ShareSheet = ({ open, country, amount, onClose }) => {
  if (!open || !country) return null;
  const amountEth = Number(amount || 0);
  const estimatedTokens = country.priceWETH > 0 ? amountEth / country.priceWETH : 0;
  return (
    <>
      <div className="sheet-backdrop" onClick={onClose} />
      <div className="sheet-panel">
        <div className="sheet-grab" />
        <div style={{
          textAlign: 'center', padding: '8px 0 20px',
          background: `radial-gradient(80% 80% at 50% 0%, ${country.color}33, transparent 60%)`,
          borderRadius: 18,
        }}>
          <div className="sfd" style={{ fontSize: 26, fontWeight: 700 }}>Country backed</div>
          <div style={{ fontSize: 14, color: 'rgba(235,235,245,0.6)', marginTop: 4 }}>
            Team {country.name}
          </div>
        </div>

        <div style={{
          padding: 16, borderRadius: 16,
          background: 'linear-gradient(180deg, rgba(255,255,255,0.05), rgba(255,255,255,0.01))',
          border: '0.5px solid rgba(255,255,255,0.08)',
          boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.06)',
          margin: '6px 0 14px',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <FlagRect code={country.code} w={40} h={27} style={{ borderRadius: 4 }} />
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14, fontWeight: 600 }}>{country.name}</div>
              <div className="mono" style={{ fontSize: 11, color: 'rgba(235,235,245,0.5)' }}>{country.code} - Group {country.group}</div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div className="bgd tnum" style={{ fontSize: 22 }}>{mBuyFmtEth(amountEth, 2)}</div>
              <div className="mono" style={{ fontSize: 10, color: 'rgba(235,235,245,0.5)' }}>
                {mBuyFmtTokens(estimatedTokens)} {country.symbol || country.ticker || country.code}
              </div>
            </div>
          </div>
        </div>

        <div style={{ fontSize: 11, fontWeight: 700, color: 'rgba(235,235,245,0.5)', letterSpacing: 0.12 + 'em', textTransform: 'uppercase', padding: '10px 4px 8px' }}>
          Share to
        </div>
        <div style={{ display: 'flex', gap: 14, padding: '0 4px 12px', overflowX: 'auto' }}>
          {[
            { n: 'Messages', bg: 'linear-gradient(180deg, #5BCD45, #2DBE25)' },
            { n: 'Twitter',  bg: '#000' },
            { n: 'Telegram', bg: '#2AABEE' },
            { n: 'Discord',  bg: '#5865F2' },
            { n: 'Copy',     bg: 'rgba(118,118,128,0.24)' },
          ].map(s => (
            <button key={s.n} className="press" style={{
              background: 'transparent', border: 0, color: 'inherit', cursor: 'pointer',
              display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
              minWidth: 64,
            }}>
              <div style={{
                width: 56, height: 56, borderRadius: 14,
                background: s.bg,
                display: 'grid', placeItems: 'center',
                boxShadow: '0 2px 8px rgba(0,0,0,0.3)',
                fontSize: 22, color: '#fff', fontWeight: 700,
              }}>
                {s.n[0]}
              </div>
              <span style={{ fontSize: 11, color: 'rgba(235,235,245,0.8)' }}>{s.n}</span>
            </button>
          ))}
        </div>

        <button onClick={onClose} className="press" style={{
          width: '100%', padding: '14px 0', borderRadius: 14,
          background: 'linear-gradient(180deg, rgba(255,255,255,0.10), rgba(255,255,255,0.02))',
          border: '0.5px solid rgba(255,255,255,0.12)',
          boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.10), inset 0 -1px 0 rgba(0,0,0,0.2)',
          fontSize: 16, fontWeight: 600, color: '#fff', cursor: 'pointer',
          fontFamily: 'inherit',
          marginTop: 6,
        }}>Done</button>
      </div>
    </>
  );
};

const InstallSheet = ({ open, onClose }) => {
  if (!open) return null;
  return (
    <>
      <div className="sheet-backdrop" onClick={onClose} />
      <div className="sheet-panel" style={{ paddingBottom: 28 }}>
        <div className="sheet-grab" />
        <div style={{ textAlign: 'center', padding: '4px 0 8px' }}>
          <div style={{
            width: 64, height: 64, borderRadius: 16, margin: '0 auto 10px',
            background: 'linear-gradient(135deg, var(--gold), var(--fifa-orange))',
            display: 'grid', placeItems: 'center',
            boxShadow: '0 8px 24px -4px var(--gold)',
          }}>
            <img src="assets/logo.png" width="44" height="44" />
          </div>
          <div className="sfd" style={{ fontSize: 22, fontWeight: 700 }}>Install WCI26</div>
          <div style={{ fontSize: 14, color: 'rgba(235,235,245,0.6)', marginTop: 4, padding: '0 30px', lineHeight: 1.4 }}>
            Add to Home Screen for live buy alerts and one-tap access
          </div>
        </div>
        <div style={{ padding: '14px 0 4px' }}>
          <button onClick={onClose} className="press" style={{
            width: '100%', padding: '16px 0', borderRadius: 14,
            background: '#007AFF', border: 0,
            fontSize: 17, fontWeight: 600, color: '#fff', cursor: 'pointer',
            fontFamily: 'inherit',
          }}>Add to Home Screen</button>
          <button onClick={onClose} className="press" style={{
            marginTop: 8,
            width: '100%', padding: '16px 0', borderRadius: 14,
            background: 'rgba(118,118,128,0.24)', border: 0,
            fontSize: 17, fontWeight: 500, color: '#fff', cursor: 'pointer',
            fontFamily: 'inherit',
          }}>Not now</button>
        </div>
      </div>
    </>
  );
};

Object.assign(window, { BuySheet, ShareSheet, InstallSheet });
