/* Generate — brief builder + live prompt preview + queue */

const TONE_DESC = { Warm: "warm", Upbeat: "bright, upbeat", Cinematic: "cinematic, moody" };

function buildPrompt(f) {
  const aspect = f.aspect;
  const toneWord = (TONE_DESC[f.tone] || "warm").toUpperCase();
  const dur = f.format === "Video" ? `, ${f.duration || 6} seconds` : "";
  const who = f.who && f.who !== "—" ? ` ${f.who} in frame, reading as 40–65 homeowners/family — natural, not glossy.` : "";
  const hook = f.hook ? ` Visual hook: ${f.hook}.` : "";
  const scene = f.scene ? ` ${f.scene}.` : "";
  const ref = f.ref ? ` Reference unit (match exactly): ${f.ref}.` : "";
  const angle = f.angle ? ` Angle: ${f.angle}.` : "";
  return [
    { t: `Generate a ${aspect} `, },
    { t: toneWord, hl: true },
    { t: ` ${f.format === "Video" ? "video" : "image"}${dur}: a modern, clean-lined, single-story DETACHED ADORE backyard ADU (`, },
    { t: f.model, hl: true },
    { t: `) placed in a realistic Bay Area suburban backyard with lawn, fence and mature trees.${angle}${hook}${who}${scene}${ref}`, },
    { t: ` ${f.format === "Video" ? "Slow gentle push-in, soft light, minimal cuts." : "Soft natural light, photoreal."} Heartfelt and candid. No construction site, no on-screen text claims, no competitor logos. Native Meta Reels aesthetic, photorealistic. Return the accessible asset URL.`, },
  ];
}

