import { useState, useEffect, useCallback } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useSearchParams } from 'react-router-dom';
import { CheckCircle, XCircle, Clock, RefreshCw, Activity } from 'lucide-react';
import { eventsApi, type TradeEvent, type HealthSummary } from '../api/client';

// ── colour helpers ────────────────────────────────────────────────────────────

const LEVEL_STYLE: Record<string, { color: string; bg: string }> = {
  ERROR: { color: '#ef4444', bg: 'rgba(239,68,68,0.10)' },
  WARN:  { color: 'var(--gold)',  bg: 'var(--gold-dim)'  },
  INFO:  { color: 'var(--text3)', bg: 'rgba(0,0,0,0.04)' },
};

const CAT_STYLE: Record<string, { color: string; bg: string }> = {
  fallback:    { color: '#f97316', bg: 'rgba(249,115,22,0.10)' },
  snapshot:    { color: 'var(--cyan)',   bg: 'var(--cyan-dim)'  },
  macro:       { color: '#8b5cf6', bg: 'rgba(139,92,246,0.10)' },
  kill_switch: { color: '#ef4444', bg: 'rgba(239,68,68,0.10)' },
  broker:      { color: 'var(--gold)',  bg: 'var(--gold-dim)'  },
  lifecycle:   { color: 'var(--green)', bg: 'rgba(16,185,129,0.10)' },
  order:       { color: 'var(--cyan)',  bg: 'var(--cyan-dim)'  },
  engine:      { color: 'var(--text2)', bg: 'rgba(0,0,0,0.05)' },
  pipeline:    { color: 'var(--text3)', bg: 'rgba(0,0,0,0.04)' },
};

function LevelPill({ level }: { level: string }) {
  const s = LEVEL_STYLE[level] ?? LEVEL_STYLE.INFO;
  return (
    <span style={{
      display: 'inline-block', padding: '1px 7px', borderRadius: 4, fontSize: 11,
      fontFamily: 'var(--font-mono)', fontWeight: 600, letterSpacing: '0.05em',
      color: s.color, background: s.bg, border: '1px solid var(--border)',
    }}>
      {level}
    </span>
  );
}

function CatPill({ cat }: { cat: string | null }) {
  if (!cat) return null;
  const s = CAT_STYLE[cat] ?? { color: 'var(--text3)', bg: 'rgba(0,0,0,0.04)' };
  return (
    <span style={{
      display: 'inline-block', padding: '1px 7px', borderRadius: 4, fontSize: 11,
      fontFamily: 'var(--font-mono)', fontWeight: 500,
      color: s.color, background: s.bg, border: '1px solid var(--border)',
    }}>
      {cat}
    </span>
  );
}

// ── timestamp formatting ──────────────────────────────────────────────────────

function fmtTs(iso: string) {
  try {
    const d = new Date(iso);
    return d.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false, timeZoneName: 'short' });
  } catch {
    return iso.slice(11, 19);
  }
}

function fmtDate(iso: string) {
  try {
    return new Date(iso).toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
  } catch { return iso.slice(0, 10); }
}

function timeAgo(iso: string) {
  const diff = Date.now() - new Date(iso).getTime();
  if (diff < 60_000) return `${Math.floor(diff / 1000)}s ago`;
  if (diff < 3_600_000) return `${Math.floor(diff / 60_000)}m ago`;
  if (diff < 86_400_000) return `${Math.floor(diff / 3_600_000)}h ago`;
  return fmtDate(iso);
}

// ── Phase definitions ─────────────────────────────────────────────────────────

const PEAD_PHASES = [
  { key: 'pipeline_pre',  label: 'pipeline_pre'  },
  { key: 'run_open',      label: 'run_open'       },
  { key: 'run_close',     label: 'run_close'      },
  { key: 'pipeline_post', label: 'pipeline_post'  },
];

const ORB_PHASES = [
  { key: 'orb_pre_screen', label: 'pre_screen'  },
  { key: 'orb_detect',     label: 'detect'      },
  { key: 'orb_breakout',   label: 'breakout'    },
  { key: 'orb_stop',       label: 'stop_check'  },
  { key: 'orb_eod',        label: 'eod_exit'    },
  { key: 'orb_post_close', label: 'post_close'  },
];

// ── Health Cards ──────────────────────────────────────────────────────────────

