// theme.jsx — Chrono design tokens, theme system, motion primitives

const ChronoTokens = {
  // Spacing (4pt grid)
  s: { 4: 4, 8: 8, 12: 12, 16: 16, 20: 20, 24: 24, 32: 32, 40: 40, 48: 48, 64: 64 },
  // Radii
  r: { sm: 8, card: 12, sheet: 16, modal: 24, pill: 9999 },
  // Type stacks
  font: {
    ui: '"Geist", "Inter", -apple-system, system-ui, sans-serif',
    display: '"Geist", "Inter Tight", -apple-system, system-ui, sans-serif',
    mono: '"JetBrains Mono", "SF Mono", ui-monospace, Menlo, monospace',
  },
  // Event palette (calibrated for dark glow)
  events: {
    blue:   { base: '#5B8DEF', glow: '#3D7BFF' },
    red:    { base: '#FF5C7A', glow: '#FF3859' },
    green:  { base: '#3DDC97', glow: '#1FCB85' },
    yellow: { base: '#F5C24A', glow: '#F0B22D' },
    purple: { base: '#A78BFA', glow: '#8B5CF6' },
    pink:   { base: '#F472B6', glow: '#EC4899' },
    orange: { base: '#FB923C', glow: '#F97316' },
    // Neutral fallback for uncategorized events (no matching category).
    grey:   { base: '#8A93A6', glow: '#6B7280' },
  },
  // Accent options
  accents: {
    indigo: '#6366F1',
    purple: '#8B5CF6',
    pink:   '#EC4899',
    orange: '#F97316',
    blue:   '#3B82F6',
    green:  '#10B981',
    red:    '#EF4444',
  },
};

// Build a full palette for a given mode + bg theme + accent
function buildPalette({ mode = 'dark', bg = 'default', accent = 'indigo', futurism = 'off' }) {
  // Futurism shifts accent to a higher-chroma electric indigo/cyan blend
  const accents = { ...ChronoTokens.accents };
  if (futurism !== 'off') {
    accents.indigo = '#5B7CFF';
    accents.purple = '#7B5BFF';
    accents.blue = '#3DA8FF';
  }
  const a = accents[accent] || accents.indigo;
  const isDark = mode === 'dark';
  const signal = futurism !== 'off' ? '#3DECFF' : (isDark ? '#A78BFA' : '#8B5CF6');

  let bg0, bg1, bg2, bg3, hairline, text, textDim, textFaint, glassBg, glassBorder, ambient;

  if (isDark) {
    if (bg === 'true-black') {
      bg0 = '#000000'; bg1 = '#0A0A0A'; bg2 = '#141414'; bg3 = '#1C1C1C';
    } else if (bg === 'midnight') {
      bg0 = '#070A14'; bg1 = '#0C1020'; bg2 = '#141A2E'; bg3 = '#1C2340';
    } else if (bg === 'gradient') {
      bg0 = '#0B0D17'; bg1 = '#11131F'; bg2 = '#191C2C'; bg3 = '#222637';
    } else { // default
      bg0 = '#0A0B10'; bg1 = '#10121A'; bg2 = '#181B26'; bg3 = '#222633';
    }
    hairline = 'rgba(255,255,255,0.06)';
    text = '#F2F3F8';
    textDim = '#A8ADBC';
    textFaint = '#5A6075';
    glassBg = 'rgba(22, 24, 34, 0.72)';
    glassBorder = 'rgba(255,255,255,0.08)';
    ambient = `radial-gradient(80% 50% at 50% 0%, ${a}22 0%, transparent 70%)`;
  } else {
    bg0 = '#F6F6F9';
    bg1 = '#FFFFFF';
    bg2 = '#FAFAFC';
    bg3 = '#F0F1F5';
    hairline = 'rgba(10,12,20,0.08)';
    text = '#0E1018';
    textDim = '#5A6075';
    textFaint = '#9AA0B0';
    glassBg = 'rgba(255,255,255,0.78)';
    glassBorder = 'rgba(10,12,20,0.06)';
    ambient = `radial-gradient(80% 50% at 50% 0%, ${a}14 0%, transparent 70%)`;
  }

  return {
    mode, bg, accent, accentColor: a, futurism, signal,
    bg0, bg1, bg2, bg3, hairline,
    text, textDim, textFaint,
    glassBg, glassBorder,
    ambient,
    // Computed accent variants
    accentSoft: `${a}22`,
    accentSofter: `${a}14`,
    accentGlow: isDark
      ? `0 0 24px ${a}66, 0 0 48px ${a}22`
      : `0 0 16px ${a}44`,
    isDark,
    tokens: ChronoTokens,
  };
}

