/* Creative Studio — compose a Higgsfield brief + reference, Claude generates, you approve/give feedback,
   then send the approved asset to the Generate tab to attach to an ad.
   Generation runs through Claude (Higgsfield MCP); results land in window.__ADORE_STUDIO.items. */

function StudioTab({ modelList, onUseInGenerate }) {
  const REQ_KEY = "adore_studio_requests";
  const APPROVE_KEY = "adore_studio_approved";
  const loadReqs = () => { try { return JSON.parse(localStorage.getItem(REQ_KEY) || "[]"); } catch (e) { return []; } };
  const loadApproved = () => { try { return JSON.parse(localStorage.getItem(APPROVE_KEY) || "{}"); } catch (e) { return {}; } };

  const [reqs, setReqs] = React.useState(loadReqs);
  const [approved, setApproved] = React.useState(loadApproved);
  const [ref, setRef] = React.useState(null);
  const [refName, setRefName] = React.useState("");
  const [refType, setRefType] = React.useState("");   // "image" | "video"
  const [brief, setBrief] = React.useState("");
  const [format, setFormat] = React.useState("Video");
  const [aspect, setAspect] = React.useState("9:16");
  const [model, setModel] = React.useState(modelList[0]);
  const [copied, setCopied] = React.useState(null);
  const [fb, setFb] = React.useState({});

  const results = (window.__ADORE_STUDIO && window.__ADORE_STUDIO.items) || [];

  function saveReqs(next) { try { localStorage.setItem(REQ_KEY, JSON.stringify(next)); } catch (e) {} setReqs(next); }
  function saveApproved(next) { try { localStorage.setItem(APPROVE_KEY, JSON.stringify(next)); } catch (e) {} setApproved(next); }

  function onFile(e) {
    const f = e.target.files && e.target.files[0]; if (!f) return;
    const type = (f.type || "").startsWith("video") ? "video" : "image";
    const r = new FileReader(); r.onload = () => { setRef(r.result); setRefName(f.name); setRefType(type); }; r.readAsDataURL(f);
  }
  function clearRef() { setRef(null); setRefName(""); setRefType(""); }
  function addReq() {
    if (!brief.trim()) return;
    // persist image thumbnails (small); skip video data URLs (too big for localStorage) — keep name + type only.
    const item = { id: "REQ-" + Date.now(), brief: brief.trim(), format, aspect, model, refName, refType, refData: refType === "image" ? ref : "", createdAt: new Date().toISOString() };
    saveReqs([item, ...reqs]);
    setBrief(""); clearRef();
  }
  function removeReq(id) { saveReqs(reqs.filter(r => r.id !== id)); }
  function copy(id, text) { try { navigator.clipboard.writeText(text); } catch (e) {} setCopied(id); setTimeout(() => setCopied(null), 1500); }
  function briefText(it) { return `Higgsfield ${it.format} ${it.aspect} for ADORE (${it.model}).\nBrief: ${it.brief}\nReference ${it.refType ? it.refType : "none"}: ${it.refName || "(see chat)"}\n→ Generate it and add to the Creative Studio.`; }
  function approveResult(g) { saveApproved({ ...approved, [g.id]: new Date().toISOString() }); }

  const isVid = it => /video/i.test(it.format || "") || /\.(mp4|mov|webm)(\?|$)/i.test(it.assetUrl || "");

  return (
    <div className="gen-grid">
      {/* COMPOSER */}
      <div className="gen-form">
        <h3 className="serif">New creative request</h3>
        <div className="sub">Upload a reference, describe what you want — <b>Claude</b> generates it with Higgsfield, then you approve or give feedback.</div>

        <div className="field">
          <label>Reference image or video (optional)</label>
          <label className="studio-drop">
            {ref
              ? (refType === "video" ? <video src={ref} controls muted loop playsInline /> : <img src={ref} alt="" />)
              : <span>Click to upload an image or video for Higgsfield to work on…</span>}
            <input type="file" accept="image/*,video/*" onChange={onFile} style={{ display: "none" }} />
          </label>
          {refName && <div className="studio-refname">{refType === "video" ? "🎬 " : "🖼️ "}{refName} · <button className="link-btn" onClick={clearRef}>remove</button></div>}
        </div>

        <div className="field"><label>What should Claude create?</label>
          <textarea className="textarea" style={{ minHeight: 110 }} placeholder="e.g. Animate this Crema 572 photo into a 6s clip — slow push-in, warm light, a family walking up to the ADU door." value={brief} onChange={e => setBrief(e.target.value)} /></div>

        <div className="row">
          <div className="field"><label>Format</label>
            <select className="select" value={format} onChange={e => setFormat(e.target.value)}><option>Video</option><option>Image</option></select></div>
          <div className="field"><label>Aspect</label>
            <select className="select" value={aspect} onChange={e => setAspect(e.target.value)}><option>9:16</option><option>1:1</option><option>16:9</option><option>4:5</option></select></div>
        </div>
        <div className="field"><label>Model / product</label>
          <select className="select" value={model} onChange={e => setModel(e.target.value)}>{modelList.map(m => <option key={m}>{m}</option>)}</select></div>

        <div style={{ display: "flex", gap: 10, marginTop: 4, flexWrap: "wrap" }}>
          <button className="btn btn-accent" onClick={addReq}><Ico d={I.plus} s={15} /> Add request</button>
          <button className="btn btn-ghost" onClick={() => copy("compose", briefText({ brief, format, aspect, model, refName, refType }))} disabled={!brief.trim()}>
            <Ico d={I.copy} s={14} /> {copied === "compose" ? "Copied!" : "Copy brief for Claude"}</button>
        </div>
        <div className="how-box" style={{ marginTop: 14 }}>
          <b>How it works:</b> add your request (it's saved here), then tell <b className="cmd">Claude</b> “generate the studio requests” and share the reference image in chat. Claude runs Higgsfield and the result appears under <b>Generated</b> → approve or give feedback → <b>Use in Generate</b> to attach it to an ad.
        </div>
      </div>

      {/* QUEUE + RESULTS */}
      <div>
        {/* requests queue */}
        <div className="queue-box">
          <div className="queue-head"><h4 className="serif">Your requests <span className="qpill">{reqs.length}</span></h4>
            {reqs.length > 0 && <button className="link-btn" onClick={() => saveReqs([])}>Clear all</button>}</div>
          {reqs.length === 0 ? (
            <div className="muted" style={{ fontSize: 13, padding: "8px 2px", color: "var(--t3)" }}>No requests yet. Compose one on the left.</div>
          ) : reqs.map(it => (
            <div className="qrow" key={it.id}>
              <div style={{ display: "flex", gap: 10, alignItems: "center", minWidth: 0 }}>
                {it.refData
                  ? <img src={it.refData} alt="" style={{ width: 46, height: 46, objectFit: "cover", borderRadius: 7, flex: "none" }} />
                  : (it.refType === "video" && <span style={{ width: 46, height: 46, borderRadius: 7, flex: "none", display: "grid", placeItems: "center", background: "var(--inset)", border: "1px solid var(--line-2)", fontSize: 18 }}>🎬</span>)}
                <div style={{ minWidth: 0 }}>
                  <div className="qrow-id">{it.format} {it.aspect} · {shortModel(it.model)}{it.refType ? " · ref: " + it.refType : ""}</div>
                  <div className="qrow-scene" style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", maxWidth: 220 }}>{it.brief}</div>
                </div>
              </div>
              <div style={{ display: "flex", gap: 4 }}>
                <button className="link-btn" onClick={() => copy(it.id, briefText(it))}><Ico d={I.copy} s={13} /> {copied === it.id ? "Copied" : "Copy"}</button>
                <button className="link-btn danger" onClick={() => removeReq(it.id)}><Ico d={I.x} s={13} /></button>
              </div>
            </div>
          ))}
        </div>

        {/* generated results */}
        <div className="queue-box" style={{ marginTop: 16 }}>
          <div className="queue-head"><h4 className="serif">Generated <span className="qpill">{results.length}</span></h4></div>
          {results.length === 0 ? (
            <div className="muted" style={{ fontSize: 13, padding: "8px 2px", color: "var(--t3)" }}>Nothing generated yet. Ask Claude to generate your requests — results show here.</div>
          ) : results.map(g => {
            const vid = isVid(g);
            const ok = !!approved[g.id];
            return (
              <div className="studio-result" key={g.id}>
                <div className="studio-media">
                  {g.assetUrl ? (vid
                    ? <video src={g.assetUrl} controls loop muted playsInline />
                    : <img src={g.assetUrl} alt="" />) : <div className="studio-pending">Generating…</div>}
                </div>
                <div className="studio-result-body">
                  <div className="studio-result-meta mono">{g.format} {g.aspect} · {shortModel(g.model || "")} {ok && <span className="studio-approved">✓ Approved</span>}</div>
                  <div className="studio-result-brief">{g.brief}</div>
                  {g.note && <div className="studio-result-note">{g.note}</div>}
                  <div className="studio-actions">
                    <button className={"btn btn-sm " + (ok ? "btn-ghost" : "btn-accent")} onClick={() => approveResult(g)} disabled={!g.assetUrl}>
                      <Ico d={I.check} s={13} /> {ok ? "Approved" : "Approve"}</button>
                    <button className="btn btn-ghost btn-sm" onClick={() => onUseInGenerate(g)} disabled={!g.assetUrl}>
                      <Ico d={I.arrowUp} s={13} /> Use in Generate</button>
                  </div>
                  <div className="studio-fb">
                    <input className="input" placeholder="Request changes (feedback)…" value={fb[g.id] || ""} onChange={e => setFb({ ...fb, [g.id]: e.target.value })} />
                    <button className="link-btn" disabled={!(fb[g.id] || "").trim()}
                      onClick={() => copy("fb-" + g.id, `Modify ${g.id} (${g.format} ${g.aspect}, ${g.model}): ${fb[g.id]}`)}>
                      <Ico d={I.copy} s={13} /> {copied === "fb-" + g.id ? "Copied" : "Copy feedback"}</button>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}
window.StudioTab = StudioTab;
