/* ===========================================================================
   shared-bits.jsx — shared visual components used across multiple screens
   Extracted from the original screen-studio.jsx + screen-competitor.jsx
   =========================================================================== */

/* ---- Generated creative frame (Higgsfield mock) ----------------------- */
const GEN_GRADS = [
  ["#5e6ad2", "#3a3f8c"],
  ["#2f72c4", "#1d4a87"],
  ["#3f9d6b", "#266046"],
  ["#8257d6", "#523592"],
  ["#c4554d", "#8a3a34"],
  ["#1f8f8a", "#135a57"],
];
function genGrad(id) {
  let h = 0; for (let i = 0; i < (id || "").length; i++) h = (h * 31 + id.charCodeAt(i)) >>> 0;
  return GEN_GRADS[h % GEN_GRADS.length];
}

function GenFrame({ script, ratio = "1/1", showBadge = true, fit = "contain" }) {
  const [c1, c2] = genGrad(script.id);
  // If the script has a real asset URL from our backend, use it; otherwise fall back to a fauxgrad
  if (script.asset_url) {
    return (
      <div style={{ position: "relative", aspectRatio: ratio, overflow: "hidden", borderRadius: 10, background: "#0a0a0a" }}>
        {script.asset_type === "video" ? (
          <video src={script.asset_url} muted loop autoPlay playsInline style={{ width: "100%", height: "100%", objectFit: fit, display: "block" }}/>
        ) : (
          <img src={script.asset_url} alt="" loading="lazy" style={{ width: "100%", height: "100%", objectFit: fit, display: "block" }}/>
        )}
        {showBadge && (
          <div style={{ position: "absolute", top: 9, left: 9, zIndex: 4 }}>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 4, fontSize: 9.5, fontWeight: 600, color: "#fff", background: "rgba(0,0,0,0.55)", backdropFilter: "blur(4px)", padding: "3px 8px", borderRadius: 6 }}><Icon name="sparkle" size={11}/> Higgsfield</span>
          </div>
        )}
      </div>
    );
  }
  return (
    <div style={{ position: "relative", aspectRatio: ratio, background: `linear-gradient(150deg, ${c1}, ${c2})`, overflow: "hidden", display: "grid", placeItems: "center", borderRadius: 10 }}>
      <svg viewBox="0 0 100 130" style={{ position: "absolute", bottom: 0, left: "50%", transform: "translateX(-50%)", height: "80%" }}>
        <ellipse cx="50" cy="44" rx="20" ry="22" fill="rgba(255,255,255,0.16)"/>
        <path d="M16 130 Q18 78 50 74 Q82 78 84 130 Z" fill="rgba(255,255,255,0.16)"/>
      </svg>
      <div style={{ position: "absolute", inset: 0, background: "linear-gradient(to top, rgba(8,9,10,0.5), transparent 58%)" }}/>
      <div style={{ position: "relative", alignSelf: "flex-end", padding: "0 14px 16px", textAlign: "center", zIndex: 3 }}>
        <div style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: "clamp(13px, 2.3vw, 19px)", lineHeight: 1.18, color: "#fff", letterSpacing: "-0.01em" }}>{script.ctaOverlay}</div>
      </div>
      {showBadge && (
        <div style={{ position: "absolute", top: 9, left: 9, zIndex: 4 }}>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 4, fontSize: 9.5, fontWeight: 600, color: "#fff", background: "rgba(255,255,255,0.18)", backdropFilter: "blur(4px)", padding: "3px 8px", borderRadius: 6 }}><Icon name="sparkle" size={11}/> Higgsfield</span>
        </div>
      )}
    </div>
  );
}