function PhaseRow({ label, phase, data }: { label: string; phase: string; data: HealthSummary['phases'] }) {
  const info = data[phase];
  const ok = info?.status === 'success';
  const color = !info ? 'var(--text3)' : ok ? 'var(--green)' : '#ef4444';
  const Icon = !info ? Clock : ok ? CheckCircle : XCircle;
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '6px 0', borderBottom: '1px solid var(--border)' }}>
      <Icon size={14} style={{ color, flexShrink: 0 }} />
      <span style={{ fontSize: 13, color: 'var(--text2)', minWidth: 100 }}>{label}</span>
      {info ? (
        <span style={{ fontSize: 12, fontFamily: 'var(--font-mono)', color }}>
          {ok ? '✓' : '✗'} {timeAgo(info.last_ts)}
        </span>
      ) : (
        <span style={{ fontSize: 12, color: 'var(--text3)', fontFamily: 'var(--font-mono)' }}>not yet today</span>
      )}
    </div>
  );
}

function PhaseCard({ title, phases, data }: {
  title: string;
  phases: { key: string; label: string }[];
  data: HealthSummary['phases'];
}) {
  return (
    <div style={{ background: 'var(--bg1)', border: '1px solid var(--border)', borderRadius: 10, padding: '14px 16px' }}>
      <div style={{ fontSize: 12, fontFamily: 'var(--font-mono)', color: 'var(--text3)', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: 10 }}>
        {title}
      </div>
      {phases.map(p => (
        <PhaseRow key={p.key} label={p.label} phase={p.key} data={data} />
      ))}
    </div>
  );
}

