/* global React, CRYPTOLIVE_DATA, Coin, Sparkline, PremiumGauge, Icon, fmtPrice, fmtPct, fmtUSD, fmtKRW, upDownClass, useT */
const { useState: useStateH, useMemo: useMemoH, useEffect: useEffectH } = React;

function getMarketStatus(market, now, t) {
  const _now = now || new Date();
  const utc = _now.getTime() + _now.getTimezoneOffset() * 60000;
  const local = new Date(utc + market.tzOffset * 3600000);
  const day = local.getDay();
  const minutes = local.getHours() * 60 + local.getMinutes();
  if (day === 0 || day === 6) {
    return { state: 'closed', label: t('marketClosed'), tone: 'neutral' };
  }
  for (const w of market.windows) {
    if (minutes >= w.from && minutes < w.to) {
      return { state: w.state, label: t(w.labelKey), tone: w.tone };
    }
  }
  return { state: 'closed', label: t('marketEnded'), tone: 'neutral' };
}

function GlobalMarketsWidget() {
  const t = useT();
  const [now, setNow] = useStateH(() => new Date());
  useEffectH(() => {
    const t = setInterval(() => setNow(new Date()), 30000);
    return () => clearInterval(t);
  }, []);

  const MARKETS = useMemoH(() => ([
    {
      id: 'kospi', region: t('krRegion'), name: 'KOSPI', value: 2_678.34, change: 0.43, tzOffset: 9,
      windows: [{ from: 9 * 60, to: 15 * 60 + 30, state: 'live', labelKey: 'regular', tone: 'up' }],
    },
    {
      id: 'kosdaq', region: t('krRegion'), name: 'KOSDAQ', value: 762.15, change: -0.18, tzOffset: 9,
      windows: [{ from: 9 * 60, to: 15 * 60 + 30, state: 'live', labelKey: 'regular', tone: 'up' }],
    },
    {
      id: 'spx', region: t('usRegion'), name: 'S&P 500', value: 5_812.40, change: 0.27, tzOffset: -5,
      windows: [
        { from: 4 * 60, to: 9 * 60 + 30, state: 'pre', labelKey: 'preMarket', tone: 'warn' },
        { from: 9 * 60 + 30, to: 16 * 60, state: 'live', labelKey: 'regular', tone: 'up' },
        { from: 16 * 60, to: 20 * 60, state: 'post', labelKey: 'afterHours', tone: 'warn' },
      ],
    },
    {
      id: 'ndx', region: t('usRegion'), name: 'NASDAQ', value: 18_521.79, change: 0.51, tzOffset: -5,
      windows: [
        { from: 4 * 60, to: 9 * 60 + 30, state: 'pre', labelKey: 'preMarket', tone: 'warn' },
        { from: 9 * 60 + 30, to: 16 * 60, state: 'live', labelKey: 'regular', tone: 'up' },
        { from: 16 * 60, to: 20 * 60, state: 'post', labelKey: 'afterHours', tone: 'warn' },
      ],
    },
    {
      id: 'crypto', region: '🌐 24/7', name: 'Crypto', value: 2_348_900, change: 1.12, tzOffset: 0,
      windows: [{ from: 0, to: 24 * 60, state: 'live', labelKey: 'regular', tone: 'up' }],
    },
  ]), [t]);

  const toneStyle = (tone, state) => {
    if (state === 'live') return { bg: 'var(--up-soft, rgba(0,200,120,0.12))', fg: 'var(--up)', dot: 'var(--up)', pulse: true };
    if (tone === 'warn') return { bg: 'var(--warn-soft, rgba(255,180,84,0.14))', fg: 'var(--warn)', dot: 'var(--warn)', pulse: false };
    return { bg: 'var(--bg-muted)', fg: 'var(--fg-3)', dot: 'var(--fg-4)', pulse: false };
  };

  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))', gap: 10, marginTop: 16 }}>
      {MARKETS.map(m => {
        const st = getMarketStatus(m, now, t);
        const tone = toneStyle(st.tone, st.state);
        const up = m.change >= 0;
        return (
          <div key={m.id} style={{
            padding: '12px 14px',
            borderRadius: 14,
            background: 'var(--bg-card)',
            border: '1px solid var(--line-soft)',
            display: 'flex',
            flexDirection: 'column',
            gap: 6,
          }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 6 }}>
              <div className="t-meta" style={{ fontWeight: 600, fontSize: 11, color: 'var(--fg-3)' }}>{m.region}</div>
              <div style={{
                display: 'inline-flex', alignItems: 'center', gap: 5,
                padding: '2px 8px', borderRadius: 999,
                background: tone.bg, color: tone.fg,
                fontSize: 10, fontWeight: 700, letterSpacing: '0.02em',
              }}>
                <span className={tone.pulse ? 'pulse-dot' : ''} style={{ width: 6, height: 6, borderRadius: '50%', background: tone.dot, display: 'inline-block' }} />
                {st.label}
              </div>
            </div>
            <div style={{ fontWeight: 800, fontSize: 14, letterSpacing: '-0.01em' }}>{m.name}</div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 8 }}>
              <div className="t-num" style={{ fontWeight: 700, fontSize: 15 }}>
                {m.value.toLocaleString('en-US', { maximumFractionDigits: 2 })}
              </div>
              <div className={`t-num ${up ? 'c-up' : 'c-down'}`} style={{ fontSize: 12, fontWeight: 700 }}>
                {fmtPct(m.change)}
              </div>
            </div>
          </div>
        );
      })}
    </div>
  );
}

