// Cybergard AI — hero loop scenes
// Palette, helpers, and scene components. Loads after animations.jsx.

const CG = {
  bg:        'oklch(0.14 0.012 250)',
  bgDeep:    'oklch(0.10 0.012 250)',
  panel:     'oklch(0.18 0.014 250)',
  panelHi:   'oklch(0.22 0.014 250)',
  line:      'oklch(0.28 0.012 250)',
  mute:      'oklch(0.52 0.010 250)',
  text:      'oklch(0.94 0.008 250)',
  dim:       'oklch(0.72 0.010 250)',
  crimson:   'oklch(0.62 0.21 25)',
  crimsonSoft: 'oklch(0.72 0.16 25)',
  crimsonGlow: 'oklch(0.62 0.21 25 / 0.55)',
  crimsonTint: 'oklch(0.62 0.21 25 / 0.12)',
  ok:        'oklch(0.78 0.14 25)',
};

const FONT_TITLE = "'Orbitron', 'Arial Black', sans-serif";
const FONT_BODY  = "'Syne', 'Helvetica Neue', sans-serif";
const FONT_MONO  = "'JetBrains Mono', ui-monospace, monospace";

// ── Grid backdrop ───────────────────────────────────────────────────────────
function GridBackdrop({ opacity = 0.5 }) {
  const t = useTime();
  // subtle drift
  const shift = (t * 8) % 40;
  return (
    <div style={{
      position: 'absolute', inset: 0,
      backgroundImage:
        `linear-gradient(${CG.line} 1px, transparent 1px),
         linear-gradient(90deg, ${CG.line} 1px, transparent 1px)`,
      backgroundSize: '40px 40px',
      backgroundPosition: `${shift}px ${shift}px`,
      opacity,
      maskImage: 'radial-gradient(ellipse at center, #000 30%, transparent 75%)',
      WebkitMaskImage: 'radial-gradient(ellipse at center, #000 30%, transparent 75%)',
    }}/>
  );
}

// ── Soft crimson ambient glow ───────────────────────────────────────────────
function AmbientGlow({ x = 960, y = 540, size = 900, intensity = 0.6 }) {
  return (
    <div style={{
      position: 'absolute',
      left: x - size/2, top: y - size/2,
      width: size, height: size,
      background: `radial-gradient(circle, ${CG.crimson} 0%, transparent 60%)`,
      opacity: intensity,
      filter: 'blur(40px)',
      pointerEvents: 'none',
    }}/>
  );
}

// ── Scene 1: Excel chaos ────────────────────────────────────────────────────
// A dense Excel-style grid. Cells flash red. Title fades in.

function ExcelChaos({ start, end }) {
  return (
    <Sprite start={start} end={end}>
      {({ localTime, duration, progress }) => {
        // Grid layout: 8 cols x 14 rows
        const cols = 8, rows = 14;
        const cellW = 160, cellH = 44;
        const gridW = cols * cellW;
        const gridH = rows * cellH;
        const gx = (1920 - gridW) / 2;
        const gy = 180;

        // Deterministic "red cells" schedule
        const redCells = [
          { r: 1, c: 3, t: 0.3 },
          { r: 2, c: 6, t: 0.5 },
          { r: 4, c: 1, t: 0.7 },
          { r: 5, c: 5, t: 0.9 },
          { r: 7, c: 2, t: 1.1 },
          { r: 8, c: 7, t: 1.3 },
          { r: 10, c: 4, t: 1.5 },
          { r: 11, c: 0, t: 1.7 },
          { r: 12, c: 6, t: 1.9 },
          { r: 3, c: 4, t: 2.1 },
          { r: 6, c: 3, t: 2.3 },
          { r: 9, c: 1, t: 2.5 },
        ];

        const exitFade = localTime > duration - 0.7
          ? clamp((localTime - (duration - 0.7)) / 0.7, 0, 1)
          : 0;

        const enterFade = Easing.easeOutCubic(clamp(localTime / 0.6, 0, 1));
        const shake = localTime > 2.4 ? Math.sin(localTime * 30) * clamp((localTime - 2.4) * 3, 0, 2) : 0;

        return (
          <div style={{
            position: 'absolute', inset: 0,
            opacity: enterFade * (1 - exitFade),
            transform: `translateX(${shake}px) scale(${1 - exitFade * 0.08})`,
          }}>
            {/* Title */}
            <div style={{
              position: 'absolute', top: 80, left: 0, right: 0,
              textAlign: 'center',
              fontFamily: FONT_MONO,
              fontSize: 13,
              color: CG.mute,
              letterSpacing: '0.3em',
              textTransform: 'uppercase',
            }}>
              audit_iso27001.xlsx &nbsp;·&nbsp; v47_FINAL_final.xlsx
            </div>
            <div style={{
              position: 'absolute', top: 108, left: 0, right: 0,
              textAlign: 'center',
              fontFamily: FONT_TITLE,
              fontSize: 44,
              fontWeight: 700,
              color: CG.text,
              letterSpacing: '0.02em',
            }}>
              DES SEMAINES D'AUDIT MANUEL
            </div>

            {/* Grid */}
            <div style={{
              position: 'absolute',
              left: gx, top: gy,
              width: gridW, height: gridH,
              background: CG.panel,
              border: `1px solid ${CG.line}`,
              boxShadow: '0 40px 80px rgba(0,0,0,0.5)',
            }}>
              {/* Header row */}
              <div style={{
                position: 'absolute', top: 0, left: 0, right: 0,
                height: cellH,
                background: CG.panelHi,
                borderBottom: `1px solid ${CG.line}`,
                display: 'flex',
              }}>
                {['CONTRÔLE', 'DOMAINE', 'STATUT', 'PREUVE', 'OWNER', 'ÉCHÉANCE', 'RISQUE', 'NOTES'].map((h, i) => (
                  <div key={i} style={{
                    width: cellW,
                    padding: '0 14px',
                    display: 'flex', alignItems: 'center',
                    fontFamily: FONT_MONO,
                    fontSize: 11,
                    color: CG.dim,
                    letterSpacing: '0.1em',
                    borderRight: `1px solid ${CG.line}`,
                  }}>{h}</div>
                ))}
              </div>

              {/* Body cells */}
              {Array.from({ length: rows - 1 }).map((_, r) =>
                Array.from({ length: cols }).map((_, c) => {
                  const cellText = c === 0
                    ? `A.${5 + (r % 9)}.${1 + ((r * 3 + c) % 12)}`
                    : c === 2
                    ? ['—', 'OK', '?', '—', 'KO'][(r + c) % 5]
                    : c === 6
                    ? ['Faible', 'Moyen', 'Élevé', '—'][(r * 2) % 4]
                    : '··········'.slice(0, 4 + ((r * c + r) % 7));

                  const red = redCells.find(rc => rc.r === r && rc.c === c);
                  const isRed = red && localTime > red.t;
                  const flashIntensity = isRed
                    ? clamp((localTime - red.t) / 0.25, 0, 1)
                    : 0;

                  return (
                    <div key={`${r}-${c}`} style={{
                      position: 'absolute',
                      top: cellH * (r + 1),
                      left: cellW * c,
                      width: cellW, height: cellH,
                      padding: '0 14px',
                      display: 'flex', alignItems: 'center',
                      borderRight: `1px solid ${CG.line}`,
                      borderBottom: `1px solid ${CG.line}`,
                      fontFamily: c === 0 || c === 2 ? FONT_MONO : FONT_BODY,
                      fontSize: c === 0 ? 12 : 13,
                      color: isRed ? CG.crimsonSoft : (c === 2 ? CG.mute : CG.dim),
                      background: isRed
                        ? `oklch(0.62 0.21 25 / ${flashIntensity * 0.22})`
                        : 'transparent',
                      boxShadow: isRed ? `inset 0 0 0 1px ${CG.crimson}` : 'none',
                      transition: 'none',
                    }}>
                      {cellText}
                    </div>
                  );
                })
              )}
            </div>

            {/* Stat strip bottom */}
            <div style={{
              position: 'absolute',
              bottom: 80, left: 0, right: 0,
              textAlign: 'center',
              fontFamily: FONT_MONO,
              fontSize: 14,
              color: CG.mute,
              letterSpacing: '0.18em',
            }}>
              114 CONTRÔLES &nbsp;·&nbsp; 37 DOMAINES &nbsp;·&nbsp; 0 AUTOMATION
            </div>
          </div>
        );
      }}
    </Sprite>
  );
}