// Spring-y animation helper — returns CSS transition value
const Spring = {
  // Standard
  std: 'cubic-bezier(0.34, 1.56, 0.64, 1)',
  // Smooth (no overshoot)
  smooth: 'cubic-bezier(0.4, 0.0, 0.2, 1)',
  // Snappy
  snap: 'cubic-bezier(0.22, 1, 0.36, 1)',
};

// Theme context
const ThemeCtx = React.createContext(null);
function useTheme() { return React.useContext(ThemeCtx); }

// Inject global font + base styles (once)
function ChronoGlobalStyles() {
  return (
    <style>{`
      @import url('https://fonts.googleapis.com/css2?family=Geist:wght@300;400;500;600;700;800;900&family=Inter+Tight:wght@400;500;600;700;800&family=JetBrains+Mono:wght@400;500;600&display=swap');

      @keyframes chrono-pulse {
        0%, 100% { opacity: 1; transform: scale(1); }
        50% { opacity: 0.85; transform: scale(1.03); }
      }
      @keyframes chrono-shimmer {
        0% { background-position: -200% 0; }
        100% { background-position: 200% 0; }
      }
      @keyframes chrono-rotate {
        to { transform: rotate(360deg); }
      }
      @keyframes chrono-fade-up {
        from { opacity: 0; transform: translateY(8px); }
        to { opacity: 1; transform: translateY(0); }
      }
      @keyframes chrono-fade-in {
        from { opacity: 0; }
        to { opacity: 1; }
      }
      @keyframes chrono-scale-in {
        from { opacity: 0; transform: scale(0.96); }
        to { opacity: 1; transform: scale(1); }
      }
      @keyframes chrono-blob {
        0%,100% { transform: translate(0,0) scale(1); }
        33% { transform: translate(30px,-20px) scale(1.1); }
        66% { transform: translate(-20px,20px) scale(0.95); }
      }
      @keyframes chrono-glow {
        0%, 100% { filter: brightness(1); }
        50% { filter: brightness(1.3); }
      }
      @keyframes chrono-stream-cursor {
        0%, 50% { opacity: 1; }
        51%, 100% { opacity: 0; }
      }
      @keyframes chrono-tick {
        from { transform: rotate(0); }
        to { transform: rotate(360deg); }
      }
      @keyframes chrono-orb-1 {
        0%,100% { transform: translate(-30%,-30%) scale(1); }
        50% { transform: translate(20%,10%) scale(1.4); }
      }
      @keyframes chrono-orb-2 {
        0%,100% { transform: translate(20%,30%) scale(1.2); }
        50% { transform: translate(-30%,-20%) scale(0.9); }
      }
      @keyframes chrono-now-ping {
        0% { transform: scale(1); opacity: 1; }
        100% { transform: scale(2.5); opacity: 0; }
      }
      @keyframes chrono-scan {
        0% { transform: translateY(-20%); opacity: 0; }
        15% { opacity: 1; }
        85% { opacity: 1; }
        100% { transform: translateY(120%); opacity: 0; }
      }
      @keyframes chrono-grid-drift {
        from { background-position: 0 0; }
        to { background-position: 40px 40px; }
      }
      @keyframes chrono-hud-blink {
        0%, 92%, 100% { opacity: 1; }
        94%, 98% { opacity: 0.3; }
      }
      @keyframes chrono-telemetry {
        0% { transform: translateX(0); }
        100% { transform: translateX(-50%); }
      }
      @keyframes chrono-corner-flicker {
        0%, 96%, 100% { opacity: 1; }
        97%, 99% { opacity: 0.55; }
      }
      @keyframes chrono-arc-spin {
        to { transform: rotate(360deg); }
      }
      @keyframes chrono-aurora {
        0%, 100% { transform: translate(0, 0) scale(1); }
        33% { transform: translate(40px, -30px) scale(1.1); }
        66% { transform: translate(-20px, 40px) scale(0.95); }
      }
      @keyframes chrono-spin {
        to { transform: rotate(360deg); }
      }
      @keyframes chrono-float {
        0%, 100% { transform: translateY(0px) rotate(0deg); }
        50% { transform: translateY(-12px) rotate(0.5deg); }
      }
      @keyframes chrono-page-in {
        from { opacity: 0; transform: translateY(8px) scale(0.985); filter: blur(4px); }
        to   { opacity: 1; transform: translateY(0) scale(1); filter: blur(0); }
      }
      @keyframes chrono-modal-in {
        from { opacity: 0; transform: scale(0.94) translateY(12px); filter: blur(6px); }
        to   { opacity: 1; transform: scale(1) translateY(0); filter: blur(0); }
      }
      @keyframes chrono-backdrop-in {
        from { opacity: 0; backdrop-filter: blur(0px); -webkit-backdrop-filter: blur(0px); }
        to   { opacity: 1; backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px); }
      }
      @keyframes chrono-sheen {
        0%   { transform: translateX(-130%) skewX(-20deg); }
        100% { transform: translateX(230%) skewX(-20deg); }
      }
      @keyframes chrono-stagger-up {
        from { opacity: 0; transform: translateY(6px); }
        to   { opacity: 1; transform: translateY(0); }
      }
      @keyframes chrono-pulse-ring {
        0%   { transform: scale(1); opacity: 0.7; }
        100% { transform: scale(1.7); opacity: 0; }
      }

      /* Page transition wrapper */
      .chrono-page { animation: chrono-page-in 360ms ${Spring.snap} both; }

      /* Enhanced tap/hover button class */
      .chrono-btn { position: relative; overflow: hidden; transition:
        transform 160ms ${Spring.snap},
        box-shadow 200ms ease,
        background-color 200ms ease,
        border-color 200ms ease,
        filter 200ms ease;
      }
      .chrono-btn:hover { transform: translateY(-1px); filter: brightness(1.06); }
      .chrono-btn:active { transform: translateY(0) scale(0.97); filter: brightness(0.95); }
      .chrono-btn::after {
        content: ''; position: absolute; inset: 0; pointer-events: none;
        background: linear-gradient(110deg, transparent 30%, rgba(255,255,255,0.35) 50%, transparent 70%);
        transform: translateX(-130%) skewX(-20deg);
        transition: transform 700ms ${Spring.snap};
      }
      .chrono-btn:hover::after { transform: translateX(230%) skewX(-20deg); }

      /* Sidebar item hover */
      .chrono-side { transition: background-color 180ms ease, color 180ms ease, transform 160ms ${Spring.snap}; }
      .chrono-side:hover { transform: translateX(2px); }

      /* Generic ring pulse on focus indicators */
      .chrono-ring { position: relative; }
      .chrono-ring::before {
        content: ''; position: absolute; inset: -3px; border-radius: inherit;
        border: 1.5px solid currentColor; opacity: 0;
        animation: chrono-pulse-ring 1.6s ease-out infinite;
      }

      .chrono-scrollbar::-webkit-scrollbar { width: 0; height: 0; }
      .chrono-scrollbar { scrollbar-width: none; }
      .chrono-tap { transition: transform 120ms ${Spring.snap}, opacity 120ms; }
      .chrono-tap:active { transform: scale(0.97); opacity: 0.85; }

      .chrono-fade-up > * { animation: chrono-fade-up 480ms ${Spring.snap} both; }
      .chrono-fade-up > *:nth-child(1) { animation-delay: 0ms; }
      .chrono-fade-up > *:nth-child(2) { animation-delay: 60ms; }
      .chrono-fade-up > *:nth-child(3) { animation-delay: 120ms; }
      .chrono-fade-up > *:nth-child(4) { animation-delay: 180ms; }
      .chrono-fade-up > *:nth-child(5) { animation-delay: 240ms; }
      .chrono-fade-up > *:nth-child(6) { animation-delay: 300ms; }
      .chrono-fade-up > *:nth-child(7) { animation-delay: 360ms; }
      .chrono-fade-up > *:nth-child(8) { animation-delay: 420ms; }
      .chrono-fade-up > *:nth-child(n+9) { animation-delay: 480ms; }
    `}</style>
  );
}

