// Finale section — scroll-driven dramatic car animation as the page's
// closing moment. Tall section: car drives from left to right as user
// scrolls, with intensifying speed streaks, brightening headlight,
// distant city/container skyline receding in parallax, and three
// big headlines that fade in at progress milestones.

const { useEffect: useEffectF, useRef: useRefF, useState: useStateF } = React;

const FINALE_I18N = {
  en: {
    eyebrow: "THE LAST MILE",
    h1: "Your car is on its way.",
    h2: "From Shenzhen.",
    h3: "To your door.",
    foot: "Cleared. Registered. Ready.",
  },
  fr: {
    eyebrow: "LE DERNIER KILOMÈTRE",
    h1: "Votre voiture est en route.",
    h2: "Depuis Shenzhen.",
    h3: "Jusqu'à votre porte.",
    foot: "Dédouanée. Immatriculée. Prête.",
  },
  es: {
    eyebrow: "EL ÚLTIMO KILÓMETRO",
    h1: "Tu coche está en camino.",
    h2: "Desde Shenzhen.",
    h3: "Hasta tu puerta.",
    foot: "Despachado. Matriculado. Listo.",
  },
  ar: {
    eyebrow: "الميل الأخير",
    h1: "سيارتك في الطريق.",
    h2: "من شنزن.",
    h3: "إلى بابك.",
    foot: "مخلَّصة. مسجَّلة. جاهزة.",
  },
};

