// ============================================================
// Core layout components — TopBar, AlertsRail, Hero, Pipeline
// ============================================================

function TopBar({ portfolio, directive, lastUpdated, dataMode, actions }) {
  const mode = portfolio?.paper_trading !== false ? 'PAPER' : 'LIVE';
  const liveAuth = directive?.live_execution_authorized;
  const cb = portfolio?.circuit_breaker_tripped;

  let statusKind = 'ok';
  let statusText = 'System nominal';
  if (cb) { statusKind = 'bad'; statusText = 'Circuit breaker active'; }
  else if (liveAuth === false) { statusKind = 'warn'; statusText = 'Live exec blocked'; }
  else if (directive?.cold_start) { statusKind = 'cool'; statusText = `Cold-start day ${directive.cold_start_day}/14`; }

  return (
    <div className="topbar">
      <div className="brand">
        <div className="brand-mark">₿</div>
        <div className="brand-text">
          <div className="brand-title">BTC Agents</div>
          <div className="brand-sub">Autonomous outperformance system</div>
        </div>
      </div>
      <div className="topbar-status">
        <div className={`status-pill ${statusKind === 'ok' ? '' : statusKind}`}>
          <div className="dot pulse"></div>
          <span>{statusText}</span>
        </div>
        <div className="topbar-time">Sync · {lastUpdated}</div>
        {actions}
      </div>
    </div>
  );
}

// ------------------------------------------------------------
// AlertsRail — operational alerts only when relevant
// ------------------------------------------------------------

function AlertsRail({ portfolio, directive }) {
  const alerts = [];

  if (portfolio?.circuit_breaker_tripped) {
    alerts.push({
      kind: 'bad',
      icon: '!',
      title: 'Circuit breaker tripped',
      detail: `BTC-denominated drawdown ${BTC.fmt(portfolio.btc_denominated_drawdown_pct)}% from peak — trading halted pending Orchestrator review.`,
    });
  }

  if (directive?.live_execution_authorized === false) {
    const note = directive.live_execution_blocker_reason || directive?.operational_reconciliation_required?.issue;
    alerts.push({
      kind: 'warn',
      icon: '◐',
      title: 'Live execution blocked',
      detail: note ? BTC.truncate(note, 200) : 'Live order placement disabled by directive.',
    });
  }

  if (directive?.cold_start) {
    const day = directive.cold_start_day;
    const rem = directive.cold_start_days_remaining;
    alerts.push({
      kind: 'info',
      icon: 'C',
      title: `Cold-start protocol · day ${day} of 14`,
      detail: `${rem} day${rem === 1 ? '' : 's'} remaining of conservative observation window. Allocation floor ≥90% BTC regardless of signals.`,
    });
  }

  if (directive?.crisis_mode) {
    alerts.push({ kind: 'bad', icon: '⚠', title: 'Crisis mode active', detail: 'Defensive directives in force.' });
  }

  // funding-mismatch
  const recon = directive?.operational_reconciliation_required;
  if (recon?.issue) {
    alerts.push({
      kind: 'warn',
      icon: '$',
      title: 'Paper / live funding mismatch',
      detail: BTC.truncate(recon.issue, 160) + ' — operator decision pending.',
    });
  }

  if (alerts.length === 0) return null;

  return (
    <div className="alerts">
      {alerts.map((a, i) => (
        <div key={i} className={`alert ${a.kind}`}>
          <div className="alert-icon">{a.icon}</div>
          <div className="alert-body">
            <div className="alert-title">{a.title}</div>
            <div className="alert-detail">{a.detail}</div>
          </div>
        </div>
      ))}
    </div>
  );
}

// ------------------------------------------------------------
// HeroScoreboard — vs hodl, btc stack, allocation, system
// ------------------------------------------------------------

