// SmartSend — consolidate multiple finalized quotes into one customer email

const SS_PACKAGES = [
  {
    id: "ss-acme",
    customer: "Acme Industrial",
    contact: { name: "Jenna Park", role: "VP Procurement", email: "j.park@acmeind.com", initials: "JP", color: "#76ADFF" },
    state: "ready",
    addedBy: { name: "You", at: "Today, 11:24 am" },
    quotes: [
      { id: "Q-982510", opp: "Plant 4 Conveyor Refit",     status: "Finalized",  amount: 84500,  lines: 12, doc: "Q-982510_Acme_Conveyor.pdf",   addedAt: "10:42 am", flagged: false },
      { id: "Q-982511", opp: "Plant 4 Conveyor Refit",     status: "Finalized",  amount: 12700,  lines: 4,  doc: "Q-982511_Acme_ServicePlan.pdf", addedAt: "10:44 am", flagged: false },
      { id: "Q-982544", opp: "Warehouse 2 Lift Upgrade",   status: "Finalized",  amount: 56200,  lines: 8,  doc: "Q-982544_Acme_LiftUpgrade.pdf", addedAt: "Yesterday", flagged: false },
      { id: "Q-982601", opp: "Annual Lubricant Supply",    status: "Needs Review", amount: 9400,  lines: 18, doc: "Q-982601_Acme_Lubricants.pdf", addedAt: "Today, 11:08 am", flagged: true, flagReason: "Pricing approval pending from Sales Mgr" },
    ],
  },
  {
    id: "ss-northwave",
    customer: "Northwave Logistics",
    contact: { name: "Marcus Lee", role: "Director, Ops", email: "marcus@northwave.co", initials: "ML", color: "#7B3DCC" },
    state: "needsReview",
    addedBy: { name: "You", at: "Yesterday, 4:18 pm" },
    quotes: [
      { id: "Q-982488", opp: "Fleet Telematics Rollout", status: "Finalized",    amount: 138200, lines: 22, doc: "Q-982488_NW_Telematics.pdf",    addedAt: "Yesterday", flagged: false },
      { id: "Q-982491", opp: "Driver Training Modules",  status: "Needs Review", amount: 22400,  lines: 6,  doc: "Q-982491_NW_Training.pdf",      addedAt: "Yesterday", flagged: true, flagReason: "Contact may differ — verify recipient" },
    ],
  },
  {
    id: "ss-orbital",
    customer: "Orbital Foods",
    contact: { name: "Priya Shah", role: "Plant Manager", email: "p.shah@orbitalfoods.com", initials: "PS", color: "#22863A" },
    state: "sent",
    addedBy: { name: "Karim N.", at: "Apr 28, 3:02 pm" },
    sentAt: "Apr 28, 4:11 pm",
    quotes: [
      { id: "Q-981990", opp: "Cold Storage Retrofit", status: "Sent", amount: 212000, lines: 14, doc: "Q-981990_Orbital_ColdStorage.pdf", addedAt: "Apr 28", flagged: false },
      { id: "Q-981995", opp: "Cold Storage Retrofit", status: "Sent", amount: 38400,  lines: 5,  doc: "Q-981995_Orbital_Install.pdf",     addedAt: "Apr 28", flagged: false },
      { id: "Q-982010", opp: "Sanitation Supplies",   status: "Sent", amount: 14750,  lines: 22, doc: "Q-982010_Orbital_Sanitation.pdf",  addedAt: "Apr 28", flagged: false },
    ],
  },
];

const SS_STATE_META = {
  ready:       { tone: "success", label: "Ready to Send" },
  needsReview: { tone: "warning", label: "Needs Review" },
  sent:        { tone: "neutral", label: "Sent" },
};

const fmtMoney = (n) => "$" + n.toLocaleString("en-US");

// ---------------- Queue page ----------------

const SS_INBOX = [
  { id: "Q-982712", customer: "Acme Industrial",    opp: "Spare Parts Restock", amount: 4280,  finalizedAt: "2 min ago", contact: "Jenna Park",  suggestedPkg: "ss-acme" },
  { id: "Q-982705", customer: "Helix Manufacturing", opp: "Press Line Service",  amount: 18900, finalizedAt: "18 min ago", contact: "Devon Cruz",  suggestedPkg: null },
  { id: "Q-982698", customer: "Northwave Logistics", opp: "Yard Cameras Phase 2", amount: 31200, finalizedAt: "42 min ago", contact: "Marcus Lee", suggestedPkg: "ss-northwave" },
];

