// vsl-app.jsx — Avend VSL page

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "videoUrl": "https://www.w3schools.com/html/mov_bbb.mp4",
  "headline": "Descubra como a Avend transforma espaços em renda recorrente.",
  "subhead": "Assista ao vídeo abaixo até o fim. As próximas instruções aparecerão automaticamente quando ele terminar.",
  "showProgress": true,
  "lockSeek": true,
  "lockPause": true,
  "showCtaAtSeconds": 30,
  "ctaLabel": "Falar com um consultor",
  "ctaUrl": "#contato",
  "fakeProgressCurve": 0.4,
  "endMessage": "Em breve entraremos em contato.",
  "testFastForward": false
}/*EDITMODE-END*/;

const MUTE_STORAGE_KEY = "avend_vsl_muted";

const { useState, useEffect, useRef, useCallback } = React;

// ───────────────────────────────────────────────────────────────────────
// Utility
// ───────────────────────────────────────────────────────────────────────
function fmt(t) {
  if (!isFinite(t) || t < 0) t = 0;
  const m = Math.floor(t / 60);
  const s = Math.floor(t % 60);
  return `${m}:${s.toString().padStart(2, "0")}`;
}

// ───────────────────────────────────────────────────────────────────────
// Top header — Avend logo
// ───────────────────────────────────────────────────────────────────────
function Header() {
  return (
    <header className="header">
      <div className="header-inner">
        <a className="brand" href="https://avend.com.br" target="_blank" rel="noreferrer">
          <img src="assets/avend-watermark.png" alt="Avend" />
        </a>
      </div>
    </header>
  );
}