// ── Scene 2: Transition — cells detach and reorganize ───────────────────────
function Transition({ start, end }) {
  return (
    <Sprite start={start} end={end}>
      {({ progress, localTime, duration }) => {
        const p = Easing.easeInOutCubic(progress);
        // Cells flying from grid positions to node grid positions
        const NODES = 24;
        const cells = Array.from({ length: NODES }).map((_, i) => {
          const startCol = i % 8;
          const startRow = Math.floor(i / 8) + 1;
          const sx = 320 + startCol * 160;
          const sy = 180 + startRow * 44;

          const nCols = 6;
          const ncol = i % nCols;
          const nrow = Math.floor(i / nCols);
          const ex = 560 + ncol * 140;
          const ey = 340 + nrow * 100;

          const delay = (i / NODES) * 0.4;
          const localP = clamp((p - delay) / (1 - delay), 0, 1);
          const eased = Easing.easeInOutCubic(localP);

          const x = sx + (ex - sx) * eased;
          const y = sy + (ey - sy) * eased;
          const scale = 1 + eased * 0.2 * Math.sin(eased * Math.PI);
          const w = 140 - eased * 80;
          const h = 44 - eased * 20;

          return { x, y, w, h, scale, localP };
        });

        return (
          <div style={{ position: 'absolute', inset: 0 }}>
            {/* Fading crimson sweep */}
            <div style={{
              position: 'absolute', inset: 0,
              background: `radial-gradient(circle at 50% 50%, ${CG.crimsonTint} 0%, transparent 60%)`,
              opacity: Math.sin(progress * Math.PI),
            }}/>

            {cells.map((c, i) => (
              <div key={i} style={{
                position: 'absolute',
                left: c.x, top: c.y,
                width: c.w, height: c.h,
                background: `oklch(0.22 0.014 250 / ${0.6 + c.localP * 0.4})`,
                border: `1px solid ${c.localP > 0.5 ? CG.crimson : CG.line}`,
                borderRadius: 4 + c.localP * 4,
                boxShadow: c.localP > 0.5
                  ? `0 0 ${c.localP * 20}px ${CG.crimsonGlow}`
                  : 'none',
                transform: `scale(${c.scale})`,
              }}/>
            ))}

            <div style={{
              position: 'absolute', top: 540, left: 0, right: 0,
              textAlign: 'center',
              fontFamily: FONT_MONO,
              fontSize: 13,
              color: CG.crimsonSoft,
              letterSpacing: '0.3em',
              opacity: Math.sin(progress * Math.PI),
            }}>
              &gt; INITIALISATION AUDIT CONTINU
            </div>
          </div>
        );
      }}
    </Sprite>
  );
}

Object.assign(window, { CG, FONT_TITLE, FONT_BODY, FONT_MONO, GridBackdrop, AmbientGlow, ExcelChaos, Transition });
