// tab-overview.jsx — Sector Premium Chart (Phase 1)
// Fetches /api/sector-premium-rollup, renders CSS flex bar chart with tap-to-expand detail.

window.TabOverview = function() {
  const [data,    setData]    = React.useState(null);   // { sectors, baseline_label, last_updated }
  const [loading, setLoading] = React.useState(true);
  const [error,   setError]   = React.useState(false);
  const [selected, setSelected] = React.useState(null); // tapped sector object

  const fetchData = React.useCallback(async () => {
    setError(false);
    setLoading(prev => !data && prev);  // show spinner only on first load
    try {
      const res = await fetch(`${window.API_BASE}/api/sector-premium-rollup`, {
        headers: window.API_HEADERS,
      });
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const json = await res.json();
      setData(json);
      setLoading(false);
    } catch (_err) {
      setError(true);
      setLoading(false);
    }
  }, [data]);

  React.useEffect(() => {
    fetchData();
    const id = setInterval(fetchData, 2 * 60 * 1000); // re-poll every 2 min (matches cron cadence)
    return () => clearInterval(id);
  }, []);

  // ── Loading ──────────────────────────────────────────────────────────────────
  if (loading) {
    return (
      <div className="space-y-3 animate-pulse">
        <div className="h-10 bg-surface rounded-xl border border-line" />
        <div className="h-4 bg-surface rounded w-1/3" />
        <div className="h-48 bg-surface rounded-xl border border-line" />
      </div>
    );
  }

  // ── Error ────────────────────────────────────────────────────────────────────
  if (error) {
    return (
      <div className="bg-surface rounded-xl border border-line px-4 py-6 text-center space-y-3">
        <p className="text-warn text-sm">Sector data unavailable — retrying</p>
        <button
          onClick={fetchData}
          className="text-xs text-indLite border border-indLite/40 rounded px-3 py-1.5 tap hover:bg-indLite/10"
        >
          Retry
        </button>
      </div>
    );
  }

  const sectors = data?.sectors ?? [];

  // ── Empty ────────────────────────────────────────────────────────────────────
  if (!sectors.length) {
    return (
      <div className="bg-surface rounded-xl border border-line px-4 py-8 text-center">
        <p className="text-tmuted text-sm">Building baseline — first data Tuesday 9:32 AM ET</p>
      </div>
    );
  }

  const maxPremium = Math.max(...sectors.map(s => s.total_premium));
  const hasThin    = sectors.some(s => s.symbol_count < 4);

  const sqrtScale = (value, max) => {
    if (!value || !max) return 0;
    return Math.sqrt(value) / Math.sqrt(max);
  };

  function barColor(netDir) {
    if (netDir > 0.10)  return '#22c55e';
    if (netDir < -0.10) return '#ef4444';
    return '#6b7280';
  }

  const lastTime = data?.last_updated
    ? new Date(data.last_updated).toLocaleTimeString('en-US', {
        hour: '2-digit', minute: '2-digit', timeZone: 'America/New_York',
      }) + ' ET'
    : null;

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

      {/* ── Narrative card ────────────────────────────────────────────────── */}
      <div className="bg-surface rounded-xl border border-line px-3 py-3">
        <p className="text-xs text-tmuted italic">
          Sector flow snapshot — narrative coming soon
        </p>
      </div>

      {/* ── Baseline label + timestamp ────────────────────────────────────── */}
      <div className="flex items-center justify-between px-0.5">
        <span className="text-[10px] text-tmuted uppercase tracking-wide">
          {data?.baseline_label ?? 'Today vs week avg'}
        </span>
        {lastTime && (
          <span className="text-[10px] text-tmuted font-mono">{lastTime}</span>
        )}
      </div>

      {/* ── Bar chart ────────────────────────────────────────────────────── */}
      <div className="bg-surface rounded-xl border border-line px-3 pt-4 pb-3">
        {/* Y-axis max label */}
        <div className="flex justify-between mb-1 px-0">
          <span className="text-[9px] text-tmuted">{fmtPremium(maxPremium)}</span>
          <span className="text-[9px] text-tmuted">$0</span>
        </div>

        {/* Bars */}
        <div
          style={{ display: 'flex', alignItems: 'flex-end', height: '160px', gap: '6px' }}
          className="relative"
        >
          {/* Horizontal reference line at 50% */}
          <div
            style={{
              position: 'absolute', left: 0, right: 0, bottom: '50%',
              borderTop: '1px dashed #2d4a7a', pointerEvents: 'none',
            }}
          />

          {sectors.map(s => {
            const pct    = sqrtScale(s.total_premium, maxPremium) * 100;
            const color  = barColor(s.net_direction);
            const isThin = s.symbol_count < 4;
            const isSel  = selected?.sector_etf === s.sector_etf;

            return (
              <div
                key={s.sector_etf}
                style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', minWidth: 0 }}
                onClick={() => setSelected(isSel ? null : s)}
                className="tap cursor-pointer"
              >
                {/* Bar column — grows from bottom */}
                <div style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column', justifyContent: 'flex-end' }}>
                  <div
                    style={{
                      width: '100%',
                      height: `${pct}%`,
                      background: color,
                      borderRadius: '3px 3px 0 0',
                      minHeight: '4px',
                      position: 'relative',
                      opacity: isSel ? 1 : 0.85,
                      outline: isSel ? `2px solid ${color}` : 'none',
                      outlineOffset: '1px',
                      transition: 'opacity 0.15s',
                    }}
                  >
                    {isThin && (
                      <span
                        style={{
                          position: 'absolute', top: 2, right: 3,
                          fontSize: 9, color: 'white', fontWeight: 700, lineHeight: 1,
                        }}
                      >*</span>
                    )}
                  </div>
                </div>

                {/* X-axis label */}
                <div style={{ textAlign: 'center', marginTop: 5, lineHeight: 1.2 }}>
                  <div style={{ fontSize: 11, color: isSel ? '#fff' : '#cbd5e1' }}>
                    {s.emoji} {s.sector_etf}
                  </div>
                  <div style={{ fontSize: 8, color: '#6b7280', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: '100%' }}>
                    {s.sector_name}
                  </div>
                </div>
              </div>
            );
          })}
        </div>

        {/* Thin sector footnote */}
        {hasThin && (
          <p className="text-[9px] text-tmuted mt-3">
            * Thin sector — one symbol may dominate the aggregate
          </p>
        )}
        <p className="text-[9px] text-tmuted mt-1">
          Bar heights use proportional scaling for readability
        </p>
      </div>

      {/* ── Expanded detail card ─────────────────────────────────────────── */}
      {selected && (
        <div className="bg-cardDeep rounded-xl border border-line px-4 py-3 space-y-2">
          <div className="flex items-center justify-between">
            <span className="text-sm font-semibold text-white">
              {selected.emoji} {selected.sector_etf}
              <span className="text-tmuted font-normal ml-1 text-xs">— {selected.sector_name}</span>
            </span>
            <button
              onClick={() => setSelected(null)}
              className="text-tmuted text-xs hover:text-white tap"
              aria-label="Close detail"
            >✕</button>
          </div>

          {/* Top symbol */}
          {selected.top_symbol && (
            <div className="flex items-baseline gap-1.5">
              <span className="text-ok font-semibold text-sm">{selected.top_symbol}</span>
              <span className="text-white text-sm">{fmtPremium(selected.top_symbol_prem)}</span>
              <span className="text-tmuted text-xs">
                ({selected.total_premium > 0
                  ? Math.round((selected.top_symbol_prem / selected.total_premium) * 100)
                  : 0}% of {selected.sector_etf})
              </span>
            </div>
          )}

          {/* Premium breakdown */}
          <div className="grid grid-cols-3 gap-2 text-center">
            <div>
              <div className="text-[10px] text-tmuted uppercase">Total</div>
              <div className="text-xs text-white font-mono">{fmtPremium(selected.total_premium)}</div>
            </div>
            <div>
              <div className="text-[10px] text-ok uppercase">Calls</div>
              <div className="text-xs text-ok font-mono">{fmtPremium(selected.call_premium)}</div>
            </div>
            <div>
              <div className="text-[10px] text-danger uppercase">Puts</div>
              <div className="text-xs text-danger font-mono">{fmtPremium(selected.put_premium)}</div>
            </div>
          </div>

          {/* Counts row */}
          <div className="flex gap-4 text-[10px] text-tmuted border-t border-line pt-2">
            <span>{selected.contract_count.toLocaleString()} contracts</span>
            <span>
              {selected.symbol_count} symbol{selected.symbol_count !== 1 ? 's' : ''}
              {selected.symbol_count < 4 && (
                <span className="text-warn ml-1">— thin sector</span>
              )}
            </span>
          </div>
        </div>
      )}

    </div>
  );
};