// ───────────────────────────────────────────────────────────────────────
// VSL Player
// ───────────────────────────────────────────────────────────────────────
function VSLPlayer({ tweaks }) {
  const videoRef = useRef(null);
  const wrapRef = useRef(null);
  const pauseBypassRef = useRef(false); // user-intentional pause (mute) skips lockPause
  const [armed, setArmed] = useState(false);     // user clicked the unmute gate
  const [muted, setMuted] = useState(true);
  const [playing, setPlaying] = useState(false);
  const [time, setTime] = useState(0);
  const [duration, setDuration] = useState(0);
  const [ended, setEnded] = useState(false);
  const [showCta, setShowCta] = useState(false);
  const [bufferingHint, setBufferingHint] = useState(false);
  const [isFullscreen, setIsFullscreen] = useState(false);

  // Wall-clock CTA reveal — N seconds after the page mounts, not after video time
  useEffect(() => {
    if (!tweaks.showCtaAtSeconds || tweaks.showCtaAtSeconds <= 0) return;
    const id = setTimeout(() => setShowCta(true), tweaks.showCtaAtSeconds * 1000);
    return () => clearTimeout(id);
  }, [tweaks.showCtaAtSeconds]);

  // Autoplay muted on mount
  useEffect(() => {
    const v = videoRef.current;
    if (!v) return;
    v.muted = true;
    v.playsInline = true;
    const tryPlay = () => {
      const p = v.play();
      if (p && p.catch) p.catch(() => {});
    };
    tryPlay();
  }, []);

  // Time tracking + locked-seek enforcement
  useEffect(() => {
    const v = videoRef.current;
    if (!v) return;

    let lastTime = 0;
    const onTime = () => {
      // Locked seek: reject any forward jump > 1.5s
      if (tweaks.lockSeek && v.currentTime - lastTime > 1.5) {
        v.currentTime = lastTime;
      } else {
        lastTime = v.currentTime;
      }
      setTime(v.currentTime);
    };
    const onLoaded = () => setDuration(v.duration || 0);
    const onPlay = () => { setPlaying(true); setBufferingHint(false); };
    const onPause = () => {
      setPlaying(false);
      // Skip lock when the pause was user-intentional (mute toggle)
      if (pauseBypassRef.current) return;
      // If locked, immediately resume — unless ended or pre-armed (still in muted preroll)
      if (tweaks.lockPause && armed && !v.ended) {
        setTimeout(() => { v.play().catch(() => {}); }, 30);
      }
    };
    const onEnded = () => { setPlaying(false); setEnded(true); };
    const onSeeking = () => {
      if (tweaks.lockSeek && Math.abs(v.currentTime - lastTime) > 1.5) {
        v.currentTime = lastTime;
      }
    };
    const onWaiting = () => setBufferingHint(true);
    const onPlaying = () => setBufferingHint(false);

    v.addEventListener("timeupdate", onTime);
    v.addEventListener("loadedmetadata", onLoaded);
    v.addEventListener("durationchange", onLoaded);
    v.addEventListener("play", onPlay);
    v.addEventListener("pause", onPause);
    v.addEventListener("ended", onEnded);
    v.addEventListener("seeking", onSeeking);
    v.addEventListener("waiting", onWaiting);
    v.addEventListener("playing", onPlaying);

    return () => {
      v.removeEventListener("timeupdate", onTime);
      v.removeEventListener("loadedmetadata", onLoaded);
      v.removeEventListener("durationchange", onLoaded);
      v.removeEventListener("play", onPlay);
      v.removeEventListener("pause", onPause);
      v.removeEventListener("ended", onEnded);
      v.removeEventListener("seeking", onSeeking);
      v.removeEventListener("waiting", onWaiting);
      v.removeEventListener("playing", onPlaying);
    };
  }, [armed, tweaks.lockSeek, tweaks.lockPause]);

  // Block context menu on the video so users can't open native controls / save
  useEffect(() => {
    const w = wrapRef.current;
    if (!w) return;
    const onCtx = (e) => e.preventDefault();
    w.addEventListener("contextmenu", onCtx);
    return () => w.removeEventListener("contextmenu", onCtx);
  }, []);

  // Block keyboard seeking shortcuts when video focused
  useEffect(() => {
    const onKey = (e) => {
      if (!armed) return;
      const blocked = ["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown", " ", "k", "K", "j", "J", "l", "L"];
      if (blocked.includes(e.key)) {
        e.preventDefault();
        e.stopPropagation();
      }
    };
    window.addEventListener("keydown", onKey, true);
    return () => window.removeEventListener("keydown", onKey, true);
  }, [armed]);

  const arm = useCallback(() => {
    const v = videoRef.current;
    if (!v) return;
    // Gate click is an explicit "unmute" intent — always honor it,
    // and clear any stale saved preference from a previous session.
    v.muted = false;
    v.currentTime = 0;
    setMuted(false);
    setArmed(true);
    setEnded(false);
    try { localStorage.setItem(MUTE_STORAGE_KEY, "0"); } catch (_) {}
    const p = v.play();
    if (p && p.catch) p.catch(() => {});
  }, []);

  const toggleMute = useCallback(() => {
    const v = videoRef.current;
    if (!v) return;
    const willMute = !v.muted;
    v.muted = willMute;
    setMuted(willMute);
    try { localStorage.setItem(MUTE_STORAGE_KEY, willMute ? "1" : "0"); } catch (_) {}
    if (willMute) {
      // User-intentional pause — bypass lockPause auto-resume for this stop
      pauseBypassRef.current = true;
      v.pause();
    } else {
      pauseBypassRef.current = false;
      const p = v.play();
      if (p && p.catch) p.catch(() => {});
    }
  }, []);

  const toggleFullscreen = useCallback(() => {
    setIsFullscreen((prev) => !prev);
  }, []);

  // Lock body scroll while in pseudo-fullscreen (mobile)
  useEffect(() => {
    if (!isFullscreen) return;
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => { document.body.style.overflow = prevOverflow; };
  }, [isFullscreen]);

  // Test fast-forward (Tweaks)
  useEffect(() => {
    if (!tweaks.testFastForward) return;
    const v = videoRef.current;
    if (!v || !duration) return;
    v.currentTime = Math.max(0, duration - 1.5);
  }, [tweaks.testFastForward, duration]);

  const realProgress = duration ? time / duration : 0;
  const curve = Math.max(0.05, Math.min(1, tweaks.fakeProgressCurve || 0.4));
  const fakeProgress = Math.pow(realProgress, curve) * 100;
  const remaining = duration ? Math.max(0, duration - time) : 0;

  return (
    <section className="player-section">
      <div className={`player-frame ${isFullscreen ? "is-fs" : ""}`} ref={wrapRef}>
        <div className={`player ${ended ? "is-ended" : ""}`}>
          <video
            ref={videoRef}
            src={tweaks.videoUrl}
            playsInline
            preload="auto"
            disablePictureInPicture
            controlsList="nodownload nofullscreen noremoteplayback noplaybackrate"
            onContextMenu={(e) => e.preventDefault()}
          />

          {/* Click guard — blocks native pause/double-click */}
          <div className="click-guard" />

          {/* Watermark */}
          <div className="wm">
            <img src="assets/avend-symbol.png" alt="" />
          </div>

          {/* Mute toggle — visible after arming */}
          {armed && !ended && (
            <button
              type="button"
              className="mute-btn"
              onClick={toggleMute}
              aria-label={muted ? "Ativar som" : "Mutar som"}
            >
              {muted ? (
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" aria-hidden="true">
                  <path d="M11 5L6 9H3a1 1 0 0 0-1 1v4a1 1 0 0 0 1 1h3l5 4V5Z" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round"/>
                  <path d="M16 9l6 6M22 9l-6 6" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/>
                </svg>
              ) : (
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" aria-hidden="true">
                  <path d="M11 5L6 9H3a1 1 0 0 0-1 1v4a1 1 0 0 0 1 1h3l5 4V5Z" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round"/>
                  <path d="M16 9c1.2 1 1.2 5 0 6M19 6c2.5 2.5 2.5 9.5 0 12" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/>
                </svg>
              )}
            </button>
          )}

          {/* Fullscreen toggle — mobile only via CSS, doesn't rotate */}
          {!ended && (
            <button
              type="button"
              className="fs-btn"
              onClick={toggleFullscreen}
              aria-label={isFullscreen ? "Sair da tela cheia" : "Tela cheia"}
            >
              {isFullscreen ? (
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" aria-hidden="true">
                  <path d="M9 4v5H4M15 4v5h5M9 20v-5H4M15 20v-5h5" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
              ) : (
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" aria-hidden="true">
                  <path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
              )}
            </button>
          )}

          {/* Pre-arm overlay: click to enable sound */}
          {!armed && !ended && (
            <button className="unmute-gate" onClick={arm}>
              <div className="unmute-gate-inner">
                <div className="unmute-icon">
                  <svg width="28" height="28" viewBox="0 0 24 24" fill="none">
                    <path d="M11 5L6 9H3a1 1 0 0 0-1 1v4a1 1 0 0 0 1 1h3l5 4V5Z" stroke="currentColor" strokeWidth="1.5" strokeLinejoin="round"/>
                    <path d="M16 9c1.2 1 1.2 5 0 6M19 6c2.5 2.5 2.5 9.5 0 12" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
                  </svg>
                </div>
                <div className="unmute-copy">
                  <strong>Seu vídeo já começou</strong>
                  <span>Toque para ativar o som</span>
                </div>
              </div>
              <div className="unmute-pulse" />
            </button>
          )}

          {/* End state */}
          {ended && (
            <div className="end-overlay">
              <div className="end-card">
                <div className="end-check" aria-hidden="true">
                  <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
                    <path d="M5 12.5l4.5 4.5L19 7.5" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                  </svg>
                </div>
                <h2>{tweaks.endMessage}</h2>
                <p>Mantenha seu WhatsApp por perto. Nosso consultor irá direcionar os próximos passos da sua conversa com a Avend.</p>
                <div className="end-meta">
                  <span className="dot" /> Você está na fila de atendimento
                </div>
              </div>
            </div>
          )}

          {/* Buffering hint */}
          {bufferingHint && armed && !ended && (
            <div className="buffering">
              <div className="spinner" />
            </div>
          )}
        </div>

        {/* Progress bar — non-interactive, non-linear (fast at start, slow at end) */}
        {tweaks.showProgress && !ended && (
          <div className="progress-row" aria-hidden="true">
            <div className="progress-track">
              <div className="progress-fill" style={{ width: `${fakeProgress}%` }} />
            </div>
          </div>
        )}
      </div>

      {/* Wall-clock CTA — stays visible after the video ends */}
      {showCta && tweaks.showCtaAtSeconds > 0 && (
        <a className="mid-cta mid-cta-green" href={tweaks.ctaUrl || "#contato"}>
          {tweaks.ctaLabel} <span aria-hidden>→</span>
        </a>
      )}
    </section>
  );
}

