"use client";

import { useEffect, useState, type ReactNode } from "react";

type CarModel = {
  width: number;
  body: string;
  window: string;
  wheels: Array<{ cx: number; r: number; rInner: number }>;
  frontLight: { cx: number; cyTop: number; cyBot: number };
  rearLight: { cx: number; cy: number };
};

type CarPalette = {
  body: string;
  window: string;
};

function pickRandom<T>(arr: T[]): T {
  return arr[Math.floor(Math.random() * arr.length)];
}

/**
 * Piéton d'ambiance qui traverse la scène. Le composant est purement décoratif
 * (positionnement + animation via CSS .mf-walker--N). Les animations CSS ne
 * démarrent qu'après le lever de soleil (delay ≥ 11s), donc invisibles la nuit.
 */
function Walker({ slot }: { slot: 1 | 2 | 3 | 4 }) {
  return (
    <g className={`mf-walker mf-walker--${slot}`}>
      <g className="mf-walker__bob">
        <circle cx="0" cy="-58" r="5" fill="#d4ccb6" stroke="#1a1c2c" strokeWidth="0.5" />
        <path d="M-4,-50 L4,-50 L6,-25 L-6,-25 Z" fill="#a89e83" stroke="#1a1c2c" strokeWidth="0.5" />
        <line x1="-3" y1="-46" x2="-7" y2="-28" stroke="#a89e83" strokeWidth="2.6" strokeLinecap="round" />
        <line x1="3" y1="-46" x2="7" y2="-28" stroke="#a89e83" strokeWidth="2.6" strokeLinecap="round" />
        <g className="mf-walker__legs">
          <line x1="-2" y1="-25" x2="-4" y2="0" stroke="#7a7160" strokeWidth="3" strokeLinecap="round" />
          <line x1="2" y1="-25" x2="4" y2="0" stroke="#7a7160" strokeWidth="3" strokeLinecap="round" />
        </g>
      </g>
    </g>
  );
}

/**
 * Une voiture aléatoire (modèle + couleur), re-tirée à chaque cycle d'animation.
 * Toutes les formes sont dessinées avec l'avant à droite (cx croissant) ;
 * pour les voies droite→gauche on applique un flip horizontal sur le sous-<g>.
 *
 * `lane` détermine l'orientation du cône de phares :
 *  - "back"  → voitures du fond, faisceau évasé vers le haut de l'écran
 *  - "front" → voitures de devant, faisceau évasé vers le bas (vers le sol proche)
 *
 * `animationDelay` aléatoire (négatif) au mount → chaque voiture démarre à une
 * phase différente de son cycle, l'effet est un trafic non-synchronisé.
 */
