// App — composes the site, handles the audit modal + video modal + scroll reveal + icon init.
// The audit form (AuditModal) and the useModalA11y hook live in the shared AuditModal.jsx, loaded before this file.

function VideoModal({ onClose }) {
  const vref = React.useRef(null);
  const [playing, setPlaying] = React.useState(false);
  const [started, setStarted] = React.useState(false);
  const [t, setT] = React.useState(0);
  const [dur, setDur] = React.useState(0);
  const [done, setDone] = React.useState(false);
  const [closing, setClosing] = React.useState(false);
  const [isFull, setIsFull] = React.useState(false);
  const close = () => { setClosing(true); setTimeout(onClose, 300); };
  const toggle = () => {
    const v = vref.current; if (!v) return;
    if (done) { v.currentTime = 0; v.play(); return; }
    if (v.paused) v.play(); else v.pause();
  };
  const pct = dur ? (t / dur) * 100 : 0;
  const fmt = s => '0:' + String(Math.max(0, Math.floor(s))).padStart(2, '0');
  const ref = useModalA11y(close);
  const secs = dur ? Math.round(dur) : 49;
  const setTime = nt => { const v = vref.current; if (!v) return; const c = Math.max(0, Math.min(dur || 0, nt)); v.currentTime = c; setT(c); };
  const seek = e => {
    if (!dur) return;
    const r = e.currentTarget.getBoundingClientRect();
    const x = (e.touches ? e.touches[0].clientX : e.clientX) - r.left;
    setTime(Math.max(0, Math.min(1, x / r.width)) * dur);
  };
  const toggleFull = e => {
    e && e.stopPropagation();
    const d = document, m = ref.current, v = vref.current;
    if (d.fullscreenElement || d.webkitFullscreenElement) {
      (d.exitFullscreen || d.webkitExitFullscreen).call(d);
    } else if (m && m.requestFullscreen) { m.requestFullscreen(); }
    else if (m && m.webkitRequestFullscreen) { m.webkitRequestFullscreen(); }
    else if (v && v.webkitEnterFullscreen) { v.webkitEnterFullscreen(); } // iPhone fallback
  };
  React.useEffect(() => {
    const h = () => setIsFull(!!(document.fullscreenElement || document.webkitFullscreenElement));
    document.addEventListener('fullscreenchange', h);
    document.addEventListener('webkitfullscreenchange', h);
    return () => { document.removeEventListener('fullscreenchange', h); document.removeEventListener('webkitfullscreenchange', h); };
  }, []);
  return (
    <div className={'video-scrim' + (closing ? ' closing' : '')} onClick={close}>
      <div className="video-modal" ref={ref} tabIndex={-1} role="dialog" aria-modal="true" aria-label="How Origo works" onClick={e => e.stopPropagation()}>
        <div className="video-head">
          <span className="vt"><span className="vdot"></span>How Origo works</span>
          <span className="vhr">
            <button className="vfs" onClick={toggleFull} aria-label={isFull ? 'Exit fullscreen' : 'Fullscreen'}>
              {isFull
                ? <svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" strokeWidth="2"><path d="M3 8h3a2 2 0 0 0 2-2V3M21 8h-3a2 2 0 0 1-2-2V3M3 16h3a2 2 0 0 1 2 2v3M21 16h-3a2 2 0 0 0-2 2v3"/></svg>
                : <svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" strokeWidth="2"><path d="M8 3H5a2 2 0 0 0-2 2v3M16 3h3a2 2 0 0 1 2 2v3M8 21H5a2 2 0 0 1-2-2v-3M16 21h3a2 2 0 0 0 2-2v-3"/></svg>}
            </button>
            <button className="vx" onClick={close} aria-label="Close">×</button>
          </span>
        </div>
        <div className={'video-stage' + ((started || t > 0) ? ' is-playing' : '')} onClick={toggle}>
          <div className="video-glow"></div>
          <img className="video-wmk" src="assets/origo-o.svg?v=4" alt="" />
          <video
            ref={vref}
            className="video-el"
            src="assets/origo-trailer.mp4?v=51"
            poster="assets/origo-trailer-poster.jpg?v=51"
            playsInline
            preload="metadata"
            onLoadedMetadata={e => setDur(e.target.duration)}
            onTimeUpdate={e => setT(e.target.currentTime)}
            onPlay={() => { setPlaying(true); setStarted(true); setDone(false); }}
            onPause={() => setPlaying(false)}
            onEnded={() => { setPlaying(false); setDone(true); }}
          />
          {(!playing && !done && !started) && (
            <button className="play-big" aria-label="Play"><svg viewBox="0 0 24 24" width="26" height="26" fill="#000"><path d="M5 3.5v17l14-8.5z"/></svg></button>
          )}
          {(!playing && started) && (
            <button className="play-big play-resume" aria-label={done ? 'Replay' : 'Play'}><svg viewBox="0 0 24 24" width="26" height="26" fill="#000"><path d="M5 3.5v17l14-8.5z"/></svg></button>
          )}
          {(!started && t === 0) && <div className="video-cap">A {secs}-second look at how we get you cited</div>}
          {done && <div className="video-cap">Replay</div>}
        </div>
        <div className="video-bar" onClick={seek} role="slider" aria-label="Seek" tabIndex={0}
             aria-valuemin={0} aria-valuemax={secs} aria-valuenow={Math.floor(t)}
             onKeyDown={e => { const v = vref.current; if (!v || !dur) return; if (e.key === 'ArrowRight') setTime(v.currentTime + 5); if (e.key === 'ArrowLeft') setTime(v.currentTime - 5); }}>
          <div className="video-fill" style={{ width: pct + '%' }}></div>
        </div>
        <div className="video-foot"><span className="vtime">{fmt(t)} / {fmt(secs)}</span></div>
      </div>
    </div>
  );
}

function App() {
  const [modal, setModal] = React.useState(false);
  const [video, setVideo] = React.useState(false);
  const open = () => setModal(true);

  React.useEffect(() => {
    if (window.lucide) window.lucide.createIcons();
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) e.target.classList.add('in'); });
    }, { threshold: 0.12 });
    document.querySelectorAll('.reveal').forEach(el => io.observe(el));
    return () => io.disconnect();
  }, []);

  return (
    <React.Fragment>
      <Nav onDemo={open} />
      <main id="main">
        <Hero onDemo={open} onVideo={() => setVideo(true)} />
        <EngineStrip />
        <Method />
        <ShareBars />
        <Showcase />
        <CTA onDemo={open} />
      </main>
      <Footer />
      {modal && <AuditModal onClose={() => setModal(false)} />}
      {video && <VideoModal onClose={() => setVideo(false)} />}
    </React.Fragment>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);