function FinaleDrive({ lang = "en" }) {
  const ref = useRefF(null);
  const [p, setP] = useStateF(0); // 0 → 1 across section

  useEffectF(() => {
    const el = ref.current;
    if (!el) return;
    let raf = 0;
    const onScroll = () => {
      if (raf) return;
      raf = requestAnimationFrame(() => {
        raf = 0;
        const r = el.getBoundingClientRect();
        const vh = window.innerHeight || 800;
        // Progress: 0 when section top hits bottom of viewport, 1 when section bottom hits top
        const total = r.height + vh;
        const scrolled = vh - r.top;
        const pp = Math.max(0, Math.min(1, scrolled / total));
        setP(pp);
      });
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll);
    return () => {
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("resize", onScroll);
      if (raf) cancelAnimationFrame(raf);
    };
  }, []);

  const tx = FINALE_I18N[lang] || FINALE_I18N.en;

  // Eased progress for car position
  const ease = (x) => 1 - Math.pow(1 - x, 2.4);
  const ep = ease(p);

  const carX = -25 + ep * 145;            // -25% → 120%
  const wheelRot = p * 2160;              // 6 full spins
  const light = 0.35 + p * 0.65;
  const cityShift = -p * 60;              // distant skyline pan
  const shipShift = -p * 35;              // farther ship parallax
  const streakLen = 60 + p * 380;
  const showH1 = p > 0.10 && p < 0.65;
  const showH2 = p > 0.30 && p < 0.85;
  const showH3 = p > 0.55;
  const headlineOp = (start, end) => {
    if (p < start) return 0;
    if (p > end) return Math.max(0, 1 - (p - end) * 6);
    return Math.min(1, (p - start) * 8);
  };

  return (
    <section
      ref={ref}
      id="finale"
      className="fin-section"
      aria-label="Closing animation"
    >
      <div className="fin-bg" />

      {/* Distant skyline silhouettes — parallax */}
      <div className="fin-skyline" style={{ transform: `translateX(${cityShift}%)` }}>
        <svg viewBox="0 0 2400 220" preserveAspectRatio="xMinYMax meet">
          <defs>
            <linearGradient id="finSkyG" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor="#0c1530" stopOpacity="0" />
              <stop offset="60%" stopColor="#0c1530" stopOpacity="0.7" />
              <stop offset="100%" stopColor="#080d1f" stopOpacity="0.95" />
            </linearGradient>
          </defs>
          {/* Generic stylized cityscape with varying building heights */}
          <g fill="url(#finSkyG)">
            <path d="M0 220 L0 140 L60 140 L60 100 L120 100 L120 130 L180 130 L180 80 L240 80 L240 110 L300 110 L300 70 L320 70 L320 50 L380 50 L380 95 L460 95 L460 60 L500 60 L500 30 L560 30 L560 90 L620 90 L620 120 L700 120 L700 75 L760 75 L760 105 L840 105 L840 55 L920 55 L920 95 L1000 95 L1000 70 L1080 70 L1080 110 L1160 110 L1160 80 L1240 80 L1240 50 L1320 50 L1320 95 L1400 95 L1400 60 L1480 60 L1480 100 L1560 100 L1560 75 L1640 75 L1640 110 L1720 110 L1720 85 L1800 85 L1800 55 L1880 55 L1880 100 L1960 100 L1960 70 L2040 70 L2040 105 L2120 105 L2120 80 L2200 80 L2200 120 L2280 120 L2280 90 L2400 90 L2400 220 Z" />
          </g>
          {/* Window dots */}
          <g fill="#e8732e" opacity="0.45">
            {Array.from({ length: 60 }).map((_, i) => (
              <rect key={i} x={40 + i * 40 + (i % 3) * 7} y={110 + ((i * 17) % 60)} width="2" height="3" />
            ))}
          </g>
        </svg>
      </div>

      {/* Container ship far back — parallax slower */}
      <div className="fin-ship" style={{ transform: `translateX(${shipShift}%) translateY(0)` }}>
        <svg viewBox="0 0 600 110" preserveAspectRatio="xMidYMax meet" aria-hidden="true">
          <defs>
            <linearGradient id="finShipG" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor="#1a2640" stopOpacity="0.85" />
              <stop offset="100%" stopColor="#0a1126" stopOpacity="1" />
            </linearGradient>
          </defs>
          {/* hull */}
          <path d="M40 80 L560 80 L540 100 L60 100 Z" fill="url(#finShipG)" />
          {/* containers stack */}
          <g fill="url(#finShipG)" opacity="0.95">
            <rect x="90"  y="50" width="60" height="30" />
            <rect x="155" y="40" width="60" height="40" />
            <rect x="220" y="55" width="60" height="25" />
            <rect x="285" y="35" width="60" height="45" />
            <rect x="350" y="48" width="60" height="32" />
            <rect x="415" y="60" width="60" height="20" />
            {/* upper layer */}
            <rect x="170" y="22" width="40" height="18" />
            <rect x="300" y="14" width="40" height="22" />
          </g>
          {/* bridge tower */}
          <rect x="475" y="36" width="42" height="44" fill="#0a1126" />
          <rect x="482" y="42" width="4" height="6" fill="#e8732e" opacity="0.8" />
          {/* mast lights */}
          <circle cx="498" cy="32" r="2" fill="#fffbe0" opacity="0.9" />
          {/* waterline ripple */}
          <line x1="50" y1="102" x2="555" y2="102" stroke="rgba(255,255,255,0.06)" strokeWidth="1" />
        </svg>
      </div>

      {/* Reflective road surface */}
      <div className="fin-road">
        <div className="fin-road-grad" />
        {/* Dashed lane line — animated */}
        <div className="fin-lane" aria-hidden="true">
          <div className="fin-lane-strip" style={{ backgroundPosition: `${-p * 1800}px 0px` }} />
        </div>
      </div>

      {/* Speed lines layer */}
      <div className="fin-streaks" aria-hidden="true">
        {Array.from({ length: 14 }).map((_, i) => {
          const y = 18 + i * 5.2 + (i % 3) * 1.2;
          const w = streakLen * (0.4 + ((i * 37) % 70) / 100);
          const op = (0.10 + (i % 5) * 0.05) * Math.max(0, p - 0.05);
          const col = i % 4 === 0 ? "rgba(232,115,46,0.9)" : "rgba(247,241,229,0.9)";
          const left = ((i * 47) % 100);
          return (
            <span key={i}
              style={{
                top: `${y}%`,
                left: `calc(${left}% + ${carX - 10}%)`,
                width: w,
                opacity: op,
                background: `linear-gradient(90deg, transparent, ${col})`,
              }}
            />
          );
        })}
      </div>

      {/* Headlines layer */}
      <div className="fin-copy wrap">
        <div className="fin-eyebrow mono">{tx.eyebrow}</div>
        <div className="fin-headlines">
          <h2 className="fin-h serif fin-h1" style={{ opacity: headlineOp(0.05, 0.40), transform: `translateY(${(1 - headlineOp(0.05, 0.40)) * 18}px)` }}>{tx.h1}</h2>
          <h2 className="fin-h serif fin-h2" style={{ opacity: headlineOp(0.32, 0.65), transform: `translateY(${(1 - headlineOp(0.32, 0.65)) * 18}px)` }}>{tx.h2}</h2>
          <h2 className="fin-h serif fin-h3" style={{ opacity: headlineOp(0.58, 1.2), transform: `translateY(${(1 - headlineOp(0.58, 1.2)) * 18}px)` }}>{tx.h3}</h2>
        </div>
        <div className="fin-foot mono" style={{ opacity: Math.max(0, p - 0.7) * 3.3 }}>
          {tx.foot}
        </div>
      </div>

      {/* THE CAR */}
      <div className="fin-car" style={{ left: `${carX}%` }}>
        {/* Long headlight beam projecting forward */}
        <div className="fin-beam" style={{ opacity: 0.15 + light * 0.55, transform: `scaleX(${0.5 + p * 1.4})` }} />

        <svg viewBox="0 0 1100 360" preserveAspectRatio="xMidYMid meet" className="fin-car-svg">
          <defs>
            <linearGradient id="finPaint" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%"  stopColor="#FFD63A" />
              <stop offset="32%" stopColor="#F4B41A" />
              <stop offset="72%" stopColor="#9B6D0B" />
              <stop offset="100%" stopColor="#3a2607" />
            </linearGradient>
            <linearGradient id="finSheen" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor="#fffbe0" stopOpacity="0.9" />
              <stop offset="100%" stopColor="#fffbe0" stopOpacity="0" />
            </linearGradient>
            <linearGradient id="finWindow" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%"  stopColor="#1c2a3e" stopOpacity="0.95" />
              <stop offset="100%" stopColor="#050a14" stopOpacity="1" />
            </linearGradient>
            <linearGradient id="finLower" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor="#1a1a1a" />
              <stop offset="100%" stopColor="#050505" />
            </linearGradient>
            <radialGradient id="finHead" cx="0.5" cy="0.5" r="0.5">
              <stop offset="0%" stopColor="#fffbe0" stopOpacity={light} />
              <stop offset="60%" stopColor="#ffd58a" stopOpacity={light * 0.5} />
              <stop offset="100%" stopColor="#ffb27a" stopOpacity="0" />
            </radialGradient>
            <radialGradient id="finTail" cx="0.5" cy="0.5" r="0.5">
              <stop offset="0%" stopColor="#ff3a3a" stopOpacity={light * 0.85} />
              <stop offset="100%" stopColor="#ff3a3a" stopOpacity="0" />
            </radialGradient>
            <radialGradient id="finContact" cx="0.5" cy="0.5" r="0.5">
              <stop offset="0%" stopColor="#000" stopOpacity="0.78" />
              <stop offset="100%" stopColor="#000" stopOpacity="0" />
            </radialGradient>
            <filter id="finBlur" x="-30%" y="-30%" width="160%" height="160%">
              <feGaussianBlur stdDeviation="6" />
            </filter>
          </defs>

          {/* Tail-light glow trail behind */}
          <ellipse cx="135" cy="218" rx={70 + p * 80} ry={14 + p * 6} fill="url(#finTail)" filter="url(#finBlur)" />

          {/* Headlight forward bloom */}
          <ellipse cx="980" cy="240" rx={80 + p * 60} ry={18 + p * 8} fill="url(#finHead)" filter="url(#finBlur)" />

          {/* Ground reflection mirror */}
          <g transform="translate(0,590) scale(1,-1)" opacity="0.2">
            <path d="M 120 270 C 165 215, 240 196, 320 192 L 405 122 C 430 100, 478 90, 530 90 L 720 90 C 768 92, 808 110, 836 144 L 905 200 C 945 206, 970 222, 985 248 L 120 270 Z" fill="url(#finPaint)" />
          </g>

          {/* Contact shadow */}
          <ellipse cx="540" cy="300" rx="380" ry="16" fill="url(#finContact)" />

          {/* Lower side skirt */}
          <path d="M 145 268 L 935 268 C 950 268, 960 274, 956 282 L 940 296 L 170 296 L 150 282 C 142 274, 138 268, 145 268 Z" fill="url(#finLower)" />

          {/* Body */}
          <path d="M 130 270
                   C 165 215, 240 196, 320 192
                   L 405 122
                   C 430 100, 478 90, 530 90
                   L 720 90
                   C 768 92, 808 110, 836 144
                   L 905 200
                   C 945 206, 970 222, 985 248
                   C 995 264, 985 274, 968 274
                   L 152 274
                   C 134 274, 124 268, 130 270 Z" fill="url(#finPaint)" />

          {/* Sheen */}
          <path d="M 360 145 C 410 110, 470 100, 540 100 L 720 100 C 770 102, 798 122, 820 150 L 860 200 L 360 215 Z" fill="url(#finSheen)" opacity="0.55" />

          {/* Windshield */}
          <path d="M 332 192 C 360 138, 410 116, 460 114 L 700 114 C 738 118, 770 138, 790 168 L 815 192 L 332 192 Z" fill="url(#finWindow)" />
          <line x1="570" y1="114" x2="570" y2="192" stroke="rgba(0,0,0,0.55)" strokeWidth="1.4" />

          {/* Roof highlight */}
          <path d="M 412 122 C 436 102, 482 92, 530 92 L 720 92 C 766 94, 802 112, 828 142" fill="none" stroke="rgba(255,251,224,0.85)" strokeWidth="0.9" />

          {/* Character lines */}
          <path d="M 200 230 L 920 222" stroke="rgba(0,0,0,0.22)" strokeWidth="1" />
          <path d="M 230 254 L 900 246" stroke="rgba(255,255,255,0.08)" strokeWidth="0.7" />

          {/* Side mirror */}
          <path d="M 470 170 L 488 158 L 498 168 L 484 180 Z" fill="#0a0a0a" />

          {/* Door handles */}
          <rect x="430" y="232" width="22" height="3" rx="1.5" fill="rgba(0,0,0,0.35)" />
          <rect x="640" y="232" width="22" height="3" rx="1.5" fill="rgba(0,0,0,0.35)" />

          {/* Headlight bar */}
          <rect x="920" y="232" width="55" height="4" rx="2" fill="#150505" />
          <rect x="924" y="234" width="46" height="2.4" rx="1.2" fill="#fffbe0" opacity={light} />
          <path d="M 962 234 Q 975 240 968 246" stroke="#ffd58a" strokeWidth="1.2" fill="none" opacity={light} />

          {/* Tail light bar */}
          <rect x="140" y="232" width="170" height="4" rx="2" fill="#150505" />
          <rect x="140" y="232" width="170" height="2.4" rx="1.2" fill="#ff3a3a" opacity={0.7 + p * 0.3} />

          {/* Wheels */}
          <g>
            <circle cx="270" cy="275" r="44" fill="#050505" />
            <circle cx="270" cy="275" r="38" fill="#0e0e10" />
            <g transform={`rotate(${wheelRot} 270 275)`} style={{ transformOrigin: "270px 275px" }}>
              <circle cx="270" cy="275" r="32" fill="#16161a" />
              <g stroke="rgba(255,255,255,0.18)" strokeWidth="1.4" fill="none" strokeLinecap="round">
                {[0, 36, 72, 108, 144, 180, 216, 252, 288, 324].map((a, i) => (
                  <line key={i}
                    x1={270 + Math.cos(a * Math.PI / 180) * 8}
                    y1={275 + Math.sin(a * Math.PI / 180) * 8}
                    x2={270 + Math.cos(a * Math.PI / 180) * 28}
                    y2={275 + Math.sin(a * Math.PI / 180) * 28}
                  />
                ))}
              </g>
              <circle cx="270" cy="275" r="7" fill="#1a1a1f" />
            </g>
          </g>
          <g>
            <circle cx="870" cy="275" r="44" fill="#050505" />
            <circle cx="870" cy="275" r="38" fill="#0e0e10" />
            <g transform={`rotate(${wheelRot} 870 275)`} style={{ transformOrigin: "870px 275px" }}>
              <circle cx="870" cy="275" r="32" fill="#16161a" />
              <g stroke="rgba(255,255,255,0.18)" strokeWidth="1.4" fill="none" strokeLinecap="round">
                {[0, 36, 72, 108, 144, 180, 216, 252, 288, 324].map((a, i) => (
                  <line key={i}
                    x1={870 + Math.cos(a * Math.PI / 180) * 8}
                    y1={275 + Math.sin(a * Math.PI / 180) * 8}
                    x2={870 + Math.cos(a * Math.PI / 180) * 28}
                    y2={275 + Math.sin(a * Math.PI / 180) * 28}
                  />
                ))}
              </g>
              <circle cx="870" cy="275" r="7" fill="#1a1a1f" />
            </g>
          </g>

          {/* Underbody warm strip */}
          <ellipse cx="560" cy="296" rx="320" ry={3 + p * 4} fill="#E85D2A" opacity={0.3 + p * 0.45} filter="url(#finBlur)" />
        </svg>
      </div>

      <style>{`
        .fin-section {
          position: relative;
          min-height: 140vh;
          background: #050913;
          overflow: hidden;
          color: #F7F1E5;
          border-top: 1px solid var(--line);
          isolation: isolate;
        }
        .fin-bg {
          position: absolute; inset: 0;
          background:
            radial-gradient(ellipse at 50% 30%, rgba(232,93,42,0.10) 0%, transparent 50%),
            radial-gradient(ellipse at 80% 70%, rgba(29,58,168,0.18) 0%, transparent 55%),
            radial-gradient(ellipse at 20% 100%, rgba(232,93,42,0.06) 0%, transparent 55%),
            linear-gradient(180deg, #050913 0%, #020610 100%);
          pointer-events: none;
        }
        .fin-skyline {
          position: absolute; left: -10%; right: -10%; bottom: 22%;
          height: 28%; max-height: 240px;
          opacity: 0.55;
          will-change: transform;
          transition: transform .1s linear;
          pointer-events: none;
        }
        .fin-skyline svg { width: 100%; height: 100%; display: block; }
        .fin-ship {
          position: absolute; left: 5%; bottom: 30%;
          width: 22%; max-width: 360px; min-width: 200px;
          opacity: 0.55;
          will-change: transform;
          transition: transform .1s linear;
          pointer-events: none;
        }
        .fin-ship svg { width: 100%; height: auto; display: block; }
        .fin-road {
          position: absolute; left: 0; right: 0; bottom: 0;
          height: 22%;
          pointer-events: none;
        }
        .fin-road-grad {
          position: absolute; inset: 0;
          background:
            linear-gradient(180deg, rgba(232,115,46,0.04) 0%, rgba(0,0,0,0.4) 50%, rgba(0,0,0,0.9) 100%),
            linear-gradient(90deg, transparent 0%, rgba(232,115,46,0.06) 50%, transparent 100%);
          border-top: 1px solid rgba(247,241,229,0.06);
        }
        .fin-lane {
          position: absolute; left: 0; right: 0; top: 38%; height: 3px;
          overflow: hidden;
        }
        .fin-lane-strip {
          position: absolute; inset: 0;
          background-image: linear-gradient(90deg, rgba(255,210,140,0.55) 0 60px, transparent 60px 120px);
          background-size: 120px 100%;
          background-repeat: repeat-x;
        }

        .fin-streaks { position: absolute; inset: 0; pointer-events: none; }
        .fin-streaks > span {
          position: absolute;
          height: 1px;
          filter: blur(0.4px);
          will-change: opacity, width, left;
          pointer-events: none;
        }

        .fin-copy {
          position: absolute;
          left: 50%; top: 50%;
          transform: translate(-50%, -55%);
          text-align: center;
          z-index: 3;
          pointer-events: none;
        }
        .fin-eyebrow {
          font-size: 11px; letter-spacing: 0.28em;
          text-transform: uppercase;
          color: #E85D2A;
          margin-bottom: 22px;
        }
        .fin-headlines {
          position: relative;
          min-height: clamp(120px, 14vw, 220px);
        }
        .fin-h {
          position: absolute;
          left: 50%;
          top: 0;
          transform: translateX(-50%);
          margin: 0;
          font-weight: 400;
          font-size: clamp(40px, 7vw, 96px);
          line-height: 1.0;
          letter-spacing: -0.02em;
          color: #F7F1E5;
          white-space: nowrap;
          transition: opacity .35s ease, transform .35s ease;
        }
        .fin-h1 em, .fin-h2 em, .fin-h3 em { font-style: italic; color: var(--amber); }
        .fin-h2 { color: rgba(247,241,229,0.85); }
        .fin-h3 { font-style: italic; color: #E85D2A; }
        .fin-foot {
          margin-top: clamp(160px, 18vw, 260px);
          font-size: 11px;
          letter-spacing: 0.28em;
          text-transform: uppercase;
          color: rgba(247,241,229,0.55);
          transition: opacity .35s ease;
        }

        /* Car */
        .fin-car {
          position: absolute;
          top: 58%;
          width: clamp(420px, 60vw, 880px);
          aspect-ratio: 1100 / 360;
          transform: translate(-50%, -50%);
          will-change: left, transform;
          z-index: 2;
          filter: drop-shadow(0 30px 50px rgba(0,0,0,0.7));
        }
        .fin-car-svg { width: 100%; height: 100%; display: block; }
        .fin-beam {
          position: absolute;
          top: 56%;
          left: 60%;
          width: 70%;
          height: 14%;
          background: radial-gradient(ellipse at left center, rgba(255,251,224,0.55) 0%, rgba(255,210,140,0.18) 35%, transparent 70%);
          filter: blur(8px);
          transform-origin: left center;
          will-change: opacity, transform;
          pointer-events: none;
          z-index: 1;
        }

        /* Mobile */
        @media (max-width: 760px) {
          .fin-section { min-height: 110vh; }
          .fin-h { font-size: clamp(32px, 9vw, 56px); }
          .fin-car { width: 96vw; top: 62%; }
          .fin-foot { margin-top: clamp(140px, 28vw, 200px); }
        }

        @media (prefers-reduced-motion: reduce) {
          .fin-car, .fin-skyline, .fin-ship, .fin-beam, .fin-lane-strip { transition: none !important; }
        }
      `}</style>
    </section>
  );
}

window.FinaleDrive = FinaleDrive;
