// The Trading Vault, Mentorship: VSL Modal, shared "Vault Viewing Chamber" opened by every Apply CTA.
// Usage: call window.__ttvOpenVSL(triggerEl) to open. Mount <VSLModal /> once in the app root.

const VSL_YT_ID = "2N5lFptIikk";
const TYPEFORM_URL = APPLY_URL;

function emitVSL(name, detail) {
  window.dispatchEvent(new CustomEvent(name, { detail }));
}

function ModalHeader({ onClose }) {
  return (
    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "16px clamp(18px,3vw,28px)", borderBottom: "1px solid var(--vault-line-soft)", flex: "none" }}>
      <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
        <span style={{ fontFamily: "var(--font-sans)", fontWeight: 700, fontSize: 12.5, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--vault-ink)" }}>The Trading Vault</span>
        <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--vault-ink-4)" }}>Privévertoning</span>
      </div>
      <button
        onClick={onClose}
        aria-label="Sluiten"
        style={{ width: 34, height: 34, flex: "none", display: "flex", alignItems: "center", justifyContent: "center", background: "transparent", border: "1px solid var(--vault-line)", borderRadius: "var(--radius-xs)", color: "var(--vault-ink-3)", cursor: "pointer", fontSize: 16, lineHeight: 1, transition: "color .18s, border-color .18s" }}
        onMouseEnter={(e) => { e.currentTarget.style.color = "var(--vault-ink)"; e.currentTarget.style.borderColor = "var(--vault-ink-4)"; }}
        onMouseLeave={(e) => { e.currentTarget.style.color = "var(--vault-ink-3)"; e.currentTarget.style.borderColor = "var(--vault-line)"; }}
      >
        &#10005;
      </button>
    </div>
  );
}

function YouTubeFacadePlayer({ videoId, poster, title, onPlay, onComplete }) {
  const [state, setState] = React.useState("idle"); // idle | loading | playing | error
  const [hover, setHover] = React.useState(false);
  const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;

  const start = () => {
    setState("loading");
    onPlay && onPlay();
  };

  const src = `https://www.youtube-nocookie.com/embed/${videoId}?autoplay=1&playsinline=1&rel=0&enablejsapi=1&controls=1&origin=${encodeURIComponent(window.location.origin)}`;

  return (
    <div style={{ position: "relative", width: "100%", aspectRatio: "16 / 9", background: "#000", borderRadius: "var(--radius-sm)", overflow: "hidden", border: "1px solid var(--vault-line)", boxShadow: "var(--shadow-lg)" }}>
      {/* YouTube iframe, only created once play is requested */}
      {(state === "loading" || state === "playing") && (
        <iframe
          src={src}
          title={title}
          frameBorder="0"
          allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
          referrerPolicy="strict-origin-when-cross-origin"
          allowFullScreen
          onLoad={() => setState("playing")}
          onError={() => setState("error")}
          style={{ position: "absolute", inset: 0, width: "100%", height: "100%", border: 0, opacity: state === "playing" ? 1 : 0, transition: reduce ? "none" : "opacity .28s var(--ease-out)" }}
        />
      )}

      {/* Custom facade, covers the iframe until playback is requested */}
      {state !== "playing" && (
        <button
          onClick={start}
          onMouseEnter={() => setHover(true)}
          onMouseLeave={() => setHover(false)}
          aria-label="Speel de presentatie van The Vault af"
          style={{
            position: "absolute",
            inset: 0,
            width: "100%",
            height: "100%",
            border: 0,
            padding: 0,
            cursor: "pointer",
            background: "transparent",
            opacity: state === "loading" ? 0 : 1,
            transition: reduce ? "opacity .15s linear" : "opacity .25s var(--ease-out)",
            pointerEvents: state === "loading" ? "none" : "auto",
          }}
        >
          {poster ? (
            <img
              src={poster}
              alt=""
              loading="lazy"
              style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover", filter: hover ? "brightness(1.06)" : "brightness(1)", transform: hover && !reduce ? "scale(1.01)" : "scale(1)", transition: reduce ? "none" : "filter .25s var(--ease-out), transform .25s var(--ease-out)" }}
            />
          ) : (
            <div style={{ position: "absolute", inset: 0, background: "linear-gradient(168deg, #17171a 0%, #0d0d0f 60%, #0a0a0c 100%)" }} />
          )}
          <div aria-hidden="true" style={{ position: "absolute", inset: 0, background: "linear-gradient(180deg, rgba(6,6,7,.5), rgba(6,6,7,.62))" }} />
          {hover && !reduce && (
            <div aria-hidden="true" style={{ position: "absolute", inset: 0, background: "linear-gradient(115deg, transparent 42%, rgba(255,255,255,.06) 52%, transparent 62%)" }} />
          )}
          <div style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 14 }}>
            <span style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--vault-ink-4)" }}>Privévertoning</span>
            <span
              style={{
                width: "clamp(56px,7vw,76px)",
                height: "clamp(56px,7vw,76px)",
                borderRadius: "50%",
                border: `1px solid ${hover ? "var(--vault-ink)" : "var(--vault-ink-4)"}`,
                background: "rgba(10,10,12,.55)",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                transition: "border-color .25s var(--ease-out)",
              }}
            >
              <span aria-hidden="true" style={{ marginLeft: 4, width: 0, height: 0, borderStyle: "solid", borderWidth: "12px 0 12px 19px", borderColor: "transparent transparent transparent #fff" }} />
            </span>
          </div>
          {state === "loading" && (
            <div style={{ position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center" }}>
              <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--vault-ink-4)" }}>Laden&hellip;</span>
            </div>
          )}
        </button>
      )}

      {state === "error" && (
        <div style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 10, background: "rgba(6,6,7,.9)" }}>
          <span style={{ fontFamily: "var(--font-sans)", fontSize: 13, color: "var(--vault-ink-3)" }}>De video kon niet worden geladen.</span>
          <a href={`https://www.youtube.com/watch?v=${videoId}`} target="_blank" rel="noopener noreferrer" style={{ fontFamily: "var(--font-sans)", fontSize: 12.5, color: "var(--vault-ink-2)", textDecoration: "underline" }}>
            Bekijk op YouTube
          </a>
        </div>
      )}
    </div>
  );
}