function GenerateTab({ nextId, queue, setQueue, modelList, onCopy, copied, onSave, prefill, clearPrefill }) {
  const [f, setF] = React.useState({
    model: modelList[0], format: "Video", aspect: "9:16", tone: "Warm", duration: 6,
    who: "Family + dog", angle: "", hook: "", scene: "", ref: "", assetUrl: "", headline: "Tour the South Bay's Largest ADU Showroom", cta: "Book Now", primary: "",
  });
  const [saved, setSaved] = React.useState(null);
  // prefill from Creative Studio "Use in Generate" — drops in the approved asset + model/format.
  React.useEffect(() => {
    if (!prefill) return;
    setF(p => ({ ...p, ...prefill }));
    if (clearPrefill) clearPrefill();
  }, [prefill]);
  const set = (k) => (e) => setF(p => ({ ...p, [k]: e.target.value }));
  const prompt = buildPrompt(f);

  function addToQueue() {
    setQueue(q => [...q, { id: nextId(q.length), ...f }]);
  }
  function saveToGallery() {
    if (!onSave) return;
    const id = onSave(f);
    setSaved(id);
    setTimeout(() => setSaved(null), 3500);
  }
  function reset() {
    setF({ model: modelList[0], format: "Video", aspect: "9:16", tone: "Warm", duration: 6, who: "Family + dog", angle: "", hook: "", scene: "", ref: "", assetUrl: "", headline: "", cta: "Book Now", primary: "" });
  }
  function removeQ(i) { setQueue(q => q.filter((_, idx) => idx !== i)); }

  return (
    <div className="gen-grid">
      {/* FORM */}
      <div className="gen-form">
        <h3 className="serif">New creative brief</h3>
        <div className="sub">Compose a Higgsfield brief → queue it → hand off to Claude Code. Next id: <b>{nextId(queue.length)}</b></div>

        <div className="field">
          <label>Model / product focus</label>
          <select className="select" value={f.model} onChange={set("model")}>
            {modelList.map(m => <option key={m}>{m}</option>)}
          </select>
        </div>
        <div className="row">
          <div className="field"><label>Format</label>
            <select className="select" value={f.format} onChange={set("format")}><option>Video</option><option>Image</option></select></div>
          <div className="field"><label>Aspect</label>
            <select className="select" value={f.aspect} onChange={set("aspect")}><option>9:16</option><option>1:1</option><option>16:9</option></select></div>
        </div>
        <div className="row">
          <div className="field"><label>Tone (test variable)</label>
            <select className="select" value={f.tone} onChange={set("tone")}><option>Warm</option><option>Upbeat</option><option>Cinematic</option></select></div>
          <div className="field"><label>{f.format === "Video" ? "Duration (s)" : "Composition"}</label>
            {f.format === "Video"
              ? <input className="input" value={f.duration} onChange={set("duration")} />
              : <input className="input" placeholder="e.g. hero centered" value={f.scene} onChange={set("scene")} />}
          </div>
        </div>
        <div className="field"><label>Who's in frame</label>
          <select className="select" value={f.who} onChange={set("who")}>
            <option>Family + dog</option><option>Couple</option><option>Multi-gen family</option><option>Solo homeowner</option><option>— Unit only —</option>
          </select></div>
        <div className="field"><label>Marketing angle</label>
          <input className="input" placeholder="e.g. Multi-gen / Rental-income / Speed-no-mess" value={f.angle} onChange={set("angle")} /></div>
        <div className="field"><label>Visual hook (one line)</label>
          <input className="input" placeholder="e.g. Grandparent + grandkids on the ADU step" value={f.hook} onChange={set("hook")} /></div>
        <div className="field"><label>Scene description</label>
          <textarea className="textarea" placeholder="What happens in the shot…" value={f.scene} onChange={set("scene")} /></div>
        <div className="field"><label>Reference unit (optional — must match exactly)</label>
          <input className="input" placeholder="e.g. Crema 572 board-and-batten, dark window frames" value={f.ref} onChange={set("ref")} /></div>
        <div className="field"><label>Asset URL (optional — paste if you already have the image/video)</label>
          <input className="input" placeholder="https://… .mp4 / .jpg — leave blank to generate later" value={f.assetUrl} onChange={set("assetUrl")} /></div>
        <div className="row">
          <div className="field"><label>Headline</label>
            <input className="input" value={f.headline} onChange={set("headline")} /></div>
          <div className="field"><label>CTA</label>
            <select className="select" value={f.cta} onChange={set("cta")}><option>Book Now</option><option>Learn More</option><option>Get Quote</option><option>Sign Up</option></select></div>
        </div>
        <div className="field"><label>Primary ad copy (optional)</label>
          <textarea className="textarea" placeholder="Leave blank to write later" value={f.primary} onChange={set("primary")} /></div>

        <div style={{ display: "flex", gap: 10, marginTop: 4, flexWrap: "wrap" }}>
          <button className="btn btn-accent" onClick={saveToGallery}><Ico d={I.check} s={15} /> Save to Gallery &amp; Launch</button>
          <button className="btn btn-ghost" onClick={addToQueue}><Ico d={I.plus} s={15} /> Add to Higgsfield queue</button>
          <button className="btn btn-ghost" onClick={reset}>Reset</button>
        </div>
        {saved && <div style={{ marginTop: 10, font: "12.5px var(--sans)", color: "var(--ok)" }}>✓ Saved {saved} to Gallery &amp; Launch{f.assetUrl ? "" : " (queued — add an asset to make it launch-ready)"}.</div>}
      </div>

      {/* PREVIEW + QUEUE */}
      <div>
        <div className="prompt-preview">
          <div className="pp-label">Higgsfield prompt preview · /adu-{f.tone.toLowerCase()}-{f.format.toLowerCase()}</div>
          <div className="pp-body">
            {prompt.map((seg, i) => <span key={i} className={seg.hl ? "hl" : ""}>{seg.t}</span>)}
          </div>
        </div>

        <div className="how-box">
          <b>How generation works:</b> the browser never holds Higgsfield credentials. You queue briefs here, then <b>copy the command</b> into Claude Code, which runs the Higgsfield MCP, writes assets back to the sheet, and rebuilds this dashboard. Or paste the <span className="cmd">slate rows</span> straight into the workbook's <span className="cmd">creative_slate</span> tab.
        </div>

        <div className="queue-box">
          <div className="queue-head">
            <h4 className="serif">Brief queue <span className="qpill">{queue.length} queued</span></h4>
            {queue.length > 0 && <button className="link-btn" onClick={() => setQueue([])}>Clear all</button>}
          </div>
          {queue.length === 0 ? (
            <div className="muted" style={{ fontSize: 13, padding: "10px 2px" }}>No briefs queued yet. Compose one on the left and add it here.</div>
          ) : (
            <>
              {queue.map((q, i) => (
                <div className="qrow" key={i}>
                  <div>
                    <div className="qrow-id">{q.id} · {q.angle || "—"}</div>
                    <div className="qrow-meta">{q.format} {q.aspect} · {shortModel(q.model)} · {q.tone}</div>
                    {q.hook && <div className="qrow-scene">{q.hook}</div>}
                  </div>
                  <button className="link-btn danger" onClick={() => removeQ(i)}><Ico d={I.x} s={13} /> Remove</button>
                </div>
              ))}
              <div style={{ display: "flex", gap: 10, marginTop: 14 }}>
                <button className="btn btn-accent" onClick={onCopy}><Ico d={I.copy} s={14} /> {copied === "cmd" ? "Copied!" : "Copy generate command"}</button>
                <button className="btn" onClick={onCopy}><Ico d={I.copy} s={14} /> {copied === "tsv" ? "Copied!" : "Copy slate rows (TSV)"}</button>
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { GenerateTab, buildPrompt });
