/* global React */
const { useEffect, useRef, useState } = React;

/* ============================================================================
   CityBackdrop — procedural cinematic GTA-coded night skyline (no text, no
   stock imagery). Pure SVG layers so we can parallax each one independently.

   Layers (back to front):
   0  Sky gradient (smoked graphite to near-black)
   1  Stars / sky lights
   2  Far-distance buildings (silhouettes, low contrast)
   3  Fog haze band at horizon
   4  Mid buildings with lit windows
   5  Foreground building corners (left + right framing)
   6  Wet asphalt strip at bottom
   7  Muted chrome/red reflections in wet asphalt
   8  Street-light glow orbs
   9  Vignette + grain
   ============================================================================ */

function CityBackdrop({ parallax = { mx: 0, my: 0, y: 0 }, intensity = 1, variant = "hero" }) {
  const px = (depth) => parallax.mx * depth * 14;
  const py = (depth) => parallax.my * depth * 8 + parallax.y * depth * 60;
  return (
    <div
      aria-hidden="true"
      style={{
        position: "absolute", inset: 0,
        overflow: "hidden",
        background: "linear-gradient(180deg, #171a1f 0%, #0d0f12 35%, #050607 70%, #050505 100%)",
      }}
    >
      {/* STARS / sky lights ------------------------------------------------- */}
      <svg
        viewBox="0 0 1920 600"
        preserveAspectRatio="xMidYMid slice"
        style={{
          position: "absolute", top: 0, left: 0, width: "100%", height: "55%",
          transform: `translate3d(${px(0.3)}px, ${py(0.2)}px, 0)`,
        }}
      >
        {Array.from({ length: 70 }).map((_, i) => {
          const x = ((i * 277) % 1920);
          const y = ((i * 167) % 480);
          const r = (i % 9 === 0) ? 1.6 : 0.7;
          const op = 0.15 + ((i * 13) % 70) / 100;
          return <circle key={i} cx={x} cy={y} r={r} fill="#cfe7ff" opacity={op} />;
        })}
      </svg>

      {/* FAR BUILDINGS -------------------------------------------------------- */}
      <svg
        viewBox="0 0 1920 600"
        preserveAspectRatio="xMidYMax slice"
        style={{
          position: "absolute", left: 0, bottom: "30%", width: "100%", height: "55%",
          transform: `translate3d(${px(0.4)}px, ${py(0.3)}px, 0)`,
          opacity: 0.65,
        }}
      >
        <FarSkyline />
      </svg>

      {/* FOG HAZE BAND -------------------------------------------------------- */}
      <div style={{
        position: "absolute", left: 0, right: 0,
        bottom: "32%", height: "20%",
        background: "linear-gradient(180deg, transparent 0%, rgba(42, 43, 47, 0.42) 40%, rgba(18, 18, 20, 0.2) 100%)",
        filter: "blur(14px)",
        transform: `translateY(${py(0.2)}px)`,
        pointerEvents: "none",
      }}></div>

      {/* MID BUILDINGS with lit windows ------------------------------------- */}
      <svg
        viewBox="0 0 1920 700"
        preserveAspectRatio="xMidYMax slice"
        style={{
          position: "absolute", left: 0, bottom: "28%", width: "100%", height: "55%",
          transform: `translate3d(${px(0.7)}px, ${py(0.5)}px, 0)`,
        }}
      >
        <MidSkyline />
      </svg>

      {/* FOREGROUND framing buildings (left + right) ------------------------ */}
      <svg
        viewBox="0 0 1920 1080"
        preserveAspectRatio="xMidYMax slice"
        style={{
          position: "absolute", inset: 0, width: "100%", height: "100%",
          transform: `translate3d(${px(1.2)}px, ${py(0.9)}px, 0)`,
        }}
      >
        <ForegroundFrame />
      </svg>

      {/* WET ASPHALT base + reflections ------------------------------------- */}
      <div style={{
        position: "absolute", left: 0, right: 0, bottom: 0,
        height: "28%",
        background: "linear-gradient(180deg, #060809 0%, #0a0a0a 50%, #0a0a0a 100%)",
      }}>
        <svg viewBox="0 0 1920 300" preserveAspectRatio="xMidYMax slice"
             style={{ position: "absolute", inset: 0, width: "100%", height: "100%" }}>
          <Reflections intensity={intensity} />
        </svg>
      </div>

      {/* STREET LIGHT GLOWS -------------------------------------------------- */}
      <div style={{ position: "absolute", inset: 0, pointerEvents: "none" }}>
        <GlowOrb x="18%" y="50%" color="rgba(200,48,47,0.30)"  size={420} />
        <GlowOrb x="82%" y="58%" color="rgba(200,204,210,0.24)" size={500} />
        <GlowOrb x="48%" y="46%" color="rgba(129,136,145,0.14)" size={620} />
        <GlowOrb x="68%" y="68%" color="rgba(155,28,28,0.22)"  size={260} />
      </div>

      {/* VIGNETTE ------------------------------------------------------------ */}
      <div style={{
        position: "absolute", inset: 0,
        background: `
          radial-gradient(80% 60% at 50% 45%, transparent 0%, rgba(0,0,0,0.6) 100%),
          linear-gradient(180deg, rgba(10,10,10,0.30) 0%, transparent 30%, transparent 60%, rgba(10,10,10,0.95) 100%)
        `,
        pointerEvents: "none",
      }}></div>
    </div>
  );
}