function Car({
  slot,
  direction,
  lane,
}: {
  slot: 1 | 2 | 3 | 4;
  direction: "rtl" | "ltr";
  lane: "back" | "front";
}) {
  const [model, setModel] = useState<CarModel>(CAR_MODELS[0]);
  const [palette, setPalette] = useState<CarPalette>(CAR_PALETTES[0]);
  const [delaySec, setDelaySec] = useState(0);

  // Two-pass render : init déterministe au SSR, randomisation après hydratation.
  useEffect(() => {
    // eslint-disable-next-line react-hooks/set-state-in-effect
    setModel(pickRandom(CAR_MODELS));
    setPalette(pickRandom(CAR_PALETTES));
    setDelaySec(-Math.random() * 6);
  }, []);

  // L'event animationiteration bubble depuis les enfants. On filtre sur le nom
  // de l'animation du slot pour ne re-tirer qu'à la fin d'un vrai cycle (6s).
  const reroll = (e: React.AnimationEvent<SVGGElement>) => {
    if (e.animationName !== `mf-car-${slot}`) return;
    setModel(pickRandom(CAR_MODELS));
    setPalette(pickRandom(CAR_PALETTES));
  };

  const flip =
    direction === "rtl"
      ? `scale(-1, 1) translate(-${model.width}, 0)`
      : undefined;

  // Cône : pointe au phare, base à 310px devant. La base reste sur la chaussée
  // qui correspond à la voie : back occupe y∈[780, 815] (bord haut de la route),
  // front occupe y∈[793, 878] (s'étend vers le sol proche).
  const beamFarX = model.width + 310;
  const beamTopY = lane === "back" ? 782 : 793;
  const beamBotY = lane === "back" ? 815 : 878;
  const beamPath = `M ${model.frontLight.cx + 2},${model.frontLight.cyTop - 1} L ${beamFarX},${beamTopY} L ${beamFarX},${beamBotY} L ${model.frontLight.cx + 2},${model.frontLight.cyBot + 2} Z`;

  return (
    <g
      className={`mf-car mf-car--${slot}`}
      style={{ animationDelay: `${delaySec}s` }}
      onAnimationIteration={reroll}
    >
      <g transform={flip}>
        {/* Cône de phares : trapèze partant des deux phares, orientation selon la voie */}
        <path
          className="mf-car__beam"
          d={beamPath}
          fill="url(#mfBeam)"
          filter="url(#mfBeamBlur)"
        />
        <path d={model.body} fill={palette.body} />
        <path d={model.window} fill={palette.window} />
        <circle
          cx={model.frontLight.cx}
          cy={model.frontLight.cyTop}
          r={3}
          fill="#fff7c2"
        />
        <circle
          cx={model.frontLight.cx - 2}
          cy={model.frontLight.cyBot}
          r={2.5}
          fill="#ffe27a"
        />
        <circle
          cx={model.rearLight.cx}
          cy={model.rearLight.cy}
          r={2.5}
          fill="#c0392b"
        />
        {model.wheels.map((w, i) => (
          <g key={i}>
            <circle cx={w.cx} cy={805} r={w.r} fill="#0a0c1f" />
            <circle cx={w.cx} cy={805} r={w.rInner} fill="#2a2e4d" />
          </g>
        ))}
      </g>
    </g>
  );
}

/**
 * Scène d'accueil animée. Choreographie ~6s :
 *   nuit → voiture passe → piéton arrive → tire la ficelle → soleil → modal.
 * `prefers-reduced-motion` : on saute direct au modal sur fond aurore statique.
 */
