// tab-home.jsx — Landing screen, default first tab
const { useState: useHomeState, useEffect: useHomeEffect } = React;

function useHomeClock() {
  const [time, setTime] = useHomeState('');
  useHomeEffect(() => {
    function tick() {
      setTime(new Date().toLocaleTimeString('en-US', {
        hour: '2-digit', minute: '2-digit', second: '2-digit',
        timeZone: 'America/New_York', hour12: true,
      }) + ' ET');
    }
    tick();
    const id = setInterval(tick, 1000);
    return () => clearInterval(id);
  }, []);
  return time;
}

function useHomeCountdown() {
  const [label, setLabel] = useHomeState('');
  useHomeEffect(() => {
    function tick() {
      const parts = Object.fromEntries(
        new Intl.DateTimeFormat('en-US', {
          timeZone: 'America/New_York',
          weekday: 'short', hour: 'numeric', minute: '2-digit', second: '2-digit', hour12: false,
        }).formatToParts(new Date()).map(p => [p.type, p.value])
      );
      const h = parseInt(parts.hour), m = parseInt(parts.minute), s = parseInt(parts.second);
      const day = parts.weekday;
      const isWeekend = day === 'Sat' || day === 'Sun';
      const totalSec = h * 3600 + m * 60 + s;
      const totalMin = h * 60 + m;
      const pad = v => String(v).padStart(2, '0');
      const fmt = secs => {
        const hh = Math.floor(secs / 3600), mm = Math.floor((secs % 3600) / 60), ss = secs % 60;
        return `${hh}:${pad(mm)}:${pad(ss)}`;
      };
      if (isWeekend) {
        const d = day === 'Sat' ? 2 : 1;
        setLabel(`Opens Monday ${fmt((86400 - totalSec) + (d - 1) * 86400 + 9 * 3600 + 1800)}`);
      } else if (totalMin < 240) {
        setLabel(`Pre-market opens in ${fmt(4 * 3600 - totalSec)}`);
      } else if (totalMin < 570) {
        setLabel(`Market opens in ${fmt(9 * 3600 + 1800 - totalSec)}`);
      } else {
        setLabel('');
      }
    }
    tick();
    const id = setInterval(tick, 1000);
    return () => clearInterval(id);
  }, []);
  return label;
}

