// Day/Night cinematic section — real time-lapse video, scrubbed by toggle
function DayNight() {
  const [mode, setMode] = useState('day'); // day | night
  const rootRef = useRef(null);
  const videoRef = useRef(null);
  const animRef = useRef(null);

  // Video time anchors. Source clip is 8s dawn → night.
  const DAY_T = 0.0;
  const NIGHT_T = 7.6;
  const SCRUB_MS = 2200; // a beat slower than the original 2.5s for that wow

  // Smoothly scrub video.currentTime to a target. Pauses native playback,
  // runs an rAF loop with easeInOutQuad. Reliable across browsers (reverse
  // playback via playbackRate is not).
  const seekTo = useCallback((target) => {
    const v = videoRef.current;
    if (!v) return;
    v.pause();
    cancelAnimationFrame(animRef.current);
    const start = v.currentTime;
    const t0 = performance.now();
    const tick = (now) => {
      const t = Math.min((now - t0) / SCRUB_MS, 1);
      const eased = t < 0.5 ? 2*t*t : -1 + (4 - 2*t)*t;
      v.currentTime = start + (target - start) * eased;
      if (t < 1) animRef.current = requestAnimationFrame(tick);
    };
    animRef.current = requestAnimationFrame(tick);
  }, []);

  useEffect(() => {
    if (!rootRef.current) return;
    rootRef.current.style.setProperty('--dn', mode === 'night' ? '1' : '0');
  }, [mode]);

  // On mount, park the video at the day frame.
  useEffect(() => {
    const v = videoRef.current;
    if (!v) return;
    const park = () => { try { v.currentTime = DAY_T; } catch {} };
    if (v.readyState >= 1) park();
    else v.addEventListener('loadedmetadata', park, { once: true });
    return () => cancelAnimationFrame(animRef.current);
  }, []);

  const handleToggle = (next) => {
    if (next === mode) return;
    setMode(next);
    seekTo(next === 'night' ? NIGHT_T : DAY_T);
  };

  return (
    <section id="daynight" ref={rootRef} className="dn-section" style={{ padding: '140px 0 140px', overflow: 'hidden' }}>
      <div className="container-x">
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'end', gap: 40, flexWrap: 'wrap', marginBottom: 40 }}>
          <div style={{ maxWidth: 720 }}>
            <Reveal><div className="eyebrow" style={{ color: mode === 'night' ? 'rgba(250,247,241,.7)' : 'var(--forest-800)' }}><span className="dot" /> Dark‑sky standards</div></Reveal>
            <Reveal delay={1}><h2 className="h2" style={{ marginTop: 18 }}>A quiet presence,<br/><span className="italic-serif" style={{ color: mode === 'night' ? 'var(--accent)' : 'var(--forest-800)' }}>day and night.</span></h2></Reveal>
          </div>
          <Reveal delay={2}>
            <p className="dn-muted" style={{ fontSize: 16, lineHeight: 1.6, maxWidth: 420 }}>
              Lighting and fencing standards are written to reduce glare, protect night skies, and allow wildlife to maintain movement patterns. Toggle between day and night to see how the campus settles into the landscape after sundown.
            </p>
          </Reveal>
        </div>

        {/* Scene */}
        <Reveal delay={2}>
          <div style={{ position: 'relative', borderRadius: 28, overflow: 'hidden', border: '1px solid rgba(255,255,255,.08)', boxShadow: '0 20px 60px rgba(0,0,0,.3)' }}>
            <div style={{ position: 'relative', aspectRatio: '16 / 9', background: '#000' }}>
              <video
                ref={videoRef}
                src="/video/daynight.mp4"
                muted
                playsInline
                preload="auto"
                style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', display: 'block' }}
              />

              {/* Bottom gradient — adds depth + kills the "Veo" watermark contrast */}
              <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none', background: 'linear-gradient(180deg, rgba(0,0,0,0) 55%, rgba(0,0,0,.55) 100%)' }} />

              {/* Toggle */}
              <div style={{ position: 'absolute', left: 20, top: 20, display: 'flex', gap: 10 }}>
                <span className="pill pill-dark" style={{ background: 'rgba(0,0,0,.45)', color: 'white' }}>{mode === 'day' ? 'Daytime view' : 'Nighttime view · dark‑sky compliant'}</span>
              </div>
              <div style={{ position: 'absolute', right: 20, top: 20 }}>
                <div className="glass-dark" style={{ display: 'inline-flex', padding: 4, borderRadius: 999, gap: 2 }}>
                  {[{k:'day', label:'Day', Icon: Icons.Sun}, {k:'night', label:'Night', Icon: Icons.Moon}].map(opt => (
                    <button key={opt.k} onClick={() => handleToggle(opt.k)} style={{
                      display: 'inline-flex', alignItems: 'center', gap: 8,
                      padding: '10px 16px', borderRadius: 999, border: 'none', cursor: 'pointer',
                      background: mode === opt.k ? 'white' : 'transparent',
                      color: mode === opt.k ? 'var(--ink)' : 'rgba(255,255,255,.85)',
                      fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 13,
                      transition: 'background .3s, color .3s'
                    }}>
                      <opt.Icon size={16} /> {opt.label}
                    </button>
                  ))}
                </div>
              </div>

              {/* Time bar + Fig. 03 */}
              <div style={{ position: 'absolute', left: 20, right: 20, bottom: 20 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                  <span className="tag-mono" style={{ color: 'rgba(255,255,255,.85)' }}>{mode === 'day' ? '14:00' : '23:40'}</span>
                  <div style={{ flex: 1, height: 4, borderRadius: 999, background: 'rgba(255,255,255,.2)', position: 'relative', overflow: 'hidden' }}>
                    <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: mode === 'day' ? '20%' : '95%', background: 'linear-gradient(90deg, #fff5c4, var(--accent))', transition: `width ${SCRUB_MS}ms ease` }} />
                  </div>
                  <span className="tag-mono" style={{ color: 'rgba(255,255,255,.7)', letterSpacing: '.18em' }}>Fig. 03 · Time‑lapse</span>
                </div>
              </div>
            </div>
          </div>
        </Reveal>

        {/* Stat row */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 18, marginTop: 28 }}>
          {[
            { k: 'Dark‑sky', v: 'Lighting standards', text: 'Glare reduced; night skies and wildlife movement protected.' },
            { k: 'Inward', v: 'Equipment oriented', text: 'Generators and cooling face the interior — away from property lines.' },
            { k: 'Before 4pm', v: 'Generator testing', text: 'Limited to Monday–Friday before 4pm; required by design.' },
          ].map((s, i) => (
            <Reveal key={i} delay={i+1} className="dn-card" style={{ padding: 22, borderRadius: 18, border: '1px solid rgba(10,24,18,.08)' }}>
              <div className="font-display" style={{ fontWeight: 600, fontSize: 22 }}>{s.k}</div>
              <div className="tag-mono" style={{ marginTop: 4 }}>{s.v}</div>
              <div className="dn-muted" style={{ fontSize: 14.5, lineHeight: 1.55, marginTop: 10 }}>{s.text}</div>
            </Reveal>
          ))}
        </div>
      </div>
      <style>{`@media(max-width: 820px){ #daynight > .container-x > div:last-child { grid-template-columns: 1fr !important; } }`}</style>
    </section>
  );
}
window.DayNight = DayNight;