const SmartSendQueuePage = ({ onOpen }) => {
  const [filter, setFilter] = React.useState("all");
  const [added, setAdded] = React.useState(new Set());
  const filtered = filter === "all" ? SS_PACKAGES : SS_PACKAGES.filter((p) => p.state === filter);

  const totals = {
    ready: SS_PACKAGES.filter((p) => p.state === "ready").length,
    needsReview: SS_PACKAGES.filter((p) => p.state === "needsReview").length,
    sent: SS_PACKAGES.filter((p) => p.state === "sent").length,
    quotes: SS_PACKAGES.reduce((s, p) => s + p.quotes.length, 0),
    customers: new Set(SS_PACKAGES.map((p) => p.customer)).size,
  };

  return (
    <div data-screen-label="02 SmartSend Queue" style={{ padding: "24px 28px" }}>
      <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 16, marginBottom: 18 }}>
        <div>
          <div style={{ fontSize: 12, color: "var(--mw-text-tertiary)", display: "flex", alignItems: "center", gap: 6 }}>
            <span>Sales</span>
            <Icon name="chevronRight" size={12} opacity={0.5} />
            <span>SmartSend</span>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 6 }}>
            <h1 className="mw-h1" style={{ fontSize: 26, margin: 0 }}>SmartSend Queue</h1>
            <Chip tone="info">{totals.quotes} quotes</Chip>
          </div>
          <div style={{ fontSize: 13, color: "var(--mw-text-tertiary)", marginTop: 6, maxWidth: 720 }}>
            Bundle finalized quotes destined for the same customer contact into a single consolidated email. Less inbox spam, more confidence everything was delivered together.
          </div>
        </div>
        <Button kind="ai" icon="ai">AI Draft All Packages</Button>
      </div>

      {/* Stat strip */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12, marginBottom: 18 }}>
        {[
          { l: "Ready to Send",   v: totals.ready,        tone: "success", icon: "check" },
          { l: "Needs Review",    v: totals.needsReview,  tone: "warning", icon: "infoCircle" },
          { l: "Sent (30d)",      v: totals.sent,         tone: "neutral", icon: "send" },
          { l: "Customers",       v: totals.customers,    tone: "info",    icon: "user" },
        ].map((s, i) => (
          <div key={i} className="mw-card" style={{ padding: 14, display: "flex", alignItems: "center", gap: 12 }}>
            <span style={{
              width: 32, height: 32, borderRadius: 8, flexShrink: 0,
              background: s.tone === "success" ? "#DAF0E0" : s.tone === "warning" ? "#FFF9E0" : s.tone === "info" ? "#E8E9F6" : "#F1F2F4",
              display: "inline-flex", alignItems: "center", justifyContent: "center",
            }}>
              <Icon name={s.icon} size={16} opacity={0.7} />
            </span>
            <div>
              <div style={{ fontSize: 22, fontWeight: 600, lineHeight: 1, fontVariantNumeric: "tabular-nums" }}>{s.v}</div>
              <div style={{ fontSize: 11, color: "var(--mw-text-tertiary)", marginTop: 4, textTransform: "uppercase", letterSpacing: 0.5, fontWeight: 600 }}>{s.l}</div>
            </div>
          </div>
        ))}
      </div>

      {/* Finalize → Add entry point: recently finalized quotes inbox */}
      <div className="mw-card" style={{ padding: 0, marginBottom: 18, overflow: "hidden" }}>
        <div style={{ padding: "12px 16px", borderBottom: "1px solid var(--mw-border-soft)", display: "flex", alignItems: "center", gap: 10 }}>
          <Icon name="reminder" size={14} opacity={0.7} />
          <span style={{ fontSize: 13, fontWeight: 600 }}>Recently Finalized Quotes</span>
          <Chip tone="info">{SS_INBOX.length} ready to bundle</Chip>
          <div style={{ flex: 1 }} />
          <div style={{ fontSize: 11, color: "var(--mw-text-tertiary)" }}>
            Finalize a quote → Add to SmartSend → Review → Send
          </div>
        </div>
        {SS_INBOX.map((q, i) => {
          const isAdded = added.has(q.id);
          return (
            <div key={q.id} style={{
              padding: "10px 16px", display: "flex", alignItems: "center", gap: 12, fontSize: 13,
              borderTop: i > 0 ? "1px solid var(--mw-border-soft)" : "none",
              opacity: isAdded ? 0.55 : 1,
            }}>
              <span style={{ width: 28, height: 28, background: "#FCE2E2", color: "#C02F32", borderRadius: 6, display: "inline-flex", alignItems: "center", justifyContent: "center", fontSize: 9, fontWeight: 700, flexShrink: 0 }}>PDF</span>
              <div style={{ minWidth: 0, flex: 1, display: "grid", gridTemplateColumns: "1.2fr 1fr 1fr auto", gap: 12, alignItems: "center" }}>
                <div>
                  <span style={{ fontFamily: "var(--mw-font-mono)", fontWeight: 600 }}>{q.id}</span>
                  <span style={{ color: "var(--mw-text-tertiary)", marginLeft: 8, fontSize: 12 }}>finalized {q.finalizedAt}</span>
                </div>
                <div style={{ color: "var(--mw-text-secondary)" }}>{q.customer} · <span style={{ color: "var(--mw-text-tertiary)" }}>{q.contact}</span></div>
                <div style={{ color: "var(--mw-text-tertiary)", fontSize: 12, display: "flex", alignItems: "center", gap: 4 }}>
                  <Icon name="branch" size={10} opacity={0.5} /> {q.opp}
                </div>
                <div style={{ display: "flex", alignItems: "center", gap: 10, justifyContent: "flex-end" }}>
                  <span style={{ fontWeight: 600, fontVariantNumeric: "tabular-nums" }}>{fmtMoney(q.amount)}</span>
                  {isAdded ? (
                    <Chip tone="success" dot>Added</Chip>
                  ) : (
                    <button onClick={() => setAdded((s) => new Set([...s, q.id]))} style={{
                      padding: "5px 10px", fontSize: 12, fontWeight: 500, borderRadius: 6,
                      border: "1px solid var(--mw-border-strong)", background: "#fff", cursor: "pointer",
                      display: "inline-flex", alignItems: "center", gap: 4,
                    }}>
                      <Icon name="plus" size={11} opacity={0.7} />
                      {q.suggestedPkg ? "Add to existing package" : "Start new package"}
                    </button>
                  )}
                </div>
              </div>
            </div>
          );
        })}
      </div>

      {/* Filter bar */}
      <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 14 }}>
        {[
          { id: "all", label: `All (${SS_PACKAGES.length})` },
          { id: "ready", label: `Ready (${totals.ready})` },
          { id: "needsReview", label: `Needs Review (${totals.needsReview})` },
          { id: "sent", label: `Sent (${totals.sent})` },
        ].map((f) => (
          <button key={f.id} onClick={() => setFilter(f.id)} style={{
            padding: "5px 12px", fontSize: 13, borderRadius: 9999,
            border: filter === f.id ? "1px solid var(--mw-brand-500)" : "1px solid var(--mw-border)",
            background: filter === f.id ? "var(--mw-brand-50)" : "#fff",
            color: filter === f.id ? "var(--mw-brand-500)" : "var(--mw-text-secondary)",
            cursor: "pointer", fontWeight: 500,
          }}>{f.label}</button>
        ))}
      </div>

      {/* Packages */}
      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        {filtered.map((p, i) => (
          <SmartSendPackageCard key={p.id} pkg={p} idx={i} onOpen={() => onOpen && onOpen(p)} />
        ))}
      </div>
    </div>
  );
};