export function LoginScene({ children }: { children: ReactNode }) {
  const [modalReady, setModalReady] = useState(false);

  useEffect(() => {
    const reduced = window.matchMedia(
      "(prefers-reduced-motion: reduce)",
    ).matches;
    const delay = reduced ? 0 : 10500;
    const t = window.setTimeout(() => setModalReady(true), delay);
    return () => window.clearTimeout(t);
  }, []);

  return (
    <div className="mf-scene" aria-hidden={false}>
      <svg
        className="mf-scene__svg"
        viewBox="0 0 1600 900"
        preserveAspectRatio="xMidYMax slice"
        role="img"
        aria-label="Scène d'accueil animée : une ville la nuit, un piéton allume le soleil"
      >
        <defs>
          {/* Ciel nuit */}
          <linearGradient id="mfSkyNight" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="#080a1f" />
            <stop offset="55%" stopColor="#11163a" />
            <stop offset="100%" stopColor="#1d1f4a" />
          </linearGradient>
          {/* Ciel sunrise (overlay qui fade-in) */}
          <linearGradient id="mfSkyDawn" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="#2b1b54" />
            <stop offset="35%" stopColor="#7d3a76" />
            <stop offset="65%" stopColor="#e96a4e" />
            <stop offset="90%" stopColor="#f6b06b" />
            <stop offset="100%" stopColor="#fde2b3" />
          </linearGradient>
          {/* Halo du soleil/ampoule */}
          <radialGradient id="mfSunGlow" cx="0.5" cy="0.5" r="0.5">
            <stop offset="0%" stopColor="#fff5d0" stopOpacity="1" />
            <stop offset="40%" stopColor="#ffce6a" stopOpacity="0.85" />
            <stop offset="75%" stopColor="#ff9b54" stopOpacity="0.35" />
            <stop offset="100%" stopColor="#ff9b54" stopOpacity="0" />
          </radialGradient>
          {/* Phares de la voiture (halo radial, conservé pour d'éventuels usages) */}
          <radialGradient id="mfHeadlight" cx="0.5" cy="0.5" r="0.5">
            <stop offset="0%" stopColor="#fff7c2" stopOpacity="0.9" />
            <stop offset="100%" stopColor="#fff7c2" stopOpacity="0" />
          </radialGradient>
          {/* Cône de phares : intense près de la source, fade en s'éloignant */}
          <linearGradient id="mfBeam" x1="0" y1="0" x2="1" y2="0">
            <stop offset="0%" stopColor="#fff7c2" stopOpacity="0.85" />
            <stop offset="60%" stopColor="#fff7c2" stopOpacity="0.25" />
            <stop offset="100%" stopColor="#fff7c2" stopOpacity="0" />
          </linearGradient>
          {/* Flou pour adoucir les bords du cône (sinon arête trop nette) */}
          <filter id="mfBeamBlur" x="-10%" y="-10%" width="120%" height="120%">
            <feGaussianBlur stdDeviation="4" />
          </filter>
        </defs>

        {/* Calques de ciel : nuit en dessous, sunrise par-dessus avec opacité animée */}
        <rect x="0" y="0" width="1600" height="900" fill="url(#mfSkyNight)" />
        <rect
          className="mf-sky-dawn"
          x="0"
          y="0"
          width="1600"
          height="900"
          fill="url(#mfSkyDawn)"
        />

        {/* Étoiles (g pour fade collectif) */}
        <g className="mf-stars" fill="#ffffff">
          {STAR_POSITIONS.map(([cx, cy, r, op], i) => (
            <circle
              key={i}
              cx={cx}
              cy={cy}
              r={r}
              opacity={op}
              style={{ animationDelay: `${(i % 6) * 0.3}s` }}
              className="mf-star"
            />
          ))}
        </g>

        {/* Lune (croissant : intersection de deux disques de rayon 46, centres C1=(1320,200) et C2=(1340,190)) */}
        <g className="mf-moon">
          <path
            d="M 1310.04 155.09 A 46 46 0 1 0 1349.96 234.91 A 46 46 0 0 1 1310.04 155.09 Z"
            fill="#f0e7d8"
          />
        </g>

        {/* Skyline arrière (montagnes / collines lointaines) */}
        <path
          className="mf-skyline mf-skyline--far"
          d="M0,700 L0,640 L80,610 L160,625 L240,580 L340,605 L430,560 L520,590 L640,540 L760,575 L880,545 L990,580 L1100,535 L1220,565 L1340,520 L1450,555 L1600,540 L1600,700 Z"
        />

        {/* Skyline mi-distance (immeubles flous) */}
        <path
          className="mf-skyline mf-skyline--mid"
          d="M0,700 L0,520 L60,520 L60,460 L130,460 L130,500 L210,500 L210,440 L280,440 L280,480 L360,480 L360,420 L440,420 L440,470 L520,470 L520,500 L600,500 L600,450 L680,450 L680,490 L760,490 L760,430 L840,430 L840,475 L920,475 L920,460 L1000,460 L1000,510 L1080,510 L1080,450 L1160,450 L1160,485 L1240,485 L1240,440 L1320,440 L1320,505 L1400,505 L1400,470 L1480,470 L1480,500 L1560,500 L1560,460 L1600,460 L1600,700 Z"
        />

        {/* Skyline avant (immeubles principaux + fenêtres qui s'allument) */}
        <g className="mf-skyline mf-skyline--front">
          {/* Buildings (silhouettes) */}
          <path d="M0,730 L0,420 L90,420 L90,370 L180,370 L180,420 L260,420 L260,330 L380,330 L380,400 L470,400 L470,360 L560,360 L560,310 L660,310 L660,380 L760,380 L760,340 L860,340 L860,300 L970,300 L970,355 L1080,355 L1080,395 L1180,395 L1180,335 L1290,335 L1290,375 L1390,375 L1390,330 L1490,330 L1490,400 L1600,400 L1600,730 Z" />
          {/* Fenêtres : petits carrés qui s'allument à l'aube */}
          {WINDOW_RECTS.map(([x, y], i) => (
            <rect
              key={i}
              className="mf-window"
              x={x}
              y={y}
              width="6"
              height="8"
              style={{ animationDelay: `${9.7 + (i % 7) * 0.08}s` }}
            />
          ))}
        </g>

        {/* Ficelle qui pend du haut, avec ampoule/soleil au bout */}
        <g className="mf-string-group">
          <line
            className="mf-string"
            x1="800"
            y1="0"
            x2="800"
            y2="430"
            stroke="#3a3f6a"
            strokeWidth="1.5"
          />
          {/* Halo du soleil (apparaît au climax) */}
          <circle
            className="mf-sun-glow"
            cx="800"
            cy="450"
            r="240"
            fill="url(#mfSunGlow)"
          />
          {/* Rayons */}
          <g className="mf-sun-rays" stroke="#ffd57a" strokeWidth="2.5" strokeLinecap="round">
            {Array.from({ length: 12 }).map((_, i) => {
              const a = (i * Math.PI * 2) / 12;
              const x1 = 800 + Math.cos(a) * 60;
              const y1 = 450 + Math.sin(a) * 60;
              const x2 = 800 + Math.cos(a) * 95;
              const y2 = 450 + Math.sin(a) * 95;
              return (
                <line
                  key={i}
                  x1={x1}
                  y1={y1}
                  x2={x2}
                  y2={y2}
                  style={{ animationDelay: `${9.7 + i * 0.04}s` }}
                  className="mf-sun-ray"
                />
              );
            })}
          </g>
          {/* Ampoule / soleil */}
          <circle
            className="mf-bulb"
            cx="800"
            cy="450"
            r="22"
            fill="#1a1d3f"
            stroke="#3a3f6a"
            strokeWidth="1.5"
          />
        </g>

        {/* Route */}
        <rect x="0" y="780" width="1600" height="120" fill="#0a0c1f" />
        <g className="mf-road-marks" stroke="#5a4a30" strokeWidth="3" strokeDasharray="40 30">
          <line x1="0" y1="830" x2="1600" y2="830" />
        </g>

        {/* Ordre des plans (du plus loin au plus proche du spectateur) :
            1. Piétons (chorégraphique + ambiance) : au fond, derrière tout
            2. Voitures voie du fond : passent à hauteur des piétons et les cachent
            3. Voitures voie de devant : premier plan */}

        {/* Piéton — silhouette claire pour rester visible la nuit */}
        <g className="mf-pedestrian">
          <g className="mf-pedestrian__bob">
            {/* Tête */}
            <circle cx="0" cy="-65" r="9" fill="#e2e0d6" stroke="#1a1c2c" strokeWidth="0.6" />
            {/* Corps */}
            <path
              d="M-7,-55 L7,-55 L9,-25 L-9,-25 Z"
              fill="#c9c2b0"
              stroke="#1a1c2c"
              strokeWidth="0.6"
            />
            {/* Bras gauche au repos */}
            <line
              x1="-6"
              y1="-50"
              x2="-12"
              y2="-28"
              stroke="#c9c2b0"
              strokeWidth="3.5"
              strokeLinecap="round"
            />
            {/* Bras droit qui se lève */}
            <g className="mf-pedestrian__arm">
              <line
                x1="0"
                y1="-52"
                x2="0"
                y2="-30"
                stroke="#c9c2b0"
                strokeWidth="3.5"
                strokeLinecap="round"
              />
            </g>
            {/* Jambes */}
            <g className="mf-pedestrian__legs">
              <line
                x1="-3"
                y1="-25"
                x2="-8"
                y2="0"
                stroke="#a8a08c"
                strokeWidth="4"
                strokeLinecap="round"
              />
              <line
                x1="3"
                y1="-25"
                x2="8"
                y2="0"
                stroke="#a8a08c"
                strokeWidth="4"
                strokeLinecap="round"
              />
            </g>
          </g>
        </g>

        {/* Piétons d'ambiance — apparaissent au lever du soleil (delay CSS ≥ 11s) */}
        <Walker slot={1} />
        <Walker slot={2} />
        <Walker slot={3} />
        <Walker slot={4} />

        {/* Voitures voie du fond : APRÈS les piétons → les masquent à hauteur */}
        <Car slot={1} direction="rtl" lane="back" />
        <Car slot={3} direction="rtl" lane="back" />

        {/* Voitures voie de devant : premier plan */}
        <Car slot={2} direction="ltr" lane="front" />
        <Car slot={4} direction="ltr" lane="front" />

        {/* Sol devant la route — léger reflet pour l'aube */}
        <rect
          className="mf-ground-glow"
          x="0"
          y="700"
          width="1600"
          height="80"
          fill="url(#mfSunGlow)"
        />
      </svg>

      {/* Modal slot — révélé après la chorégraphie */}
      <div className={`mf-modal-wrap ${modalReady ? "mf-modal-wrap--in" : ""}`}>
        {children}
      </div>

      {/* Branding minimal en haut-gauche, footer bas-gauche */}
      <header className="mf-overlay mf-overlay--top">
        <div className="mf-logo">
          <span className="mf-logo__chip">mf</span>
          <span className="mf-logo__text">
            <span className="mf-logo__brand">missioflow</span>
            <span className="mf-logo__sub">SuperAdmin</span>
          </span>
        </div>
      </header>
      <footer className="mf-overlay mf-overlay--bottom">
        <span className="mf-overlay__url">sysop.missioflow.fr</span>
        <span className="mf-overlay__meta">
          © {new Date().getFullYear()} missioflow · v0.1
        </span>
      </footer>
    </div>
  );
}