window.TabHome = function({ data, onNavigate, loading }) {
  const { snapshot, whales, leaps, smallcap } = data || {};

  const liveTime  = useHomeClock();
  const countdown = useHomeCountdown();
  const [darkMoney, setDarkMoney] = useHomeState([]);

  useHomeEffect(() => {
    fetch(`${window.API_BASE}/api/dark-money`, { headers: window.API_HEADERS })
      .then(r => r.ok ? r.json() : [])
      .then(d => setDarkMoney(Array.isArray(d) ? d : []))
      .catch(() => {});
  }, []);

  const session    = snapshot?.session || 'closed';
  const liveMarket = snapshot?.market_hours || false;
  const spyPct     = snapshot?.spy?.change_pct ?? null;
  const rotation   = snapshot?.rotation || null;

  const topWhale    = Array.isArray(whales)   && whales.length   > 0 ? [...whales].sort((a, b)   => (b.total_premium  || 0) - (a.total_premium  || 0))[0] : null;
  const topLeap     = Array.isArray(leaps)    && leaps.length    > 0 ? [...leaps].sort((a, b)    => (b.approx_premium || 0) - (a.approx_premium || 0))[0] : null;
  const topSmallCap = Array.isArray(smallcap) && smallcap.length > 0 ? [...smallcap].sort((a, b) => (b.vol_oi_ratio   || 0) - (a.vol_oi_ratio   || 0))[0] : null;

  const SESSION_BADGE = {
    regular:    { label: 'LIVE',      cls: 'bg-green-900/60 text-green-300 border-green-600/40' },
    premarket:  { label: 'PREMARKET', cls: 'bg-blue-900/60 text-blue-300 border-blue-600/40' },
    afterhours: { label: 'AFTER HRS', cls: 'bg-purple-900/60 text-purple-300 border-purple-600/40' },
    closed:     { label: 'CLOSED',    cls: 'bg-slate-800 text-slate-400 border-slate-600/40' },
  };
  const badge = SESSION_BADGE[session] || SESSION_BADGE.closed;

  const chevron = (
    <svg className="w-3.5 h-3.5 text-tmuted shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}>
      <path strokeLinecap="round" strokeLinejoin="round" d="M9 5l7 7-7 7" />
    </svg>
  );

  const Skel = () => <div className="skel h-6 w-16 rounded mt-0.5" />;

  return (
    <div className="pb-4 space-y-3">

      {/* Hero clock + status */}
      <Card>
        <div className="px-4 pt-4 pb-3">
          <div className="flex items-center justify-between mb-2">
            <span className="font-mono font-extrabold text-white text-base tracking-widest">BANDITRADES</span>
            <span className={`text-[10px] font-semibold uppercase tracking-wider px-2 py-0.5 rounded border ${badge.cls} flex items-center gap-1.5`}>
              {liveMarket && <span className="w-1.5 h-1.5 rounded-full bg-ok animate-livedot inline-block" />}
              {badge.label}
            </span>
          </div>
          <div className="font-mono text-2xl font-bold text-white tnum leading-none">{liveTime || '—'}</div>
          {countdown && (
            <div className="text-[11px] text-tmuted font-mono mt-1.5 tnum">{countdown}</div>
          )}
        </div>
      </Card>

      {/* AI Observer brief */}
      <AIObserver tab="market" />

      {/* 2×2 nav cards */}
      <div className="grid grid-cols-2 gap-2.5">

        {/* Market */}
        <button onClick={() => onNavigate('dashboard')}
          className="tap text-left bg-surface rounded-xl border border-line p-3 active:opacity-75 transition-opacity w-full">
          <div className="flex items-center justify-between mb-2">
            <span className="text-xl leading-none">📊</span>
            {chevron}
          </div>
          <div className="text-[10px] text-tmuted uppercase tracking-wider font-semibold mb-1">Market</div>
          {loading ? <Skel /> : spyPct != null ? (
            <div className={`font-mono font-extrabold text-xl num-pop leading-none ${spyPct >= 0 ? 'text-ok' : 'text-danger'}`}>
              SPY {fmtPct(spyPct)}
            </div>
          ) : (
            <div className="text-tmuted text-sm">—</div>
          )}
          {rotation && !loading && (
            <div className="text-[10px] text-tmuted mt-1.5 leading-tight">
              <span className="text-ok font-mono">{rotation.leader_etf}</span>{' '}leading
              {' · '}
              <span className="text-danger font-mono">{rotation.laggard_etf}</span>{' '}lagging
            </div>
          )}
        </button>

        {/* Flow */}
        <button onClick={() => onNavigate('flow')}
          className="tap text-left bg-surface rounded-xl border border-line p-3 active:opacity-75 transition-opacity w-full">
          <div className="flex items-center justify-between mb-2">
            <span className="text-xl leading-none">🌊</span>
            {chevron}
          </div>
          <div className="text-[10px] text-tmuted uppercase tracking-wider font-semibold mb-1">Flow</div>
          {loading ? <Skel /> : topWhale ? (
            <>
              <div className="font-mono font-extrabold text-xl text-white num-pop leading-none">{topWhale.symbol}</div>
              <div className="prem-pop text-sm mt-0.5">{fmtPremium(topWhale.total_premium)}</div>
            </>
          ) : (
            <div className="text-tmuted text-sm">—</div>
          )}
        </button>

        {/* LEAP */}
        <button onClick={() => onNavigate('leap')}
          className="tap text-left bg-surface rounded-xl border border-line p-3 active:opacity-75 transition-opacity w-full">
          <div className="flex items-center justify-between mb-2">
            <span className="text-xl leading-none">🔭</span>
            {chevron}
          </div>
          <div className="text-[10px] text-tmuted uppercase tracking-wider font-semibold mb-1">LEAP</div>
          {loading ? <Skel /> : topLeap ? (
            <>
              <div className="font-mono font-extrabold text-xl text-white num-pop leading-none">{topLeap.symbol}</div>
              <div className="prem-pop text-sm mt-0.5">{fmtPremium(topLeap.approx_premium)}</div>
            </>
          ) : (
            <div className="text-tmuted text-sm">—</div>
          )}
        </button>

        {/* Small Cap */}
        <button onClick={() => onNavigate('smallcap')}
          className="tap text-left bg-surface rounded-xl border border-line p-3 active:opacity-75 transition-opacity w-full">
          <div className="flex items-center justify-between mb-2">
            <span className="text-xl leading-none">⚡</span>
            {chevron}
          </div>
          <div className="text-[10px] text-tmuted uppercase tracking-wider font-semibold mb-1">Small Cap</div>
          {loading ? <Skel /> : topSmallCap ? (
            <>
              <div className="font-mono font-extrabold text-xl text-white num-pop leading-none">{topSmallCap.symbol}</div>
              <div className="text-[10px] text-tmuted mt-0.5">
                <span className={`font-mono font-bold text-base ${(topSmallCap.vol_oi_ratio || 0) >= 10 ? 'text-danger' : 'text-ok'}`}>
                  {(topSmallCap.vol_oi_ratio || 0).toFixed(1)}x
                </span>
                {' '}vol/OI
              </div>
            </>
          ) : (
            <div className="text-tmuted text-sm">—</div>
          )}
        </button>

      </div>

      {/* Dark Money — only shown when today has alerts */}
      {darkMoney.length > 0 && (
        <div>
          <div className="text-[10px] text-tmuted uppercase tracking-wider font-semibold mb-2 px-0.5">🕵️ Quiet Accumulation</div>
          <div className="space-y-2">
            {darkMoney.map((alert, i) => (
              <div key={i} className="rounded-xl bg-surface border-line px-3 py-2.5"
                style={{ border: '1px solid #2d4a7a', borderLeft: '2px solid rgba(245,158,11,0.8)' }}>
                <p className="text-xs text-white leading-relaxed">{alert.observation}</p>
                {alert.created_at && (
                  <p className="text-[10px] text-tmuted mt-1">
                    {new Date(alert.created_at).toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', timeZone: 'America/New_York' })} ET
                  </p>
                )}
              </div>
            ))}
          </div>
        </div>
      )}

    </div>
  );
};