const SmartSendPackageCard = ({ pkg, idx, onOpen }) => {
  const meta = SS_STATE_META[pkg.state];
  const total = pkg.quotes.reduce((s, q) => s + q.amount, 0);
  const opps = [...new Set(pkg.quotes.map((q) => q.opp))];
  const flagged = pkg.quotes.filter((q) => q.flagged).length;

  return (
    <div className="mw-card" style={{
      padding: 18, cursor: "pointer",
      animation: `mw-row-in 280ms ${idx * 50}ms var(--mw-ease) both`,
    }} onClick={onOpen}>
      <div style={{ display: "flex", alignItems: "flex-start", gap: 16 }}>
        {/* Left: contact */}
        <div style={{ display: "flex", alignItems: "center", gap: 10, minWidth: 240 }}>
          <Avatar initials={pkg.contact.initials} color={pkg.contact.color} size={42} />
          <div style={{ minWidth: 0 }}>
            <div style={{ fontSize: 15, fontWeight: 600 }}>{pkg.customer}</div>
            <div style={{ fontSize: 12, color: "var(--mw-text-tertiary)" }}>
              {pkg.contact.name} · {pkg.contact.role}
            </div>
            <div style={{ fontSize: 11, color: "var(--mw-text-quaternary)", fontFamily: "var(--mw-font-mono)" }}>
              {pkg.contact.email}
            </div>
          </div>
        </div>

        {/* Middle: opportunities + quotes summary */}
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 6 }}>
            <Chip tone={meta.tone} dot={pkg.state !== "sent"}>{meta.label}</Chip>
            {flagged > 0 && pkg.state !== "sent" && (
              <Chip tone="warning">
                <Icon name="infoCircle" size={10} opacity={0.7} />
                <span style={{ marginLeft: 3 }}>{flagged} flagged</span>
              </Chip>
            )}
            <span style={{ fontSize: 11, color: "var(--mw-text-tertiary)" }}>
              · {pkg.quotes.length} quote{pkg.quotes.length !== 1 && "s"} across {opps.length} {opps.length === 1 ? "opportunity" : "opportunities"}
            </span>
          </div>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
            {opps.map((o, k) => (
              <span key={k} style={{
                display: "inline-flex", alignItems: "center", gap: 4,
                padding: "2px 8px", borderRadius: 6, fontSize: 12,
                background: "var(--mw-bg)", color: "var(--mw-text-secondary)",
              }}>
                <Icon name="branch" size={10} opacity={0.5} />
                {o}
              </span>
            ))}
          </div>
          <div style={{ display: "flex", gap: 14, marginTop: 10, fontSize: 12, color: "var(--mw-text-tertiary)" }}>
            <span><Icon name="paperclip" size={11} opacity={0.6} /> {pkg.quotes.length} PDFs</span>
            <span>Added {pkg.addedBy.at} by {pkg.addedBy.name}</span>
            {pkg.sentAt && <span>· Sent {pkg.sentAt}</span>}
          </div>
        </div>

        {/* Right: total + actions */}
        <div style={{ textAlign: "right", minWidth: 160 }}>
          <div style={{ fontSize: 11, color: "var(--mw-text-tertiary)", textTransform: "uppercase", letterSpacing: 0.5, fontWeight: 600 }}>Package Total</div>
          <div style={{ fontSize: 22, fontWeight: 600, color: "var(--mw-text-primary)", marginTop: 2, fontVariantNumeric: "tabular-nums" }}>{fmtMoney(total)}</div>
          <div style={{ marginTop: 12 }}>
            {pkg.state === "sent"
              ? <Button kind="secondary" size="sm" icon="files">View Sent</Button>
              : <Button kind={pkg.state === "ready" ? "primary" : "secondary"} size="sm" icon={pkg.state === "ready" ? "send" : "pen"}>
                  {pkg.state === "ready" ? "Review & Send" : "Resolve & Review"}
                </Button>}
          </div>
        </div>
      </div>
    </div>
  );
};

// ---------------- Review / Send page ----------------

