/**
 * HeaderStatsBar - Compact inline stats display for the header
 * Shows: elapsed time | context usage | tool calls | cost
 * Stats appear progressively at wider breakpoints:
 *   md (768px+): elapsed time only
 *   lg (1024px+): + context usage, tool calls
 *   xl (1280px+): + cost
 * Click to open StatsDrawer (Phase 4)
 */

import { useMemo } from 'react';
import { Clock, Cpu, Wrench, DollarSign } from 'lucide-react';
import { EventItem, SessionLimits } from '../types';
import { calculateStats } from '../utils/statsCalculator';
import { formatDurationCompact, formatTokensAbbrev, formatCost, formatPercentage } from '../utils/formatters';
import { useSessionTimerElapsed, useSessionTimerActive } from '../context/SessionTimerContext';
import { useUiClientEvents } from '../context/UiClientContext';

interface HeaderStatsBarProps {
  /** @deprecated events are now read from UiClientEventsContext internally */
  events?: EventItem[];
  agentModels: Record<string, { provider?: string; model?: string; contextLimit?: number; node?: string }>;
  sessionLimits?: SessionLimits | null;
  onClick?: () => void;
  /** When true, renders a condensed layout suitable for narrow/mobile viewports. */
  compact?: boolean;
}

export function HeaderStatsBar({
  events: eventsProp,
  agentModels,
  sessionLimits,
  onClick,
  compact = false,
}: HeaderStatsBarProps) {
  const { events: eventsCtx } = useUiClientEvents();
  const events = eventsProp ?? eventsCtx;
  const globalElapsedMs = useSessionTimerElapsed();
  const isSessionActive = useSessionTimerActive();
  const { session, perAgent } = useMemo(() => calculateStats(events, sessionLimits), [events, sessionLimits]);
  
  // Enhance perAgent stats with context limits from agentModels if missing
  const enrichedPerAgent = useMemo(() => {
    return perAgent.map(agentStats => ({
      ...agentStats,
      maxContextTokens: agentStats.maxContextTokens ?? agentModels[agentStats.agentId]?.contextLimit
    }));
  }, [perAgent, agentModels]);
  
  // Don't show stats bar if there are no actual session events
  if (session.totalMessages === 0 && session.totalToolCalls === 0) {
    return null;
  }
  
  // Calculate context usage (single agent or aggregate)
  const totalContextTokens = enrichedPerAgent.reduce((sum, a) => sum + a.currentContextTokens, 0);
  const totalMaxContext = enrichedPerAgent.reduce((sum, a) => sum + (a.maxContextTokens || 0), 0);
  
  // Context display - show percentage instead of raw tokens
  // TODO: The 80% warning threshold is hardcoded to match the backend's ContextMiddleware default.
  // This should be exposed via SessionLimits (context_warn_at_percent) in a future enhancement.
  const contextDisplay = totalMaxContext > 0
    ? formatPercentage(totalContextTokens, totalMaxContext)
    : formatTokensAbbrev(totalContextTokens);
  
  // Cost display with limit if configured
  const costDisplay = !session.hasCostData
    ? null
    : session.limits?.max_cost_usd
      ? `${formatCost(session.totalCostUsd)}/${formatCost(session.limits.max_cost_usd)}`
      : formatCost(session.totalCostUsd);
  
  // Context usage percentage for color coding
  // Use 80% as the critical threshold (matches backend ContextConfig.warn_at_percent default)
  const contextPercent = totalMaxContext > 0 ? (totalContextTokens / totalMaxContext) * 100 : 0;
  const costPercent = session.limits?.max_cost_usd ? (session.totalCostUsd / session.limits.max_cost_usd) * 100 : 0;

  // When compact (mobile), hide everything except elapsed time via JS.
  // On desktop (non-compact), use CSS breakpoints for progressive disclosure.
  const hideContext = compact ? 'hidden' : 'hidden md:flex';
  const hideToolCalls = compact ? 'hidden' : 'hidden lg:flex';
  const hideCost = compact ? 'hidden' : 'hidden lg:flex';
  const hideContextSep = compact ? 'hidden' : 'hidden md:inline';
  const hideToolCallsSep = compact ? 'hidden' : 'hidden lg:inline';
  const hideCostSep = compact ? 'hidden' : 'hidden lg:inline';
  
  return (
    <div
      onClick={onClick}
      data-testid="header-stats-bar"
      className={`flex items-center ${compact ? 'gap-1.5 px-2 py-1' : 'gap-1.5 lg:gap-3 px-2 lg:px-3 py-1'} rounded-lg border border-surface-border/40 bg-surface-elevated/50 text-xs font-mono transition-colors ${
        onClick ? 'cursor-pointer hover:border-accent-primary/60 hover:bg-surface-elevated/80' : ''
      }`}
      title="Click for detailed stats"
    >
      {/* Elapsed Time — always visible */}
      <div className="flex items-center gap-1.5">
        <Clock className={`w-3.5 h-3.5 ${isSessionActive ? 'text-accent-primary animate-pulse' : 'text-ui-muted'}`} />
        <span className="text-ui-secondary">{formatDurationCompact(globalElapsedMs)}</span>
      </div>
      
      <span data-testid="stats-separator" className={`text-surface-border ${hideContextSep}`}>│</span>
      
      {/* Context Usage — visible at md+ */}
      <div className={`items-center gap-1.5 ${hideContext}`}>
        <Cpu className={`w-3.5 h-3.5 ${
          contextPercent >= 80 ? 'text-status-warning' : 
          contextPercent >= 70 ? 'text-accent-primary' : 
          'text-ui-muted'
        }`} />
        <span className={`${
          contextPercent >= 80 ? 'text-status-warning' : 
          contextPercent >= 70 ? 'text-accent-primary' : 
          'text-ui-secondary'
        }`}>
          {contextDisplay}
        </span>
      </div>
      
      <span data-testid="stats-separator" className={`text-surface-border ${hideToolCallsSep}`}>│</span>
      
      {/* Tool Calls — visible at lg+ */}
      <div className={`items-center gap-1.5 ${hideToolCalls}`}>
        <Wrench className="w-3.5 h-3.5 text-ui-muted" />
        <span className="text-ui-secondary">{session.totalToolCalls}</span>
      </div>
      
      {costDisplay && (
        <>
          <span data-testid="stats-separator" className={`text-surface-border ${hideCostSep}`}>│</span>
          
          {/* Cost — visible at xl+ */}
          <div className={`items-center gap-1.5 ${hideCost}`}>
            <DollarSign className={`w-3.5 h-3.5 ${
              costPercent > 90 ? 'text-status-warning' : 
              costPercent > 70 ? 'text-accent-primary' : 
              'text-ui-muted'
            }`} />
            <span className={`${
              costPercent > 90 ? 'text-status-warning' : 
              costPercent > 70 ? 'text-accent-primary' : 
              'text-accent-primary'
            }`}>
              {costDisplay}
            </span>
          </div>
        </>
      )}
    </div>
  );
}