/* ---- Shared ad thumbnail + card --------------------------------------- */
function AdThumb({ ad, big }) {
  // Use real media if backend provided it
  if (ad.media) {
    return (
      <div className={big ? "" : "ad-thumb"} style={{ background: "#0a0a0a", color: "#fff", ...(big ? { aspectRatio: "4/5", position: "relative", display: "grid", placeItems: "center", borderBottom: "var(--bd) solid var(--ink)" } : { position: "relative" }) }}>
        {ad.media_type === "video" ? (
          <video src={ad.media} muted loop autoPlay playsInline style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }}/>
        ) : (
          <img src={ad.media} alt="" loading="lazy" style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }}/>
        )}
        <a href={downloadHref(ad.media)} title="Download" onClick={(e) => e.stopPropagation()} style={{ position: "absolute", top: 8, right: 8, zIndex: 6, display: "inline-flex", alignItems: "center", justifyContent: "center", width: 28, height: 28, borderRadius: 999, background: "rgba(0,0,0,0.65)", color: "#fff", textDecoration: "none" }}>
          <Icon name="download" size={13}/>
        </a>
        {!big && (
          <>
            <div className="ad-flags">
              <Chip tone={ad.kind === "video" ? "magenta" : "teal"}><Icon name={ad.kind === "video" ? "video" : "image"} size={11}/> {ad.kind}</Chip>
              {ad.best && <Chip tone="gold"><Icon name="trophy" size={11}/></Chip>}
            </div>
            <div className="ad-days">{ad.days}d</div>
          </>
        )}
      </div>
    );
  }
  const th = themeFor ? themeFor(ad.id) : { bg: "#5e6ad2", fg: "#fff", pat: "dots" };
  return (
    <div className={big ? "" : "ad-thumb"} style={{ background: th.bg, color: th.fg, ...(big ? { aspectRatio: "4/5", position: "relative", display: "grid", placeItems: "center", borderBottom: "var(--bd) solid var(--ink)" } : {}) }}>
      {typeof PatternBG !== "undefined" && <PatternBG pat={th.pat} fg={th.fg}/>}
      <div className={big ? "dc-copy" : "thumb-copy"} style={{ color: th.fg }}>"{typeof headlineFor !== "undefined" ? headlineFor(ad) : (ad.copy || "").slice(0, 60)}"</div>
      {ad.kind === "video" && (
        <div className="play-btn" style={big ? { bottom: 16, left: 16 } : {}}><Icon name="play" size={20}/></div>
      )}
      {!big && (
        <>
          <div className="ad-flags">
            <Chip tone={ad.kind === "video" ? "magenta" : "teal"}><Icon name={ad.kind === "video" ? "video" : "image"} size={11}/> {ad.kind}</Chip>
            {ad.best && <Chip tone="gold"><Icon name="trophy" size={11}/></Chip>}
          </div>
          <div className="ad-days">{ad.days}d</div>
        </>
      )}
    </div>
  );
}

function advColor(name) {
  const palette = ["#5e6ad2", "#3f9d6b", "#8257d6", "#2f72c4", "#b07e1d", "#c4554d"];
  let h = 0; for (let i = 0; i < (name || "").length; i++) h = (h * 17 + name.charCodeAt(i)) >>> 0;
  return palette[h % palette.length];
}

function AdCard({ ad, go }) {
  return (
    <div className="ad-card" onClick={() => go && go({ name: "creative", id: ad.id })}>
      <AdThumb ad={ad}/>
      <div className="ad-foot">
        <div className="ad-advertiser">
          <span className="sponsor-ava" style={{ background: advColor(ad.advertiser) }}>{(ad.advertiser || "?")[0]}</span>
          {ad.advertiser}
          <span style={{ marginLeft: "auto", fontFamily: "var(--mono)", fontSize: 10, color: "var(--ink-faint)", textTransform: "uppercase" }}>{ad.line}</span>
        </div>
        <div className="ad-copy">{ad.copy}</div>
        <div className="ad-cta">{ad.cta} →</div>
      </div>
    </div>
  );
}

