/* ===========================================================================
   screen-videos.jsx — Founder videos + overlay editing pipeline
   props: store
   =========================================================================== */
const FV = window.STUDIO;

function OverlayCard({ o }) {
  const [open, setOpen] = useState(false);
  const hasAsset = o.motion_url || o.static_url;
  return (
    <div className="card" style={{ overflow: "hidden", padding: 0, marginBottom: 16 }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "12px 18px", background: "var(--paper-2)", borderBottom: "var(--bd) solid var(--line)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <span style={{ fontFamily: "var(--mono)", fontSize: 12, fontWeight: 700, color: "var(--ink)" }}>{o.moment}</span>
          <span style={{ padding: "3px 9px", background: "var(--accent)", color: "#fff", fontSize: 10, fontFamily: "var(--mono)", fontWeight: 700, letterSpacing: "0.06em", textTransform: "uppercase", borderRadius: 999 }}>{(o.role || "overlay").replace(/_/g, " ")}</span>
        </div>
        {hasAsset && (
          <a className="btn ghost sm" href={downloadHref(o.motion_url || o.static_url)} style={{ textDecoration: "none" }}>
            <Icon name="download" size={12}/> Download
          </a>
        )}
      </div>
      {hasAsset && (
        <div style={{ background: "#0a0a0a", aspectRatio: "1/1", position: "relative" }}>
          {o.motion_url
            ? <video src={o.motion_url} muted loop autoPlay playsInline style={{ width: "100%", height: "100%", objectFit: "contain", display: "block" }}/>
            : <img src={o.static_url} alt="" style={{ width: "100%", height: "100%", objectFit: "contain", display: "block" }}/>}
          {o.motion_url && o.static_url && (
            <div style={{ position: "absolute", top: 8, right: 8, padding: "3px 8px", background: "rgba(0,0,0,0.65)", color: "#fff", fontFamily: "var(--mono)", fontSize: 9.5, letterSpacing: "0.05em", textTransform: "uppercase", borderRadius: 6 }}>Animated</div>
          )}
        </div>
      )}
      <div style={{ padding: "14px 18px" }}>
        {o.trigger_words && (
          <div style={{ fontSize: 13.5, color: "var(--ink)", fontStyle: "italic", lineHeight: 1.5, padding: "10px 14px", background: "var(--accent-soft)", borderRadius: "var(--r-sm)", borderLeft: "3px solid var(--accent)", marginBottom: 12 }}>
            "{o.trigger_words}"
          </div>
        )}
        <button className="btn ghost sm" onClick={() => setOpen(!open)} style={{ fontSize: 11 }}>
          {open ? "▲ Hide prompts" : "▼ Show prompts"}
        </button>
        {open && (
          <div style={{ marginTop: 12, fontSize: 13, color: "var(--ink-soft)", lineHeight: 1.6 }}>
            {o.static_prompt && (
              <div style={{ marginBottom: 12 }}>
                <div style={{ fontFamily: "var(--mono)", fontSize: 10.5, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--ink-faint)", fontWeight: 700, marginBottom: 4 }}>Static prompt</div>
                <div>{o.static_prompt}</div>
              </div>
            )}
            {o.motion_prompt && (
              <div>
                <div style={{ fontFamily: "var(--mono)", fontSize: 10.5, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--ink-faint)", fontWeight: 700, marginBottom: 4 }}>Motion prompt</div>
                <div>{o.motion_prompt}</div>
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
}

function FounderVideoBlock({ v }) {
  return (
    <div className="card" style={{ marginBottom: 32, padding: 0, overflow: "hidden" }}>
      <div style={{ padding: "20px 24px", borderBottom: "var(--bd) solid var(--line)" }}>
        <div className="eyebrow"><Icon name="video" size={13}/> Founder video</div>
        <h2 style={{ fontFamily: "var(--display)", fontSize: 22, fontWeight: 700, letterSpacing: "-0.02em", margin: "8px 0 6px" }}>{v.topic}</h2>
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
          {v.product_name && <Chip tone="ghost">{v.product_name}</Chip>}
          <Chip tone="ghost">{v.format}</Chip>
          {v.duration_seconds && <Chip tone="ghost">{Math.round(v.duration_seconds)}s</Chip>}
          <Chip tone="ghost">{v.overlays.length} overlay{v.overlays.length === 1 ? "" : "s"}</Chip>
        </div>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1fr) minmax(0, 1.3fr)", gap: 0 }}>
        <div style={{ padding: 24, borderRight: "var(--bd) solid var(--line)", background: "var(--surface-2)" }}>
          {v.edited_url && (
            <div style={{ marginBottom: 18 }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 10 }}>
                <div style={{ fontFamily: "var(--mono)", fontSize: 10.5, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--accent)", fontWeight: 700 }}>Edited · with overlays</div>
                <a className="btn ghost sm" href={downloadHref(v.edited_url)} style={{ textDecoration: "none" }}>
                  <Icon name="download" size={12}/>
                </a>
              </div>
              <video src={v.edited_url} controls preload="metadata" style={{ width: "100%", borderRadius: "var(--r-sm)", background: "#000" }}/>
            </div>
          )}
          <div>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 10 }}>
              <div style={{ fontFamily: "var(--mono)", fontSize: 10.5, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--ink-faint)", fontWeight: 700 }}>Original recording</div>
              <a className="btn ghost sm" href={downloadHref(v.source_url)} style={{ textDecoration: "none" }}>
                <Icon name="download" size={12}/>
              </a>
            </div>
            <video src={v.source_url} controls preload="metadata" style={{ width: "100%", borderRadius: "var(--r-sm)", background: "#000" }}/>
          </div>
        </div>
        <div style={{ padding: 24 }}>
          <div className="section-label" style={{ marginBottom: 16 }}>Overlay timeline · {v.overlays.length} moments</div>
          {v.overlays.length === 0
            ? <div style={{ color: "var(--ink-soft)", fontSize: 13 }}>No overlays defined.</div>
            : v.overlays.map((o) => <OverlayCard key={o.id} o={o}/>)}
        </div>
      </div>
    </div>
  );
}

/* ---- Grid card for a founder video --------------------------------- */
function VideoGalleryCard({ v, onClick }) {
  const previewUrl = v.edited_url || v.source_url;
  return (
    <div className="card" onClick={onClick} style={{ cursor: "pointer", overflow: "hidden", padding: 0, transition: "transform .15s, box-shadow .15s" }}
      onMouseEnter={(e) => { e.currentTarget.style.transform = "translateY(-2px)"; e.currentTarget.style.boxShadow = "var(--shadow-lg)"; }}
      onMouseLeave={(e) => { e.currentTarget.style.transform = ""; e.currentTarget.style.boxShadow = ""; }}>
      <div style={{ aspectRatio: "9/16", background: "#0a0a0a", position: "relative", maxHeight: 380, overflow: "hidden" }}>
        <video src={previewUrl} muted loop autoPlay playsInline preload="metadata" style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }}/>
        {v.edited_url && (
          <div style={{ position: "absolute", top: 10, left: 10, padding: "4px 10px", background: "var(--accent)", color: "#fff", fontSize: 10, fontFamily: "var(--mono)", fontWeight: 700, letterSpacing: "0.06em", textTransform: "uppercase", borderRadius: 999 }}>Edited</div>
        )}
        <div style={{ position: "absolute", bottom: 10, right: 10, padding: "4px 10px", background: "rgba(0,0,0,0.65)", color: "#fff", fontSize: 10.5, fontFamily: "var(--mono)", fontWeight: 700, borderRadius: 6 }}>
          {v.duration_seconds ? `${Math.round(v.duration_seconds)}s` : v.format}
        </div>
        <div style={{ position: "absolute", inset: 0, background: "linear-gradient(180deg, transparent 55%, rgba(0,0,0,0.55) 100%)", pointerEvents: "none" }}/>
      </div>
      <div style={{ padding: "14px 16px 16px" }}>
        <div style={{ fontFamily: "var(--display)", fontSize: 15, fontWeight: 700, letterSpacing: "-0.01em", lineHeight: 1.3, marginBottom: 6 }}>{v.topic}</div>
        <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
          {v.product_name && <Chip tone="ghost">{v.product_name}</Chip>}
          <Chip tone="ghost">{v.overlays.length} overlay{v.overlays.length === 1 ? "" : "s"}</Chip>
        </div>
      </div>
    </div>
  );
}

function VideosPage({ store }) {
  const [selectedId, setSelectedId] = useState(null);
  const videos = (FV.founder_videos || []);

  if (selectedId) {
    const v = videos.find((x) => x.id === selectedId);
    if (v) {
      return (
        <div className="content">
          <button className="btn ghost sm" onClick={() => setSelectedId(null)} style={{ marginBottom: 18, marginLeft: -6 }}>
            <Icon name="arrowLeft" size={14}/> All videos
          </button>
          <FounderVideoBlock v={v}/>
        </div>
      );
    }
  }

  if (videos.length === 0) {
    return (
      <div className="content">
        <Empty icon="video" title="No founder videos yet" desc="Once Alli sends raw recordings (uploaded from the brief modal on Analysis → Scripts), they'll show up here with the editing timeline + generated overlay assets."/>
      </div>
    );
  }

  return (
    <div className="content">
      <div className="page-head">
        <div className="eyebrow"><Icon name="video" size={13}/> Founder footage</div>
        <h1 className="page-title sm">Videos & overlays</h1>
        <p className="page-desc">Alli's recordings, the moments we've identified, the generated assets to layer in, and the edited Reel previews.</p>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(260px, 1fr))", gap: 20 }}>
        {videos.map((v) => <VideoGalleryCard key={v.id} v={v} onClick={() => { setSelectedId(v.id); window.scrollTo(0, 0); }}/>)}
      </div>
    </div>
  );
}

Object.assign(window, { VideosPage, FounderVideoBlock, OverlayCard, VideoGalleryCard });
