// ============================================================
// Tab views — Today, Strategies, Market, Operations
// ============================================================

// ------------------------------------------------------------
// TodayView — the calm at-a-glance default
// ------------------------------------------------------------

function TodayView({ data, onOpenStrategy }) {
  const { portfolio, strategies, research, signals, directive, syslog } = data;
  const perf = portfolio?.performance || {};
  const btcEq = portfolio?.btc_equivalent_total || perf.btc_equivalent_total || 0;
  const vsHodl = perf.vs_hodl_btc_pct ?? 0;
  const satsAhead = perf.sats_ahead_of_hodl ?? 0;
  const alloc = portfolio?.current_btc_allocation_pct ?? 0;
  const sats = Math.round(btcEq * 1e8);

  const snap = research?.market_snapshot || {};
  const perp = research?.perp_signals || {};

  const allStrats = (strategies?.strategies || []).filter((s) => s.status !== 'retired');
  const focusId = signals?.evaluation_summary?.closest_to_triggering?.split('—')[0].trim();
  const focusStrat = allStrats.find((s) => s.id === focusId)
    || [...allStrats].sort((a, b) => (b.score || 0) - (a.score || 0))[0];

  const lastEntry = (syslog?.entries || [])
    .slice().sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp))[0];
  const nextAgent = BTC.AGENTS
    .map((a) => ({ ...a, next: BTC.nextRunFor(a), nextMin: nextRunMinutes(a) }))
    .sort((a, b) => a.nextMin - b.nextMin)[0];

  const hasSignals = (signals?.signals || []).length > 0;
  const hasPositions = (portfolio?.open_positions || []).length > 0;

  const fg = snap.fear_greed_index ?? 0;
  const fgColor =
    fg < 20 ? 'var(--red)' :
    fg < 40 ? 'var(--amber)' :
    fg < 60 ? 'var(--text-dim)' :
    fg < 80 ? 'var(--blue)' : 'var(--green)';

  return (
    <div className="view-stack">
      <AlertsRail portfolio={portfolio} directive={directive} />

      {/* Single-row scoreboard */}
      <div className="focus-hero">
        <div className="focus-hero-main">
          <div className="focus-label">vs Hodl</div>
          <div className={`focus-big ${BTC.signClass(vsHodl)}`}>
            {BTC.fmtPctSigned(vsHodl, 2)}
          </div>
          <div className="focus-sub">
            <span className={BTC.signClass(satsAhead)}>
              {satsAhead >= 0 ? '+' : ''}{Math.round(satsAhead).toLocaleString()}
            </span>{' '}
            <span className="c-muted">sats vs hodl · 7d {BTC.fmtPctSigned(directive?.system_health?.vs_hodl_btc_7d_pct, 1)} · 30d {BTC.fmtPctSigned(directive?.system_health?.vs_hodl_btc_30d_pct, 1)}</span>
          </div>
        </div>
        <div className="focus-hero-cells">
          <div className="focus-cell">
            <div className="focus-cell-label">stack</div>
            <div className="focus-cell-val">₿{BTC.fmtBTC(btcEq, 6)}</div>
            <div className="focus-cell-sub c-accent">{sats.toLocaleString()} sats</div>
          </div>
          <div className="focus-cell">
            <div className="focus-cell-label">allocation</div>
            <div className="focus-cell-val">{Math.round(alloc)}<span className="focus-unit">%</span></div>
            <div className="focus-cell-sub c-muted">target {portfolio?.target_btc_allocation_pct || 100}% · {Math.max(0, 100 - alloc).toFixed(0)}% USDT</div>
          </div>
          <div className="focus-cell">
            <div className="focus-cell-label">positions</div>
            <div className="focus-cell-val">{(portfolio?.open_positions || []).length}<span className="focus-unit"> open</span></div>
            <div className="focus-cell-sub c-muted">{perf.total_trades || 0} total{perf.total_trades > 0 ? ` · ${BTC.fmt(perf.win_rate_pct || 0)}% win` : ' · no trades yet'}</div>
          </div>
          <div className="focus-cell">
            <div className="focus-cell-label">next routine</div>
            <div className="focus-cell-val">{nextAgent?.name.split(' ')[0] || '—'}</div>
            <div className="focus-cell-sub c-muted">
              {nextAgent?.next || '—'}
              {lastEntry && <> · last {BTC.relTime(lastEntry.timestamp)}</>}
            </div>
          </div>
        </div>
      </div>

      <div className="today-grid">
        {/* Today panel */}
        <div className="focus-today">
          <div className="focus-today-head">
            <div className="focus-today-tag">
              <span className="focus-today-dot"></span>
              Today
            </div>
            <div className="c-muted" style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.12em' }}>
              {snap.btc_spot_price_usdt ? BTC.fmtUSD(snap.btc_spot_price_usdt) : '—'} ·{' '}
              <span className={BTC.deltaClass(snap.change_24h_pct) === 'pos' ? 'c-pos' : BTC.deltaClass(snap.change_24h_pct) === 'neg' ? 'c-neg' : ''}>
                {BTC.fmtPctSigned(snap.change_24h_pct, 2)} 24h
              </span>
              {' · '}
              <span style={{ color: fgColor }}>F&G {fg} · {snap.fear_greed_label || ''}</span>
              {' · '}
              regime {research?.market_regime?.replace('_', ' ') || '—'}
            </div>
          </div>

          {hasSignals ? (
            <TodaySignals signals={signals} research={research} directive={directive} />
          ) : (
            <div className="focus-today-body">
              <div className="focus-today-summary">
                <div className="focus-today-title">
                  <span className="focus-today-status-dot warn"></span>
                  Standing pat · {(signals?.evaluation_summary?.strategies_triggered ?? 0)} of {allStrats.length} strategies firing
                </div>
                <div className="focus-today-desc">
                  {BTC.truncate(signals?.no_signal_reason || 'No signals generated today.', 320)}
                </div>
              </div>

              {focusStrat && (
                <div className="focus-strategy-wrap clickable" onClick={() => onOpenStrategy(focusStrat)}>
                  <div className="focus-strategy-tag">
                    <span>Closest to firing</span>
                    <span className="focus-strategy-tag-hint">click for full notes</span>
                  </div>
                  <div className="chevron">→</div>
                  <Strategy strat={focusStrat} research={research} isFocus={true} />
                </div>
              )}
            </div>
          )}
        </div>

        {/* Right column: positions if any + allocation + market signals */}
        <div className="view-stack">
          {hasPositions && <OpenPositions portfolio={portfolio} />}
          <AllocationDonut portfolio={portfolio} />
          <div className="card focus-market accent-cyan">
            <div className="card-head">
              <div className="card-head-row">
                <span className="section-label">MARKET_SIGNALS</span>
              </div>
              <div className="section-meta">{snap.sentiment_summary || '—'} · vol ${(snap.volume_24h_usdt / 1e9).toFixed(2)}B</div>
            </div>
            <CardCommand command="./scan_signals.sh" flag="--live" live={true} />
            <div className="focus-market-grid">
              <FocusStat
                label="Funding"
                value={`${((perp.funding_rate_latest_realized || 0) * 10000).toFixed(2)} bps`}
                sub={`pred ${((perp.funding_rate_current_predicted || 0) * 10000).toFixed(2)}`}
                tone={perp.funding_rate_latest_realized < 0 ? 'pos' : 'flat'}
              />
              <FocusStat
                label="L/S ratio"
                value={(perp.long_short_ratio || 0).toFixed(3)}
                sub={perp.ls_signal}
                tone="flat"
              />
              <FocusStat
                label="OI 24h"
                value={BTC.fmtPctSigned(perp.open_interest_24h_change_pct, 2)}
                sub={`peak ${BTC.fmtPctSigned(perp.open_interest_peak_to_current_24h_pct, 1)}`}
                tone={BTC.deltaClass(perp.open_interest_24h_change_pct)}
              />
              <FocusStat
                label="Basis"
                value={perp.basis_pct != null ? `${perp.basis_pct.toFixed(3)}%` : '—'}
                sub={perp.basis_signal}
                tone="flat"
              />
              <FocusStat
                label="BTC dominance"
                value={`${snap.btc_dominance_pct?.toFixed(2) || '—'}%`}
                sub={(research?.btc_dominance_trend || '').replace('btc_dominance_', '')}
                tone="flat"
              />
              <FocusStat
                label="Spot vs ranges"
                value={BTC.fmtPctSigned(snap.pct_off_30d_high, 1)}
                sub={`+${snap.pct_off_30d_low?.toFixed(1)}% off 30d low`}
                tone={BTC.deltaClass(snap.pct_off_30d_high)}
              />
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function FocusStat({ label, value, sub, tone }) {
  const toneClass = tone === 'pos' ? 'c-pos' : tone === 'neg' ? 'c-neg' : '';
  return (
    <div className="focus-stat">
      <div className="focus-stat-label">{label}</div>
      <div className={`focus-stat-val ${toneClass}`}>{value}</div>
      {sub && <div className="focus-stat-sub">{sub}</div>}
    </div>
  );
}

function nextRunMinutes(agent) {
  const now = new Date();
  const next = new Date(now);
  next.setUTCHours(agent.scheduleHour, 0, 0, 0);
  if (next <= now) next.setUTCDate(next.getUTCDate() + 1);
  return Math.round((next - now) / 60000);
}

// ------------------------------------------------------------
// StrategiesView — full leg meters, click for details
// ------------------------------------------------------------

function StrategiesView({ data, onOpenStrategy }) {
  const { strategies, research, signals, portfolio } = data;
  const list = (strategies?.strategies || []);
  const active = list.filter((s) => s.status !== 'retired').sort((a, b) => (b.score || 0) - (a.score || 0));
  const retired = list.filter((s) => s.status === 'retired');
  const focusId = signals?.evaluation_summary?.closest_to_triggering?.split('—')[0].trim();

  return (
    <div className="view-stack">
      <div className="view-header">
        <div>
          <div className="view-title">Strategies</div>
          <div className="view-subtitle">
            {active.length} active · {retired.length} retired · {strategies?.evaluation_summary_today?.strategies_triggered ?? 0} triggered today
          </div>
        </div>
        <div className="view-header-stats">
          <ViewStat label="evaluated" value={strategies?.evaluation_summary_today?.strategies_evaluated ?? 0} />
          <ViewStat label="top score" value={`${active[0]?.score ?? 0}/100`} />
          <ViewStat label="closest" value={focusId || '—'} />
        </div>
      </div>

      <div className="strategies-grid">
        {active.map((s) => (
          <div key={s.id} className="clickable strategy-clickwrap" onClick={() => onOpenStrategy(s)}>
            <div className="chevron">→</div>
            <Strategy strat={s} research={research} isFocus={focusId && s.id === focusId} />
          </div>
        ))}
      </div>

      {strategies?.evaluation_summary_today?.closest_to_triggering && (
        <div className="card subtle">
          <div className="section-label" style={{ marginBottom: 8 }}>TODAYS_EVALUATION</div>
          <div style={{ fontSize: 11, color: 'var(--text-dim)', lineHeight: 1.65 }}>
            {strategies.evaluation_summary_today.closest_to_triggering}
          </div>
          {strategies.evaluation_summary_today.regression_observed && (
            <div style={{ fontSize: 11, color: 'var(--text-dim)', lineHeight: 1.65, marginTop: 8, paddingTop: 8, borderTop: '1px solid var(--border)' }}>
              <span className="c-muted" style={{ fontSize: 9, textTransform: 'uppercase', letterSpacing: '0.12em', marginRight: 4 }}>regression</span>
              {strategies.evaluation_summary_today.regression_observed}
            </div>
          )}
        </div>
      )}

      {retired.length > 0 && (
        <div className="card">
          <div className="card-head">
            <div className="card-head-row">
              <span className="section-label">RETIRED</span>
              <span className="badge neutral">{retired.length}</span>
            </div>
          </div>
          {retired.map((s) => (
            <div key={s.id} className="retired-row">
              <span className="retired-name">{s.name}</span>
              <span className="c-muted">{s.id}</span>
              <span className="badge retired">retired</span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// ------------------------------------------------------------
// MarketView — full snapshot + tier-1 + watchlist
// ------------------------------------------------------------

function MarketView({ data }) {
  const { research, watchlist } = data;
  return (
    <div className="view-stack">
      <div className="view-header">
        <div>
          <div className="view-title">Market</div>
          <div className="view-subtitle">
            Regime · {research?.market_regime?.replace('_', ' ') || '—'} · data quality {research?.data_quality || '—'}
          </div>
        </div>
      </div>

      <MarketContext research={research} />

      <div className="market-grid">
        <MarketSnapshot research={research} />
        <OptionsCard research={research} />
        <WatchlistPanel watchlist={watchlist} />
      </div>
    </div>
  );
}

function OptionsCard({ research }) {
  const opts = research?.options_signals || {};
  return (
    <div className="card">
      <div className="card-head">
        <div className="card-head-row">
          <span className="section-label">OPTIONS_AND_ONCHAIN</span>
        </div>
      </div>
      <div className="market-row">
        <span className="market-key">P/C ratio (7d)</span>
        <span className="market-val">{opts.put_call_oi_ratio_7d?.toFixed(2) || '—'}</span>
      </div>
      <div className="market-row">
        <span className="market-key">Put skew (weekly)</span>
        <span className="market-val">{opts.skew_iv_diff_pct_comparable_22MAY26?.toFixed(2) || '—'} IV pts</span>
      </div>
      <div className="market-row">
        <span className="market-key">Max pain (monthly)</span>
        <span className="market-val">{opts.monthly_max_pain_usdt ? BTC.fmtUSD(opts.monthly_max_pain_usdt) : '—'}</span>
      </div>
      <div className="market-row">
        <span className="market-key">Hashrate (3d)</span>
        <span className="market-val">{research?.onchain_signals?.hashrate_eh_current?.toFixed(0) || '—'} EH/s</span>
      </div>
      <div className="market-row">
        <span className="market-key">Mempool</span>
        <span className="market-val">{research?.onchain_signals?.mempool_unconfirmed_tx_count?.toLocaleString() || '—'} tx</span>
      </div>
    </div>
  );
}

// ------------------------------------------------------------
// OperationsView — pipeline + directive + log
// ------------------------------------------------------------

function OperationsView({ data }) {
  const { syslog, directive } = data;

  return (
    <div className="view-stack">
      <div className="view-header">
        <div>
          <div className="view-title">Operations</div>
          <div className="view-subtitle">
            Cold-start day {directive?.cold_start_day || '—'} of 14 ·{' '}
            {syslog?.entries?.length || 0} agent runs logged
          </div>
        </div>
      </div>

      <AgentPipeline syslog={syslog} />

      <DirectivePanel directive={directive} />

      <SysLogFeed syslog={syslog} />
    </div>
  );
}

function ViewStat({ label, value }) {
  return (
    <div className="view-stat">
      <div className="view-stat-label">{label}</div>
      <div className="view-stat-val">{value}</div>
    </div>
  );
}

// ------------------------------------------------------------
// StrategyDrawer — slide-in detail panel
// ------------------------------------------------------------

function StrategyDrawer({ strategy, research, onClose }) {
  // close on Esc
  useEffect(() => {
    if (!strategy) return;
    const h = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, [strategy, onClose]);

  if (!strategy) return null;
  const s = strategy;

  return (
    <React.Fragment>
      <div className="drawer-backdrop" onClick={onClose}></div>
      <aside className="drawer">
        <div className="drawer-head">
          <div>
            <div className="drawer-tag">{s.id} · {s.type}</div>
            <div className="drawer-title">{s.name}</div>
          </div>
          <button className="drawer-close" onClick={onClose}>✕</button>
        </div>

        <div className="drawer-body">
          <div className="drawer-row">
            <div className="drawer-stat">
              <div className="drawer-stat-label">Score</div>
              <div className="drawer-stat-val">{s.score ?? '—'}<span className="c-muted">/100</span></div>
            </div>
            <div className="drawer-stat">
              <div className="drawer-stat-label">Status</div>
              <div className="drawer-stat-val">
                <span className={`badge ${BTC.statusBadge(s.status)}`}>{(s.status || '').replace('_', ' ')}</span>
              </div>
            </div>
            <div className="drawer-stat">
              <div className="drawer-stat-label">Days active</div>
              <div className="drawer-stat-val">{s.days_active || 0}</div>
            </div>
            <div className="drawer-stat">
              <div className="drawer-stat-label">Trades</div>
              <div className="drawer-stat-val">{s.trades_taken || 0}</div>
            </div>
          </div>

          <DrawerSection label="Description">
            <div className="drawer-text">{s.description}</div>
          </DrawerSection>

          <DrawerSection label="Entry condition">
            <div className="drawer-code">{s.entry_condition}</div>
          </DrawerSection>

          <DrawerSection label="Exit condition">
            <div className="drawer-code">{s.exit_condition}</div>
          </DrawerSection>

          {s.trigger_distance_notes && (
            <DrawerSection label="Today's proximity">
              <div className="drawer-text">{s.trigger_distance_notes}</div>
            </DrawerSection>
          )}

          {s.score_notes_today && (
            <DrawerSection label="Today's scoring">
              <div className="drawer-text">{s.score_notes_today}</div>
            </DrawerSection>
          )}

          {s.backtest_notes && (
            <DrawerSection label="Backtest notes">
              <div className="drawer-text">{s.backtest_notes}</div>
            </DrawerSection>
          )}

          {s.score_history?.length > 0 && (
            <DrawerSection label="Score history">
              <div className="drawer-history">
                {s.score_history.map((h, i) => (
                  <div key={i} className="drawer-history-row">
                    <span className="c-muted">{h.date}</span>
                    <span>{h.score}/100</span>
                  </div>
                ))}
              </div>
            </DrawerSection>
          )}
        </div>
      </aside>
    </React.Fragment>
  );
}

function DrawerSection({ label, children }) {
  return (
    <div className="drawer-section">
      <div className="drawer-section-label">{label}</div>
      {children}
    </div>
  );
}

Object.assign(window, {
  TodayView, StrategiesView, MarketView, OperationsView,
  StrategyDrawer,
});