// ───────────────────────────────────────────────────────────────────────
// Trust strip
// ───────────────────────────────────────────────────────────────────────
function TrustStrip() {
  const items = [
    ["+250", "unidades ativas"],
    ["16", "estados no Brasil"],
    ["24/7", "operação contínua"],
    ["+80", "franqueados ativos"],
  ];
  return (
    <section className="trust">
      <div className="trust-inner">
        {items.map(([n, l], i) => (
          <div key={i} className="trust-item">
            <strong>{n}</strong>
            <span>{l}</span>
          </div>
        ))}
      </div>
    </section>
  );
}

// ───────────────────────────────────────────────────────────────────────
// Footer
// ───────────────────────────────────────────────────────────────────────
function Footer() {
  return (
    <footer className="footer">
      <div className="footer-inner">
        <span>© 2026 Grupo Avend — Todos os direitos reservados</span>
        <span className="dim">CNPJ 47.443.212/0001-07</span>
      </div>
    </footer>
  );
}

// ───────────────────────────────────────────────────────────────────────
// App
// ───────────────────────────────────────────────────────────────────────
function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);

  return (
    <div className="page">
      <Header />

      <main className="main">
        <h1 className="hook-title">{t.headline}</h1>

        <VSLPlayer tweaks={t} />
      </main>

      <div className="footnote">
        © Grupo Avend · CNPJ 47.443.212/0001-07
      </div>

      <TweaksPanel>
        <TweakSection label="Conteúdo" />
        <TweakText label="Headline" value={t.headline} onChange={(v) => setTweak('headline', v)} />
        <TweakText label="Subhead"  value={t.subhead}  onChange={(v) => setTweak('subhead', v)} />
        <TweakText label="Mensagem final" value={t.endMessage} onChange={(v) => setTweak('endMessage', v)} />
        <TweakText label="URL do vídeo" value={t.videoUrl} onChange={(v) => setTweak('videoUrl', v)} />

        <TweakSection label="Mecânicas VSL" />
        <TweakToggle label="Bloquear avanço (seek)" value={t.lockSeek} onChange={(v) => setTweak('lockSeek', v)} />
        <TweakToggle label="Bloquear pausa" value={t.lockPause} onChange={(v) => setTweak('lockPause', v)} />
        <TweakToggle label="Mostrar barra de progresso" value={t.showProgress} onChange={(v) => setTweak('showProgress', v)} />
        <TweakSlider label="Revelar CTA aos" value={t.showCtaAtSeconds} min={0} max={300} step={5} unit="s" onChange={(v) => setTweak('showCtaAtSeconds', v)} />
        <TweakText  label="Texto da CTA" value={t.ctaLabel} onChange={(v) => setTweak('ctaLabel', v)} />
        <TweakText  label="URL da CTA"   value={t.ctaUrl}   onChange={(v) => setTweak('ctaUrl', v)} />
        <TweakSlider label="Curva da barra (menor = mais rápida no início)" value={t.fakeProgressCurve} min={0.2} max={1} step={0.05} unit="" onChange={(v) => setTweak('fakeProgressCurve', v)} />

        <TweakSection label="Teste" />
        <TweakToggle label="Saltar para o final" value={t.testFastForward} onChange={(v) => setTweak('testFastForward', v)} />
      </TweaksPanel>
    </div>
  );
}

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