// Cybergard AI — main app: timeline assembly, tweaks, root

const DEFAULT_TWEAKS = /*EDITMODE-BEGIN*/{
  "accent": "oklch(0.62 0.21 25)",
  "headline": "AUDIT CONTINU PILOTÉ PAR IA",
  "speed": 1.0,
  "showLogoFlash": true
}/*EDITMODE-END*/;

const BASE_DURATION = 14; // seconds total loop

function usePortrait() {
  const [portrait, setPortrait] = React.useState(() =>
    typeof window !== 'undefined'
      ? window.matchMedia('(max-aspect-ratio: 1/1)').matches
      : false
  );
  React.useEffect(() => {
    const mq = window.matchMedia('(max-aspect-ratio: 1/1)');
    const on = () => setPortrait(mq.matches);
    mq.addEventListener ? mq.addEventListener('change', on) : mq.addListener(on);
    return () => {
      mq.removeEventListener ? mq.removeEventListener('change', on) : mq.removeListener(on);
    };
  }, []);
  return portrait;
}

const FR_COPY = {
  headers: ['CONTRÔLE', 'STATUT', 'OWNER', 'RISQUE'],
  title: "DES SEMAINES D'AUDIT MANUEL",
  bottomStrip: '114 CONTRÔLES · 37 DOMAINES · 0 AUTOMATION',
  liveTag: 'AUDIT CONTINU',
  scoreLabel: 'SCORE CONFORMITÉ',
  overallLabel: 'CONFORMITÉ GLOBALE',
  certified: 'Seuil certifiable atteint.',
  analyzing: 'Analyse en cours…',
  in4h: 'EN 4H',
  frameworks: [
    { name: 'ISO 27001', sub: '114 CONTRÔLES',  activate: 1.0 },
    { name: 'NIS2',      sub: 'DIRECTIVE UE',    activate: 1.4 },
    { name: 'DORA',      sub: 'RÉSILIENCE OPS',  activate: 1.8 },
    { name: 'CIS V8',    sub: '18 MESURES',      activate: 2.2 },
  ],
  rag: {
    title: 'ASSISTANT RAG · CYBERGARD',
    lines: [
      { who: 'rssi', text: 'Statut contrôle A.8.9 ?', delay: 0 },
      { who: 'ai',   text: 'Config : 94%. 3 serveurs hors baseline CIS.', delay: 0.3 },
      { who: 'ai',   text: "→ Plan d'action généré · EBIOS RM à jour", delay: 0.7 },
    ],
  },
  feed: {
    title: 'CONTRÔLES · TEMPS RÉEL',
    controls: [
      { id: 'A.5.23', name: 'Sécurité services cloud', status: 'OK' },
      { id: 'A.8.9',  name: 'Gestion configuration',   status: 'OK' },
      { id: 'A.8.28', name: 'Codage sécurisé',         status: 'OK' },
      { id: 'A.5.30', name: 'Préparation TIC',         status: 'OK' },
      { id: 'A.8.16', name: 'Surveillance activités',  status: 'OK' },
      { id: 'A.6.3',  name: 'Sensibilisation',         status: 'OK' },
      { id: 'A.8.2',  name: "Droits d'accès",          status: 'OK' },
    ],
  },
};

function CybergardHero() {
  const [tweaks, setTweaks] = React.useState(DEFAULT_TWEAKS);
  const [tweaksOpen, setTweaksOpen] = React.useState(false);
  const portrait = usePortrait();

  // Inject accent override into CG palette at runtime
  React.useEffect(() => {
    if (tweaks.accent && tweaks.accent !== CG.crimson) {
      // Allow full override
      CG.crimson = tweaks.accent;
    }
  }, [tweaks.accent]);

  // Tweaks edit-mode wiring
  React.useEffect(() => {
    const onMessage = (e) => {
      if (e.data?.type === '__activate_edit_mode') setTweaksOpen(true);
      if (e.data?.type === '__deactivate_edit_mode') setTweaksOpen(false);
    };
    window.addEventListener('message', onMessage);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', onMessage);
  }, []);

  const updateTweak = (key, value) => {
    setTweaks(prev => ({ ...prev, [key]: value }));
    window.parent.postMessage({
      type: '__edit_mode_set_keys',
      edits: { [key]: value },
    }, '*');
  };

  const duration = BASE_DURATION / tweaks.speed;

  // Scene timings (scaled by speed)
  const s1 = [0, 3.6 / tweaks.speed];              // Excel
  const s2 = [3.2 / tweaks.speed, 4.8 / tweaks.speed]; // Transition (overlap)
  const s3 = [4.4 / tweaks.speed, duration];       // Dashboard (runs till end)

  return (
    <>
      <Stage
        width={portrait ? 1080 : 1920}
        height={portrait ? 1920 : 1080}
        duration={duration}
        background={CG.bg}
        persistKey="cybergard-hero"
      >
        <div style={{
          position: 'absolute', inset: 0,
          background: `radial-gradient(ellipse at 50% 50%, ${CG.bg} 0%, ${CG.bgDeep} 100%)`,
        }}/>
        <GridBackdrop opacity={0.35}/>
        <AmbientGlow
          x={portrait ? 540 : 960}
          y={portrait ? 960 : 540}
          size={portrait ? 1200 : 1400}
          intensity={0.15}
        />

        {portrait ? (
          <>
            <PortraitExcel start={s1[0]} end={s1[1]} copy={FR_COPY}/>
            <Transition start={s2[0]} end={s2[1]}/>
            <PortraitDashboard start={s3[0]} end={s3[1]} headline={tweaks.headline} copy={FR_COPY}/>
          </>
        ) : (
          <>
            <ExcelChaos start={s1[0]} end={s1[1]}/>
            <Transition start={s2[0]} end={s2[1]}/>
            <AIDashboard start={s3[0]} end={s3[1]} headline={tweaks.headline}/>
          </>
        )}

        {/* Scan line */}
        <ScanLine/>
        {/* Vignette */}
        <div style={{
          position: 'absolute', inset: 0,
          background: 'radial-gradient(ellipse at center, transparent 55%, rgba(0,0,0,0.55) 100%)',
          pointerEvents: 'none',
        }}/>
        {/* Timestamp label (for comments) */}
        <TimestampLabel/>
      </Stage>

      {tweaksOpen && (
        <TweaksPanel tweaks={tweaks} onChange={updateTweak}/>
      )}
    </>
  );
}