function HeroScoreboard({ portfolio, directive, research, syslog }) {
  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 target = portfolio?.target_btc_allocation_pct ?? 100;
  const openCount = (portfolio?.open_positions || []).length;
  const totalTrades = perf.total_trades || 0;
  const winRate = perf.win_rate_pct || 0;

  const sats = Math.round(btcEq * 1e8);
  const hodlSats = Math.round((perf.hodl_btc_benchmark || portfolio?.hodl_btc_benchmark || btcEq) * 1e8);

  // vs-hodl mini sparkline from syslog
  const trendValues = useMemo(() => {
    const ts = (syslog?.entries || [])
      .filter((e) => e.vs_hodl_btc_pct != null)
      .sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp))
      .map((e) => e.vs_hodl_btc_pct);
    return ts;
  }, [syslog]);

  return (
    <div className="hero">
      {/* vs hodl — the actual scoreboard */}
      <div className="hero-cell primary">
        <div className="hero-label">
          <span>vs Hodl benchmark</span>
          <span className="tag">SATS = SCORE</span>
        </div>
        <div className="hero-value">
          <span className={BTC.signClass(vsHodl)}>{BTC.fmtPctSigned(vsHodl, 2)}</span>
        </div>
        <div className="hero-sub">
          <div className="hero-sub-row">
            <span className="lbl">Δ vs hodl</span>
            <span className={`mono ${BTC.signClass(satsAhead)}`}>
              {satsAhead >= 0 ? '+' : ''}{Math.round(satsAhead).toLocaleString()} sats
            </span>
          </div>
          <div className="hero-sub-row">
            <span className="lbl">7d / 30d</span>
            <span className="mono">
              {BTC.fmtPctSigned(directive?.system_health?.vs_hodl_btc_7d_pct, 1)} ·{' '}
              {BTC.fmtPctSigned(directive?.system_health?.vs_hodl_btc_30d_pct, 1)}
            </span>
          </div>
        </div>
        {trendValues.length >= 2 && (
          <div className="hero-trend" style={{ color: BTC.signClass(vsHodl) === 'c-neg' ? 'var(--red)' : 'var(--green)' }}>
            <span className="hero-trend-label">trend</span>
            <Sparkline values={trendValues} width={140} height={28} color="currentColor" area={true} />
          </div>
        )}
      </div>

      {/* BTC stack */}
      <div className="hero-cell">
        <div className="hero-label">BTC stack</div>
        <div className="hero-value">
          <span>₿{BTC.fmtBTC(btcEq, 6)}</span>
        </div>
        <div className="hero-sub">
          <div className="hero-sub-row">
            <span className="lbl">sats</span>
            <span className="mono c-accent">{sats.toLocaleString()}</span>
          </div>
          <div className="hero-sub-row">
            <span className="lbl">hodl benchmark</span>
            <span className="mono c-muted">{hodlSats.toLocaleString()}</span>
          </div>
        </div>
      </div>

      {/* allocation */}
      <div className="hero-cell">
        <div className="hero-label">Allocation</div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
          <div className="alloc-ring" style={{ '--pct': alloc }}>
            <div className="alloc-ring-inner">{Math.round(alloc)}%</div>
          </div>
          <div style={{ flex: 1, fontSize: 11 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
              <span className="c-muted">target</span>
              <span className="mono">{target}%</span>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
              <span className="c-muted">USDT</span>
              <span className="mono">{Math.max(0, 100 - alloc).toFixed(0)}%</span>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
              <span className="c-muted">max position</span>
              <span className="mono">{directive?.max_position_size_pct || '—'}%</span>
            </div>
          </div>
        </div>
      </div>

      {/* trading activity */}
      <div className="hero-cell">
        <div className="hero-label">Activity</div>
        <div className="hero-value">
          <span>{totalTrades}</span>
          <span className="hero-unit">trades</span>
        </div>
        <div className="hero-sub">
          <div className="hero-sub-row">
            <span className="lbl">open positions</span>
            <span className="mono">{openCount}</span>
          </div>
          <div className="hero-sub-row">
            <span className="lbl">win rate</span>
            <span className="mono">{totalTrades > 0 ? BTC.fmt(winRate) + '%' : '—'}</span>
          </div>
          <div className="hero-sub-row">
            <span className="lbl">closed</span>
            <span className="mono">{(portfolio?.closed_trades || []).length}</span>
          </div>
        </div>
      </div>
    </div>
  );
}

// ------------------------------------------------------------
// AgentPipeline — 5-step horizontal strip
// ------------------------------------------------------------

function AgentPipeline({ syslog }) {
  const entries = syslog?.entries || [];

  return (
    <div className="pipeline">
      {BTC.AGENTS.map((agent) => {
        const last = BTC.findLastByAgent(entries, agent.key);
        const ranToday = last && last.timestamp && (new Date() - new Date(last.timestamp)) < 30 * 60 * 60 * 1000;
        const status = !last ? 'idle' :
          last.status?.includes('fail') || last.errors?.length ? 'bad' :
          ranToday ? 'ok' : 'warn';

        return (
          <div key={agent.key} className="pipeline-step">
            <div className="pipeline-head">
              <div className="agent-glyph" style={{ background: 'color-mix(in oklab, ' + agent.color + ' 18%, transparent)', color: agent.color }}>
                {agent.badge}
              </div>
              <div className="agent-name">{agent.name}</div>
              <div className={`pipeline-status ${status}`}></div>
            </div>
            <div className="pipeline-schedule">{agent.scheduleLabel}</div>
            <div className="pipeline-meta">
              {last ? (
                <>
                  <div>
                    <span className="lbl">last </span>
                    <span>{BTC.relTime(last.timestamp)}</span>
                  </div>
                  <div className="c-muted" style={{ fontSize: 10 }}>
                    next {BTC.nextRunFor(agent)}
                  </div>
                </>
              ) : (
                <>
                  <div className="c-muted">Not run yet</div>
                  <div className="c-muted" style={{ fontSize: 10 }}>
                    next {BTC.nextRunFor(agent)}
                  </div>
                </>
              )}
            </div>
          </div>
        );
      })}
    </div>
  );
}

Object.assign(window, { TopBar, AlertsRail, HeroScoreboard, AgentPipeline });