/* ----- Far-distance building silhouette ----------------------------------- */
function FarSkyline() {
  // Deterministic skyline: each building is a rect with a few window dots.
  const buildings = [];
  let x = 0;
  let seed = 17;
  while (x < 1920) {
    const w = 50 + (seed * 37) % 80;
    const h = 130 + (seed * 53) % 240;
    seed = (seed * 9301 + 49297) % 233280;
    buildings.push({ x, w, h, y: 600 - h });
    x += w + 6;
  }
  return (
    <g>
      {buildings.map((b, i) => (
        <g key={i}>
          <rect x={b.x} y={b.y} width={b.w} height={b.h} fill="#0c1a20" />
          {/* sparse windows */}
          {Array.from({ length: Math.floor(b.h / 18) }).map((_, ri) => (
            Array.from({ length: Math.floor(b.w / 12) }).map((_, ci) => {
              const lit = ((i * 7 + ri * 3 + ci * 5) % 11) < 2;
              if (!lit) return null;
              return (
                <rect key={`${ri}-${ci}`}
                  x={b.x + 4 + ci * 12}
                  y={b.y + 10 + ri * 18}
                  width="3" height="5"
                  fill={(ci + ri) % 4 === 0 ? "#c8302f" : "#c8ccd2"}
                  opacity="0.65"
                />
              );
            })
          )).flat()}
        </g>
      ))}
    </g>
  );
}

/* ----- Mid buildings: bigger, more windows -------------------------------- */
function MidSkyline() {
  const buildings = [];
  let x = -40;
  let seed = 91;
  while (x < 1960) {
    const w = 110 + (seed * 19) % 130;
    const h = 220 + (seed * 71) % 380;
    seed = (seed * 6151 + 13) % 233280;
    buildings.push({ x, w, h, y: 700 - h });
    x += w - 8;     // slight overlap
  }
  return (
    <g>
      {buildings.map((b, i) => (
        <g key={i}>
          {/* main body */}
          <rect x={b.x} y={b.y} width={b.w} height={b.h} fill="#0a1014" />
          {/* roof crown (random) */}
          {i % 3 === 0 && (
            <rect x={b.x + b.w / 2 - 4} y={b.y - 16} width="8" height="16" fill="#0a1014" />
          )}
          {/* window grid */}
          {Array.from({ length: Math.floor(b.h / 22) }).map((_, ri) => (
            Array.from({ length: Math.floor(b.w / 16) }).map((_, ci) => {
              const k = i * 13 + ri * 7 + ci * 11;
              const lit = (k % 9) < 4;
              if (!lit) return null;
              const warm = (k % 13) > 8;
              const tint = warm ? "#fbbf24" : "#fef3c7";
              const op = 0.5 + ((k * 3) % 50) / 100;
              return (
                <rect key={`${ri}-${ci}`}
                  x={b.x + 6 + ci * 16}
                  y={b.y + 12 + ri * 22}
                  width="6" height="9"
                  fill={tint}
                  opacity={op}
                />
              );
            })
          )).flat()}
          {/* hot pop window (rare) */}
          {i % 4 === 0 && (
            <rect x={b.x + 8 + (i % 5) * 16} y={b.y + 20 + (i % 7) * 22}
                  width="6" height="9" fill="#c8ccd2" opacity="0.85" />
          )}
        </g>
      ))}
    </g>
  );
}