const SmartSendReviewPage = ({ pkg, onBack }) => {
  const [included, setIncluded] = React.useState(() => new Set(pkg.quotes.filter((q) => !q.flagged).map((q) => q.id)));
  const [sent, setSent] = React.useState(pkg.state === "sent");
  const [streamIdx, setStreamIdx] = React.useState(0);

  const includedQuotes = pkg.quotes.filter((q) => included.has(q.id));
  const total = includedQuotes.reduce((s, q) => s + q.amount, 0);
  const opps = [...new Set(includedQuotes.map((q) => q.opp))];

  // Build the AI email
  const defaultSubject = `${pkg.customer} — ${includedQuotes.length} quote${includedQuotes.length !== 1 ? "s" : ""} ready for your review`;
  const defaultBodyParagraphs = [
    `Hi ${pkg.contact.name.split(" ")[0]},`,
    `We've finalized ${includedQuotes.length} quote${includedQuotes.length !== 1 ? "s" : ""} for ${pkg.customer} totaling ${fmtMoney(total)} across ${opps.length} ${opps.length === 1 ? "opportunity" : "opportunities"}. To keep things tidy, we've consolidated everything into this single email so your team can review the full package side-by-side.`,
    `Each quote is attached as a PDF and grouped below by opportunity. Pricing is held for 30 days. If you'd like to walk through any of the line items together, I'm happy to schedule a call.`,
    `Thanks,\nNicole Maddox\nMindworks Sales`,
  ];

  // Edit state — overrides the generated draft when user has edited
  const [editing, setEditing] = React.useState(false);
  const [editedSubject, setEditedSubject] = React.useState(null);
  const [editedBody, setEditedBody] = React.useState(null);  // stores HTML when edited
  const [aiRewriting, setAiRewriting] = React.useState(false);
  const editorRef = React.useRef(null);

  const subject = editedSubject !== null ? editedSubject : defaultSubject;
  // Body can be plain text (default AI draft) or HTML (after editing)
  const bodyText = editedBody !== null ? editedBody : defaultBodyParagraphs.join("\n\n");
  const isEditedHTML = editedBody !== null;
  const bodyParagraphs = bodyText.split(/\n{2,}/);
  const isEdited = editedSubject !== null || editedBody !== null;

  // Convert plain text body to simple HTML for the editor
  const textToHTML = (txt) =>
    txt.split(/\n{2,}/).map((p) => `<p>${p.replace(/\n/g, "<br>")}</p>`).join("");

  // Draft buffers used while editing
  const [draftSubject, setDraftSubject] = React.useState(subject);
  const [draftBodyHTML, setDraftBodyHTML] = React.useState(
    isEditedHTML ? bodyText : textToHTML(bodyText)
  );
  React.useEffect(() => {
    if (editing) {
      setDraftSubject(subject);
      const html = isEditedHTML ? bodyText : textToHTML(bodyText);
      setDraftBodyHTML(html);
      // Inject into the editable element on enter
      requestAnimationFrame(() => {
        if (editorRef.current && editorRef.current.innerHTML !== html) {
          editorRef.current.innerHTML = html;
        }
      });
    }
  }, [editing]);

  const onSaveEdit = () => {
    setEditedSubject(draftSubject);
    setEditedBody(editorRef.current ? editorRef.current.innerHTML : draftBodyHTML);
    setEditing(false);
  };
  const onResetToAI = () => {
    setEditedSubject(null);
    setEditedBody(null);
    setEditing(false);
  };
  const onAIRewrite = (tone) => {
    setAiRewriting(true);
    setTimeout(() => {
      const variants = {
        warmer:   `Hi ${pkg.contact.name.split(" ")[0]},\n\nHope you're doing well! I'm excited to share that we've put together ${includedQuotes.length} finalized quote${includedQuotes.length !== 1 ? "s" : ""} for ${pkg.customer} — ${fmtMoney(total)} in total across ${opps.length} ${opps.length === 1 ? "opportunity" : "opportunities"}. Bundling them so it's easier to compare side by side.\n\nEach quote is attached as a PDF, grouped by opportunity below. Happy to jump on a quick call any time — just let me know what works.\n\nWarmly,\nNicole`,
        shorter:  `Hi ${pkg.contact.name.split(" ")[0]},\n\nAttached: ${includedQuotes.length} finalized quote${includedQuotes.length !== 1 ? "s" : ""} for ${pkg.customer} (${fmtMoney(total)} total) across ${opps.length} ${opps.length === 1 ? "opportunity" : "opportunities"}. Pricing valid 30 days.\n\nHappy to walk through any of it together.\n\n— Nicole`,
        formal:   `Dear ${pkg.contact.name},\n\nPlease find attached ${includedQuotes.length} finalized quote${includedQuotes.length !== 1 ? "s" : ""} for ${pkg.customer}, with a combined value of ${fmtMoney(total)} spanning ${opps.length} ${opps.length === 1 ? "opportunity" : "opportunities"}. Each document is grouped by opportunity in the summary below.\n\nThese terms remain valid for thirty (30) days. I am available to schedule a review session at your convenience.\n\nRegards,\nNicole Maddox\nMindworks Sales`,
      };
      const newHTML = textToHTML(variants[tone] || "");
      setDraftBodyHTML(newHTML);
      if (editorRef.current) editorRef.current.innerHTML = newHTML;
      setAiRewriting(false);
    }, 900);
  };

  // Token stream effect for the AI-drafted body (only when NOT editing & not customized)
  const tokens = React.useMemo(() => bodyText.split(/(\s+)/), [bodyText]);

  React.useEffect(() => {
    if (sent) { setStreamIdx(tokens.length); return; }
    if (isEdited) { setStreamIdx(tokens.length); return; }  // skip streaming after user edits
    setStreamIdx(0);
    let i = 0;
    const id = setInterval(() => {
      i += 2;
      setStreamIdx(i);
      if (i >= tokens.length) clearInterval(id);
    }, 18);
    return () => clearInterval(id);
  }, [pkg.id, tokens.length, included.size, isEdited]);

  const streamedText = tokens.slice(0, streamIdx).join("");
  const isStreaming = streamIdx < tokens.length;

  const toggle = (qid) => {
    setIncluded((prev) => {
      const next = new Set(prev);
      if (next.has(qid)) next.delete(qid); else next.add(qid);
      return next;
    });
  };

  const flaggedRemaining = pkg.quotes.filter((q) => q.flagged && included.has(q.id));
  const canSend = flaggedRemaining.length === 0 && includedQuotes.length > 0 && !sent;

  const meta = SS_STATE_META[pkg.state];

  return (
    <div data-screen-label="02b SmartSend Review" style={{ padding: "24px 28px" }}>
      {/* Breadcrumb + header */}
      <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 16, marginBottom: 18 }}>
        <div style={{ minWidth: 0 }}>
          <div style={{ fontSize: 12, color: "var(--mw-text-tertiary)", display: "flex", alignItems: "center", gap: 6 }}>
            <span style={{ cursor: "pointer" }} onClick={onBack}>SmartSend</span>
            <Icon name="chevronRight" size={12} opacity={0.5} />
            <span>{pkg.customer}</span>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 6 }}>
            <button onClick={onBack} style={{ width: 28, height: 28, borderRadius: 8, border: "1px solid var(--mw-border)", background: "#fff", cursor: "pointer", display: "inline-flex", alignItems: "center", justifyContent: "center" }}>
              <Icon name="chevronRight" size={14} style={{ transform: "rotate(180deg)" }} opacity={0.7} />
            </button>
            <h1 className="mw-h1" style={{ fontSize: 24, margin: 0 }}>{pkg.customer} · Review Package</h1>
            <Chip tone={sent ? "success" : meta.tone} dot={!sent}>{sent ? "Sent" : meta.label}</Chip>
          </div>
          <div style={{ fontSize: 12, color: "var(--mw-text-tertiary)", marginTop: 6 }}>
            To: <span style={{ color: "var(--mw-text-secondary)", fontWeight: 500 }}>{pkg.contact.name}</span> · {pkg.contact.email} ·  {pkg.contact.role}
          </div>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <Button kind="secondary" icon="pen" onClick={() => setEditing(true)} disabled={sent}>Edit Draft</Button>
          <Button kind={canSend ? "primary" : "secondary"} icon={sent ? "check" : "send"} disabled={!canSend && !sent}
            onClick={() => canSend && setSent(true)}>
            {sent ? "Sent" : `Send Consolidated Email (${includedQuotes.length})`}
          </Button>
        </div>
      </div>

      {/* Duplicate-send guardrail */}
      {sent && (
        <div style={{
          marginBottom: 14, padding: "10px 14px", borderRadius: 10,
          background: "#DAF0E0", border: "1px solid rgba(34, 134, 58, .25)",
          display: "flex", alignItems: "center", gap: 10,
        }}>
          <Icon name="check" size={16} color="brand" />
          <span style={{ fontSize: 13, color: "#22863A", fontWeight: 500 }}>
            Sent to {pkg.contact.email} · {includedQuotes.length} quotes attached · This package is now locked to prevent duplicate sends.
          </span>
        </div>
      )}
      {flaggedRemaining.length > 0 && !sent && (
        <div style={{
          marginBottom: 14, padding: "10px 14px", borderRadius: 10,
          background: "#FFF9E0", border: "1px solid rgba(178, 121, 26, .25)",
          display: "flex", alignItems: "flex-start", gap: 10,
        }}>
          <Icon name="infoCircle" size={16} opacity={0.7} style={{ marginTop: 1 }} />
          <div style={{ fontSize: 13, color: "#7a5212" }}>
            <span style={{ fontWeight: 600 }}>Resolve {flaggedRemaining.length} flagged quote{flaggedRemaining.length !== 1 ? "s" : ""} before sending.</span>
            <span style={{ display: "block", marginTop: 2, fontSize: 12 }}>
              {flaggedRemaining[0].flagReason} · Remove or resolve to enable sending.
            </span>
          </div>
        </div>
      )}

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1.15fr", gap: 20 }}>
        {/* LEFT: Included Quotes */}
        <div className="mw-card" style={{ padding: 0, alignSelf: "flex-start" }}>
          <div style={{ padding: "14px 18px", borderBottom: "1px solid var(--mw-border-soft)", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
            <div>
              <div style={{ fontSize: 13, fontWeight: 600 }}>Included Quotes</div>
              <div style={{ fontSize: 11, color: "var(--mw-text-tertiary)", marginTop: 2 }}>{includedQuotes.length} of {pkg.quotes.length} selected · grouped by opportunity</div>
            </div>
            <div style={{ textAlign: "right" }}>
              <div style={{ fontSize: 11, color: "var(--mw-text-tertiary)", textTransform: "uppercase", letterSpacing: 0.5, fontWeight: 600 }}>Total</div>
              <div style={{ fontSize: 18, fontWeight: 600, fontVariantNumeric: "tabular-nums" }}>{fmtMoney(total)}</div>
            </div>
          </div>

          {opps.length === 0 && [...new Set(pkg.quotes.map((q) => q.opp))].map((o, gi) => null)}
          {[...new Set(pkg.quotes.map((q) => q.opp))].map((o, gi) => {
            const qs = pkg.quotes.filter((q) => q.opp === o);
            const oppTotal = qs.filter((q) => included.has(q.id)).reduce((s, q) => s + q.amount, 0);
            return (
              <div key={gi} style={{ borderBottom: gi < opps.length ? "1px solid var(--mw-border-soft)" : "none" }}>
                <div style={{
                  padding: "10px 18px", background: "var(--mw-bg)",
                  display: "flex", alignItems: "center", justifyContent: "space-between",
                }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                    <Icon name="branch" size={12} opacity={0.6} />
                    <span style={{ fontSize: 12, fontWeight: 600, color: "var(--mw-text-secondary)" }}>{o}</span>
                    <span style={{ fontSize: 11, color: "var(--mw-text-tertiary)" }}>· {qs.length} quote{qs.length !== 1 && "s"}</span>
                  </div>
                  <span style={{ fontSize: 12, color: "var(--mw-text-tertiary)", fontVariantNumeric: "tabular-nums" }}>{fmtMoney(oppTotal)}</span>
                </div>
                {qs.map((q) => {
                  const on = included.has(q.id);
                  return (
                    <div key={q.id} style={{
                      padding: "12px 18px", display: "flex", alignItems: "center", gap: 12,
                      opacity: on ? 1 : 0.55,
                      borderTop: "1px solid var(--mw-border-soft)",
                    }}>
                      <button onClick={() => !sent && toggle(q.id)} disabled={sent} style={{
                        width: 18, height: 18, borderRadius: 5, padding: 0, flexShrink: 0,
                        border: on ? "1.5px solid var(--mw-brand-500)" : "1.5px solid var(--mw-border-strong)",
                        background: on ? "var(--mw-brand-500)" : "#fff",
                        display: "inline-flex", alignItems: "center", justifyContent: "center",
                        cursor: sent ? "not-allowed" : "pointer",
                      }}>
                        {on && <Icon name="check" size={11} color="white" />}
                      </button>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                          <span style={{ fontSize: 13, fontWeight: 600, fontFamily: "var(--mw-font-mono)" }}>{q.id}</span>
                          <Chip tone={q.status === "Finalized" ? "success" : q.status === "Sent" ? "neutral" : "warning"}>{q.status}</Chip>
                          {q.flagged && (
                            <span title={q.flagReason} style={{
                              display: "inline-flex", alignItems: "center", gap: 3, padding: "1px 6px",
                              borderRadius: 4, fontSize: 10, fontWeight: 600,
                              background: "#FFF9E0", color: "#B2791A",
                            }}>
                              <Icon name="flag" size={10} opacity={0.7} /> FLAGGED
                            </span>
                          )}
                        </div>
                        <div style={{ fontSize: 12, color: "var(--mw-text-tertiary)", marginTop: 2 }}>
                          {q.lines} line items · added {q.addedAt}
                        </div>
                        <div style={{ fontSize: 11, color: "var(--mw-brand-500)", marginTop: 4, display: "flex", alignItems: "center", gap: 4 }}>
                          <Icon name="paperclip" size={11} color="brand" /> {q.doc}
                        </div>
                        {q.flagged && (
                          <div style={{ fontSize: 11, color: "#7a5212", marginTop: 6, padding: "4px 8px", background: "#FFF9E0", borderRadius: 6, border: "1px solid rgba(178,121,26,.2)" }}>
                            {q.flagReason}
                          </div>
                        )}
                      </div>
                      <div style={{ fontSize: 14, fontWeight: 600, fontVariantNumeric: "tabular-nums", textAlign: "right", minWidth: 90 }}>
                        {fmtMoney(q.amount)}
                      </div>
                      {!sent && (
                        <button onClick={() => toggle(q.id)} title="Remove" style={{
                          width: 24, height: 24, borderRadius: 6, border: "1px solid var(--mw-border)",
                          background: "#fff", cursor: "pointer", display: "inline-flex", alignItems: "center", justifyContent: "center",
                        }}>
                          <Icon name="cross" size={10} opacity={0.6} />
                        </button>
                      )}
                    </div>
                  );
                })}
              </div>
            );
          })}

          {/* Safeguards */}
          <div style={{ padding: "12px 18px", background: "var(--mw-bg)", display: "flex", flexDirection: "column", gap: 6 }}>
            <div style={{ fontSize: 11, fontWeight: 600, color: "var(--mw-text-tertiary)", textTransform: "uppercase", letterSpacing: 0.5 }}>Safeguards</div>
            {[
              { ok: true, label: `All quotes destined for ${pkg.contact.name}` },
              { ok: !flaggedRemaining.length, label: flaggedRemaining.length ? `${flaggedRemaining.length} flagged quote${flaggedRemaining.length !== 1 ? "s" : ""} need resolution` : "No flagged quotes in package" },
              { ok: !sent, label: sent ? "Package already sent — locked" : "No prior send detected for this set" },
            ].map((s, k) => (
              <div key={k} style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12, color: s.ok ? "var(--mw-text-secondary)" : "#B2791A" }}>
                <span style={{
                  width: 14, height: 14, borderRadius: "50%",
                  background: s.ok ? "#DAF0E0" : "#FFF9E0",
                  display: "inline-flex", alignItems: "center", justifyContent: "center",
                }}>
                  <Icon name={s.ok ? "check" : "infoCircle"} size={9} opacity={0.8} />
                </span>
                {s.label}
              </div>
            ))}
          </div>
        </div>

        {/* RIGHT: Email Preview */}
        <div className="mw-card" style={{ padding: 0, alignSelf: "flex-start", overflow: "hidden" }}>
          <div style={{ padding: "10px 16px", background: "var(--mw-bg)", borderBottom: "1px solid var(--mw-border-soft)",
            display: "flex", alignItems: "center", gap: 8 }}>
            <AIOrb size={14} spin={isStreaming || aiRewriting} />
            <span style={{ fontSize: 12, fontWeight: 600 }}>
              {editing ? "Editing Draft" : isEdited ? "Custom Draft" : "AI Draft"} · Email Preview
            </span>
            {isStreaming && !editing && <span style={{ fontSize: 11, color: "var(--mw-brand-500)" }}>Composing…</span>}
            {isEdited && !editing && (
              <Chip tone="warning" style={{ marginLeft: 4 }}>
                <Icon name="pen" size={10} opacity={0.7} /> <span style={{ marginLeft: 3 }}>Edited</span>
              </Chip>
            )}
            <div style={{ flex: 1 }} />
            {!editing && !sent && (
              <>
                {isEdited && (
                  <button onClick={onResetToAI} style={{ fontSize: 11, color: "var(--mw-text-tertiary)", border: 0, background: "transparent", cursor: "pointer", fontWeight: 500 }}>
                    Reset to AI
                  </button>
                )}
                <button onClick={() => setEditing(true)} style={{
                  fontSize: 11, color: "var(--mw-brand-500)", border: 0, background: "transparent",
                  cursor: "pointer", fontWeight: 500, display: "inline-flex", alignItems: "center", gap: 4,
                }}>
                  <Icon name="pen" size={10} color="brand" /> Edit
                </button>
                <button onClick={() => { setEditedSubject(null); setEditedBody(null); }} style={{
                  fontSize: 11, color: "var(--mw-brand-500)", border: 0, background: "transparent",
                  cursor: "pointer", fontWeight: 500,
                }}>Regenerate</button>
              </>
            )}
            {editing && (
              <>
                <button onClick={() => setEditing(false)} style={{
                  fontSize: 12, color: "var(--mw-text-secondary)", padding: "4px 10px", borderRadius: 6,
                  border: "1px solid var(--mw-border)", background: "#fff", cursor: "pointer", fontWeight: 500,
                }}>Cancel</button>
                <button onClick={onSaveEdit} style={{
                  fontSize: 12, color: "#fff", padding: "4px 10px", borderRadius: 6,
                  border: 0, background: "var(--mw-brand-500)", cursor: "pointer", fontWeight: 500,
                  display: "inline-flex", alignItems: "center", gap: 4,
                }}>
                  <Icon name="check" size={11} color="white" /> Save Draft
                </button>
              </>
            )}
          </div>

          {editing ? (
            <>
              {/* AI tone helpers */}
              <div style={{
                padding: "10px 20px", borderBottom: "1px solid var(--mw-border-soft)",
                background: "linear-gradient(90deg, rgba(123,200,255,.06), rgba(83,74,255,.04))",
                display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap",
              }}>
                <span style={{ fontSize: 11, fontWeight: 600, color: "var(--mw-text-tertiary)", textTransform: "uppercase", letterSpacing: 0.5 }}>
                  AI assist:
                </span>
                {[
                  { id: "warmer",  label: "Make warmer",   icon: "star" },
                  { id: "shorter", label: "Make shorter",  icon: "doubleChevronRight" },
                  { id: "formal",  label: "More formal",   icon: "files" },
                ].map((t) => (
                  <button key={t.id} onClick={() => onAIRewrite(t.id)} disabled={aiRewriting} style={{
                    display: "inline-flex", alignItems: "center", gap: 5,
                    padding: "4px 10px", borderRadius: 9999,
                    border: "1px solid rgba(83,74,255,.25)", background: "#fff",
                    color: "var(--mw-brand-500)", fontSize: 11, fontWeight: 500, cursor: aiRewriting ? "wait" : "pointer",
                    opacity: aiRewriting ? 0.6 : 1,
                  }}>
                    <Icon name={t.icon} size={10} color="brand" /> {t.label}
                  </button>
                ))}
                {aiRewriting && (
                  <span style={{ fontSize: 11, color: "var(--mw-brand-500)", display: "inline-flex", alignItems: "center", gap: 4 }}>
                    <AIOrb size={10} spin /> rewriting…
                  </span>
                )}
              </div>

              {/* From / To shown read-only, Subject editable */}
              <div style={{ padding: "14px 20px", borderBottom: "1px solid var(--mw-border-soft)", fontSize: 13, lineHeight: 1.6 }}>
                <div style={{ display: "flex", gap: 8 }}>
                  <span style={{ color: "var(--mw-text-tertiary)", width: 56 }}>From:</span>
                  <span>Nicole Maddox &lt;nicole@mindworks.com&gt;</span>
                </div>
                <div style={{ display: "flex", gap: 8 }}>
                  <span style={{ color: "var(--mw-text-tertiary)", width: 56 }}>To:</span>
                  <span><strong>{pkg.contact.name}</strong> &lt;{pkg.contact.email}&gt;</span>
                </div>
                <div style={{ display: "flex", gap: 8, alignItems: "center", marginTop: 4 }}>
                  <span style={{ color: "var(--mw-text-tertiary)", width: 56 }}>Subject:</span>
                  <input
                    type="text"
                    value={draftSubject}
                    onChange={(e) => setDraftSubject(e.target.value)}
                    style={{
                      flex: 1, fontSize: 13, fontWeight: 600,
                      padding: "6px 10px", borderRadius: 6,
                      border: "1px solid var(--mw-border-strong)", background: "#fff",
                      color: "var(--mw-text-primary)", fontFamily: "inherit",
                    }}
                  />
                </div>
              </div>

              {/* Editable body — rich text */}
              <RichTextToolbar editorRef={editorRef} />
              <div style={{ padding: "0 20px 16px" }}>
                <div
                  ref={editorRef}
                  contentEditable
                  suppressContentEditableWarning
                  onInput={(e) => setDraftBodyHTML(e.currentTarget.innerHTML)}
                  onPaste={(e) => {
                    // Strip rich pasted formatting back to plain text for a cleaner draft
                    e.preventDefault();
                    const text = (e.clipboardData || window.clipboardData).getData("text/plain");
                    document.execCommand("insertText", false, text);
                  }}
                  style={{
                    minHeight: 260,
                    padding: 14, borderRadius: 10,
                    border: "1px solid var(--mw-border-strong)", background: "#fff",
                    fontFamily: "inherit", fontSize: 13, lineHeight: 1.6,
                    color: "var(--mw-text-primary)",
                    outline: "none",
                  }}
                />
                <div style={{ display: "flex", justifyContent: "space-between", marginTop: 8, fontSize: 11, color: "var(--mw-text-tertiary)" }}>
                  <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
                    <Icon name="infoCircle" size={11} opacity={0.5} />
                    Rich text: select text and use the toolbar above. Cmd/Ctrl + B / I / U also works.
                  </span>
                  <span>{(editorRef.current?.innerText || "").length} characters</span>
                </div>
              </div>

              {/* Read-only: quote summary card */}
              <div style={{ padding: "0 20px 18px" }}>
                <div style={{ border: "1px solid var(--mw-border)", borderRadius: 10, overflow: "hidden", opacity: 0.7 }}>
                  <div style={{ padding: "8px 12px", background: "var(--mw-bg)", fontSize: 11, fontWeight: 600, color: "var(--mw-text-tertiary)", textTransform: "uppercase", letterSpacing: 0.5,
                    display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                    <span>Quote Summary (auto-generated)</span>
                    <span style={{ fontSize: 10, fontWeight: 500, textTransform: "none", letterSpacing: 0 }}>Pinned — not editable</span>
                  </div>
                  <div style={{ padding: "10px 12px", fontSize: 12, color: "var(--mw-text-tertiary)" }}>
                    {includedQuotes.length} quote{includedQuotes.length !== 1 ? "s" : ""} · {opps.length} {opps.length === 1 ? "opportunity" : "opportunities"} · {fmtMoney(total)} total
                  </div>
                </div>
              </div>
            </>
          ) : (
            <>
              {/* From / To / Subject */}
              <div style={{ padding: "14px 20px", borderBottom: "1px solid var(--mw-border-soft)", fontSize: 13, lineHeight: 1.6 }}>
                <div style={{ display: "flex", gap: 8 }}>
                  <span style={{ color: "var(--mw-text-tertiary)", width: 56 }}>From:</span>
                  <span>Nicole Maddox &lt;nicole@mindworks.com&gt;</span>
                </div>
                <div style={{ display: "flex", gap: 8 }}>
                  <span style={{ color: "var(--mw-text-tertiary)", width: 56 }}>To:</span>
                  <span><strong>{pkg.contact.name}</strong> &lt;{pkg.contact.email}&gt;</span>
                </div>
                <div style={{ display: "flex", gap: 8 }}>
                  <span style={{ color: "var(--mw-text-tertiary)", width: 56 }}>Subject:</span>
                  <span style={{ fontWeight: 600 }}>{subject}</span>
                </div>
              </div>

              {/* Body — render HTML if edited, otherwise plain text stream */}
              <div style={{ padding: "18px 20px", fontSize: 13, lineHeight: 1.65, color: "var(--mw-text-primary)", minHeight: 200 }}
                   className="mw-email-body">
                {isEditedHTML ? (
                  <div dangerouslySetInnerHTML={{ __html: bodyText }} />
                ) : (
                  <div style={{ whiteSpace: "pre-wrap" }}>
                    {streamedText}
                    {isStreaming && <span style={{ display: "inline-block", width: 7, height: 14, background: "var(--mw-brand-500)", marginLeft: 2, verticalAlign: "middle", animation: "mw-blink 1s steps(2) infinite" }} />}
                  </div>
                )}
              </div>

              {/* Quote summary card embedded in email */}
              {!isStreaming && (
                <div style={{ padding: "0 20px 18px" }}>
                  <div style={{ border: "1px solid var(--mw-border)", borderRadius: 10, overflow: "hidden" }}>
                    <div style={{ padding: "8px 12px", background: "var(--mw-bg)", fontSize: 11, fontWeight: 600, color: "var(--mw-text-tertiary)", textTransform: "uppercase", letterSpacing: 0.5 }}>
                      Quote Summary
                    </div>
                    {[...new Set(includedQuotes.map((q) => q.opp))].map((o, k) => {
                      const qs = includedQuotes.filter((q) => q.opp === o);
                      return (
                        <div key={k} style={{ padding: "10px 12px", borderTop: k > 0 ? "1px solid var(--mw-border-soft)" : "none" }}>
                          <div style={{ fontSize: 12, fontWeight: 600, color: "var(--mw-text-primary)", marginBottom: 4 }}>{o}</div>
                          {qs.map((q) => (
                            <div key={q.id} style={{ display: "flex", justifyContent: "space-between", fontSize: 12, color: "var(--mw-text-secondary)", padding: "2px 0" }}>
                              <span style={{ fontFamily: "var(--mw-font-mono)" }}>{q.id} <span style={{ color: "var(--mw-text-tertiary)" }}>· {q.lines} items</span></span>
                              <span style={{ fontVariantNumeric: "tabular-nums" }}>{fmtMoney(q.amount)}</span>
                            </div>
                          ))}
                        </div>
                      );
                    })}
                    <div style={{ padding: "10px 12px", borderTop: "1px solid var(--mw-border-soft)", display: "flex", justifyContent: "space-between", fontSize: 13, fontWeight: 600 }}>
                      <span>Total</span>
                      <span style={{ fontVariantNumeric: "tabular-nums" }}>{fmtMoney(total)}</span>
                    </div>
                  </div>
                </div>
              )}

              {/* Attachments */}
              {!isStreaming && (
                <div style={{ padding: "14px 20px", borderTop: "1px solid var(--mw-border-soft)", background: "var(--mw-bg)" }}>
                  <div style={{ fontSize: 11, fontWeight: 600, color: "var(--mw-text-tertiary)", textTransform: "uppercase", letterSpacing: 0.5, marginBottom: 8 }}>
                    {includedQuotes.length} Attachment{includedQuotes.length !== 1 && "s"}
                  </div>
                  <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                    {includedQuotes.map((q) => (
                      <div key={q.id} style={{
                        display: "flex", alignItems: "center", gap: 8, padding: "6px 10px",
                        background: "#fff", border: "1px solid var(--mw-border)", borderRadius: 8,
                        fontSize: 12,
                      }}>
                        <span style={{ width: 22, height: 22, background: "#FCE2E2", color: "#C02F32", borderRadius: 4, display: "inline-flex", alignItems: "center", justifyContent: "center", fontSize: 9, fontWeight: 700 }}>PDF</span>
                        <span style={{ flex: 1, fontFamily: "var(--mw-font-mono)" }}>{q.doc}</span>
                        <span style={{ color: "var(--mw-text-tertiary)" }}>· {q.id}</span>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </>
          )}
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { SmartSendQueuePage, SmartSendReviewPage, SS_PACKAGES });

// ---------------- Rich Text Toolbar ----------------
// A lightweight toolbar of formatting buttons that operate on the current
// selection inside the contentEditable email body. Uses document.execCommand —
// fine for prototype-grade rich text editing.

function RichTextToolbar({ editorRef }) {
  const [linkOpen, setLinkOpen] = React.useState(false);
  const [linkUrl, setLinkUrl] = React.useState("https://");
  const savedRange = React.useRef(null);

  const focusEditor = () => editorRef.current && editorRef.current.focus();

  const exec = (cmd, value = null) => (e) => {
    e.preventDefault();
    focusEditor();
    document.execCommand(cmd, false, value);
  };

  const saveSelection = () => {
    const sel = window.getSelection();
    if (sel && sel.rangeCount > 0) savedRange.current = sel.getRangeAt(0);
  };
  const restoreSelection = () => {
    if (savedRange.current) {
      const sel = window.getSelection();
      sel.removeAllRanges();
      sel.addRange(savedRange.current);
    }
  };

  const insertLink = (e) => {
    e.preventDefault();
    if (linkUrl) {
      focusEditor();
      restoreSelection();
      document.execCommand("createLink", false, linkUrl);
    }
    setLinkOpen(false);
    setLinkUrl("https://");
  };

  const TbBtn = ({ onMouseDown, title, children, active }) => (
    <button onMouseDown={onMouseDown} title={title} style={{
      width: 28, height: 28, padding: 0, borderRadius: 6, border: 0,
      background: active ? "var(--mw-brand-50)" : "transparent",
      color: active ? "var(--mw-brand-500)" : "var(--mw-text-secondary)",
      cursor: "pointer", fontSize: 13, fontWeight: 600,
      display: "inline-flex", alignItems: "center", justifyContent: "center",
    }}>{children}</button>
  );
  const Sep = () => <span style={{ width: 1, height: 18, background: "var(--mw-border)" }} />;

  return (
    <div style={{
      margin: "12px 20px 8px", padding: "5px 8px", borderRadius: 10,
      border: "1px solid var(--mw-border)", background: "#fff",
      display: "flex", alignItems: "center", gap: 4, flexWrap: "wrap",
      position: "relative",
    }}>
      <TbBtn onMouseDown={exec("bold")} title="Bold (Cmd+B)"><span style={{ fontWeight: 700 }}>B</span></TbBtn>
      <TbBtn onMouseDown={exec("italic")} title="Italic (Cmd+I)"><span style={{ fontStyle: "italic" }}>I</span></TbBtn>
      <TbBtn onMouseDown={exec("underline")} title="Underline (Cmd+U)"><span style={{ textDecoration: "underline" }}>U</span></TbBtn>
      <TbBtn onMouseDown={exec("strikeThrough")} title="Strikethrough"><span style={{ textDecoration: "line-through" }}>S</span></TbBtn>
      <Sep />
      <select onMouseDown={(e) => e.stopPropagation()} onChange={(e) => {
        focusEditor();
        const v = e.target.value;
        if (v === "p") document.execCommand("formatBlock", false, "P");
        else document.execCommand("formatBlock", false, v);
        e.target.value = "p";
      }} defaultValue="p" style={{
        height: 28, padding: "0 6px", border: 0, background: "transparent",
        color: "var(--mw-text-secondary)", fontSize: 12, fontWeight: 500,
        cursor: "pointer", borderRadius: 6,
      }}>
        <option value="p">Paragraph</option>
        <option value="H2">Heading</option>
        <option value="H3">Subheading</option>
        <option value="BLOCKQUOTE">Quote</option>
      </select>
      <Sep />
      <TbBtn onMouseDown={exec("insertUnorderedList")} title="Bulleted list">
        <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round">
          <circle cx="2.5" cy="4" r="1" fill="currentColor" stroke="none" />
          <circle cx="2.5" cy="8" r="1" fill="currentColor" stroke="none" />
          <circle cx="2.5" cy="12" r="1" fill="currentColor" stroke="none" />
          <line x1="6" y1="4" x2="14" y2="4" />
          <line x1="6" y1="8" x2="14" y2="8" />
          <line x1="6" y1="12" x2="14" y2="12" />
        </svg>
      </TbBtn>
      <TbBtn onMouseDown={exec("insertOrderedList")} title="Numbered list">
        <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round">
          <text x="0.5" y="5.5" fontSize="5" fill="currentColor" fontWeight="700" stroke="none">1</text>
          <text x="0.5" y="9.5" fontSize="5" fill="currentColor" fontWeight="700" stroke="none">2</text>
          <text x="0.5" y="13.5" fontSize="5" fill="currentColor" fontWeight="700" stroke="none">3</text>
          <line x1="6" y1="4" x2="14" y2="4" />
          <line x1="6" y1="8" x2="14" y2="8" />
          <line x1="6" y1="12" x2="14" y2="12" />
        </svg>
      </TbBtn>
      <Sep />
      <TbBtn onMouseDown={exec("justifyLeft")} title="Align left">
        <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round">
          <line x1="2" y1="4" x2="14" y2="4" /><line x1="2" y1="8" x2="10" y2="8" /><line x1="2" y1="12" x2="13" y2="12" />
        </svg>
      </TbBtn>
      <TbBtn onMouseDown={exec("justifyCenter")} title="Align center">
        <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round">
          <line x1="2" y1="4" x2="14" y2="4" /><line x1="4" y1="8" x2="12" y2="8" /><line x1="3" y1="12" x2="13" y2="12" />
        </svg>
      </TbBtn>
      <Sep />
      <TbBtn onMouseDown={(e) => { e.preventDefault(); saveSelection(); setLinkOpen((v) => !v); }} title="Insert link" active={linkOpen}>
        <Icon name="paperclip" size={13} color={linkOpen ? "brand" : null} />
      </TbBtn>
      <TbBtn onMouseDown={exec("removeFormat")} title="Clear formatting">
        <Icon name="cross" size={12} opacity={0.7} />
      </TbBtn>
      <div style={{ flex: 1 }} />
      <TbBtn onMouseDown={exec("undo")} title="Undo (Cmd+Z)">
        <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
          <path d="M4 8 L2 6 L4 4" /><path d="M2 6 H10 a4 4 0 0 1 0 8 H6" />
        </svg>
      </TbBtn>
      <TbBtn onMouseDown={exec("redo")} title="Redo (Cmd+Shift+Z)">
        <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
          <path d="M12 8 L14 6 L12 4" /><path d="M14 6 H6 a4 4 0 0 0 0 8 H10" />
        </svg>
      </TbBtn>

      {linkOpen && (
        <div style={{
          position: "absolute", top: "calc(100% + 6px)", left: 8, zIndex: 10,
          background: "#fff", border: "1px solid var(--mw-border)", borderRadius: 10,
          padding: 10, boxShadow: "var(--mw-shadow-pop)",
          display: "flex", gap: 6, alignItems: "center", minWidth: 320,
        }}>
          <input
            autoFocus
            value={linkUrl}
            onChange={(e) => setLinkUrl(e.target.value)}
            onKeyDown={(e) => { if (e.key === "Enter") insertLink(e); }}
            placeholder="https://"
            style={{
              flex: 1, padding: "6px 10px", borderRadius: 6,
              border: "1px solid var(--mw-border-strong)", fontSize: 12,
            }}
          />
          <button onMouseDown={insertLink} style={{
            padding: "6px 12px", borderRadius: 6, border: 0,
            background: "var(--mw-brand-500)", color: "#fff", fontSize: 12, fontWeight: 600,
            cursor: "pointer",
          }}>Insert</button>
          <button onMouseDown={(e) => { e.preventDefault(); setLinkOpen(false); }} style={{
            width: 26, height: 26, padding: 0, borderRadius: 6, border: 0,
            background: "transparent", cursor: "pointer",
          }}>
            <Icon name="cross" size={12} opacity={0.6} />
          </button>
        </div>
      )}
    </div>
  );
}
