/* ============================================================
   Composer — Claude drafting loop + refine chips.
   Props: target {brand,lane,event,contacts}, contact, thread (messages),
          subject, onSent(), onSaved(), compact, accent
   ============================================================ */

const REFINE_CHIPS = ["Shorter", "Warmer", "More direct", "Punchier"];

function Composer({ target, contact, thread, subject, onSent, onSaved, autostart = true, initialDraft = null }) {
  const [draft, setDraft] = React.useState(initialDraft || "");
  const [loading, setLoading] = React.useState(false);
  const [activeRefine, setActiveRefine] = React.useState(null);
  const [instruction, setInstruction] = React.useState("");
  const [sent, setSent] = React.useState(false);
  const [savedAt, setSavedAt] = React.useState(null);
  const [usedClaude, setUsedClaude] = React.useState(false);
  const taRef = React.useRef(null);
  const reqId = React.useRef(0);

  const gen = React.useCallback(async (opts = {}) => {
    const myReq = ++reqId.current;
    setLoading(true);
    setSent(false);
    const liveClaude = !!(window.claude && window.claude.complete);
    setUsedClaude(liveClaude);
    const out = await window.draftEngine.generate({
      contact: contact || target?.contacts?.[0],
      brand: target?.brand, lane: target?.lane, event: target?.event,
      thread: thread || null,
      refine: opts.refine || null,
      instruction: opts.instruction || null,
    });
    if (myReq !== reqId.current) return; // stale
    setDraft(out);
    setLoading(false);
  }, [contact, target, thread]);

  React.useEffect(() => {
    if (initialDraft) { setDraft(initialDraft); setLoading(false); return; }
    if (autostart) gen();
    // eslint-disable-next-line
  }, [target?.id, contact?.id]);

  const doRefine = (chip) => {
    setActiveRefine(chip);
    gen({ refine: chip }).then(() => setActiveRefine(null));
  };
  const doInstruction = () => {
    if (!instruction.trim()) return;
    const i = instruction;
    setInstruction("");
    gen({ instruction: i });
  };

  const copy = () => {
    navigator.clipboard?.writeText(draft);
    setSavedAt("Copied to clipboard");
    setTimeout(() => setSavedAt(null), 1800);
  };
  const save = () => {
    setSavedAt("Draft saved");
    onSaved && onSaved(draft);
    setTimeout(() => setSavedAt(null), 1800);
  };
  const markSent = () => {
    setSent(true);
    onSent && onSent(draft);
  };
  const gmail = () => {
    const to = (contact || target?.contacts?.[0])?.email || "";
    const su = subject || `We The Creators × ${target?.brand || ""}`;
    const url = `https://mail.google.com/mail/?view=cm&fs=1&to=${encodeURIComponent(to)}&su=${encodeURIComponent(su)}&body=${encodeURIComponent(draft)}`;
    window.open(url, "_blank");
  };

  const to = (contact || target?.contacts?.[0]);

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
      {/* draft header */}
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <span style={{
            display: "inline-flex", alignItems: "center", gap: 6,
            fontSize: 11.5, fontWeight: 650, letterSpacing: "0.04em", textTransform: "uppercase",
            color: "var(--accent)",
          }}>
            <Icon name="sparkles" size={14} />
            {loading ? "Claude is drafting…" : "Draft ready"}
          </span>
          {to && <span style={{ fontSize: 12, color: "var(--text-3)" }}>· to {to.name} &lt;{to.email}&gt;</span>}
        </div>
        <button className="btn btn--sm btn--ghost" onClick={() => gen()} disabled={loading} title="Regenerate">
          <Icon name="refresh" size={13} /> Regenerate
        </button>
      </div>

      {/* textarea / skeleton */}
      <div style={{ position: "relative" }}>
        {loading ? (
          <div style={{
            minHeight: 150, borderRadius: "var(--r-md)", border: "1px solid var(--line)",
            background: "var(--surface)", padding: 16, display: "flex", flexDirection: "column", gap: 11,
          }}>
            {[92, 100, 84, 70, 96, 60].map((w, i) => (
              <div key={i} className="shimmer" style={{ width: w + "%", height: 11, borderRadius: 6 }}></div>
            ))}
          </div>
        ) : (
          <textarea ref={taRef} value={draft} onChange={(e) => setDraft(e.target.value)}
            spellCheck="false"
            style={{
              width: "100%", minHeight: 150, resize: "vertical",
              background: "var(--surface)", border: "1px solid var(--line)",
              borderRadius: "var(--r-md)", color: "var(--text)",
              fontFamily: "var(--font)", fontSize: 14, lineHeight: 1.62, padding: 16,
            }}
            onFocus={(e) => (e.target.style.borderColor = "var(--accent-strong)")}
            onBlur={(e) => (e.target.style.borderColor = "var(--line)")} />
        )}
      </div>

      {/* refine chips */}
      <div style={{ display: "flex", flexWrap: "wrap", alignItems: "center", gap: 7 }}>
        <span style={{ fontSize: 12, color: "var(--text-3)", marginRight: 2 }}>Refine:</span>
        {REFINE_CHIPS.map((c) => (
          <button key={c} className="refine-chip" disabled={loading}
            onClick={() => doRefine(c)}
            style={activeRefine === c ? { borderColor: "var(--accent)", color: "var(--accent)" } : null}>
            {c}
          </button>
        ))}
      </div>

      {/* freeform instruction */}
      <div style={{ display: "flex", gap: 8 }}>
        <input className="input" placeholder="Tell Claude how to change it…"
          value={instruction} onChange={(e) => setInstruction(e.target.value)}
          onKeyDown={(e) => e.key === "Enter" && doInstruction()} disabled={loading} />
        <button className="btn" onClick={doInstruction} disabled={loading || !instruction.trim()}>
          <Icon name="sparkles" size={14} /> Apply
        </button>
      </div>

      {/* actions */}
      <div style={{ display: "flex", alignItems: "center", gap: 8, paddingTop: 4, borderTop: "1px solid var(--line-soft)", marginTop: 2 }}>
        <button className="btn btn--primary" onClick={markSent} disabled={loading || sent}>
          <Icon name={sent ? "check" : "send"} size={15} /> {sent ? "Sent" : "Mark sent"}
        </button>
        <button className="btn" onClick={gmail} disabled={loading}>
          <Icon name="mail" size={14} /> Open in Gmail
        </button>
        <button className="btn btn--ghost btn--icon" onClick={copy} disabled={loading} title="Copy">
          <Icon name="copy" size={15} />
        </button>
        <button className="btn btn--ghost btn--icon" onClick={save} disabled={loading} title="Save draft">
          <Icon name="draft" size={15} />
        </button>
        <div style={{ flex: 1 }}></div>
        {savedAt && <span style={{ fontSize: 12, color: "var(--green)" }}>{savedAt}</span>}
        <span style={{ fontSize: 11, color: "var(--text-3)", display: "flex", alignItems: "center", gap: 5 }}>
          <span className="stagedot" style={{ background: usedClaude ? "var(--green)" : "var(--text-3)" }}></span>
          {usedClaude ? "Claude" : "sample voice"}
        </span>
      </div>
    </div>
  );
}

Object.assign(window, { Composer });