/* ----- Foreground left + right framing ------------------------------------ */
function ForegroundFrame() {
  return (
    <g>
      {/* Left dark wall */}
      <path d="M 0 1080 L 0 200 L 110 200 L 130 230 L 200 220 L 220 260 L 270 240 L 285 290 L 320 280 L 340 1080 Z" fill="#06090b" />
      {/* Left building windows */}
      {[260, 320, 380, 440, 500, 560, 620, 680, 740, 800, 860, 920, 980].map((y, i) => (
        <g key={`L${y}`}>
          {[60, 130, 200, 270].map((cx, ci) => {
            if ((i + ci) % 5 === 0) return null;
            const lit = (i + ci) % 3 !== 0;
            if (!lit) return null;
            const tint = (i + ci) % 7 === 0 ? "#c8ccd2" : ((i + ci) % 4 === 0 ? "#c8302f" : "#edeff2");
            return <rect key={ci} x={cx} y={y} width="10" height="16"
                         fill={tint} opacity={0.65 + ((i * ci) % 30) / 100} />;
          })}
        </g>
      ))}

      {/* Right dark wall */}
      <path d="M 1920 1080 L 1920 180 L 1800 180 L 1780 210 L 1720 200 L 1700 240 L 1640 230 L 1620 280 L 1580 270 L 1560 1080 Z" fill="#06090b" />
      {/* Right building windows */}
      {[240, 300, 360, 420, 480, 540, 600, 660, 720, 780, 840, 900, 960].map((y, i) => (
        <g key={`R${y}`}>
          {[1620, 1690, 1760, 1830].map((cx, ci) => {
            if ((i + ci) % 6 === 0) return null;
            const lit = (i * ci + 1) % 3 !== 0;
            if (!lit) return null;
            const tint = (i + ci) % 9 === 0 ? "#c8302f" : "#edeff2";
            return <rect key={ci} x={cx} y={y} width="10" height="16"
                         fill={tint} opacity={0.6 + ((i * 3 + ci) % 30) / 100} />;
          })}
        </g>
      ))}

      {/* Bottom street horizon line */}
      <line x1="0" y1="850" x2="1920" y2="850" stroke="#0e1a20" strokeWidth="2" opacity="0.6" />
    </g>
  );
}

/* ----- Wet asphalt reflections (vertical streaks) ------------------------ */
function Reflections({ intensity }) {
  const streaks = [
    { x: 220,  w: 4,  color: "rgba(200,48,47,0.62)" },
    { x: 380,  w: 3,  color: "rgba(200,204,210,0.45)" },
    { x: 540,  w: 6,  color: "rgba(129,136,145,0.36)" },
    { x: 760,  w: 2,  color: "rgba(155,28,28,0.48)" },
    { x: 920,  w: 4,  color: "rgba(200,204,210,0.52)" },
    { x: 1140, w: 5,  color: "rgba(200,48,47,0.46)" },
    { x: 1320, w: 3,  color: "rgba(200,204,210,0.42)" },
    { x: 1500, w: 7,  color: "rgba(200,48,47,0.50)" },
    { x: 1680, w: 4,  color: "rgba(129,136,145,0.34)" },
  ];
  return (
    <g>
      <defs>
        <linearGradient id="reflGrad" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%"  stopColor="white" stopOpacity="0.0" />
          <stop offset="20%" stopColor="white" stopOpacity="0.9" />
          <stop offset="100%" stopColor="white" stopOpacity="0" />
        </linearGradient>
      </defs>
      {/* Street centerline dashes */}
      {Array.from({ length: 8 }).map((_, i) => (
        <rect key={i} x={930 + i * 8} y={140 + i * 18} width={6 + i * 2} height={3 + i * 0.5}
              fill="rgba(200,48,47,0.34)" />
      ))}
      {/* Light streaks */}
      {streaks.map((s, i) => (
        <rect key={i} x={s.x} y={20} width={s.w} height={280}
              fill={s.color} opacity={intensity}
              mask="url(#mask)" />
      ))}
      {/* Soft wash overlay using gradient for fade-down */}
      <rect x="0" y="0" width="1920" height="300"
            fill="url(#reflGrad)" opacity="0.06" />
    </g>
  );
}

/* ----- Glow orb (positioned by % within container) ------------------------ */
function GlowOrb({ x, y, color, size = 300 }) {
  return (
    <div style={{
      position: "absolute",
      left: x, top: y,
      width: size, height: size,
      transform: "translate(-50%, -50%)",
      background: `radial-gradient(circle, ${color} 0%, transparent 70%)`,
      filter: "blur(6px)",
      pointerEvents: "none",
    }}></div>
  );
}

Object.assign(window, { CityBackdrop });