function HookCard({ hook, rank, ads }) {
  return (
    <div className="hook-card">
      <div className="hook-head">
        <div className="hook-rank">{rank}</div>
        <div>
          <div className="hook-title">{hook.title}</div>
          <div style={{ marginTop: 7, display: "flex", gap: 8, alignItems: "center" }}>
            <Chip tone="ghost">{hook.tag}</Chip>
            <span style={{ fontFamily: "var(--mono)", fontSize: 11, color: "var(--ink-soft)" }}>{(hook.lines || []).length} live variants</span>
          </div>
        </div>
      </div>
      <div className="hook-quote">"{hook.example}"</div>
      <div className="hook-body">
        <ul className="hook-lines">{(hook.lines || []).map((l, i) => <li key={i}>{l}</li>)}</ul>
        <div className="ai-note">
          <div className="ai-tag"><Icon name="sparkle" size={12}/> AI read</div>
          {hook.analysis}
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 11 }}>
            <span style={{ fontFamily: "var(--mono)", fontSize: 10, textTransform: "uppercase", color: "var(--ink-soft)" }}>Strength</span>
            <div className="strength-bar" style={{ flex: 1 }}><span style={{ width: `${hook.strength}%` }}/></div>
            <span style={{ fontFamily: "var(--mono)", fontSize: 11, color: "var(--ink)", fontWeight: 700 }}>{hook.strength}</span>
          </div>
        </div>
        {ads && ads.length > 0 && (
          <div style={{ marginTop: 16, paddingTop: 14, borderTop: "var(--bd) solid var(--line)" }}>
            <div style={{ fontFamily: "var(--mono)", fontSize: 10.5, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--ink-faint)", fontWeight: 700, marginBottom: 10 }}>Ads using this hook · {ads.length}</div>
            <div style={{ display: "grid", gridTemplateColumns: `repeat(${Math.min(ads.length, 3)}, 1fr)`, gap: 10 }}>
              {ads.slice(0, 3).map((a) => (
                <div key={a.id} style={{ borderRadius: 8, overflow: "hidden", border: "var(--bd) solid var(--line)" }}>
                  <AdThumb ad={a}/>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

/* ---- Analysis tab pieces (Patterns / Best / Scripts) ----------------- */
function AngleRow({ a }) {
  return (
    <div className="row-item">
      <LevelPill level={a.level}/>
      <div><div className="row-title">{a.title}</div><div className="row-desc">{a.desc}</div></div>
    </div>
  );
}

function FormatRow({ f }) {
  return (
    <div className="row-item">
      <LevelPill level={f.level}/>
      <div style={{ flex: 1 }}><div className="row-title">{f.title}</div><div className="row-desc">{f.desc}</div></div>
      <div className="share-track">
        <div style={{ fontFamily: "var(--display)", fontSize: 17 }}>{f.share}%</div>
        <div className="share-bar"><span style={{ width: `${f.share}%` }}/></div>
        <div style={{ fontFamily: "var(--mono)", fontSize: 8.5, textTransform: "uppercase", color: "var(--ink-soft)", marginTop: 3 }}>of mix</div>
      </div>
    </div>
  );
}

function BestCard({ b, go }) {
  return (
    <div className="best-card">
      <div style={{ display: "flex", gap: 10, alignItems: "center", flexWrap: "wrap" }}>
        <span className="sponsor-ava" style={{ background: advColor(b.advertiser), width: 26, height: 26 }}>{(b.advertiser || "?")[0]}</span>
        <span style={{ fontFamily: "var(--mono)", fontSize: 12, opacity: 0.8 }}>{b.advertiser}</span>
        <Chip tone="gold"><Icon name="clock" size={12}/> {b.days}d</Chip>
      </div>
      <div className="best-quote" style={{ fontSize: 20 }}>"{b.quote}"</div>
      <div className="best-why">{b.why}</div>
    </div>
  );
}

function ScriptCard({ s, store }) {
  const [open, setOpen] = useState(false);
  const th = typeof themeFor !== "undefined" ? themeFor(s.id) : { bg: "#5e6ad2", fg: "#fff", pat: "dots" };
  const inShot = store && store.shot.some((x) => x.id === s.id);
  const copyScript = () => {
    const text = `${s.slug}\n\nHOOK: ${s.hook}\n\nBODY: ${s.body}\n\nCTA: ${s.cta}\nOverlay: ${s.ctaOverlay}`;
    try { navigator.clipboard.writeText(text); } catch (e) {}
    store && store.toast("Script copied to clipboard", { label: "OK", fn: () => {} });
  };
  return (
    <div className={`script-card ${open ? "open" : ""}`}>
      <div className="script-head" onClick={() => setOpen(!open)}>
        <div className="script-thumb" style={{ background: th.bg }}>
          {typeof PatternBG !== "undefined" && <PatternBG pat={th.pat} fg={th.fg}/>}
          <Icon name={s.generated ? "sparkle" : "script"} size={22} style={{ color: th.fg, position: "relative" }}/>
          {s.generated && <span className="gen-tag">Higgsfield</span>}
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="script-name">{s.slug}</div>
          <div className="script-hook">"{s.hook}"</div>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 6, alignItems: "flex-end", flex: "0 0 auto" }}>
          <Chip tone="ghost"><Icon name="clock" size={11}/> {s.length}</Chip>
          <span style={{ fontFamily: "var(--mono)", fontSize: 10, color: "var(--ink-faint)" }}>{open ? "▲ collapse" : "▼ expand"}</span>
        </div>
      </div>
      {open && (
        <div className="script-body-wrap">
          <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginBottom: 16 }}>
            <Chip tone="teal">{s.format}</Chip>
            {(s.props || []).map((p, i) => <Chip key={i} tone="ghost">{p}</Chip>)}
          </div>
          <div className="ai-note" style={{ marginBottom: 18 }}>
            <div className="ai-tag"><Icon name="hook" size={12}/> Inspired by</div>{s.inspired}
          </div>
          <div className="beat"><div className="beat-label">Hook · 0–3s</div><div><div className="beat-text script-quote">"{s.hook}"</div><div className="beat-dir">{s.hookDir}</div></div></div>
          <div className="beat"><div className="beat-label">Body</div><div className="beat-text">{s.body}</div></div>
          <div className="beat"><div className="beat-label">CTA</div><div><div className="beat-text">{s.cta}</div><div className="overlay-note">Overlay: "{s.ctaOverlay}"</div></div></div>
          <div className="ai-note" style={{ background: "var(--card)", marginTop: 6 }}>
            <div className="ai-tag" style={{ color: "var(--olive)" }}><Icon name="check" size={12}/> Why it works</div>{s.why}
          </div>
          {s.generated && (
            <div style={{ marginTop: 16 }}>
              <div className="section-label"><Icon name="sparkle" size={13}/> Generated frame</div>
              <div style={{ maxWidth: 220 }}><GenFrame script={s} ratio="4/5"/></div>
            </div>
          )}
          <div style={{ display: "flex", gap: 10, marginTop: 16, flexWrap: "wrap" }}>
            {inShot
              ? <button className="btn gold sm" disabled style={{ opacity: 0.95 }}><Icon name="check" size={14} stroke={3}/> In Alli's shot list</button>
              : <button className="btn primary sm" onClick={() => { store && store.addShot(s.id); store && store.toast("Sent to Alli's shot list", { label: "View", fn: () => store.goLibrary("shot") }); }}><Icon name="video" size={14}/> Send to Alli's shot list</button>}
            <button className="btn sm" onClick={copyScript}><Icon name="script" size={14}/> Copy script</button>
            {s.brief_url && <a className="btn sm" href={s.brief_url} target="_blank" rel="noopener" style={{ textDecoration: "none" }}><Icon name="script" size={14}/> Open brief</a>}
          </div>
        </div>
      )}
    </div>
  );
}

/* ---- Grid-style script card (image-first) --------------------------- */
function ScriptGridCard({ s, store }) {
  const [open, setOpen] = useState(false);
  const [briefOpen, setBriefOpen] = useState(false);
  const inShot = store && store.shot.some((x) => x.id === s.id);
  const stubAction = (label) => {
    store && store.toast(label + " · routed to your Slack bot", { label: "OK", fn: () => {} });
  };
  const copyScript = () => {
    const text = `${s.slug}\n\nHOOK: ${s.hook}\n\nBODY: ${s.body}\n\nCTA: ${s.cta}\nOverlay: ${s.ctaOverlay}`;
    try { navigator.clipboard.writeText(text); } catch (e) {}
    store && store.toast("Script copied to clipboard", { label: "OK", fn: () => {} });
  };
  return (
    <div className="card" style={{ overflow: "hidden", display: "flex", flexDirection: "column", padding: 0 }}>
      <div style={{ position: "relative" }}>
        <GenFrame script={s} ratio="1/1" fit="contain" showBadge={true}/>
        <div style={{ position: "absolute", top: 10, right: 10, zIndex: 5, padding: "4px 9px", background: "rgba(0,0,0,0.65)", color: "#fff", fontSize: 9.5, fontFamily: "var(--mono)", fontWeight: 700, letterSpacing: "0.05em", textTransform: "uppercase", borderRadius: 6 }}>
          {s.asset_type === "video" ? "Video" : s.asset_url ? "Image" : "No asset"}
        </div>
      </div>
      <div style={{ padding: "14px 16px 12px", display: "flex", flexDirection: "column", gap: 8, flex: 1 }}>
        <div style={{ fontFamily: "var(--display)", fontSize: 14.5, fontWeight: 700, letterSpacing: "-0.01em", color: "var(--ink)" }}>{s.slug}</div>
        <div style={{ fontSize: 13, color: "var(--ink-soft)", lineHeight: 1.4, fontStyle: "italic" }}>"{s.hook}"</div>
        <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginTop: 2 }}>
          <Chip tone="ghost"><Icon name="clock" size={11}/> {s.length}</Chip>
          {s.format && <Chip tone="ghost">{s.format}</Chip>}
        </div>
        <div style={{ display: "flex", gap: 6, marginTop: "auto", paddingTop: 12, flexWrap: "wrap" }}>
          {inShot
            ? <button className="btn gold sm" disabled style={{ opacity: 0.95 }}><Icon name="check" size={12} stroke={3}/> In shot list</button>
            : <button className="btn primary sm" onClick={() => { store && store.addShot(s.id); store && store.toast("Sent to shot list", { label: "View", fn: () => store.goLibrary("shot") }); }}><Icon name="video" size={12}/> Send to Alli</button>}
          {s.brief && <button className="btn sm" onClick={() => setBriefOpen(true)}><Icon name="script" size={12}/> Brief</button>}
          {s.asset_url && <a className="btn sm" href={downloadHref(s.asset_url)} title="Download asset" style={{ textDecoration: "none" }}><Icon name="download" size={12}/></a>}
          <button className="btn ghost sm" onClick={() => setOpen(!open)} style={{ marginLeft: "auto" }}>{open ? "▲ Less" : "▼ Details"}</button>
        </div>
        {s.asset_url && (
          <div style={{ display: "flex", gap: 6, marginTop: 8, paddingTop: 8, borderTop: "var(--bd) solid var(--line)", flexWrap: "wrap" }}>
            <button className="btn sm" onClick={() => stubAction("Create ad campaign")} style={{ flex: 1, justifyContent: "center", fontSize: 11.5 }} title="Create a Meta ads campaign with this asset">
              <Icon name="bolt" size={12}/> Create ad campaign
            </button>
            <button className="btn sm" onClick={() => stubAction("Post to Instagram")} style={{ flex: 1, justifyContent: "center", fontSize: 11.5 }} title="Schedule this asset to post on Instagram">
              <Icon name="image" size={12}/> Post to Instagram
            </button>
          </div>
        )}
      </div>
      {open && (
        <div style={{ padding: "14px 16px 16px", borderTop: "var(--bd) solid var(--line)", background: "var(--paper-2)" }}>
          <div className="ai-note" style={{ marginBottom: 12 }}>
            <div className="ai-tag"><Icon name="hook" size={12}/> Inspired by</div>{s.inspired}
          </div>
          <div className="beat"><div className="beat-label">Hook · 0–3s</div><div><div className="beat-text script-quote">"{s.hook}"</div>{s.hookDir && <div className="beat-dir">{s.hookDir}</div>}</div></div>
          <div className="beat"><div className="beat-label">Body</div><div className="beat-text">{s.body}</div></div>
          <div className="beat"><div className="beat-label">CTA</div><div><div className="beat-text">{s.cta}</div>{s.ctaOverlay && <div className="overlay-note">Overlay: "{s.ctaOverlay}"</div>}</div></div>
          <div className="ai-note" style={{ background: "var(--card)", marginTop: 6 }}>
            <div className="ai-tag" style={{ color: "var(--olive)" }}><Icon name="check" size={12}/> Why it works</div>{s.why}
          </div>
          <button className="btn sm" onClick={copyScript} style={{ marginTop: 12 }}><Icon name="script" size={13}/> Copy full script</button>
        </div>
      )}
      {briefOpen && <BriefModal script={s} brief={s.brief} store={store} onClose={() => setBriefOpen(false)}/>}
    </div>
  );
}

/* ---- Drag & drop file picker --------------------------------------- */
const { useRef } = React;
function DropZone({ file, onFile, onClear }) {
  const [dragOver, setDragOver] = useState(false);
  const inputRef = useRef(null);
  const handleFiles = (files) => {
    if (!files || files.length === 0) return;
    const f = files[0];
    if (f && f.type.startsWith("video/")) onFile(f);
  };
  if (file) {
    return (
      <div style={{ border: "var(--bd) solid var(--line-strong)", borderRadius: "var(--r-md)", padding: "16px 18px", background: "#fff", display: "flex", alignItems: "center", gap: 14 }}>
        <div style={{ width: 44, height: 44, background: "var(--accent-soft)", color: "var(--accent)", borderRadius: 10, display: "grid", placeItems: "center", flex: "0 0 44px" }}>
          <Icon name="video" size={22}/>
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontWeight: 600, fontSize: 14, color: "var(--ink)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{file.name}</div>
          <div style={{ fontSize: 12, color: "var(--ink-soft)", fontFamily: "var(--mono)" }}>{(file.size / 1024 / 1024).toFixed(1)} MB · ready to upload</div>
        </div>
        <button onClick={onClear} className="btn ghost sm" title="Choose a different file">
          <Icon name="x" size={14}/>
        </button>
      </div>
    );
  }
  return (
    <div
      onClick={() => inputRef.current && inputRef.current.click()}
      onDragOver={(e) => { e.preventDefault(); e.dataTransfer.dropEffect = "copy"; setDragOver(true); }}
      onDragLeave={() => setDragOver(false)}
      onDrop={(e) => {
        e.preventDefault();
        setDragOver(false);
        handleFiles(e.dataTransfer.files);
      }}
      style={{
        border: `2px dashed ${dragOver ? "var(--accent)" : "var(--line-strong)"}`,
        borderRadius: "var(--r-md)",
        padding: "36px 22px",
        textAlign: "center",
        cursor: "pointer",
        background: dragOver ? "var(--accent-soft)" : "#fff",
        transition: "all .15s ease",
      }}
    >
      <div style={{ display: "inline-grid", placeItems: "center", width: 52, height: 52, background: dragOver ? "var(--accent)" : "var(--paper-2)", color: dragOver ? "#fff" : "var(--ink-soft)", borderRadius: 14, marginBottom: 12, transition: "all .15s ease" }}>
        <Icon name="download" size={26} style={{ transform: "rotate(180deg)" }}/>
      </div>
      <div style={{ fontFamily: "var(--display)", fontWeight: 700, fontSize: 16, letterSpacing: "-0.01em", color: "var(--ink)", marginBottom: 4 }}>
        {dragOver ? "Drop it here" : "Drag video here"}
      </div>
      <div style={{ fontSize: 13, color: "var(--ink-soft)" }}>
        or <span style={{ color: "var(--accent)", fontWeight: 600 }}>click to browse</span> · MP4, MOV, up to 500 MB
      </div>
      <input ref={inputRef} type="file" accept="video/*" hidden onChange={(e) => handleFiles(e.target.files)}/>
    </div>
  );
}

/* ---- Brief modal (replaces standalone brief page navigation) ---------- */
function BriefModal({ script, brief, store, onClose }) {
  const [file, setFile] = useState(null);
  const [uploading, setUploading] = useState(false);
  const [result, setResult] = useState(null);

  const fmtTime = (s) => {
    if (typeof s !== "number" || isNaN(s)) return "?";
    const m = Math.floor(s / 60), sec = Math.floor(s % 60);
    return `${m}:${sec.toString().padStart(2, "0")}`;
  };

  const submit = async () => {
    if (!file) return;
    setUploading(true);
    const form = new FormData();
    form.append("video", file);
    form.append("slug", "supermush");
    form.append("competitor", script.competitor_id || "gruns");
    form.append("scriptId", script.id);
    try {
      const r = await fetch("upload-video", { method: "POST", body: form });
      const j = await r.json();
      if (!r.ok) throw new Error(j.error || "upload failed");
      setResult(j);
      store && store.toast("Recording uploaded — overlays attached", { label: "View in Videos", fn: () => { onClose(); store.setView && store.setView("videos"); } });
    } catch (e) {
      alert("Upload failed: " + e.message);
    }
    setUploading(false);
  };

  if (!brief) return null;

  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, background: "rgba(8,9,10,0.55)", backdropFilter: "blur(4px)", zIndex: 200, display: "grid", placeItems: "start center", overflowY: "auto", padding: "40px 16px" }}>
      <div onClick={(e) => e.stopPropagation()} className="card" style={{ maxWidth: 820, width: "100%", padding: 0, overflow: "hidden", boxShadow: "var(--shadow-lg)" }}>
        <div style={{ padding: "18px 24px", borderBottom: "var(--bd) solid var(--line)", display: "flex", alignItems: "center", justifyContent: "space-between", background: "var(--paper-2)", position: "sticky", top: 0, zIndex: 5 }}>
          <div className="eyebrow">Topic brief</div>
          <button onClick={onClose} style={{ background: "transparent", border: "none", color: "var(--ink-soft)", padding: 6, cursor: "pointer", borderRadius: 6 }} title="Close (Esc)">
            <Icon name="x" size={18}/>
          </button>
        </div>

        <div style={{ padding: "24px 28px" }}>
          <h1 style={{ fontFamily: "var(--display)", fontWeight: 700, fontSize: 28, letterSpacing: "-0.02em", margin: "0 0 8px", lineHeight: 1.1 }}>{brief.topic_title || script.id}</h1>
          {brief.topic_one_liner && <p style={{ fontSize: 14.5, color: "var(--ink-soft)", lineHeight: 1.55, margin: "0 0 18px", maxWidth: 640 }}>{brief.topic_one_liner}</p>}

          <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginBottom: 22 }}>
            <Chip tone="ghost">{brief.format || "9:16 Reel"}</Chip>
            <Chip tone="ghost">{brief.target_duration_seconds || 75}s target</Chip>
          </div>

          {brief.hook_opening_line && (
            <div style={{ background: "var(--ink)", color: "#fff", padding: "22px 24px", borderRadius: "var(--r-md)", marginBottom: 22 }}>
              <div style={{ fontFamily: "var(--mono)", fontSize: 10.5, letterSpacing: "0.12em", textTransform: "uppercase", opacity: 0.7, marginBottom: 10, fontWeight: 600 }}>Hook · 0–3s</div>
              <div style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 20, lineHeight: 1.3 }}>"{brief.hook_opening_line}"</div>
            </div>
          )}

          {brief.angle && (
            <div style={{ marginBottom: 22 }}>
              <div className="section-label" style={{ marginBottom: 10 }}>The angle</div>
              <div style={{ background: "#fff", border: "var(--bd) solid var(--line)", borderLeft: "3px solid var(--accent)", borderRadius: "var(--r-md)", padding: "16px 20px", fontSize: 14.5, lineHeight: 1.55 }}>{brief.angle}</div>
            </div>
          )}

          {brief.talking_points && brief.talking_points.length > 0 && (
            <div style={{ marginBottom: 22 }}>
              <h3 style={{ fontFamily: "var(--display)", fontSize: 17, fontWeight: 700, margin: "0 0 12px" }}>Talking points</h3>
              <ol style={{ listStyle: "none", padding: 0, margin: 0, counterReset: "tp", display: "flex", flexDirection: "column", gap: 8 }}>
                {brief.talking_points.map((t, i) => (
                  <li key={i} style={{ background: "#fff", border: "var(--bd) solid var(--line)", borderRadius: "var(--r-md)", padding: "14px 18px 14px 50px", position: "relative", counterIncrement: "tp" }}>
                    <span style={{ position: "absolute", left: 14, top: 14, width: 22, height: 22, background: "var(--accent)", color: "#fff", borderRadius: 999, display: "flex", alignItems: "center", justifyContent: "center", fontFamily: "var(--mono)", fontSize: 10.5, fontWeight: 700 }}>{i + 1}</span>
                    <div style={{ fontWeight: 600, fontSize: 14, lineHeight: 1.4, marginBottom: 4 }}>{t.point}</div>
                    <div style={{ fontSize: 13, color: "var(--ink-soft)", lineHeight: 1.55 }}>{t.detail}</div>
                    {t.supporting_evidence && <div style={{ display: "inline-block", fontSize: 12, color: "var(--accent)", background: "var(--accent-soft)", padding: "4px 10px", borderRadius: "var(--r-sm)", marginTop: 8, fontFamily: "var(--mono)", fontWeight: 600 }}>{t.supporting_evidence}</div>}
                  </li>
                ))}
              </ol>
            </div>
          )}

          {brief.honest_disclosures && brief.honest_disclosures.length > 0 && (
            <div style={{ background: "var(--gold-soft)", border: "var(--bd) solid #ecd292", borderRadius: "var(--r-md)", padding: "16px 22px", marginBottom: 22 }}>
              <div className="section-label" style={{ color: "var(--gold)", marginBottom: 8 }}>Honest disclosures · mandatory</div>
              <ul style={{ margin: 0, paddingLeft: 20, fontSize: 13.5, lineHeight: 1.6 }}>
                {brief.honest_disclosures.map((d, i) => <li key={i} style={{ marginBottom: 6 }}>{d}</li>)}
              </ul>
            </div>
          )}

          {brief.visual_annotations && brief.visual_annotations.length > 0 && (
            <div style={{ marginBottom: 22 }}>
              <h3 style={{ fontFamily: "var(--display)", fontSize: 17, fontWeight: 700, margin: "0 0 12px" }}>Visual timeline</h3>
              <div style={{ display: "flex", flexDirection: "column", gap: 0, borderLeft: "2px solid var(--line)", paddingLeft: 0, marginLeft: 4 }}>
                {brief.visual_annotations.map((v, i) => (
                  <div key={i} style={{ display: "flex", gap: 14, padding: "10px 12px 10px 18px", position: "relative" }}>
                    <span style={{ position: "absolute", left: -5, top: 16, width: 8, height: 8, borderRadius: 999, background: "var(--accent)", border: "2px solid var(--paper)" }}/>
                    <div style={{ flex: "0 0 70px", fontFamily: "var(--mono)", fontWeight: 700, fontSize: 11.5, color: "var(--ink)", paddingTop: 2 }}>{fmtTime(v.start_seconds)}–{fmtTime(v.end_seconds)}</div>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--accent)", fontWeight: 700, marginBottom: 3 }}>{(v.role || "none").replace(/_/g, " ")}</div>
                      <div style={{ fontSize: 13, color: "var(--ink)", lineHeight: 1.5 }}>{v.note}</div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {brief.cta && (
            <div style={{ background: "var(--accent)", color: "#fff", padding: "20px 22px", borderRadius: "var(--r-md)", marginBottom: 22 }}>
              <div style={{ fontFamily: "var(--mono)", fontSize: 10.5, letterSpacing: "0.12em", textTransform: "uppercase", opacity: 0.85, marginBottom: 8, fontWeight: 600 }}>CTA · last 5s</div>
              <div style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 17, lineHeight: 1.35 }}>"{brief.cta}"</div>
            </div>
          )}
        </div>

        <div style={{ padding: "24px 28px 28px", borderTop: "var(--bd) solid var(--line)", background: "var(--paper-2)" }}>
          {result ? (
            <div style={{ display: "flex", alignItems: "center", gap: 12, flexWrap: "wrap" }}>
              <span style={{ color: "var(--olive)", fontWeight: 600, fontSize: 14 }}>
                <Icon name="check" size={14}/> Recording uploaded · {result.overlay_count} overlays attached, {result.assets_copied} assets linked.
              </span>
              <button className="btn primary sm" onClick={() => { onClose(); store.setView && store.setView("videos"); }} style={{ marginLeft: "auto" }}>
                <Icon name="video" size={13}/> View in Videos
              </button>
            </div>
          ) : (
            <div>
              <div style={{ fontFamily: "var(--display)", fontWeight: 700, fontSize: 16, marginBottom: 6 }}>Upload Alli's recording for this script</div>
              <div style={{ fontSize: 13.5, color: "var(--ink-soft)", marginBottom: 18, lineHeight: 1.55 }}>
                The {(brief.visual_annotations || []).length} overlay moments from this brief auto-attach to the timeline — we copy the matching generated assets to the new founder video so it's editing-ready.
              </div>
              <DropZone file={file} onFile={setFile} onClear={() => setFile(null)}/>
              <button
                className="btn primary"
                disabled={!file || uploading}
                onClick={submit}
                style={{ marginTop: 14, width: "100%", justifyContent: "center", padding: "13px 20px", fontSize: 14.5, fontWeight: 700, borderRadius: "var(--r-md)" }}
              >
                {uploading
                  ? <><span style={{ display: "inline-block", width: 14, height: 14, border: "2px solid currentColor", borderTopColor: "transparent", borderRadius: "50%", animation: "spin 0.7s linear infinite", marginRight: 8 }}/>Uploading…</>
                  : <><Icon name="video" size={15}/> Upload + auto-link overlays</>}
              </button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { GenFrame, AdThumb, AdCard, HookCard, advColor, AngleRow, FormatRow, BestCard, ScriptCard, ScriptGridCard, BriefModal, DropZone });