// Modèles de voitures (dessinés avec l'avant à droite, x∈[0, width])
const CAR_MODELS: CarModel[] = [
  // Berline classique
  {
    width: 165,
    body: "M0,800 L10,775 L40,760 L90,755 L130,760 L155,775 L165,800 Z",
    window: "M40,775 L60,762 L120,762 L140,775 Z",
    wheels: [
      { cx: 35, r: 11, rInner: 5 },
      { cx: 130, r: 11, rInner: 5 },
    ],
    frontLight: { cx: 163, cyTop: 790, cyBot: 797 },
    rearLight: { cx: 3, cy: 790 },
  },
  // Compacte (plus courte, plus basse)
  {
    width: 150,
    body: "M0,800 L8,778 L30,765 L75,760 L115,765 L140,778 L150,800 Z",
    window: "M30,778 L48,766 L105,766 L122,778 Z",
    wheels: [
      { cx: 30, r: 9, rInner: 4 },
      { cx: 115, r: 9, rInner: 4 },
    ],
    frontLight: { cx: 148, cyTop: 792, cyBot: 797 },
    rearLight: { cx: 3, cy: 792 },
  },
  // SUV (plus haut, toit carré)
  {
    width: 175,
    body: "M0,800 L5,770 L25,755 L45,750 L135,750 L155,755 L170,770 L175,800 Z",
    window: "M45,768 L62,754 L125,754 L138,768 Z",
    wheels: [
      { cx: 38, r: 12, rInner: 5 },
      { cx: 138, r: 12, rInner: 5 },
    ],
    frontLight: { cx: 172, cyTop: 786, cyBot: 793 },
    rearLight: { cx: 4, cy: 786 },
  },
  // Van (long, toit haut, double vitre)
  {
    width: 185,
    body: "M0,800 L0,758 L18,748 L160,748 L180,758 L185,800 Z",
    window: "M18,762 L32,754 L72,754 L72,762 Z M82,754 L150,754 L150,762 L82,762 Z",
    wheels: [
      { cx: 32, r: 11, rInner: 5 },
      { cx: 152, r: 11, rInner: 5 },
    ],
    frontLight: { cx: 183, cyTop: 786, cyBot: 793 },
    rearLight: { cx: 3, cy: 786 },
  },
];