// ── Scan line (subtle CRT effect) ──────────────────────────────────────────
function ScanLine() {
  const t = useTime();
  const y = ((t * 120) % 1200) - 100;
  return (
    <div style={{
      position: 'absolute',
      left: 0, right: 0,
      top: y,
      height: 140,
      background: `linear-gradient(180deg, transparent 0%, ${CG.crimsonTint} 50%, transparent 100%)`,
      opacity: 0.15,
      pointerEvents: 'none',
      mixBlendMode: 'screen',
    }}/>
  );
}

function TimestampLabel() {
  const t = useTime();
  const sec = Math.floor(t);
  const stage = useTimeline();
  React.useEffect(() => {
    const root = document.querySelector('[data-video-root]');
    if (root) root.setAttribute('data-screen-label', `t=${sec}s`);
  }, [sec]);
  return null;
}

// ── Tweaks panel ───────────────────────────────────────────────────────────
function TweaksPanel({ tweaks, onChange }) {
  const accents = [
    { label: 'Crimson (brand)', value: 'oklch(0.62 0.21 25)' },
    { label: 'Deep red',        value: 'oklch(0.55 0.23 15)' },
    { label: 'Rose',            value: 'oklch(0.68 0.19 10)' },
    { label: 'Amber',           value: 'oklch(0.72 0.18 60)' },
    { label: 'Teal',            value: 'oklch(0.68 0.14 180)' },
  ];

  return (
    <div style={{
      position: 'fixed',
      right: 16, bottom: 64,
      width: 300,
      padding: 18,
      background: 'rgba(18,18,22,0.96)',
      border: `1px solid ${CG.line}`,
      borderRadius: 12,
      boxShadow: '0 20px 60px rgba(0,0,0,0.6)',
      backdropFilter: 'blur(12px)',
      fontFamily: FONT_BODY,
      color: CG.text,
      zIndex: 1000,
    }}>
      <div style={{
        fontFamily: FONT_TITLE, fontSize: 13, fontWeight: 700,
        letterSpacing: '0.22em', color: CG.crimsonSoft,
        marginBottom: 14,
      }}>TWEAKS</div>

      <Row label="ACCENT">
        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
          {accents.map(a => (
            <button
              key={a.value}
              onClick={() => onChange('accent', a.value)}
              title={a.label}
              style={{
                width: 28, height: 28,
                background: a.value,
                border: tweaks.accent === a.value
                  ? `2px solid ${CG.text}` : `1px solid ${CG.line}`,
                borderRadius: 6,
                cursor: 'pointer',
                padding: 0,
              }}
            />
          ))}
        </div>
      </Row>

      <Row label="VITESSE">
        <input
          type="range" min="0.5" max="2" step="0.1"
          value={tweaks.speed}
          onChange={e => onChange('speed', parseFloat(e.target.value))}
          style={{ width: '100%' }}
        />
        <div style={{
          fontFamily: FONT_MONO, fontSize: 11,
          color: CG.mute, marginTop: 4,
        }}>{tweaks.speed.toFixed(1)}×</div>
      </Row>

      <Row label="HEADLINE">
        <input
          type="text"
          value={tweaks.headline}
          onChange={e => onChange('headline', e.target.value)}
          style={{
            width: '100%',
            padding: '8px 10px',
            background: CG.panel,
            border: `1px solid ${CG.line}`,
            borderRadius: 6,
            color: CG.text,
            fontFamily: FONT_BODY,
            fontSize: 13,
            boxSizing: 'border-box',
          }}
        />
      </Row>

      <div style={{
        marginTop: 10,
        fontFamily: FONT_MONO, fontSize: 10,
        color: CG.mute, letterSpacing: '0.12em',
      }}>
        Space = play/pause · ←/→ = seek
      </div>
    </div>
  );
}

function Row({ label, children }) {
  return (
    <div style={{ marginBottom: 14 }}>
      <div style={{
        fontFamily: FONT_MONO, fontSize: 10,
        color: CG.mute, letterSpacing: '0.18em',
        marginBottom: 6,
      }}>{label}</div>
      {children}
    </div>
  );
}

Object.assign(window, { CybergardHero });