function ApplicationCTA() {
  const { Button } = TTV;
  return (
    <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 10, marginTop: 22 }}>
      <a
        href={TYPEFORM_URL}
        target="_blank"
        rel="noopener noreferrer"
        style={{ textDecoration: "none" }}
        onClick={() => emitVSL("application_cta_clicked")}
      >
        <Button variant="primary" size="lg">Ga Verder Naar De Aanmelding</Button>
      </a>
      <span style={{ fontFamily: "var(--font-sans)", fontSize: 12.5, color: "var(--vault-ink-3)", textAlign: "center" }}>
        Heb je de presentatie bekeken? Ga verder met de korte aanmelding.
      </span>
      <span style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, letterSpacing: "0.06em", color: "var(--vault-ink-4)" }}>
        Geen betaling nodig. Iedere aanmelding wordt persoonlijk beoordeeld.
      </span>
    </div>
  );
}

function VSLModal() {
  const [open, setOpen] = React.useState(false);
  const [entered, setEntered] = React.useState(false);
  const [playerKey, setPlayerKey] = React.useState(0);
  const dialogRef = React.useRef(null);
  const triggerRef = React.useRef(null);
  const scrollYRef = React.useRef(0);

  const close = React.useCallback(() => {
    setEntered(false);
    const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    const delay = reduce ? 0 : 160;
    setTimeout(() => {
      setOpen(false);
      setPlayerKey((k) => k + 1); // reset facade for next open, per reliability-first approach
      document.body.style.overflow = "";
      document.body.style.position = "";
      document.body.style.top = "";
      window.scrollTo(0, scrollYRef.current);
      emitVSL("vsl_modal_closed");
      if (triggerRef.current && triggerRef.current.focus) triggerRef.current.focus();
    }, delay);
  }, []);

  React.useEffect(() => {
    window.__ttvOpenVSL = (triggerEl) => {
      triggerRef.current = triggerEl || null;
      scrollYRef.current = window.scrollY;
      document.body.style.position = "fixed";
      document.body.style.top = `-${scrollYRef.current}px`;
      document.body.style.overflow = "hidden";
      setOpen(true);
      emitVSL("vsl_modal_opened");
      requestAnimationFrame(() => requestAnimationFrame(() => setEntered(true)));
    };
    return () => { delete window.__ttvOpenVSL; };
  }, []);

  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") close(); };
    window.addEventListener("keydown", onKey);
    if (dialogRef.current) dialogRef.current.focus();
    return () => window.removeEventListener("keydown", onKey);
  }, [open, close]);

  if (!open) return null;
  const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;

  return (
    <div
      onMouseDown={(e) => { if (e.target === e.currentTarget) close(); }}
      style={{
        position: "fixed",
        inset: 0,
        zIndex: 1000,
        background: "rgba(4,4,5,.9)",
        backdropFilter: "blur(14px)",
        WebkitBackdropFilter: "blur(14px)",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        padding: "clamp(0px,3vw,28px)",
        opacity: entered ? 1 : 0,
        transition: reduce ? "opacity .18s linear" : "opacity .32s var(--ease-out)",
      }}
    >
      <div
        ref={dialogRef}
        role="dialog"
        aria-modal="true"
        aria-labelledby="vsl-modal-title"
        tabIndex={-1}
        style={{
          position: "relative",
          width: "min(96vw, 1600px)",
          height: "min(94vh, 1000px)",
          maxHeight: "94vh",
          display: "flex",
          flexDirection: "column",
          background: "linear-gradient(180deg, #131316 0%, #0c0c0e 60%, #0a0a0c 100%)",
          border: "1px solid var(--vault-line)",
          borderRadius: "var(--radius-md)",
          boxShadow: "0 40px 120px rgba(0,0,0,.6), inset 0 1px 0 rgba(255,255,255,.05)",
          overflow: "hidden",
          transform: entered ? "scale(1) translateY(0)" : reduce ? "none" : "scale(.985) translateY(6px)",
          opacity: entered ? 1 : 0,
          transition: reduce ? "opacity .18s linear" : "opacity .36s var(--ease-out), transform .36s var(--ease-out)",
          outline: "none",
        }}
      >
        <div aria-hidden="true" style={{ position: "absolute", top: 0, left: "50%", width: "46%", height: "40%", transform: "translateX(-50%) skewX(-7deg)", background: "linear-gradient(180deg, rgba(255,255,255,.06), transparent 80%)", filter: "blur(10px)", pointerEvents: "none" }} />
        <ModalHeader onClose={close} />
        <div style={{ flex: 1, overflowY: "auto", padding: "clamp(20px,3vw,40px) clamp(20px,4vw,56px) clamp(28px,4vw,44px)" }}>
          <div style={{ maxWidth: 920, margin: "0 auto", display: "flex", flexDirection: "column", alignItems: "center", gap: 14 }}>
            <Kicker color="var(--vault-ink-4)">Voordat Je Je Aanmeldt</Kicker>
            <h2 id="vsl-modal-title" style={{ margin: 0, fontFamily: "var(--font-display)", fontWeight: 800, fontSize: "clamp(24px,3.2vw,34px)", letterSpacing: "-0.02em", color: "var(--vault-ink)", textAlign: "center" }}>
              Bekijk Dit Eerst.
            </h2>
            <p style={{ margin: 0, maxWidth: 620, fontFamily: "var(--font-sans)", fontSize: 14.5, lineHeight: 1.62, color: "var(--vault-ink-2)", textAlign: "center", textWrap: "pretty" }}>
              In deze korte video leg ik uit voor wie The Vault bedoeld is, hoe de begeleiding werkt en wat er van jou wordt verwacht.
            </p>
            <div style={{ width: "100%", marginTop: 10 }}>
              <YouTubeFacadePlayer
                key={playerKey}
                videoId={VSL_YT_ID}
                poster={null}
                title="The Trading Vault, Welcome"
                onPlay={() => emitVSL("vsl_play_started")}
              />
            </div>
            <ApplicationCTA />
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { VSLModal });