// Palettes (couleurs body + window) — assorties pour rester crédibles la nuit
const CAR_PALETTES: CarPalette[] = [
  { body: "#1d2240", window: "#3a4170" }, // bleu nuit
  { body: "#262a4d", window: "#454b80" }, // bleu acier
  { body: "#1a1f3c", window: "#353c6b" }, // anthracite-bleu
  { body: "#3a1f2a", window: "#6a3947" }, // bordeaux
  { body: "#1f3a2a", window: "#3a6a4a" }, // vert forêt
  { body: "#3a2f1f", window: "#6a5a3f" }, // brun terre
  { body: "#2a2a2e", window: "#5a5a62" }, // anthracite
  { body: "#cfd2d8", window: "#7a8090" }, // blanc cassé (plus visible)
];

// Étoiles : [cx, cy, r, opacity]
const STAR_POSITIONS: Array<[number, number, number, number]> = [
  [80, 90, 1.2, 0.8], [180, 140, 0.9, 0.6], [260, 60, 1.4, 0.9],
  [340, 200, 1, 0.55], [430, 110, 1.3, 0.85], [510, 50, 0.8, 0.5],
  [610, 170, 1.1, 0.7], [700, 80, 1.5, 0.95], [800, 230, 0.9, 0.55],
  [900, 60, 1.2, 0.8], [1010, 130, 1, 0.65], [1100, 220, 1.4, 0.9],
  [1200, 90, 0.9, 0.55], [1280, 260, 1.1, 0.7], [1410, 110, 1.3, 0.85],
  [1500, 180, 0.9, 0.6], [120, 280, 1, 0.55], [240, 320, 1.2, 0.8],
  [380, 280, 0.9, 0.5], [480, 350, 1.1, 0.7], [600, 300, 0.8, 0.45],
  [720, 360, 1.3, 0.85], [870, 320, 1, 0.6], [1000, 290, 1.1, 0.7],
  [1140, 340, 0.9, 0.55], [1270, 310, 1.2, 0.8], [1380, 270, 1, 0.6],
  [1480, 320, 1.3, 0.85], [50, 200, 1, 0.6], [1560, 90, 1.2, 0.75],
];

// Fenêtres : [x, y] — sur la skyline avant (s'allument à l'aube)
const WINDOW_RECTS: Array<[number, number]> = [
  [25, 470], [50, 470], [25, 500], [50, 500], [25, 530], [50, 530],
  [110, 400], [135, 400], [110, 430], [135, 430],
  [200, 460], [225, 460], [200, 490], [225, 490], [200, 520],
  [290, 360], [315, 360], [340, 360], [290, 390], [315, 390], [340, 390],
  [495, 400], [520, 400], [495, 430], [520, 430],
  [590, 350], [615, 350], [590, 380], [615, 380], [590, 410], [615, 410],
  [690, 410], [715, 410], [690, 440], [715, 440],
  [890, 340], [915, 340], [890, 370], [915, 370], [890, 400], [915, 400],
  [1110, 430], [1135, 430], [1110, 460], [1135, 460],
  [1210, 370], [1235, 370], [1210, 400], [1235, 400], [1210, 430],
  [1320, 410], [1345, 410], [1320, 440], [1345, 440],
  [1420, 370], [1445, 370], [1420, 400], [1445, 400], [1420, 430], [1445, 430],
];