function MarketSummary() {
  const t = useT();
  // Synthetic index: weighted avg of all assets' 24h change
  const idx = useMemoH(() => {
    const a = CRYPTOLIVE_DATA.assets();
    if (a.length === 0) return { change: 0, vol: 0 };
    const total = a.reduce((s, x) => s + x.vol24h, 0);
    const w = total > 0 ? a.reduce((s, x) => s + (x.change24h * x.vol24h) / total, 0) : 0;
    const vol = a.reduce((s, x) => s + x.vol24h, 0);
    return { change: w, vol };
  }, []);
  // Composite sparkline using SPY * 0.6 + sDAI delta etc.
  const spark = useMemoH(() => {
    const base = CRYPTOLIVE_DATA.assetById('spy')?.chart;
    const tsla = CRYPTOLIVE_DATA.assetById('tesla')?.chart;
    if (!Array.isArray(base) || !Array.isArray(tsla) || base.length < 2 || tsla.length < 2) return [1, 1];
    const len = Math.min(base.length, tsla.length);
    const base0 = base[0] || 1;
    const tsla0 = tsla[0] || 1;
    return base.slice(0, len).map((b, i) => (b / base0) * 0.6 + (tsla[i] / tsla0) * 0.4);
  }, []);
  const color = idx.change >= 0 ? 'var(--up)' : 'var(--down)';

  return (
    <div className="card card-pad-lg" style={{ background: 'var(--hero-grad)' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
        <div className="pulse-dot" style={{ background: 'var(--up)' }} />
        <span className="t-meta" style={{ color: 'var(--fg-2)', fontWeight: 600 }}>{t('rwaIndex')}</span>
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', gap: 16, flexWrap: 'wrap' }}>
        <div>
          <div className="t-display t-num">
            {fmtPct(idx.change, 2)}
          </div>
          <div className="t-meta" style={{ marginTop: 4 }}>{t('vol24Assets', fmtUSD(idx.vol), CRYPTOLIVE_DATA.assets().length)}</div>
        </div>
        <div style={{ width: 200, height: 60 }}>
          <Sparkline data={spark} color={color} fill={color} width={200} height={60} strokeWidth={2} />
        </div>
      </div>
      <GlobalMarketsWidget />
    </div>
  );
}

function StatCard({ label, value, sub, accent }) {
  return (
    <div className="card">
      <div className="t-meta" style={{ marginBottom: 8 }}>{label}</div>
      <div className="t-h2 t-num" style={{ color: accent || 'var(--fg-1)' }}>{value}</div>
      {sub && <div className="t-meta" style={{ marginTop: 4 }}>{sub}</div>}
    </div>
  );
}

function PremiumRow({ asset, onClick }) {
  const t = useT();
  const dir = asset.premium > 0.05 ? t('premium') : asset.premium < -0.05 ? t('discount') : t('parity');
  const cls = asset.premium > 0.05 ? 'pill--up' : asset.premium < -0.05 ? 'pill--down' : '';
  return (
    <div className="row" onClick={onClick}>
      <Coin id={asset.id} symbol={asset.symbol} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontWeight: 700, fontSize: 15 }}>{asset.symbol}</div>
        <div className="t-meta" style={{ color: 'var(--fg-3)' }}>{t('underlyingVs', asset.name)}</div>
      </div>
      <div style={{ width: 120, marginRight: 12 }} className="hide-mobile">
        <PremiumGauge value={asset.premium} max={3} />
      </div>
      <div style={{ textAlign: 'right' }}>
        <div className={`pill ${cls}`}>{fmtPct(asset.premium)} {dir}</div>
        <div className="t-meta t-num" style={{ marginTop: 4 }}>${fmtPrice(asset.tokenPrice)}</div>
      </div>
    </div>
  );
}