// Futuristic overlay — grid lattice, scan beam, corner brackets, mono telemetry HUD.
// Render INSIDE a positioned container; it absolutely fills.
function FuturisticLayer({ theme, intensity = 'subtle', telemetry, showScan = true }) {
  if (!theme.futurism || theme.futurism === 'off') return null;
  const full = intensity === 'full' || theme.futurism === 'full';
  const sig = theme.signal;

  return (
    <div style={{
      position: 'absolute', inset: 0, pointerEvents: 'none',
      zIndex: 5, overflow: 'hidden', mixBlendMode: 'normal',
    }}>
      {/* Vignetting scan beam (full intensity only) */}
      {showScan && full && (
        <div style={{
          position: 'absolute', left: 0, right: 0, top: 0, height: '40%',
          background: `linear-gradient(180deg, transparent 0%, ${sig}10 45%, ${sig}22 50%, ${sig}10 55%, transparent 100%)`,
          animation: 'chrono-scan 7s ease-in-out infinite',
        }}/>
      )}
    </div>
  );
}

// Telemetry HUD strip — a thin mono readout bar typically pinned to top or bottom of a screen.
function FuturisticHUD({ theme, items, position = 'top', style }) {
  if (!theme.futurism || theme.futurism === 'off') return null;
  const sig = theme.signal;
  const pos = position === 'top'
    ? { top: 0, left: 0, right: 0, borderBottom: `0.5px solid ${sig}30` }
    : { bottom: 0, left: 0, right: 0, borderTop: `0.5px solid ${sig}30` };

  return (
    <div style={{
      position: 'absolute', ...pos, height: 18, zIndex: 4,
      display: 'flex', alignItems: 'center', gap: 14,
      padding: '0 12px', pointerEvents: 'none',
      background: theme.isDark
        ? `linear-gradient(90deg, transparent, ${sig}08, transparent)`
        : `linear-gradient(90deg, transparent, ${theme.accentColor}06, transparent)`,
      fontFamily: ChronoTokens.font.mono, fontSize: 9, fontWeight: 500,
      letterSpacing: '0.14em', textTransform: 'uppercase',
      color: theme.isDark ? `${sig}CC` : theme.accentColor,
      ...style,
    }}>
      {items.map((it, i) => (
        <span key={i} style={{
          display: 'inline-flex', alignItems: 'center', gap: 6,
          animation: it.blink ? 'chrono-hud-blink 3.5s ease-in-out infinite' : 'none',
        }}>
          {it.dot && (
            <span style={{
              width: 5, height: 5, borderRadius: '50%',
              background: it.dot === 'sig' ? sig : (it.dot === 'warn' ? '#F0B22D' : theme.accentColor),
              boxShadow: `0 0 6px ${it.dot === 'sig' ? sig : theme.accentColor}`,
            }}/>
          )}
          {it.label}
        </span>
      ))}
    </div>
  );
}

Object.assign(window, { ChronoTokens, buildPalette, Spring, ThemeCtx, useTheme, ChronoGlobalStyles, FuturisticLayer, FuturisticHUD });
