// PRLX site — fullscreen video player modal. Supports campaigns with multiple
// videos: the main `vimeo` plus an optional `clips: [{vimeo, vhash, label}]`.
// A thumbnail strip appears under the player only when there's more than one.
function VideoThumb({ video, active, index, onClick }) {
  const { Icon } = window;
  const [thumb, setThumb] = React.useState(null);
  React.useEffect(() => {
    if (!video.vimeo) return;
    let ok = true;
    const u = `https://vimeo.com/api/oembed.json?url=${encodeURIComponent(`https://vimeo.com/${video.vimeo}/${video.vhash || ""}`)}&width=400`;
    fetch(u).then((r) => (r.ok ? r.json() : null)).then((d) => { if (ok && d && d.thumbnail_url) setThumb(d.thumbnail_url); }).catch(() => {});
    return () => { ok = false; };
  }, [video.vimeo]);
  return (
    <button onClick={onClick} title={video.label}
      style={{ flexShrink: 0, width: 132, padding: 0, background: "transparent", border: 0, cursor: "pointer", textAlign: "left" }}>
      <div style={{ position: "relative", width: "100%", aspectRatio: "16 / 9", overflow: "hidden", background: "#0a0a0b",
           border: active ? "2px solid var(--accent)" : "2px solid rgba(255,255,255,0.16)", transition: "border-color 160ms" }}>
        {thumb && <img src={thumb} alt={video.label} style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover", opacity: active ? 1 : 0.6, transition: "opacity 160ms" }} />}
        <div style={{ position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center" }}>
          <div style={{ width: 28, height: 28, borderRadius: "50%", background: active ? "var(--accent)" : "rgba(10,10,10,0.5)", border: "1px solid rgba(255,255,255,0.7)", display: "flex", alignItems: "center", justifyContent: "center" }}>
            <Icon name={active ? "Play" : "Play"} size={13} style={{ color: "#fff", marginLeft: 1 }} />
          </div>
        </div>
      </div>
      <div style={{ fontFamily: "var(--font-body)", fontSize: 11, fontWeight: 600, color: active ? "#fff" : "var(--prlx-graphite-400)", marginTop: 7, lineHeight: 1.3, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
        {video.label}
      </div>
    </button>
  );
}

function Player({ work, onClose }) {
  const { IconButton, StatusDot } = window.PRLXDesignSystem_b1b8b9;
  const { Icon, Still, useViewport } = window;
  const [playing, setPlaying] = React.useState(true);
  const [t, setT] = React.useState(0.28);
  const [activeIdx, setActiveIdx] = React.useState(0);
  const { isMobile } = useViewport();

  React.useEffect(() => { setActiveIdx(0); }, [work && work.id]);

  React.useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose]);

  if (!work) return null;

  // Build the campaign video list: main film first, then any extra clips.
  const videos = [];
  if (work.vimeo) videos.push({ vimeo: work.vimeo, vhash: work.vhash, label: work.title });
  (work.clips || []).forEach((c, i) => { if (c && c.vimeo) videos.push({ vimeo: c.vimeo, vhash: c.vhash, label: c.label || `Clip ${i + 2}` }); });
  const active = videos[Math.min(activeIdx, videos.length - 1)] || videos[0];
  const hasVideo = videos.length > 0;
  const multi = videos.length > 1;

  return (
    <div
      onClick={onClose}
      style={{
        position: "fixed", inset: 0, zIndex: 1000, background: "rgba(5,5,5,0.86)",
        backdropFilter: "blur(8px)", display: "flex", alignItems: "center", justifyContent: "center", padding: isMobile ? 16 : 40,
        animation: "prlx-fade 220ms cubic-bezier(0.22,1,0.36,1)",
      }}
    >
      <style>{`@keyframes prlx-fade{from{opacity:0}to{opacity:1}}`}</style>
      <div onClick={(e) => e.stopPropagation()} style={{ width: "min(1100px, 100%)" }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 14 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
            <StatusDot status="live" label="Playing" />
            <span style={{ fontFamily: "var(--font-display)", fontWeight: 800, textTransform: "uppercase", letterSpacing: "-0.01em", fontSize: 22, color: "#fff" }}>{active ? active.label : work.title}</span>
          </div>
          <IconButton label="Close" onClick={onClose}><Icon name="X" size={18} /></IconButton>
        </div>

        <div style={{ position: "relative", border: "2px solid rgba(255,255,255,0.18)", background: "#000" }}>
          {hasVideo ? (
            <div style={{ position: "relative", width: "100%", aspectRatio: "16 / 9" }}>
              <iframe
                key={active.vimeo}
                title={work.title}
                src={`https://player.vimeo.com/video/${active.vimeo}?h=${active.vhash || ""}&autoplay=1&autopause=0&badge=0&byline=0&portrait=0&title=0`}
                style={{ position: "absolute", inset: 0, width: "100%", height: "100%", border: 0 }}
                allow="autoplay; fullscreen; picture-in-picture"
                allowFullScreen
              />
            </div>
          ) : (
            <React.Fragment>
              <Still tone={work.tone} ratio="2.39 / 1" showPlay={false} />
              <div style={{ position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center" }}>
                <div onClick={() => setPlaying((p) => !p)} style={{ width: 76, height: 76, borderRadius: "50%", border: "2px solid rgba(255,255,255,0.9)", display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer", background: "rgba(10,10,10,0.3)" }}>
                  <Icon name={playing ? "Pause" : "Play"} size={28} style={{ color: "#fff", marginLeft: playing ? 0 : 3 }} />
                </div>
              </div>
              {/* control bar (placeholder projects only) */}
              <div style={{ position: "absolute", left: 0, right: 0, bottom: 0, padding: "16px 18px", background: "var(--scrim-bottom)" }}>
                <div onClick={(e) => { const r = e.currentTarget.getBoundingClientRect(); setT((e.clientX - r.left) / r.width); }}
                     style={{ height: 4, background: "rgba(255,255,255,0.25)", cursor: "pointer", marginBottom: 12, position: "relative" }}>
                  <div style={{ position: "absolute", left: 0, top: 0, bottom: 0, width: `${t * 100}%`, background: "var(--prlx-signal)" }} />
                  <div style={{ position: "absolute", left: `${t * 100}%`, top: "50%", width: 11, height: 11, borderRadius: "50%", background: "#fff", transform: "translate(-50%,-50%)" }} />
                </div>
                <div style={{ display: "flex", alignItems: "center", gap: 16, color: "#fff" }}>
                  <Icon name={playing ? "Pause" : "Play"} size={18} style={{ cursor: "pointer" }} />
                  <Icon name="Volume2" size={18} />
                  <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--prlx-graphite-200)" }}>
                    {fmtTime(t, work.runtime)} / {work.runtime}
                  </span>
                  <span style={{ flex: 1 }} />
                  <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--prlx-graphite-300)" }}>{work.client}</span>
                  <Icon name="Maximize" size={18} style={{ cursor: "pointer" }} />
                </div>
              </div>
            </React.Fragment>
          )}
        </div>

        {/* campaign video switcher — only when there's more than one */}
        {multi && (
          <div style={{ marginTop: 14 }}>
            <div style={{ fontFamily: "var(--font-body)", fontWeight: 700, fontSize: 10, textTransform: "uppercase", letterSpacing: "0.2em", color: "var(--prlx-graphite-400)", marginBottom: 12 }}>
              ↳ {videos.length} videos in this campaign
            </div>
            <div style={{ display: "flex", gap: 12, overflowX: "auto", paddingBottom: 6 }}>
              {videos.map((v, i) => (
                <VideoThumb key={v.vimeo + "-" + i} video={v} index={i} active={i === activeIdx} onClick={() => setActiveIdx(i)} />
              ))}
            </div>
          </div>
        )}

        {/* project description — SEO + context */}
        <div style={{ marginTop: 20, display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1fr auto", gap: isMobile ? 20 : 24, alignItems: "start" }}>
          <div>
            <div style={{ fontFamily: "var(--font-body)", fontWeight: 700, fontSize: 10, textTransform: "uppercase", letterSpacing: "0.2em", color: "var(--prlx-graphite-400)", marginBottom: 10 }}>
              ↳ About this project
            </div>
            <p style={{ fontFamily: "var(--font-body)", fontWeight: 300, fontSize: 15, lineHeight: 1.6, color: "var(--prlx-graphite-200)", margin: 0, maxWidth: "62ch" }}>
              {work.desc}
            </p>
          </div>
          <div style={{ display: "flex", flexDirection: isMobile ? "row" : "column", flexWrap: "wrap", gap: isMobile ? 20 : 10, textAlign: isMobile ? "left" : "right", flexShrink: 0 }}>
            <div>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, textTransform: "uppercase", letterSpacing: "0.16em", color: "var(--prlx-graphite-500)" }}>Client</div>
              <div style={{ fontFamily: "var(--font-body)", fontWeight: 600, fontSize: 13, color: "#fff", marginTop: 3 }}>{work.client}</div>
            </div>
            <div>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, textTransform: "uppercase", letterSpacing: "0.16em", color: "var(--prlx-graphite-500)" }}>Agency</div>
              <div style={{ fontFamily: "var(--font-body)", fontWeight: 600, fontSize: 13, color: work.agency === "In-house" ? "var(--accent)" : "#fff", marginTop: 3 }}>
                {work.agency === "In-house" ? "In-house · PRLX" : work.agency}
              </div>
            </div>
            <div>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, textTransform: "uppercase", letterSpacing: "0.16em", color: "var(--prlx-graphite-500)" }}>Discipline</div>
              <div style={{ fontFamily: "var(--font-body)", fontWeight: 600, fontSize: 13, color: "#fff", marginTop: 3 }}>{work.cat}</div>
            </div>
            <div>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, textTransform: "uppercase", letterSpacing: "0.16em", color: "var(--prlx-graphite-500)" }}>Year</div>
              <div style={{ fontFamily: "var(--font-body)", fontWeight: 600, fontSize: 13, color: "#fff", marginTop: 3 }}>{work.year}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function fmtTime(frac, runtime) {
  const parts = String(runtime).split(":").map(Number);
  const total = parts.length === 2 ? parts[0] * 60 + parts[1] : parts[0];
  const cur = Math.floor(total * frac);
  return `${Math.floor(cur / 60)}:${String(cur % 60).padStart(2, "0")}`;
}

Object.assign(window, { Player });