function HotAssetCard({ asset, onClick }) {
  const up = asset.change24h >= 0;
  return (
    <div className="card" style={{ cursor: 'pointer', transition: 'transform .12s' }}
      onClick={onClick}
      onMouseEnter={(e) => e.currentTarget.style.transform = 'translateY(-2px)'}
      onMouseLeave={(e) => e.currentTarget.style.transform = 'translateY(0)'}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 14 }}>
        <Coin id={asset.id} symbol={asset.symbol} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontWeight: 700, fontSize: 16, display: 'flex', alignItems: 'center', gap: 6 }}>
            {asset.symbol}
            {asset.hot && <Icon.flame width="14" height="14" style={{ color: 'var(--up)' }} />}
          </div>
          <div className="t-meta">{asset.sector}</div>
        </div>
      </div>
      <div style={{ height: 56, marginBottom: 12 }}>
        <Sparkline data={asset.chart}
          color={up ? 'var(--up)' : 'var(--down)'}
          fill={up ? 'var(--up)' : 'var(--down)'}
          width={300} height={56} strokeWidth={1.8} />
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
        <div className="t-h3 t-num">${fmtPrice(asset.tokenPrice)}</div>
        <div className={`pill ${up ? 'pill--up' : 'pill--down'} pill--lg`}>{fmtPct(asset.change24h)}</div>
      </div>
    </div>
  );
}

