/* PhotoSkyline — single Dubai photo + time-of-day tint + animated clouds + window-light flickers
   on the Burj Khalifa and a few neighbouring towers. */

const PhotoSkyline = ({ dubaiTime, weather, overrideHour, overrideWeather }) => {
  const cond = overrideWeather || weather?.condition || "clear";

  // Read theme reactively so the photo swaps with light/dark
  const [theme, setTheme] = React.useState(() => document.documentElement.dataset.theme || "light");
  React.useEffect(() => {
    const obs = new MutationObserver(() => setTheme(document.documentElement.dataset.theme || "light"));
    obs.observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme"] });
    return () => obs.disconnect();
  }, []);

  // Different photo + grading per theme. Posters are stills lifted from the
  // hero videos — same composition (Burj + house + family), so the photo
  // fallback that shows when autoplay is blocked matches the video frame.
  const isDark = theme === "dark";

  // Per-photo framing — both posters are ~16:9 frames lifted from the
  // hero videos. Bias toward 55% x so the Burj + family + door cluster
  // stays in view at any aspect ratio (mobile rules override at <760px).
  const photoStyle = {
    backgroundPosition: "55% center",
    backgroundSize: "cover",
    transform: "none",
    transformOrigin: "center",
  };

  const phase = isDark ? "evening" : "sunrise";
  const look = isDark
    ? {
        photoFilter: "brightness(1) saturate(1.08) contrast(1.04)",
        tint: "rgba(0,0,0,0)",
        glow: "rgba(255,150,80,0)",
        windowOpacity: 0,
      }
    : {
        // Sunrise photo — boost contrast/saturation, cool the warm haze, sharpen.
        photoFilter: "brightness(1.04) saturate(1.22) contrast(1.22) hue-rotate(-10deg)",
        tint: "rgba(170,205,230,0.12)",
        glow: "rgba(255,200,150,0.04)",
        windowOpacity: 0,
      };

  // Weather extras (over the photo)
  const wxFilter = (() => {
    if (cond === "fog")        return "blur(2px) brightness(1.05) contrast(.9)";
    if (cond === "sandstorm")  return "saturate(.8) brightness(.95) sepia(0.3)";
    if (cond === "rain")       return "brightness(.85) saturate(.85) contrast(1.05)";
    if (cond === "cloudy")     return "brightness(.95) saturate(.95)";
    return "";
  })();

  // Window hotspots — % coords on the 2132x1092 source. Rough placement on Burj Khalifa & adjacent towers.
  // x,y in % of image; cluster size determines how many flickers cluster around that spot.
  const windowSpots = [
    // Burj Khalifa spire & tiers
    { x: 49.5, y: 18, n: 3, size: 1.0 },
    { x: 49.6, y: 26, n: 5, size: 1.1 },
    { x: 49.8, y: 34, n: 6, size: 1.2 },
    { x: 50.1, y: 42, n: 7, size: 1.3 },
    { x: 50.3, y: 50, n: 8, size: 1.4 },
    { x: 50.6, y: 58, n: 9, size: 1.5 },
    // Left towers (Address Sky View / Emaar towers)
    { x: 21, y: 60, n: 6, size: 1.4 },
    { x: 28, y: 56, n: 5, size: 1.3 },
    { x: 35, y: 58, n: 4, size: 1.2 },
    { x: 41, y: 55, n: 4, size: 1.2 },
    // Right towers (Address BLVD / Boulevard Heights)
    { x: 60, y: 56, n: 5, size: 1.3 },
    { x: 67, y: 53, n: 5, size: 1.3 },
    { x: 74, y: 50, n: 6, size: 1.4 },
    { x: 81, y: 50, n: 6, size: 1.4 },
    { x: 88, y: 53, n: 4, size: 1.2 },
    // Foreground / podium
    { x: 12, y: 70, n: 3, size: 1.0 },
    { x: 95, y: 70, n: 3, size: 1.0 },
  ];

  // Generate flicker windows (deterministic seed per spot for stability)
  const windows = [];
  windowSpots.forEach((s, si) => {
    for (let i = 0; i < s.n; i++) {
      // pseudo-random offsets
      const seed = si * 17 + i * 31;
      const dx = (((seed * 9301 + 49297) % 233280) / 233280 - 0.5) * 2.4 * s.size;
      const dy = (((seed * 4007 + 17321) % 233280) / 233280 - 0.5) * 4.0 * s.size;
      const delay = (((seed * 2371) % 100) / 100) * 8;
      const dur = 3 + (((seed * 1933) % 100) / 100) * 6;
      windows.push({
        x: s.x + dx,
        y: s.y + dy,
        size: 1.5 + (((seed * 887) % 100) / 100) * 1.5,
        delay,
        dur,
        warm: (seed % 5) !== 0, // most warm, some cool
      });
    }
  });

  const darkVideoUrl = "assets/hero-v3.mp4";
  const darkMobileVideoUrl = "assets/hero-v3-mobile.mp4";
  const lightVideoUrl = "assets/hero-v2.mp4";
  const lightMobileVideoUrl = "assets/hero-v2-mobile.mp4";

  // Swap to a phone-cropped light video when the viewport is ≤760px.
  const [isMobile, setIsMobile] = React.useState(
    typeof window !== "undefined" && window.matchMedia
      ? window.matchMedia("(max-width: 760px)").matches
      : false
  );
  React.useEffect(() => {
    if (!window.matchMedia) return;
    const mq = window.matchMedia("(max-width: 760px)");
    const onChange = (e) => setIsMobile(e.matches);
    mq.addEventListener ? mq.addEventListener("change", onChange) : mq.addListener(onChange);
    return () => {
      mq.removeEventListener ? mq.removeEventListener("change", onChange) : mq.removeListener(onChange);
    };
  }, []);

  const videoUrl = isDark
    ? (isMobile ? darkMobileVideoUrl : darkVideoUrl)
    : (isMobile ? lightMobileVideoUrl : lightVideoUrl);

  const photoUrl = isDark
    ? "assets/hero-v3-poster.jpg"
    : (isMobile ? "assets/hero-v2-mobile-poster.jpg" : "assets/hero-v2-poster.jpg");

  return (
    <div className="photo-skyline" data-phase={phase}>
      {/* Base photo */}
      <div
        className="ps-photo"
        style={{
          backgroundImage: `url('${photoUrl}')`,
          filter: `${look.photoFilter} ${wxFilter}`.trim(),
          ...photoStyle,
        }}
      />

      {/* Video background — dark or light.
          iOS Safari is fussy: needs muted + playsInline + autoplay all
          set as ATTRIBUTES on the element (not just props), and silent
          tracks. We also set .muted = true imperatively because some
          iOS versions ignore the React-prop form. Poster covers
          low-power-mode users where autoplay is blocked entirely. */}
      <video
        ref={(el) => {
          if (!el) return;
          // Belt-and-braces: set the attributes directly so iOS Safari
          // sees them at parse time, not just via React's prop diff.
          el.muted = true;
          el.defaultMuted = true;
          el.setAttribute("muted", "");
          el.setAttribute("playsinline", "");
          el.setAttribute("webkit-playsinline", "");
          el.setAttribute("autoplay", "");
          el.setAttribute("loop", "");

          const tryPlay = () => {
            el.muted = true;
            const p = el.play();
            if (p && p.catch) p.catch(() => {});
          };
          tryPlay();
          const kick = () => { tryPlay(); cleanup(); };
          const cleanup = () => {
            window.removeEventListener("touchstart", kick);
            window.removeEventListener("pointerdown", kick);
            window.removeEventListener("scroll", kick);
            document.removeEventListener("visibilitychange", onVis);
          };
          // Try again when the tab becomes visible (low-power mode
          // sometimes gates autoplay until the page is foregrounded).
          const onVis = () => { if (!document.hidden) tryPlay(); };
          document.addEventListener("visibilitychange", onVis);
          window.addEventListener("touchstart", kick, { once: true, passive: true });
          window.addEventListener("pointerdown", kick, { once: true, passive: true });
          window.addEventListener("scroll", kick, { once: true, passive: true });
        }}
        key={videoUrl}
        className="ps-video"
        src={videoUrl}
        poster={photoUrl}
        autoPlay
        muted={true}
        loop
        playsInline
        webkit-playsinline="true"
        preload="metadata"
        disablePictureInPicture
        disableRemotePlayback
      />

      {/* Phase tint wash */}
      <div className="ps-tint" style={{ background: look.tint }} />

      {/* Sun overlay removed — photo already has natural horizon glow */}

      {/* Ground glow on warm phases */}
      <div className="ps-glow" style={{ background: `radial-gradient(ellipse at 50% 90%, ${look.glow} 0%, transparent 60%)` }} />

      {/* Animated drifting clouds — soft, low-opacity over the dusk sky */}
      <div className="ps-clouds" style={{ opacity: cond === "fog" ? 1 : cond === "cloudy" ? 0.55 : 0.32 }}>
        <div className="ps-cloud cloud-1" />
        <div className="ps-cloud cloud-2" />
        <div className="ps-cloud cloud-3" />
        <div className="ps-cloud cloud-4" />
        <div className="ps-cloud cloud-5" />
      </div>

      {/* Window flickers */}
      <div className="ps-windows" style={{ opacity: look.windowOpacity }}>
        {windows.map((w, i) => (
          <span
            key={i}
            className={`ps-window ${w.warm ? "warm" : "cool"}`}
            style={{
              left: `${w.x}%`,
              top: `${w.y}%`,
              width: `${w.size}px`,
              height: `${w.size * 1.3}px`,
              animationDelay: `${w.delay}s`,
              animationDuration: `${w.dur}s`,
            }}
          />
        ))}
      </div>

      {/* Sandstorm / rain layer */}
      {cond === "sandstorm" && <div className="ps-sand" />}
      {cond === "rain" && <div className="ps-rain" />}
      {cond === "fog" && <div className="ps-fog" />}

      {/* Vignette + bottom fade into page */}
      <div className="ps-vignette" />
      <div className="ps-bottom-fade" />

      <style>{`
        .photo-skyline {
          position: absolute;
          inset: 0;
          overflow: hidden;
          background: var(--bg);
        }
        .ps-photo {
          position: absolute;
          inset: 0;
          background-color: var(--bg);
          background-repeat: no-repeat;
          transition: filter 1.6s var(--ease);
          will-change: filter;
        }
        .ps-video {
          position: absolute;
          inset: 0;
          width: 100%;
          height: 100%;
          object-fit: cover;
          object-position: center 85%;
          z-index: 1;
          filter: brightness(1.05) saturate(1.05) contrast(1.05);
        }
        :root[data-theme="dark"] .ps-video {
          /* Frame for desktop — slight zoom keeps the Burj + house
             cluster centered with a touch of sky headroom. */
          object-position: 55% 45%;
          transform: scale(1.05);
          transform-origin: 55% 45%;
          filter: brightness(1.02) saturate(1.1) contrast(1.08);
          image-rendering: -webkit-optimize-contrast;
          image-rendering: crisp-edges;
        }
        /* Photo poster fallback — same scene as the video so if autoplay
           is blocked (mobile Safari, low-power mode), the right scene
           still shows. Higher opacity in dark mode is fine now. */
        :root[data-theme="dark"] .ps-photo { opacity: 0.85; }
        /* Kill the decorative blurred cloud sprites in dark mode —
           the cloud video already has real clouds and the blurred
           overlays were what made the hero look soft. */
        :root[data-theme="dark"] .ps-clouds,
        :root[data-theme="dark"] .ps-vignette { display: none; }
        /* Soften the multiply tint over the video so contrast
           stays high — keep it just enough for copy legibility. */
        :root[data-theme="dark"] .ps-tint { opacity: 0.55; }
        :root[data-theme="light"] .ps-video {
          /* Slightly darken the daytime video so black hero copy lifts
             cleanly off the sky. Frame the video so the Mercedes /
             ground line sits comfortably above the bottom — bias toward
             ~70% Y so we see more of the lower half (the cars) and
             less of the empty sky. */
          filter: brightness(0.92) saturate(0.95) contrast(1.05);
          object-position: center 70%;
          transform: scale(1.04);
          transform-origin: center 70%;
        }

        /* Mobile framing — hero is now a natural-aspect strip (handled by
           hero.jsx). Inside that strip, the video uses contain to show its
           FULL frame without any crop or stretch — what the user sees is
           exactly the video's framing. */
        @media (max-width: 760px) {
          .ps-video {
            object-position: center center;
            object-fit: cover;
            transform: none;
          }
          :root[data-theme="dark"] .ps-video {
            object-position: center center;
            transform: none;
            filter: brightness(1.0) saturate(1.1) contrast(1.08);
          }
          :root[data-theme="light"] .ps-video {
            object-fit: cover;
            object-position: center center;
            transform: none;
            filter: brightness(0.95) saturate(0.95) contrast(1.05);
          }
          .ps-photo {
            background-position: center center !important;
            background-size: cover !important;
            transform: none !important;
          }
          /* Hide the bottom fade — the strip ends naturally. */
          .ps-bottom-fade { display: none; }
          /* Disable the heavy light-mode wash on mobile so the video
             colors come through cleanly — but keep a soft bottom fade
             so the strip dissolves into the page bg under the cars. */
          :root[data-theme="light"] .photo-skyline::after {
            background: linear-gradient(
              to bottom,
              transparent 0%,
              transparent 60%,
              rgba(250,247,242,0.45) 80%,
              rgba(250,247,242,0.92) 95%,
              rgba(250,247,242,1) 100%
            ) !important;
          }
        }
        .photo-skyline[data-phase="evening"] .ps-clouds,
        .photo-skyline[data-phase="evening"] .ps-windows,
        .photo-skyline[data-phase="evening"] .ps-tint,
        .photo-skyline[data-phase="evening"] .ps-glow,
        .photo-skyline[data-phase="evening"] .ps-vignette {
          z-index: 2;
        }
        .photo-skyline[data-phase="evening"] .ps-bottom-fade { z-index: 3; }
        .ps-tint {
          position: absolute;
          inset: 0;
          mix-blend-mode: multiply;
          transition: background 1.6s var(--ease);
          pointer-events: none;
        }
        .ps-glow {
          position: absolute;
          inset: 0;
          mix-blend-mode: screen;
          transition: background 1.6s var(--ease);
          pointer-events: none;
        }
        .ps-vignette {
          position: absolute;
          inset: 0;
          background: radial-gradient(ellipse at 50% 50%, transparent 40%, rgba(0,0,0,0.25) 100%);
          pointer-events: none;
        }
        .ps-bottom-fade {
          position: absolute;
          left: 0; right: 0; bottom: 0;
          height: 40%;
          background: linear-gradient(to bottom, transparent 0%, var(--bg) 95%);
          pointer-events: none;
        }

        /* Light-mode legibility wash: warms the whole hero so dark windows don't
           clash with black copy. Sits above the video but below the content.
           The bottom is intentionally heavy so the hero blends gracefully into
           the page bg instead of slicing the Mercedes / horizon line in half. */
        :root[data-theme="light"] .photo-skyline::after {
          content: "";
          position: absolute;
          inset: 0;
          background:
            linear-gradient(
              to bottom,
              rgba(250,247,242,0.32) 0%,
              rgba(250,247,242,0.42) 35%,
              rgba(250,247,242,0.62) 70%,
              rgba(250,247,242,0.92) 90%,
              rgba(250,247,242,1) 100%
            );
          pointer-events: none;
          z-index: 3;
        }

        /* Sun & moon */
        .ps-sun {
          position: absolute;
          width: 280px;
          height: 280px;
          transform: translate(-50%, -50%);
          mix-blend-mode: screen;
          pointer-events: none;
          animation: sunPulse 6s var(--ease) infinite alternate;
        }
        @keyframes sunPulse { to { transform: translate(-50%, -50%) scale(1.08); opacity: .9; } }
        .ps-moon {
          position: absolute;
          left: 78%; top: 18%;
          width: 60px; height: 60px;
          border-radius: 50%;
          background: radial-gradient(circle at 35% 35%, #f4f1e8, #cdc7b4 70%, #8a8676);
          box-shadow: 0 0 60px rgba(220,220,255,0.3), inset -8px -8px 12px rgba(0,0,0,0.2);
          pointer-events: none;
        }

        /* Clouds */
        .ps-clouds {
          position: absolute;
          inset: 0;
          pointer-events: none;
          mix-blend-mode: screen;
          transition: opacity 1.2s var(--ease);
        }
        .ps-cloud {
          position: absolute;
          background: radial-gradient(ellipse at center, rgba(160,180,210,0.42) 0%, rgba(120,140,180,0.18) 45%, transparent 75%);
          border-radius: 50%;
          filter: blur(14px);
        }
        .photo-skyline[data-phase="night"] .ps-cloud,
        .photo-skyline[data-phase="deepNight"] .ps-cloud {
          background: radial-gradient(ellipse at center, rgba(180,190,220,0.35) 0%, rgba(120,130,170,0.15) 40%, transparent 70%);
        }
        .photo-skyline[data-phase="dawn"] .ps-cloud,
        .photo-skyline[data-phase="goldenHour"] .ps-cloud {
          background: radial-gradient(ellipse at center, rgba(255,200,160,0.55) 0%, rgba(255,170,130,0.2) 40%, transparent 70%);
        }
        .cloud-1 { width: 420px; height: 70px; top: 8%;  left: -25%; animation: cloudDrift 95s linear infinite; }
        .cloud-2 { width: 280px; height: 55px; top: 14%; left: -25%; animation: cloudDrift 130s linear infinite -40s; }
        .cloud-3 { width: 520px; height: 90px; top: 4%;  left: -25%; animation: cloudDrift 160s linear infinite -90s; }
        .cloud-4 { width: 220px; height: 50px; top: 18%; left: -25%; animation: cloudDrift 110s linear infinite -60s; }
        .cloud-5 { width: 360px; height: 65px; top: 22%; left: -25%; animation: cloudDrift 140s linear infinite -110s; }
        @keyframes cloudDrift {
          to { transform: translateX(150vw); }
        }

        /* Window flickers */
        .ps-windows {
          position: absolute;
          inset: 0;
          pointer-events: none;
          transition: opacity 1.6s var(--ease);
          mix-blend-mode: screen;
        }
        .ps-window {
          position: absolute;
          border-radius: 1px;
          transform: translate(-50%, -50%);
          animation: flicker 5s var(--ease) infinite;
        }
        .ps-window.warm {
          background: #ffd28a;
          box-shadow: 0 0 4px rgba(255,200,120,0.9), 0 0 10px rgba(255,180,100,0.5);
        }
        .ps-window.cool {
          background: #cfe6ff;
          box-shadow: 0 0 4px rgba(180,220,255,0.8), 0 0 10px rgba(140,200,255,0.4);
        }
        @keyframes flicker {
          0%,100% { opacity: 0.85; }
          15%     { opacity: 0.3; }
          30%     { opacity: 1; }
          55%     { opacity: 0.5; }
          80%     { opacity: 0.95; }
        }

        /* Weather */
        .ps-fog {
          position: absolute;
          inset: 0;
          background: linear-gradient(to bottom, rgba(220,220,225,0.6) 0%, rgba(200,200,210,0.3) 50%, transparent 80%);
          pointer-events: none;
        }
        .ps-sand {
          position: absolute;
          inset: 0;
          background: linear-gradient(to bottom, rgba(220,160,90,0.45) 0%, rgba(200,140,80,0.25) 60%, transparent 100%);
          pointer-events: none;
          mix-blend-mode: multiply;
        }
        .ps-rain {
          position: absolute;
          inset: 0;
          pointer-events: none;
          background-image:
            linear-gradient(to bottom, transparent 0%, rgba(180,200,220,0.18) 50%, transparent 100%);
          background-size: 2px 14px;
          animation: rainFall 0.6s linear infinite;
          opacity: 0.6;
        }
        @keyframes rainFall {
          to { background-position: 0 14px; }
        }
      `}</style>
    </div>
  );
};

window.PhotoSkyline = PhotoSkyline;
