/* KitRate — media kit editor, template gallery, export & share */

/* ---------- smart copy generation ---------- */
function genPitchEmail(profile, rates, config) {
  const E = KitRateEngine;
  const first = (profile.name || "there").split(" ")[0];
  const plats = Object.entries(profile.platforms || {}).filter(([, v]) => v && v.followers);
  const reach = plats.reduce((s, [, v]) => s + (v.followers || 0), 0);
  const best = plats.reduce((b, p) => (p[1].engagement || 0) > (b?.[1].engagement || 0) ? p : b, null);
  const anchor = rates.anchor;
  const pkgs = kitPackages(rates, config.packageNames);
  const featured = pkgs.find(p => p.featured) || pkgs[0];

  return `Subject: ${profile.nicheLabel || "Creator"} partnership — ${profile.name} (${E.fmtCompact(reach)} combined reach)

Hi [Brand contact],

I'm ${profile.name}${profile.tagline ? " — " + profile.tagline.toLowerCase().replace(/\.$/, "") : ""}. I think there's a strong fit between [Brand] and my audience${best ? `: ${best[1].engagement}% engagement on ${best[0].charAt(0).toUpperCase() + best[0].slice(1)}, well above platform average` : ""}.

A few numbers up front:
${plats.map(([k, v]) => `• ${k.charAt(0).toUpperCase() + k.slice(1)} — ${E.fmtCompact(v.followers)} followers${v.avgViews ? ", " + E.fmtCompact(v.avgViews) + " avg views" : ""}${v.engagement ? ", " + v.engagement + "% engagement" : ""}`).join("\n")}

${(profile.pastBrands || []).length ? `I've recently partnered with ${profile.pastBrands.slice(0, 2).map(b => b.name).join(" and ")} — ${profile.pastBrands[0].result}.` : "I keep a small number of brand slots so every partnership gets full production attention."}

Most brands start with my "${featured ? featured.name : "series"}" package${featured && config.showRates ? ` (${E.fmtRange(featured.low, featured.high)})` : ""}. Full media kit with audience data and rate card attached — happy to tailor scope, usage and exclusivity to your campaign.

Open to a quick call this week?

${first}
${profile.email || ""}${profile.website ? "\n" + profile.website : ""}`;
}

function genFollowUp(profile) {
  const first = (profile.name || "").split(" ")[0];
  return `Subject: Re: Partnership — quick follow-up

Hi [Brand contact],

Following up on the media kit I sent over last week. A couple of things that might help the decision:

• My next content window opens [date] — locking scope this week guarantees delivery for [campaign moment].
• Happy to share unedited audience screenshots or run a small paid-usage test before a bigger commitment.

If the timing isn't right this quarter, no problem at all — just let me know and I'll circle back closer to [season/launch].

${first}`;
}

function genRateExplanation(rates) {
  const c = rates.confidence;
  const top = rates.anchor;
  if (!top) return "Add platform metrics to generate a rate explanation.";
  const lead = top.reasons[0] ? top.reasons[0] : "Your rates sit at the benchmark baseline for your follower tier.";
  return `Your suggested ${top.label} rate is ${KitRateEngine.fmtRange(top.low, top.high)}. ${lead} Short-form video typically requires more production effort than static posts, which the benchmarks already reflect. Confidence is ${c.label.toLowerCase()} — ${c.detail.toLowerCase()}`;
}

function genCoverSvg(profile, rates, config) {
  const theme = KIT_THEMES.find(x => x.id === config.templateId) || KIT_THEMES[0];
  const E = KitRateEngine;
  const plats = Object.entries(profile.platforms || {}).filter(([, v]) => v && v.followers);
  const lead = plats[0];
  const rate = rates.anchor ? E.fmtRange(rates.anchor.low, rates.anchor.high) : "Rates ready";
  const esc = (s) => String(s || "").replace(/[&<>"']/g, ch => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", "\"": "&quot;", "'": "&#39;" }[ch]));
  return `<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="1500" viewBox="0 0 1200 1500">
  <rect width="1200" height="1500" fill="${theme.bg}"/>
  <rect x="72" y="72" width="1056" height="1356" fill="none" stroke="${theme.line}" stroke-width="2"/>
  <text x="96" y="132" fill="${theme.muted}" font-family="Arial, sans-serif" font-size="26" letter-spacing="7">MEDIA KIT ${new Date().getFullYear()}</text>
  <text x="96" y="610" fill="${theme.ink}" font-family="Georgia, serif" font-size="104" font-weight="500">${esc(profile.name || "Your Name")}</text>
  <text x="96" y="680" fill="${theme.muted}" font-family="Arial, sans-serif" font-size="34">${esc(profile.tagline || profile.nicheLabel || "Creator partnership kit")}</text>
  <line x1="96" y1="780" x2="1104" y2="780" stroke="${theme.line}" stroke-width="2"/>
  <text x="96" y="870" fill="${theme.accent}" font-family="Georgia, serif" font-size="62">${lead ? E.fmtCompact(lead[1].followers) : "—"}</text>
  <text x="96" y="920" fill="${theme.muted}" font-family="Arial, sans-serif" font-size="24" letter-spacing="4">${lead ? lead[0].toUpperCase() + " FOLLOWERS" : "FOLLOWERS"}</text>
  <text x="480" y="870" fill="${theme.accent}" font-family="Georgia, serif" font-size="62">${lead && lead[1].avgViews ? E.fmtCompact(lead[1].avgViews) : "—"}</text>
  <text x="480" y="920" fill="${theme.muted}" font-family="Arial, sans-serif" font-size="24" letter-spacing="4">AVG VIEWS</text>
  <text x="800" y="870" fill="${theme.accent}" font-family="Georgia, serif" font-size="62">${rates.confidence.label}</text>
  <text x="800" y="920" fill="${theme.muted}" font-family="Arial, sans-serif" font-size="24" letter-spacing="4">RATE CONFIDENCE</text>
  <rect x="96" y="1120" width="1008" height="160" fill="${theme.accent}"/>
  <text x="132" y="1188" fill="${theme.accentInk}" font-family="Arial, sans-serif" font-size="28" letter-spacing="5">ANCHOR RATE</text>
  <text x="132" y="1248" fill="${theme.accentInk}" font-family="Georgia, serif" font-size="58">${esc(rate)}</text>
  <text x="96" y="1370" fill="${theme.muted}" font-family="Arial, sans-serif" font-size="24">${esc(profile.email || "")}${profile.website ? " · " + esc(profile.website) : ""}</text>
</svg>`;
}

/* ---------- share settings ---------- */
function ShareModal({ onClose, profile, config, setConfig, toast, onPreview, onPublish }) {
  const [linkOn, setLinkOn] = useState(true);
  const [url, setUrl] = useState("");
  const [publishError, setPublishError] = useState(null);

  useEffect(() => {
    let cancelled = false;
    onPublish(null).then((nextUrl) => {
      if (!cancelled) setUrl(nextUrl);
    }).catch((error) => {
      if (!cancelled) setPublishError(error.message);
    });
    return () => { cancelled = true; };
  }, []);

  return (
    <Modal title="Share link settings" onClose={onClose} width={560}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 16 }}>
        <div>
          <div style={{ fontWeight: 600, fontSize: 14 }}>Public link</div>
          <div style={{ fontSize: 12.5, color: "var(--muted)" }}>Anyone with the link can view the kit.</div>
        </div>
        <button onClick={() => setLinkOn(!linkOn)} aria-label="Toggle public link" style={{
          width: 40, height: 23, borderRadius: 99, border: "none", position: "relative",
          background: linkOn ? "var(--accent)" : "var(--line-strong)", transition: "background 0.15s"
        }}>
          <span style={{ position: "absolute", top: 2.5, left: linkOn ? 19.5 : 2.5, width: 18, height: 18, borderRadius: "50%", background: "white", transition: "left 0.15s" }}></span>
        </button>
      </div>
      {linkOn && (
        <div style={{ display: "flex", gap: 8, marginBottom: 12 }}>
          <input className="kr-input" readOnly value={url || (publishError ? "Could not publish this kit" : "Publishing current snapshot…")} style={{ fontFamily: "var(--mono)", fontSize: 12.5 }} />
          <CopyBtn text={url} toast={toast} label="Copy" disabled={!url} />
        </div>
      )}
      {publishError && <div className="kr-error-text" style={{ marginBottom: 12 }}>{publishError}</div>}
      {linkOn && (
        <button className="kr-btn kr-btn-secondary kr-btn-sm" style={{ marginBottom: 18 }} disabled={!url} onClick={() => onPreview(null)}>
          <KrIcon d={ICONS.eye} size={13} /> Preview what brands see
        </button>
      )}
      {linkOn && url && (
        <div style={{ borderTop: "1px solid var(--line)", paddingTop: 16, marginBottom: 16 }}>
          <BrandLinksPanel baseUrl={url} toast={toast} onPreview={(link) => onPreview(link)} onPublish={onPublish} />
        </div>
      )}
      <hr className="kr-hr" style={{ margin: "4px 0 16px" }} />
      <div style={{ fontWeight: 600, fontSize: 13.5, marginBottom: 10 }}>Visible on the public link</div>
      {[["showRates", "Rate card & package pricing"], ["showRateRanges", "Show ranges (off = “from $X” only)"]].map(([k, lbl]) => (
        <label key={k} style={{ display: "flex", gap: 10, alignItems: "center", fontSize: 13.5, padding: "7px 0", cursor: "pointer" }}>
          <input type="checkbox" checked={config[k]} onChange={(e) => setConfig({ ...config, [k]: e.target.checked })} style={{ accentColor: "var(--accent)" }} />
          {lbl}
        </label>
      ))}
      <p style={{ fontSize: 12, color: "var(--muted)", marginTop: 8 }}>Hide individual sections from the “Sections” panel — hidden sections never appear on the public link.</p>
      <IntegrationNote>The link is a published snapshot. Republish after changing metrics, rates, sections, or visibility settings so a brand always sees the version you approved.</IntegrationNote>
    </Modal>
  );
}

/* ---------- pitch email modal ---------- */
function EmailModal({ onClose, profile, rates, config, toast }) {
  const [tab, setTab] = useState("pitch");
  const text = tab === "pitch" ? genPitchEmail(profile, rates, config) : genFollowUp(profile);
  return (
    <Modal title="Brand pitch email" onClose={onClose} width={640}>
      <div style={{ display: "flex", gap: 8, marginBottom: 14 }}>
        {[["pitch", "First pitch"], ["followup", "Follow-up after sending kit"]].map(([k, lbl]) => (
          <button key={k} className={"kr-btn kr-btn-sm " + (tab === k ? "kr-btn-primary" : "kr-btn-secondary")} onClick={() => setTab(k)}>{lbl}</button>
        ))}
      </div>
      <textarea className="kr-textarea kr-scroll" readOnly value={text} style={{ minHeight: 320, fontFamily: "var(--mono)", fontSize: 12.5, lineHeight: 1.6 }}></textarea>
      <div style={{ display: "flex", gap: 10, marginTop: 14, justifyContent: "flex-end" }}>
        <CopyBtn text={text} toast={toast} label="Copy email" />
      </div>
    </Modal>
  );
}

/* ---------- versions ---------- */
function VersionsModal({ onClose, versions, setVersions, config, toast, applyVersion }) {
  const [name, setName] = useState("");
  return (
    <Modal title="Saved versions" onClose={onClose} width={520}>
      <p style={{ fontSize: 13, color: "var(--muted)", marginBottom: 14 }}>Save the current template, sections and package names as a named version — one per niche or campaign type.</p>
      <div style={{ display: "flex", gap: 8, marginBottom: 18 }}>
        <input className="kr-input" placeholder="e.g. Supplement brands — Q3" value={name} onChange={(e) => setName(e.target.value)} />
        <button className="kr-btn kr-btn-primary" disabled={!name.trim()} style={!name.trim() ? { opacity: 0.5 } : null} onClick={() => {
          setVersions([...versions, { id: Date.now(), name: name.trim(), date: new Date().toISOString().slice(0, 10), config: JSON.parse(JSON.stringify(config)) }]);
          setName(""); toast("Version saved");
        }}>Save</button>
      </div>
      {versions.length === 0 ? (
        <EmptyState icon="doc" title="No versions yet" desc="Saved versions appear here — switch between them per campaign." />
      ) : versions.map(v => (
        <div key={v.id} style={{ display: "flex", alignItems: "center", gap: 12, padding: "10px 0", borderBottom: "1px solid var(--line)" }}>
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: 600, fontSize: 13.5 }}>{v.name}</div>
            <div style={{ fontSize: 11.5, color: "var(--muted)" }}>{v.date} · {KIT_THEMES.find(t => t.id === v.config.templateId)?.label}</div>
          </div>
          <button className="kr-btn kr-btn-secondary kr-btn-sm" onClick={() => { applyVersion(v.config); toast("Switched to “" + v.name + "”"); }}>Apply</button>
          <button className="kr-btn kr-btn-ghost kr-btn-sm" onClick={() => setVersions(versions.filter(x => x.id !== v.id))} aria-label="Delete version"><KrIcon d={ICONS.x} size={13} /></button>
        </div>
      ))}
    </Modal>
  );
}

/* ---------- the editor ---------- */
function KitEditor({ profile, setProfile, rates, config, setConfig, onBackToRates, onPreviewShare, onPublishShare }) {
  const [toast, toastNode] = useToast();
  const [modal, setModal] = useState(null); // share | email | versions
  const [exporting, setExporting] = useState(null);
  const [versions, setVersions] = useState(() => {
    try { return JSON.parse(localStorage.getItem("kitrate.versions.v1") || "[]"); } catch (e) { return []; }
  });
  const [dragSec, setDragSec] = useState(null);
  const [overSec, setOverSec] = useState(null);
  useEffect(() => { localStorage.setItem("kitrate.versions.v1", JSON.stringify(versions)); }, [versions]);

  const dropOn = (targetId) => {
    if (!dragSec || dragSec === targetId) { setDragSec(null); setOverSec(null); return; }
    const order = config.order.filter(x => x !== dragSec);
    order.splice(order.indexOf(targetId), 0, dragSec);
    setConfig({ ...config, order });
    setDragSec(null); setOverSec(null);
  };
  const toggleHidden = (id) => {
    const hidden = config.hidden.includes(id) ? config.hidden.filter(x => x !== id) : [...config.hidden, id];
    setConfig({ ...config, hidden });
  };
  const mockExport = (kind) => {
    if (kind === "pdf") {
      /* real export: print stylesheet isolates the kit document */
      setExporting("pdf");
      setTimeout(() => { setExporting(null); window.print(); }, 350);
      return;
    }
    if (kind === "json") {
      const payload = KitRateProduct.serializeKitData(profile, window.loadBenchmarks(), config, rates);
      KitRateProduct.downloadText(KitRateProduct.slugify(profile.name || "creator") + "-kitrate-data.json", JSON.stringify(payload, null, 2), "application/json;charset=utf-8");
      toast("Kit data exported");
      return;
    }
    setExporting(kind);
    setTimeout(() => {
      setExporting(null);
      const svg = genCoverSvg(profile, rates, config);
      KitRateProduct.downloadText(KitRateProduct.slugify(profile.name || "creator") + "-cover.svg", svg, "image/svg+xml;charset=utf-8");
      toast("Cover image exported");
    }, 500);
  };

  const setPkgName = (i, v) => {
    const names = [...config.packageNames]; names[i] = v;
    setConfig({ ...config, packageNames: names });
  };

  return (
    <div style={{ display: "grid", gridTemplateColumns: "300px minmax(0,1fr)", minHeight: "calc(100vh - 60px)" }} className="kr-editor-grid" data-screen-label="Kit editor">
      {/* control rail */}
      <aside className="kr-scroll kr-no-print" style={{ borderRight: "1px solid var(--line)", background: "var(--surface)", padding: "22px 20px 48px", overflowY: "auto", maxHeight: "calc(100vh - 60px)", position: "sticky", top: 60 }}>
        <button className="kr-btn kr-btn-ghost kr-btn-sm" onClick={onBackToRates} style={{ marginBottom: 14 }}><KrIcon d={ICONS.arrowLeft} size={13} /> Rates</button>

        <button className="kr-btn kr-btn-secondary kr-btn-sm" style={{ width: "100%", marginBottom: 20 }} onClick={() => setModal("content")}>
          <KrIcon d={ICONS.edit} size={13} /> Edit kit content
        </button>

        <div className="kr-eyebrow" style={{ marginBottom: 10 }}>Template</div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8, marginBottom: 6 }}>
          {KIT_THEMES.map(t => (
            <button key={t.id} onClick={() => setConfig({ ...config, templateId: t.id })} title={t.desc} style={{
              border: "2px solid " + (config.templateId === t.id ? "var(--accent)" : "var(--line)"),
              borderRadius: 8, padding: 0, overflow: "hidden", background: t.bg, cursor: "pointer", textAlign: "left"
            }}>
              <div style={{ padding: "10px 10px 8px" }}>
                <div style={{ fontFamily: t.serif, fontSize: 13, color: t.ink, fontWeight: 600, lineHeight: 1.1 }}>Aa</div>
                <div style={{ width: 22, height: 4, borderRadius: 2, background: t.accent, marginTop: 6 }}></div>
              </div>
              <div style={{ fontSize: 9.5, fontFamily: "var(--mono)", letterSpacing: "0.06em", textTransform: "uppercase", color: t.muted, padding: "0 10px 8px" }}>{t.label}</div>
            </button>
          ))}
        </div>
        <p style={{ fontSize: 11, color: "var(--muted)", marginBottom: 20 }}>{KIT_THEMES.find(t => t.id === config.templateId)?.desc}</p>

        <div className="kr-eyebrow" style={{ marginBottom: 4 }}>Sections</div>
        <p style={{ fontSize: 11, color: "var(--muted)", marginBottom: 8 }}>Drag to reorder — numbering updates automatically.</p>
        <div style={{ marginBottom: 20 }}>
          {config.order.map((id) => {
            const s = KIT_SECTIONS.find(x => x.id === id);
            const hidden = config.hidden.includes(id);
            const isOver = overSec === id && dragSec && dragSec !== id;
            return (
              <div key={id} draggable
                onDragStart={(e) => { setDragSec(id); e.dataTransfer.effectAllowed = "move"; }}
                onDragOver={(e) => { e.preventDefault(); e.dataTransfer.dropEffect = "move"; if (overSec !== id) setOverSec(id); }}
                onDragLeave={() => { if (overSec === id) setOverSec(null); }}
                onDrop={(e) => { e.preventDefault(); dropOn(id); }}
                onDragEnd={() => { setDragSec(null); setOverSec(null); }}
                style={{
                  display: "flex", alignItems: "center", gap: 8, padding: "5px 2px",
                  borderBottom: "1px solid var(--line)",
                  borderTop: "2px solid " + (isOver ? "var(--accent)" : "transparent"),
                  opacity: dragSec === id ? 0.35 : hidden ? 0.45 : 1,
                  background: isOver ? "var(--accent-soft)" : "transparent",
                  cursor: "grab", transition: "background 0.15s"
                }}>
                <svg width="10" height="14" viewBox="0 0 10 14" aria-hidden="true" style={{ color: "var(--line-strong)", flexShrink: 0 }}>
                  {[2, 7, 12].map(y => [2.5, 7.5].map(x => <circle key={x + "-" + y} cx={x} cy={y} r="1.2" fill="currentColor"></circle>))}
                </svg>
                <input type="checkbox" checked={!hidden} onChange={() => toggleHidden(id)} style={{ accentColor: "var(--accent)" }} aria-label={"Toggle " + s.label} />
                <span style={{ flex: 1, fontSize: 12.5, fontWeight: 500 }}>{s.label}</span>
              </div>
            );
          })}
        </div>

        {!config.hidden.includes("showcase") && (
          <div style={{ marginBottom: 20 }}>
            <div className="kr-eyebrow" style={{ marginBottom: 4 }}>Video showcase</div>
            <p style={{ fontSize: 11, color: "var(--muted)", marginBottom: 8 }}>Your best reels, auto-imported from connected accounts and ranked by:</p>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 6 }}>
              {REEL_KPI_OPTIONS.map(o => (
                <button key={o.value} className={"kr-btn kr-btn-sm " + ((config.showcaseKpi || "smart") === o.value ? "kr-btn-primary" : "kr-btn-secondary")}
                  onClick={() => setConfig({ ...config, showcaseKpi: o.value })}>{o.label}</button>
              ))}
            </div>
            <IntegrationNote>
              In production the showcase pulls each platform's top short-form via API (views, ER, likes, posted date), re-ranks on the chosen KPI, and refreshes weekly. Here it ranks the sample reel library; drop a frame onto any card to fill its thumbnail.
            </IntegrationNote>
          </div>
        )}

        <div className="kr-eyebrow" style={{ marginBottom: 10 }}>Rates</div>
        <label style={{ display: "flex", gap: 9, alignItems: "center", fontSize: 13, padding: "5px 0", cursor: "pointer" }}>
          <input type="checkbox" checked={config.showRates} onChange={(e) => setConfig({ ...config, showRates: e.target.checked })} style={{ accentColor: "var(--accent)" }} />
          Show rates in kit
        </label>
        <label style={{ display: "flex", gap: 9, alignItems: "center", fontSize: 13, padding: "5px 0 16px", cursor: "pointer" }}>
          <input type="checkbox" checked={config.showRateRanges} onChange={(e) => setConfig({ ...config, showRateRanges: e.target.checked })} style={{ accentColor: "var(--accent)" }} />
          Ranges (off = “from $X”)
        </label>

        <div className="kr-eyebrow" style={{ marginBottom: 10 }}>Package names</div>
        {config.packageNames.map((n, i) => (
          <input key={i} className="kr-input" value={n} onChange={(e) => setPkgName(i, e.target.value)} style={{ marginBottom: 8, fontSize: 13 }} />
        ))}

        <div className="kr-eyebrow" style={{ margin: "16px 0 10px" }}>Density</div>
        <div style={{ display: "flex", gap: 6 }}>
          {["comfortable", "compact"].map(d => (
            <button key={d} className={"kr-btn kr-btn-sm " + (config.density === d ? "kr-btn-primary" : "kr-btn-secondary")} onClick={() => setConfig({ ...config, density: d })} style={{ flex: 1, textTransform: "capitalize" }}>{d}</button>
          ))}
        </div>
      </aside>

      {/* preview area */}
      <div style={{ background: "var(--surface-2)", padding: "26px 28px 80px" }}>
        {/* export bar */}
        <div className="kr-card kr-no-print" style={{ display: "flex", gap: 8, alignItems: "center", padding: "10px 14px", marginBottom: 24, flexWrap: "wrap", position: "sticky", top: 74, zIndex: 30 }}>
          <span className="kr-eyebrow" style={{ marginRight: 6 }}>Export</span>
          <button className="kr-btn kr-btn-primary kr-btn-sm" onClick={() => mockExport("pdf")} disabled={!!exporting}>
            <KrIcon d={ICONS.download} size={13} /> {exporting === "pdf" ? "Rendering…" : "Download PDF"}
          </button>
          <button className="kr-btn kr-btn-secondary kr-btn-sm" onClick={() => setModal("share")}><KrIcon d={ICONS.link} size={13} /> Share link</button>
          <button className="kr-btn kr-btn-secondary kr-btn-sm" onClick={() => onPreviewShare(null)}><KrIcon d={ICONS.eye} size={13} /> View as brand</button>
          <button className="kr-btn kr-btn-secondary kr-btn-sm" onClick={() => setModal("email")}><KrIcon d={ICONS.mail} size={13} /> Pitch email</button>
          <button className="kr-btn kr-btn-secondary kr-btn-sm" onClick={() => mockExport("png")} disabled={!!exporting}>
            <KrIcon d={ICONS.download} size={13} /> {exporting === "png" ? "Exporting…" : "Cover image"}
          </button>
          <button className="kr-btn kr-btn-secondary kr-btn-sm" onClick={() => mockExport("json")}><KrIcon d={ICONS.download} size={13} /> Data backup</button>
          <div style={{ flex: 1 }}></div>
          <button className="kr-btn kr-btn-ghost kr-btn-sm" onClick={() => setModal("versions")}><KrIcon d={ICONS.clock} size={13} /> Versions ({versions.length})</button>
        </div>

        <IntegrationNote>“Download PDF” opens your browser's print dialog with only the kit visible. Share links publish the current approved snapshot and track public opens without exposing your editing workspace.</IntegrationNote>

        {/* rate explanation strip */}
        <div className="kr-no-print" style={{ maxWidth: 760, margin: "18px auto 22px", fontSize: 13, color: "var(--ink-2)", background: "var(--accent-soft)", border: "1px solid var(--accent-line)", borderRadius: 10, padding: "12px 16px", lineHeight: 1.6 }}>
          <strong style={{ color: "var(--accent)" }}>Rate note for your eyes only:</strong> {genRateExplanation(rates)}
        </div>

        <KitDocument profile={profile} rates={rates} config={config} />
      </div>

      {modal === "share" && <ShareModal onClose={() => setModal(null)} profile={profile} config={config} setConfig={setConfig} toast={toast}
        onPublish={onPublishShare} onPreview={(link) => { setModal(null); onPreviewShare(link); }} />}
      {modal === "content" && <ContentModal onClose={() => setModal(null)} profile={profile} setProfile={setProfile} />}
      {modal === "email" && <EmailModal onClose={() => setModal(null)} profile={profile} rates={rates} config={config} toast={toast} />}
      {modal === "versions" && <VersionsModal onClose={() => setModal(null)} versions={versions} setVersions={setVersions} config={config} toast={toast} applyVersion={(c) => setConfig(c)} />}
      {toastNode}
    </div>
  );
}

Object.assign(window, { KitEditor, genPitchEmail, genFollowUp, genRateExplanation });