function HealthCards({ data, system }: { data: HealthSummary; system: string }) {
  const FALLBACK_CATS = ['snapshot', 'macro', 'broker', 'kill_switch', 'fallback', 'regime'];

  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))', gap: 14, marginBottom: 20 }}>
      {/* Phase status cards */}
      {system !== 'orb' && (
        <PhaseCard title="PEAD Phases" phases={PEAD_PHASES} data={data.phases} />
      )}
      {system !== 'pead' && (
        <PhaseCard title="ORB Phases" phases={ORB_PHASES} data={data.phases} />
      )}

      {/* Fallback counts */}
      <div style={{ background: 'var(--bg1)', border: '1px solid var(--border)', borderRadius: 10, padding: '14px 16px' }}>
        <div style={{ fontSize: 12, fontFamily: 'var(--font-mono)', color: 'var(--text3)', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: 10 }}>
          Fallbacks Today
        </div>
        {FALLBACK_CATS.map(cat => {
          const counts = data.fallbacks_today[cat];
          const errCnt = counts?.error ?? 0;
          const warnCnt = counts?.warn ?? 0;
          const total = errCnt + warnCnt;
          const color = errCnt > 0 ? '#ef4444' : warnCnt > 0 ? 'var(--gold)' : 'var(--green)';
          return (
            <div key={cat} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '5px 0', borderBottom: '1px solid var(--border)' }}>
              <span style={{ fontSize: 12, fontFamily: 'var(--font-mono)', color: 'var(--text2)' }}>{cat}</span>
              <span style={{ fontSize: 12, fontFamily: 'var(--font-mono)', color, fontWeight: 600 }}>
                {total === 0 ? '—' : `${errCnt > 0 ? errCnt + ' ERR' : ''}${errCnt > 0 && warnCnt > 0 ? ' · ' : ''}${warnCnt > 0 ? warnCnt + ' WARN' : ''}`}
              </span>
            </div>
          );
        })}
      </div>

      {/* Recent errors */}
      <div style={{ background: 'var(--bg1)', border: '1px solid var(--border)', borderRadius: 10, padding: '14px 16px' }}>
        <div style={{ fontSize: 12, fontFamily: 'var(--font-mono)', color: 'var(--text3)', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: 10 }}>
          Recent Errors
        </div>
        {data.recent_errors.length === 0 ? (
          <div style={{ fontSize: 12, color: 'var(--green)', display: 'flex', alignItems: 'center', gap: 6, marginTop: 8 }}>
            <CheckCircle size={13} /> No errors today
          </div>
        ) : (
          data.recent_errors.map(e => (
            <div key={e.id} style={{ padding: '4px 0', borderBottom: '1px solid var(--border)' }}>
              <div style={{ fontSize: 11, fontFamily: 'var(--font-mono)', color: '#ef4444' }}>{e.event_name}</div>
              <div style={{ fontSize: 11, color: 'var(--text3)' }}>{e.message?.slice(0, 60) ?? '—'}</div>
              <div style={{ fontSize: 10, color: 'var(--text3)', marginTop: 1 }}>{timeAgo(e.ts_utc)}</div>
            </div>
          ))
        )}
      </div>

      {/* Snapshot freshness — PEAD only */}
      {system !== 'orb' && data.snapshot_freshness.length > 0 && (
        <div style={{ background: 'var(--bg1)', border: '1px solid var(--border)', borderRadius: 10, padding: '14px 16px' }}>
          <div style={{ fontSize: 12, fontFamily: 'var(--font-mono)', color: 'var(--text3)', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: 10 }}>
            Snapshot Freshness
          </div>
          {data.snapshot_freshness.map((sf, i) => {
            const ageMs = Date.now() - new Date(sf.last_update).getTime();
            const ageH = ageMs / 3_600_000;
            const color = ageH < 25 ? 'var(--green)' : ageH < 49 ? 'var(--gold)' : '#ef4444';
            return (
              <div key={i} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '5px 0', borderBottom: '1px solid var(--border)' }}>
                <span style={{ fontSize: 11, fontFamily: 'var(--font-mono)', color: 'var(--text2)', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: 130 }}>
                  {sf.snapshot_id ?? sf.session_id ?? '?'}
                </span>
                <span style={{ fontSize: 11, fontFamily: 'var(--font-mono)', color }}>{timeAgo(sf.last_update)}</span>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

// ── Detail side panel ─────────────────────────────────────────────────────────

function DetailPanel({ event, onClose, relatedEvents }: {
  event: TradeEvent;
  onClose: () => void;
  relatedEvents: TradeEvent[];
}) {
  let parsedDetails: Record<string, unknown> | null = null;
  try {
    if (event.details) parsedDetails = JSON.parse(event.details);
  } catch {}

  return (
    <div style={{
      width: 380, flexShrink: 0, background: 'var(--bg1)', borderLeft: '1px solid var(--border)',
      display: 'flex', flexDirection: 'column', overflow: 'hidden',
    }}>
      <div style={{ padding: '12px 16px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--text1)' }}>Event Detail</span>
        <button onClick={onClose} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text3)', fontSize: 18, lineHeight: 1, padding: '0 2px' }}>×</button>
      </div>

      <div style={{ flex: 1, overflowY: 'auto', padding: 16 }}>
        <div style={{ marginBottom: 14 }}>
          <div style={{ display: 'flex', gap: 6, marginBottom: 8, flexWrap: 'wrap' }}>
            <LevelPill level={event.level} />
            <CatPill cat={event.category} />
          </div>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 13, fontWeight: 600, color: 'var(--text1)', marginBottom: 4, wordBreak: 'break-all' }}>
            {event.event_name}
          </div>
          {event.message && (
            <div style={{ fontSize: 12, color: 'var(--text2)', marginBottom: 8 }}>{event.message}</div>
          )}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '4px 12px', fontSize: 11, fontFamily: 'var(--font-mono)', color: 'var(--text3)' }}>
            <span>Time: {fmtTs(event.ts_utc)}</span>
            <span>Source: {event.source}</span>
            {event.session_id && <span style={{ gridColumn: '1/-1' }}>Session: {event.session_id}</span>}
            {event.ticker && <span>Ticker: {event.ticker}</span>}
          </div>
          {event.job_run_id && (
            <div style={{ marginTop: 6, fontSize: 11, fontFamily: 'var(--font-mono)', color: 'var(--text3)', wordBreak: 'break-all' }}>
              Run: {event.job_run_id.slice(0, 16)}…
            </div>
          )}
        </div>

        {parsedDetails && Object.keys(parsedDetails).length > 0 && (
          <div style={{ marginBottom: 14 }}>
            <div style={{ fontSize: 11, color: 'var(--text3)', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: 6 }}>Details</div>
            <pre style={{
              margin: 0, padding: 10, background: 'var(--bg2)', borderRadius: 6,
              fontSize: 11, fontFamily: 'var(--font-mono)', color: 'var(--text2)',
              overflowX: 'auto', whiteSpace: 'pre-wrap', wordBreak: 'break-all',
              border: '1px solid var(--border)',
            }}>
              {JSON.stringify(parsedDetails, null, 2)}
            </pre>
          </div>
        )}

        {event.job_run_id && relatedEvents.length > 1 && (
          <div>
            <div style={{ fontSize: 11, color: 'var(--text3)', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: 6 }}>
              Run Timeline ({relatedEvents.length} events)
            </div>
            <div style={{ borderLeft: '2px solid var(--border)', paddingLeft: 10, display: 'flex', flexDirection: 'column', gap: 4 }}>
              {[...relatedEvents].sort((a, b) => a.ts_utc.localeCompare(b.ts_utc)).map(e => (
                <div key={e.id} style={{
                  display: 'flex', alignItems: 'flex-start', gap: 8, padding: '3px 0',
                  opacity: e.id === event.id ? 1 : 0.65,
                }}>
                  <div style={{
                    width: 7, height: 7, borderRadius: '50%', flexShrink: 0, marginTop: 3,
                    background: e.level === 'ERROR' ? '#ef4444' : e.level === 'WARN' ? 'var(--gold)' : 'var(--text3)',
                  }} />
                  <div>
                    <div style={{ fontSize: 10, fontFamily: 'var(--font-mono)', color: 'var(--text3)' }}>
                      {e.ts_utc.slice(11, 19)}
                    </div>
                    <div style={{ fontSize: 11, fontFamily: 'var(--font-mono)', color: 'var(--text2)' }}>
                      {e.event_name.length > 40 ? e.event_name.slice(0, 40) + '…' : e.event_name}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

// ── Filter bar ────────────────────────────────────────────────────────────────

const LEVEL_OPTIONS = ['', 'ERROR', 'WARN', 'INFO'];
const CAT_OPTIONS = ['', 'fallback', 'snapshot', 'macro', 'broker', 'kill_switch', 'lifecycle', 'order', 'engine', 'pipeline'];
const TIME_OPTIONS = [
  { label: 'Today',  since: () => new Date().toISOString().slice(0, 10) + 'T00:00:00' },
  { label: '24h',    since: () => new Date(Date.now() - 86_400_000).toISOString() },
  { label: '7d',     since: () => new Date(Date.now() - 7 * 86_400_000).toISOString() },
  { label: 'All',    since: () => '' },
];

function sel() {
  return {
    padding: '5px 10px', borderRadius: 6, border: '1px solid var(--border)',
    background: 'var(--bg2)', color: 'var(--text2)', fontSize: 12,
    fontFamily: 'var(--font-mono)', cursor: 'pointer', outline: 'none',
  } as React.CSSProperties;
}

// ── Tab bar ───────────────────────────────────────────────────────────────────

const TABS = [
  { key: 'all',  label: 'All'  },
  { key: 'pead', label: 'PEAD' },
  { key: 'orb',  label: 'ORB'  },
] as const;

type TabKey = typeof TABS[number]['key'];

// ── Main page ─────────────────────────────────────────────────────────────────

export function LogsPage() {
  const [sp, setSP] = useSearchParams();
  const [selected, setSelected] = useState<TradeEvent | null>(null);
  const [relatedEvents, setRelatedEvents] = useState<TradeEvent[]>([]);
  const [timeLabel, setTimeLabel] = useState('Today');

  // Active tab from URL
  const activeTab = ((sp.get('system') || 'all') as TabKey);

  // Filters from URL querystring for deep-linking
  const filters = {
    level:    sp.get('level') ?? '',
    category: sp.get('category') ?? '',
    source:   sp.get('source') ?? '',
    session_id: sp.get('session_id') ?? '',
    job_run_id: sp.get('job_run_id') ?? '',
    q:        sp.get('q') ?? '',
    since:    sp.get('since') ?? TIME_OPTIONS[0].since(),
    system:   sp.get('system') ?? '',
  };

  const setFilter = useCallback((key: string, val: string) => {
    setSP(prev => {
      const next = new URLSearchParams(prev);
      if (val) next.set(key, val);
      else next.delete(key);
      return next;
    });
  }, [setSP]);

  const { data: health, refetch: refetchHealth } = useQuery({
    queryKey: ['health'],
    queryFn: eventsApi.health,
    refetchInterval: 5_000,
  });

  const { data: sources } = useQuery({
    queryKey: ['event-sources'],
    queryFn: eventsApi.sources,
    staleTime: 60_000,
  });

  const queryKey = ['events', filters];
  const { data, isFetching, refetch } = useQuery({
    queryKey,
    queryFn: () => eventsApi.list({
      level: filters.level || undefined,
      category: filters.category || undefined,
      source: filters.source || undefined,
      session_id: filters.session_id || undefined,
      job_run_id: filters.job_run_id || undefined,
      q: filters.q || undefined,
      since: filters.since || undefined,
      limit: 200,
      system: filters.system || undefined,
    }),
    refetchInterval: 3_000,
  });

  // Load run timeline when an event with job_run_id is selected
  useEffect(() => {
    if (!selected?.job_run_id) { setRelatedEvents([]); return; }
    eventsApi.list({ job_run_id: selected.job_run_id, limit: 1000 }).then(r => setRelatedEvents(r.rows)).catch(() => {});
  }, [selected?.job_run_id]);

  const rows = data?.rows ?? [];
  const total = data?.total ?? 0;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100vh', background: 'var(--bg2)' }}>
      {/* ── Header ── */}
      <div style={{ padding: '20px 24px 14px', background: 'var(--bg1)', borderBottom: '1px solid var(--border)', flexShrink: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 4 }}>
          <Activity size={18} style={{ color: 'var(--cyan)' }} />
          <h1 style={{ margin: 0, fontSize: 20, fontWeight: 600, color: 'var(--text1)' }}>Logs / Health</h1>
          {isFetching && <RefreshCw size={13} style={{ color: 'var(--text3)', animation: 'spin 1s linear infinite' }} />}
        </div>
        <div style={{ fontSize: 12, color: 'var(--text3)' }}>
          Live event feed from PEAD engine, ORB engine, pipeline, and AutoScheduler
        </div>
      </div>

      {/* ── Tab bar ── */}
      <div style={{
        display: 'flex', gap: 0,
        background: 'var(--bg1)', borderBottom: '1px solid var(--border)',
        padding: '0 24px', flexShrink: 0,
      }}>
        {TABS.map(tab => (
          <button
            key={tab.key}
            onClick={() => setFilter('system', tab.key === 'all' ? '' : tab.key)}
            style={{
              padding: '10px 18px', fontSize: 13, fontWeight: 600,
              border: 'none',
              borderBottom: activeTab === tab.key
                ? '2px solid var(--cyan)'
                : '2px solid transparent',
              background: 'transparent', cursor: 'pointer',
              color: activeTab === tab.key ? 'var(--cyan)' : 'var(--text3)',
              fontFamily: 'var(--font-mono)', letterSpacing: '0.04em',
              transition: 'color 0.15s, border-color 0.15s',
            }}
          >
            {tab.label}
          </button>
        ))}
      </div>

      <div style={{ flex: 1, overflow: 'hidden', display: 'flex', flexDirection: 'column', minHeight: 0 }}>
        {/* ── Health Cards ── */}
        {health && (
          <div style={{ padding: '16px 24px 0', flexShrink: 0 }}>
            <HealthCards data={health} system={activeTab} />
          </div>
        )}

        {/* ── Filter bar ── */}
        <div style={{
          padding: '10px 24px', background: 'var(--bg1)', borderBottom: '1px solid var(--border)',
          display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap', flexShrink: 0,
        }}>
          {/* Time range */}
          <div style={{ display: 'flex', gap: 4 }}>
            {TIME_OPTIONS.map(opt => (
              <button
                key={opt.label}
                onClick={() => { setTimeLabel(opt.label); setFilter('since', opt.since()); }}
                style={{
                  padding: '4px 10px', borderRadius: 6, fontSize: 12, fontFamily: 'var(--font-mono)',
                  border: '1px solid var(--border)', cursor: 'pointer',
                  background: timeLabel === opt.label ? 'var(--cyan)' : 'var(--bg2)',
                  color: timeLabel === opt.label ? '#fff' : 'var(--text2)',
                }}
              >
                {opt.label}
              </button>
            ))}
          </div>

          <div style={{ width: 1, height: 20, background: 'var(--border)', flexShrink: 0 }} />

          <select value={filters.level} onChange={e => setFilter('level', e.target.value)} style={sel()}>
            {LEVEL_OPTIONS.map(l => <option key={l} value={l}>{l || 'All Levels'}</option>)}
          </select>

          <select value={filters.category} onChange={e => setFilter('category', e.target.value)} style={sel()}>
            {CAT_OPTIONS.map(c => <option key={c} value={c}>{c || 'All Categories'}</option>)}
          </select>

          <select value={filters.source} onChange={e => setFilter('source', e.target.value)} style={sel()}>
            <option value="">All Sources</option>
            {(sources ?? []).map(s => <option key={s} value={s}>{s}</option>)}
          </select>

          <input
            placeholder="Search…"
            value={filters.q}
            onChange={e => setFilter('q', e.target.value)}
            style={{
              padding: '5px 10px', borderRadius: 6, border: '1px solid var(--border)',
              background: 'var(--bg2)', color: 'var(--text2)', fontSize: 12,
              fontFamily: 'var(--font-mono)', outline: 'none', minWidth: 140,
            }}
          />

          <div style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 8 }}>
            <span style={{ fontSize: 12, color: 'var(--text3)', fontFamily: 'var(--font-mono)' }}>
              {total.toLocaleString()} events
            </span>
            <button
              onClick={() => { refetch(); refetchHealth(); }}
              title="Refresh"
              style={{
                display: 'flex', alignItems: 'center', gap: 5, padding: '5px 10px',
                borderRadius: 6, border: '1px solid var(--border)', background: 'var(--bg2)',
                cursor: 'pointer', color: 'var(--text2)', fontSize: 12,
              }}
            >
              <RefreshCw size={12} /> Refresh
            </button>
          </div>
        </div>

        {/* ── Table + Detail ── */}
        <div style={{ flex: 1, display: 'flex', overflow: 'hidden', minHeight: 0 }}>
          {/* Event table */}
          <div style={{ flex: 1, overflowY: 'auto', overflowX: 'auto', minHeight: 0 }}>
            {rows.length === 0 ? (
              <div style={{ padding: 40, textAlign: 'center', color: 'var(--text3)', fontSize: 14 }}>
                {isFetching ? 'Loading…' : 'No events match the current filters'}
              </div>
            ) : (
              <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
                <thead>
                  <tr style={{ background: 'var(--bg1)', borderBottom: '1px solid var(--border)' }}>
                    {['Time', 'Level', 'Category', 'Source', 'Event', 'Message', 'Session'].map(h => (
                      <th key={h} style={{
                        padding: '8px 12px', textAlign: 'left', fontSize: 11,
                        fontFamily: 'var(--font-mono)', color: 'var(--text3)',
                        letterSpacing: '0.06em', textTransform: 'uppercase',
                        position: 'sticky', top: 0, background: 'var(--bg1)',
                        borderBottom: '1px solid var(--border)', whiteSpace: 'nowrap',
                      }}>{h}</th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {rows.map(row => (
                    <tr
                      key={row.id}
                      onClick={() => setSelected(row.id === selected?.id ? null : row)}
                      style={{
                        cursor: 'pointer',
                        borderBottom: '1px solid var(--border)',
                        background: row.id === selected?.id
                          ? 'var(--cyan-dim)'
                          : row.level === 'ERROR' ? 'rgba(239,68,68,0.04)'
                          : row.level === 'WARN' ? 'rgba(234,179,8,0.04)'
                          : 'transparent',
                        transition: 'background 0.1s',
                      }}
                      onMouseEnter={e => { if (row.id !== selected?.id) (e.currentTarget as HTMLElement).style.background = 'var(--bg1)'; }}
                      onMouseLeave={e => { if (row.id !== selected?.id) (e.currentTarget as HTMLElement).style.background = row.level === 'ERROR' ? 'rgba(239,68,68,0.04)' : row.level === 'WARN' ? 'rgba(234,179,8,0.04)' : 'transparent'; }}
                    >
                      <td style={{ padding: '7px 12px', fontFamily: 'var(--font-mono)', color: 'var(--text3)', whiteSpace: 'nowrap' }}>
                        {fmtTs(row.ts_utc)}
                      </td>
                      <td style={{ padding: '7px 12px' }}>
                        <LevelPill level={row.level} />
                      </td>
                      <td style={{ padding: '7px 12px' }}>
                        <CatPill cat={row.category} />
                      </td>
                      <td style={{ padding: '7px 12px', fontFamily: 'var(--font-mono)', color: 'var(--text3)', fontSize: 11 }}>
                        {row.source}
                      </td>
                      <td style={{ padding: '7px 12px', fontFamily: 'var(--font-mono)', color: 'var(--text2)', maxWidth: 280, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                        {row.event_name}
                      </td>
                      <td style={{ padding: '7px 12px', color: 'var(--text2)', maxWidth: 320, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                        {row.message}
                      </td>
                      <td style={{ padding: '7px 12px', fontFamily: 'var(--font-mono)', color: 'var(--text3)', fontSize: 11, whiteSpace: 'nowrap' }}>
                        {row.session_id ?? '—'}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
          </div>

          {/* Detail panel */}
          {selected && (
            <DetailPanel
              event={selected}
              onClose={() => setSelected(null)}
              relatedEvents={relatedEvents}
            />
          )}
        </div>
      </div>
    </div>
  );
}