function LiveSignal({ event }) {
  const t = useT();
  const sevPill = event.sev === 'danger' ? 'pill--danger' : event.sev === 'warn' ? 'pill--warn' : 'pill--blue';
  const sevLabel = event.sev === 'danger' ? t('sevAlert') : event.sev === 'warn' ? t('sevWatch') : t('sevInfo');
  return (
    <div style={{ padding: '14px 0', borderBottom: '1px solid var(--line-soft)' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
        <span className={`pill ${sevPill}`}>{sevLabel}</span>
        <span className="t-meta">{t('justNow')}</span>
      </div>
      <div style={{ fontWeight: 700, fontSize: 15, marginBottom: 2 }}>{event.title}</div>
      <div className="t-body-sm">{event.msg}</div>
    </div>
  );
}

function HomeScreen({ goto }) {
  const t = useT();
  const assets = CRYPTOLIVE_DATA.assets();
  const hotPrimary = assets.filter(a => a.hot);
  const hotFiller = assets.filter(a => !a.hot).sort((a, b) => Math.abs(b.change24h) - Math.abs(a.change24h));
  const hot = [...hotPrimary, ...hotFiller].slice(0, 4);
  const topPremium = [...assets].sort((a, b) => Math.abs(b.premium) - Math.abs(a.premium)).slice(0, 5);
  const events = CRYPTOLIVE_DATA.liveEvents().slice(0, 4);
  const chats = CRYPTOLIVE_DATA.chats().slice(0, 4);
  const yieldAssets = assets.filter(a => a.yield).sort((a, b) => b.yield - a.yield);

  return (
    <div className="container page" data-screen-label="Home">
      {/* Hero */}
      <div style={{ marginBottom: 24 }}>
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 16, flexWrap: 'wrap', gap: 8 }}>
          <div>
            <div className="t-h1">{t('title24h')}</div>
            <div className="t-meta" style={{ marginTop: 4 }}>{t('subtitle24h')}</div>
          </div>
        </div>
        <MarketSummary />
      </div>

      {/* Hot */}
      <div className="section-head">
        <div>
          <h2>{t('hotAssets')}</h2>
          <div className="sub">{t('hotSub')}</div>
        </div>
        <button className="section-more" onClick={() => goto({ tab: 'market' })}>{t('viewAll')}</button>
      </div>
      <div className="grid grid-4">
        {hot.map(a => <HotAssetCard key={a.id} asset={a} onClick={() => goto({ tab: 'detail', assetId: a.id })} />)}
      </div>

      {/* Two-col: Premium + Live */}
      <div className="grid" style={{ gridTemplateColumns: '1.2fr 1fr', marginTop: 32, gap: 16 }}>
        <div className="card">
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 4 }}>
            <h2 style={{ margin: 0, fontSize: 20, fontWeight: 800, letterSpacing: '-0.015em' }}>{t('premiumTitle')}</h2>
            <button className="section-more" onClick={() => goto({ tab: 'market' })}>{t('viewAllShort')}</button>
          </div>
          <div className="t-meta" style={{ marginBottom: 8 }}>{t('premiumSub')}</div>
          {topPremium.map(a => (
            <PremiumRow key={a.id} asset={a} onClick={() => goto({ tab: 'detail', assetId: a.id })} />
          ))}
        </div>

        <div className="card">
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 4 }}>
            <h2 style={{ margin: 0, fontSize: 20, fontWeight: 800, letterSpacing: '-0.015em' }}>{t('signals')}</h2>
            <button className="section-more" onClick={() => goto({ tab: 'live' })}>{t('liveLink')}</button>
          </div>
          <div className="t-meta" style={{ marginBottom: 4 }}>{t('signalsSub')}</div>
          {events.map((e, i) => <LiveSignal key={i} event={e} />)}
        </div>
      </div>

      {/* Yield row */}
      <div className="section-head">
        <div>
          <h2>{t('yieldTitle')}</h2>
          <div className="sub">{t('yieldSub')}</div>
        </div>
        <button className="section-more" onClick={() => goto({ tab: 'market' })}>{t('viewAllShort')}</button>
      </div>
      <div className="grid grid-3">
        {yieldAssets.map(a => (
          <div key={a.id} className="card" style={{ cursor: 'pointer' }} onClick={() => goto({ tab: 'detail', assetId: a.id })}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12 }}>
              <Coin id={a.id} symbol={a.symbol} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontWeight: 700 }}>{a.symbol}</div>
                <div className="t-meta">{a.shortDesc}</div>
              </div>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end' }}>
              <div>
                <div className="t-meta">{t('annualYield')}</div>
                <div className="t-h2 t-num" style={{ color: 'var(--up)' }}>{a.yield.toFixed(2)}%</div>
              </div>
              <div className="pill pill--blue">{t('riskPill', a.risk)}</div>
            </div>
          </div>
        ))}
      </div>

      {/* Live chat preview */}
      <div className="section-head">
        <div>
          <h2>{t('liveTalk')}</h2>
          <div className="sub">{t('liveTalkSub')}</div>
        </div>
        <button className="section-more" onClick={() => goto({ tab: 'live' })}>{t('chatRoom')}</button>
      </div>
      <div className="card">
        {chats.map((c, i) => (
          <div key={i} style={{ padding: '12px 0', borderBottom: i < chats.length - 1 ? '1px solid var(--line-soft)' : 'none' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 2 }}>
              <span style={{ fontWeight: 700, fontSize: 14 }}>{c.u}</span>
              <span className="t-meta">{c.t}</span>
            </div>
            <div className="t-body-sm" style={{ color: 'var(--fg-1)' }}>{c.m}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

window.HomeScreen = HomeScreen;
window.MarketSummary = MarketSummary;
window.StatCard = StatCard;
