/* Rank Lyx — Knowledge / ICP Knowledge

   The third Knowledge page. Lets a user define up to 3 ICP profiles — the
   PEOPLE / roles / buyer profiles their content should speak to (Head of
   Marketing, VP Sales, RevOps Manager, SaaS Founder, …). These are people,
   never companies; no firmographics, ranking, or persona photos.

   UX: an ICP DASHBOARD, not a stacked editor page. The page shows up to 3
   compact slots — filled ICP cards + "Add ICP" placeholders. Clicking a filled
   card (or adding a new one) opens a large centered MODAL to edit that one ICP:
     • ICP name / role (single-line input)
     • ICP details (rich text editor, stores HTML, with undo/redo)
   "Done editing" applies the modal's edits to the page draft (does NOT persist);
   "Discard edits" closes without applying. The global Save / Discard at the
   bottom persist / revert the whole page.

   This step is MANUAL only — no "Generate from website" yet (that comes later).
   Mirrors the polished Knowledge-page standard used by Brand Profile and
   Product Knowledge: undo/redo, Save / Discard, unsaved-changes state, a subtle
   AI-accuracy note, nothing auto-saved.

   Persistence: Workspace-scoped cloud Knowledge. The page hydrates the complete
   ICP collection, stages all edits in memory, and commits the desired collection
   atomically through the existing Knowledge API only when Save is clicked.
*/

(function () {
  const { useState, useEffect, useRef, useCallback } = React;

  const AUD_MAX = 3;
  const AUD_HISTORY_MAX = 50;

  /* Starter ICP template prefilled into every NEW ICP card and restored on
     demand via the edit-modal toolbar's "Restore" button: the section headings
     plus a short writing prompt under each. Each prompt is tagged
     data-template-helper so audStripTemplateHelpers (below) can keep unchanged
     guidance out of the AI knowledge context. Audience Writing Rules restores as
     a numbered list because future AI agents consume it. */
  const AUD_TEMPLATE_SECTIONS = [
    ['Audience Overview', 'Describe who this ICP is, what they are responsible for, and why they matter to the business.'],
    ['Role in the Buying Process', 'Explain whether this person is the decision maker, budget owner, evaluator, influencer, internal champion, end user, or blocker.'],
    ['Pain Points', 'List the main problems, frustrations, risks, or blockers this ICP deals with.'],
    ['Goals / Desired Outcomes', 'List the outcomes this ICP wants to achieve.'],
    ['Buying Triggers', 'Describe the events, changes, or situations that make this ICP start looking for a solution.'],
    ['Objections / Concerns', 'List the reasons this ICP might hesitate, delay, reject, or question the purchase.'],
    ['Decision Criteria', 'List what this ICP needs to see, believe, compare, or validate before choosing a solution.'],
    ['Awareness Level', 'Explain whether this ICP is problem-aware, solution-aware, product-aware, or ready to buy.'],
    ['Messaging Angles', 'List the strongest angles, promises, or positioning ideas that would resonate with this ICP.'],
    ['Topics They Care About', 'List the topics, problems, trends, workflows, or questions this ICP is likely to care about.']
  ];
  /* Audience Writing Rules restores as a numbered list of example rules. */
  const AUD_WRITING_RULE_HELPERS = [
    'Focus on the business outcomes this ICP cares about most.',
    'Use examples that match this ICP’s day-to-day work.',
    'Avoid explaining concepts this ICP already understands.',
    'Address objections directly without sounding defensive.',
    'Keep claims specific, practical, and grounded.'
  ];

  const AUD_DEFAULT_DETAILS =
    AUD_TEMPLATE_SECTIONS
      .map(([heading, prompt]) => '<h2>' + heading + '</h2>\n<p data-template-helper="1">' + prompt + '</p>')
      .join('\n') +
    '\n<h2>Audience Writing Rules</h2>\n<ol data-template-helper="1">\n' +
    AUD_WRITING_RULE_HELPERS.map((t) => '<li data-template-helper="1">' + t + '</li>').join('\n') +
    '\n</ol>';

  /* Normalized lookup of every starter prompt (section prompts + the example
     writing rules), used to detect guidance the user left untouched. */
  const AUD_HELPER_NORM_SET = new Set(
    AUD_TEMPLATE_SECTIONS.map(([, prompt]) => prompt)
      .concat(AUD_WRITING_RULE_HELPERS)
      .map((t) => t.replace(/\s+/g, ' ').trim().toLowerCase())
  );

  /* Remove starter writing prompts the user never edited, so default helper text
     can never leak into the knowledge context sent to AI agents. Only elements
     whose visible text EXACTLY matches a starter prompt are dropped — any
     user-written content, including an edited prompt, is preserved. Handles both
     the section <p> prompts and the numbered Audience Writing Rules example
     <li>s (a list left fully default is emptied and then removed). Exposed on
     window so knowledge consumers (article / outline / research / writing
     agents, AI Writer) can call it when preparing ICP context. */
  function audStripTemplateHelpers(html) {
    const s = String(html == null ? '' : html);
    if (s.indexOf('<') === -1) return s;
    try {
      const tmp = document.createElement('div');
      tmp.innerHTML = s;
      const norm = (el) => (el.textContent || '').replace(/\s+/g, ' ').trim().toLowerCase();
      tmp.querySelectorAll('li').forEach((li) => {
        const t = norm(li);
        if (t && AUD_HELPER_NORM_SET.has(t)) li.remove();
      });
      tmp.querySelectorAll('ol, ul').forEach((list) => {
        if (!list.querySelector('li')) list.remove();
      });
      tmp.querySelectorAll('p').forEach((p) => {
        const t = norm(p);
        if (t && AUD_HELPER_NORM_SET.has(t)) p.remove();
      });
      return tmp.innerHTML;
    } catch (e) {
      return s;
    }
  }
  window.audStripTemplateHelpers = audStripTemplateHelpers;

  /* ---- Inline SVG icons (never lucide — these mount/unmount with cards and
     the modal; lucide rewriting an <i> React later removes throws removeChild
     and unmounts the app). ----------------------------------------------- */
  function AudIconUsers() {
    return (<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"></path><circle cx="9" cy="7" r="4"></circle><path d="M22 21v-2a4 4 0 0 0-3-3.87"></path><path d="M16 3.13a4 4 0 0 1 0 7.75"></path></svg>);
  }
  function AudIconCheck() {
    return (<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6 9 17l-5-5"></path></svg>);
  }
  function AudIconCheckCircle() {
    return (<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21.801 10A10 10 0 1 1 17 3.335"></path><path d="m9 11 3 3L22 4"></path></svg>);
  }
  function AudIconAlert() {
    return (<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"></circle><path d="M12 8v4"></path><path d="M12 16h.01"></path></svg>);
  }
  function AudIconReset() {
    return (<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"></path><path d="M3 3v5h5"></path></svg>);
  }
  function AudIconUndo() {
    return (<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M9 14 4 9l5-5"></path><path d="M4 9h10.5a5.5 5.5 0 0 1 5.5 5.5 5.5 5.5 0 0 1-5.5 5.5H11"></path></svg>);
  }
  function AudIconRedo() {
    return (<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m15 14 5-5-5-5"></path><path d="M20 9H9.5A5.5 5.5 0 0 0 4 14.5 5.5 5.5 0 0 0 9.5 20H13"></path></svg>);
  }
  function AudIconBold() {
    return (<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M6 12h9a4 4 0 0 1 0 8H7a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1h7a4 4 0 0 1 0 8"></path></svg>);
  }
  function AudIconItalic() {
    return (<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="19" x2="10" y1="4" y2="4"></line><line x1="14" x2="5" y1="20" y2="20"></line><line x1="15" x2="9" y1="4" y2="20"></line></svg>);
  }
  function AudIconList() {
    return (<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="8" x2="21" y1="6" y2="6"></line><line x1="8" x2="21" y1="12" y2="12"></line><line x1="8" x2="21" y1="18" y2="18"></line><line x1="3" x2="3.01" y1="6" y2="6"></line><line x1="3" x2="3.01" y1="12" y2="12"></line><line x1="3" x2="3.01" y1="18" y2="18"></line></svg>);
  }
  function AudIconListOrdered() {
    return (<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="10" x2="21" y1="6" y2="6"></line><line x1="10" x2="21" y1="12" y2="12"></line><line x1="10" x2="21" y1="18" y2="18"></line><path d="M4 6h1v4"></path><path d="M4 10h2"></path><path d="M6 18H4c0-1 2-2 2-3s-1-1.5-2-1"></path></svg>);
  }
  function AudIconTrash() {
    return (<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 6h18"></path><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"></path><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path><line x1="10" x2="10" y1="11" y2="17"></line><line x1="14" x2="14" y1="11" y2="17"></line></svg>);
  }
  function AudIconPlus() {
    return (<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14"></path><path d="M12 5v14"></path></svg>);
  }
  function AudIconEdit() {
    return (<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 20h9"></path><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4Z"></path></svg>);
  }
  function AudIconClose() {
    return (<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M18 6 6 18"></path><path d="m6 6 12 12"></path></svg>);
  }
  function AudIconSparkles() {
    return (<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"></path><path d="M20 3v4"></path><path d="M22 5h-4"></path><path d="M4 17v2"></path><path d="M5 18H3"></path></svg>);
  }
  function AudIconUpload() {
    return (<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="17 8 12 3 7 8"></polyline><line x1="12" x2="12" y1="3" y2="15"></line></svg>);
  }
  function AudIconGlobe() {
    return (<svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"></circle><path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"></path><path d="M2 12h20"></path></svg>);
  }

  /* Visible text of an HTML string. */
  function audHtmlText(html) {
    const tmp = document.createElement('div');
    tmp.innerHTML = String(html || '');
    return (tmp.textContent || '').replace(/\s+/g, ' ').trim();
  }
  /* Short preview from the first meaningful paragraph / list item. */
  function audPreview(html) {
    const tmp = document.createElement('div');
    tmp.innerHTML = String(html || '');
    const blocks = tmp.querySelectorAll('p, li');
    for (const b of blocks) {
      const t = (b.textContent || '').replace(/\s+/g, ' ').trim();
      if (t) return t.length > 150 ? t.slice(0, 150).trim() + '…' : t;
    }
    const all = audHtmlText(html);
    if (!all) return '';
    return all.length > 150 ? all.slice(0, 150).trim() + '…' : all;
  }
  /* Has the user written anything beyond the untouched default template? Used
     to decide whether deleting a card needs a confirmation. */
  function audNormHtml(s) {
    return String(s || '').replace(/>\s+</g, '><').replace(/\s+/g, ' ').trim();
  }
  function audIsMeaningful(icp) {
    if ((icp.name || '').trim()) return true;
    return audNormHtml(icp.details) !== audNormHtml(AUD_DEFAULT_DETAILS);
  }
  function audCloneMetadata(value) {
    if (!value || Object.prototype.toString.call(value) !== '[object Object]') return {};
    try {return JSON.parse(JSON.stringify(value));} catch (e) {return {};}
  }
  function audClone(icps) {
    return (icps || []).map((c, index) => ({
      id: c.id,
      name: typeof c.name === 'string' ? c.name : '',
      details: typeof c.details === 'string' ? c.details : '',
      position: Number.isInteger(c.position) ? c.position : index,
      source: c.source === 'ai' ? 'ai' : 'manual',
      metadata: audCloneMetadata(c.metadata),
      createdAt: c.createdAt || null,
      updatedAt: c.updatedAt || null
    }));
  }

  /* ------------------------------------------------------------------ */
  /* Rich text editor toolbar button. */
  function AudToolBtn({ onCmd, cmd, arg, icon, label, title, on }) {
    const access = window.ClicklyxKnowledgeAccess.useAccess();
    return (
      <button
        type="button"
        className={`ed-tool ${on ? 'ed-tool--on' : ''}`}
        title={title}
        aria-label={title}
        aria-pressed={!!on}
        disabled={!access.canMutate()}
        onMouseDown={(e) => {e.preventDefault();if (access.canMutate()) onCmd(cmd, arg);}}>
        {icon}
        {label && <span>{label}</span>}
      </button>);
  }

  /* Reusable rich text editor — contentEditable + a focused toolbar. NO
     "Generate from website" button (manual-only). Uncontrolled: the parent
     reads/writes content imperatively through `editorRef`. */
  function AudEditor({ editorRef, onInput, onRestore, canUndo, canRedo, onUndo, onRedo }) {
    const access = window.ClicklyxKnowledgeAccess.useAccess();
    const [active, setActive] = useState({ block: 'p', bold: false, italic: false, ul: false, ol: false });

    useEffect(() => {
      const safeState = (c) => {try {return document.queryCommandState(c);} catch (e) {return false;}};
      const update = () => {
        const el = editorRef.current;
        const sel = document.getSelection();
        if (!el || !sel || !sel.anchorNode || !el.contains(sel.anchorNode)) return;
        let block = 'p';
        try {
          const bv = (document.queryCommandValue('formatBlock') || '').toLowerCase();
          if (['h2', 'h3', 'p', 'div'].includes(bv)) block = bv === 'div' ? 'p' : bv;
        } catch (e) {}
        setActive({
          block,
          bold: safeState('bold'),
          italic: safeState('italic'),
          ul: safeState('insertUnorderedList'),
          ol: safeState('insertOrderedList')
        });
      };
      document.addEventListener('selectionchange', update);
      return () => document.removeEventListener('selectionchange', update);
    }, [editorRef]);

    const exec = (cmd, arg) => {try {document.execCommand(cmd, false, arg);} catch (e) {}};
    const onCmd = (cmd, arg) => {
      if (!access.canMutate()) return;
      if (editorRef.current) editorRef.current.focus();
      switch (cmd) {
        case 'format': exec('formatBlock', arg.toUpperCase()); break;
        case 'bold': exec('bold'); break;
        case 'italic': exec('italic'); break;
        case 'ul': exec('insertUnorderedList'); break;
        case 'ol': exec('insertOrderedList'); break;
        default: break;
      }
      if (onInput) onInput();
    };
    const Btn = (p) => <AudToolBtn onCmd={onCmd} {...p} />;

    return (
      <div className="bp-editor aud-editor">
        <div className="ed-toolbar bp-toolbar" role="toolbar" aria-label="Formatting">
          <div className="bp-toolbar__format">
            <div className="ed-tgroup">
              <button type="button" className="ed-tool" title="Undo" aria-label="Undo" disabled={!access.canMutate() || !canUndo}
                onMouseDown={(e) => {e.preventDefault();if (access.canMutate() && canUndo && onUndo) onUndo();}}>
                <AudIconUndo />
              </button>
              <button type="button" className="ed-tool" title="Redo" aria-label="Redo" disabled={!access.canMutate() || !canRedo}
                onMouseDown={(e) => {e.preventDefault();if (access.canMutate() && canRedo && onRedo) onRedo();}}>
                <AudIconRedo />
              </button>
            </div>
            <span className="ed-divider"></span>
            <div className="ed-tgroup">
              <Btn cmd="format" arg="p" label="¶" title="Paragraph" on={active.block === 'p'} />
              <Btn cmd="format" arg="h2" label="H2" title="Heading 2" on={active.block === 'h2'} />
              <Btn cmd="format" arg="h3" label="H3" title="Heading 3" on={active.block === 'h3'} />
            </div>
            <span className="ed-divider"></span>
            <div className="ed-tgroup">
              <Btn cmd="bold" icon={<AudIconBold />} title="Bold" on={active.bold} />
              <Btn cmd="italic" icon={<AudIconItalic />} title="Italic" on={active.italic} />
            </div>
            <span className="ed-divider"></span>
            <div className="ed-tgroup">
              <Btn cmd="ul" icon={<AudIconList />} title="Bulleted list" on={active.ul} />
              <Btn cmd="ol" icon={<AudIconListOrdered />} title="Numbered list" on={active.ol} />
            </div>
          </div>
          <div className="bp-toolbar__actions">
            <button type="button" className="bp-gen-btn bp-gen-btn--tool" disabled={!access.canMutate()} onClick={access.guard(onRestore)} title="Restore the starter template and writing prompts for this card">
              <AudIconReset />
              <span>Restore</span>
            </button>
          </div>
        </div>

        <div className="bp-editor__scroll aud-editor__scroll">
          <div
            ref={editorRef}
            className="ed-content bp-content"
            contentEditable={access.canMutate()}
            aria-readonly={!access.canMutate()}
            onBeforeInput={(e) => {if (!access.canMutate()) e.preventDefault();}}
            onPaste={(e) => {if (!access.canMutate()) e.preventDefault();}}
            onDrop={(e) => {if (!access.canMutate()) e.preventDefault();}}
            suppressContentEditableWarning={true}
            spellCheck={true}
            onInput={onInput}
            aria-label="ICP details"></div>
        </div>
      </div>);
  }

  /* ------------------------------------------------------------------ */
  /* Generate ICP — per-card generation UI SHELL (no AI yet).

     Scope: this panel only ever targets the ONE ICP card whose edit modal is
     open. It must never generate all 3 cards, never touch the other cards,
     never auto-save, and never close the underlying edit modal. The actual
     pipeline (website crawl + saved knowledge + uploaded ICP document parsing
     + model call) is wired in a later step — here we only build the UI and the
     interaction shell, and store the selected file NAME only (no parsing).

     ACCIDENTAL-OVERWRITE COPY (reserved for the future confirmation state,
     intentionally NOT activated yet): when generation is connected and the
     current ICP holds meaningful content, the flow will first warn:
       "This will replace the current ICP draft in this card only. Other ICP
        cards will not be changed."
  */
  const AUD_GEN_PREPARED = 'Source prepared. AI generation will be connected in the next step.';

  /* Document upload limits / caps for the prototype. */
  const AUD_MAX_FILE_BYTES = 10 * 1024 * 1024;   // 10MB
  const AUD_DOC_CAP = 40000;                      // practical extraction cap
  const AUD_MIN_DOC_CHARS = 200;                  // "enough readable text"
  const AUD_ACCEPT = '.pdf,.docx,.txt,.md,.markdown';

  function audFileExt(name) {
    const m = /\.([a-z0-9]+)$/i.exec(String(name || ''));
    return m ? m[1].toLowerCase() : '';
  }
  function audFormatNum(n) {
    try {return Number(n || 0).toLocaleString('en-US');} catch (e) {return String(n || 0);}
  }
  function audNormalizeUrl(raw) {
    const s = (raw || '').trim();
    return /^https?:\/\//i.test(s) ? s : 'https://' + s;
  }
  function audIsValidUrl(raw) {
    if (!raw || !raw.trim()) return false;
    try {
      const u = new URL(audNormalizeUrl(raw));
      return !!u.hostname && u.hostname.indexOf('.') > 0;
    } catch (e) {return false;}
  }

  /* ---- Browser-safe document text extraction ------------------------
     TXT/MD via FileReader; PDF via pdfjs-dist (window.pdfjsLib); DOCX via
     mammoth (window.mammoth). If a PDF/DOCX library isn't present, we throw a
     'no-…-lib' code so the UI can fall back to the paste box gracefully. Text
     is capped at AUD_DOC_CAP. Extracted text lives ONLY in modal state and is
     never written to localStorage or logged. */
  function audReadText(file, operation = window.ClicklyxKnowledgeAccess.begin(true)) {
    operation.assert();
    return new Promise((resolve, reject) => {
      const r = new FileReader();
      r.onload = () => { try { operation.assert(); resolve(String(r.result || '')); } catch (error) { reject(error); } };
      r.onerror = () => reject(new Error('read-failed'));
      r.readAsText(file);
    });
  }
  async function audExtractPdf(file, operation = window.ClicklyxKnowledgeAccess.begin(true)) {
    operation.assert();
    const lib = window.pdfjsLib;
    if (!lib || !lib.getDocument) throw new Error('no-pdf-lib');
    const buf = await operation.run(() => file.arrayBuffer());
    const doc = await operation.run(() => lib.getDocument({ data: buf }).promise);
    let out = '';
    /* Preserve page boundaries with explicit "--- PAGE N ---" markers so the
       multi-persona detector can keep separate profiles from blending. */
    for (let i = 1; i <= doc.numPages; i++) {
      const page = await operation.run(() => doc.getPage(i));
      const tc = await operation.run(() => page.getTextContent());
      const pageText = tc.items.map((it) => (it.str || '')).join(' ').replace(/[ \t]+/g, ' ').trim();
      out += '\n--- PAGE ' + i + ' ---\n' + pageText + '\n';
      if (out.length >= AUD_DOC_CAP) break;
    }
    try {if (doc.destroy) doc.destroy();} catch (e) {}
    return out;
  }
  async function audExtractDocx(file, operation = window.ClicklyxKnowledgeAccess.begin(true)) {
    operation.assert();
    const m = window.mammoth;
    if (!m || !m.extractRawText) throw new Error('no-docx-lib');
    const buf = await operation.run(() => file.arrayBuffer());
    const r = await operation.run(() => m.extractRawText({ arrayBuffer: buf }));
    return (r && r.value) ? r.value : '';
  }
  async function audExtractFile(file, operation = window.ClicklyxKnowledgeAccess.begin(true)) {
    operation.assert();
    const ext = audFileExt(file.name);
    let text = '';
    if (ext === 'txt' || ext === 'md' || ext === 'markdown') text = await operation.run(() => audReadText(file, operation));
    else if (ext === 'pdf') text = await operation.run(() => audExtractPdf(file, operation));
    else if (ext === 'docx') text = await operation.run(() => audExtractDocx(file, operation));
    else throw new Error('unsupported-type');
    text = String(text || '').replace(/\u0000/g, '').replace(/[ \t]+\n/g, '\n').replace(/\n{3,}/g, '\n\n').trim();
    if (text.length > AUD_DOC_CAP) text = text.slice(0, AUD_DOC_CAP);
    return text;
  }

  /* ==================================================================== */
  /* ICP GENERATION PIPELINE (per-card, real AI call).

     Mirrors the Brand Profile / Product Knowledge flow: a reader proxy
     (the authenticated Clicklyx route) reads static homepage + relevant internal
     pages, the model returns PLAIN STRUCTURED TEXT (never JSON / HTML / code
     fences), and a forgiving parser converts it into escaped editor HTML.
     Scope is ONE ICP card — the result only ever replaces the current edit
     modal's draft, never the dashboard or other cards, and nothing is saved.
     In production this crawl + key usage belongs in a server action; here it
     runs client-side via the same reader proxy the other generators use. */
  const AUD_NOT_FOUND = 'Not clearly found. Please add this manually.';

  /* Error messages, mapped from explicit codes. */
  const AUD_ERR_READ = 'We couldn’t read enough source content to generate this ICP. Try another URL, upload a document, or add extra instructions.';
  const AUD_ERR_AI = 'We could read the source, but couldn’t generate the ICP. Please try again or add more context.';
  const AUD_ERR_OUTPUT = 'We generated a draft, but couldn’t format it safely for the editor. Please try again.';
  const AUD_ERR_ACCESS = 'ICP generation stopped because Workspace access is temporarily unavailable. Your existing content has not changed. Try again once access is restored.';
  const AUD_ERR_UNKNOWN = 'Something went wrong while generating this ICP. Please try again.';
  const AUD_READ_CODES = ['no-content', 'read-home', 'read-corpus', 'network', 'empty', 'thin-doc'];
  function audGenErrorMessage(err) {
    const code = err && err.message ? err.message : '';
    if (AUD_READ_CODES.indexOf(code) !== -1) return AUD_ERR_READ;
    if (code === 'ai-failed' || code === 'ai-empty') return AUD_ERR_AI;
    if (code === 'bad-output') return AUD_ERR_OUTPUT;
    return AUD_ERR_UNKNOWN;
  }

  function audSafeDiag(stage, data) {
    const payload = data && typeof data === 'object' ? { ...data } : {};
    delete payload.prompt;
    delete payload.raw;
    delete payload.sourceText;
    delete payload.documentText;
    delete payload.websiteCorpus;
    console.info('[ICPGenerate] ' + stage, payload);
  }

  function audGenerationErrorMessage(err) {
    const code = err && err.message ? err.message : '';
    if (code === 'knowledge-unavailable') return 'We couldn’t load this Website’s saved Knowledge. Your existing content has not changed. Reopen the Website and try again.';
    if (AUD_READ_CODES.indexOf(code) !== -1) return 'We couldnâ€™t read this source. Check the URL or upload another document and try again.';
    if (code === 'ai-failed' || code === 'ai-empty' || code === 'ai-unavailable') return 'We couldnâ€™t reach the AI generator. Please try again.';
    if (code === 'parse-failed' || code === 'bad-output') return 'The AI response couldnâ€™t be converted into an ICP. Please try again or add more context.';
    if (code === 'validation-failed') return 'The draft was incomplete, so it wasnâ€™t saved. Please try again or add more context.';
    if (code === 'save-failed') return 'The ICP was generated but couldnâ€™t be saved. Please try again.';
    return AUD_ERR_UNKNOWN;
  }

  async function audCallIcpLLM(prompt, stage, operation = window.ClicklyxKnowledgeAccess.begin(true)) {
    operation.assert();
    const promptChars = String(prompt || '').length;
    const hasAppAdapter = typeof window !== 'undefined' && typeof window.appLLMAdapter === 'function';
    audSafeDiag('generation_request_started', {
      stage,
      promptChars,
      adapter: hasAppAdapter ? 'appLLMAdapter' : 'none',
      mode: 'icp'
    });
    if (hasAppAdapter) {
      try {
        const out = await operation.run(() => window.appLLMAdapter({ prompt, mode: 'icp', requestOrigin: operation.origin }));
        audSafeDiag('generation_request_succeeded', {
          stage,
          adapter: 'appLLMAdapter',
          responseFormat: typeof out,
          outputChars: out ? String(out).length : 0
        });
        return out;
      } catch (e) {
        audSafeDiag('generation_request_failed', {
          stage,
          adapter: 'appLLMAdapter',
          errorMessage: e && e.message ? e.message : 'AI adapter request failed.'
        });
        throw new Error('ai-failed');
      }
    }
    audSafeDiag('generation_request_failed', { stage, adapter: 'none', errorMessage: 'No live ICP LLM adapter detected.' });
    throw new Error('ai-unavailable');
  }

  function audEscape(s) {
    return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  }
  function audGenHtmlText(html) {
    return String(html || '').replace(/<[^>]*>/g, ' ').replace(/&[a-z]+;/gi, ' ').replace(/\s+/g, ' ').trim();
  }

  /* The 11 ICP sections, in required order: [key, display heading]. */
  const ICP_SECTIONS = [
  ['audience_overview', 'Audience Overview'],
  ['buying_role', 'Role in the Buying Process'],
  ['pain_points', 'Pain Points'],
  ['goals', 'Goals / Desired Outcomes'],
  ['buying_triggers', 'Buying Triggers'],
  ['objections', 'Objections / Concerns'],
  ['decision_criteria', 'Decision Criteria'],
  ['awareness_level', 'Awareness Level'],
  ['messaging_angles', 'Messaging Angles'],
  ['topics', 'Topics They Care About'],
  ['writing_rules', 'Audience Writing Rules']];

  function audNormalizeKey(s) {
    return String(s || '').toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '');
  }
  const ICP_SECTION_ALIASES = {
    icp_name: ['icp_name_role', 'icp_name', 'name_role', 'icp_name_slash_role', 'role_name', 'icp_role', 'persona_name'],
    audience_overview: ['audience_overview', 'overview', 'who_they_are', 'profile_overview', 'summary'],
    buying_role: ['role_in_the_buying_process', 'buying_role', 'role_in_buying', 'role_in_buying_process', 'buyer_role', 'buying_process_role'],
    pain_points: ['pain_points', 'pains', 'problems', 'challenges', 'frustrations'],
    goals: ['goals_desired_outcomes', 'goals', 'desired_outcomes', 'goals_and_desired_outcomes', 'objectives', 'outcomes'],
    buying_triggers: ['buying_triggers', 'triggers', 'buying_trigger', 'trigger_events'],
    objections: ['objections_concerns', 'objections', 'concerns', 'objections_and_concerns', 'risks'],
    decision_criteria: ['decision_criteria', 'criteria', 'evaluation_criteria', 'decision_factors'],
    awareness_level: ['awareness_level', 'awareness', 'level_of_awareness'],
    messaging_angles: ['messaging_angles', 'messaging', 'angles', 'message_angles', 'messaging_angle'],
    topics: ['topics_they_care_about', 'topics', 'themes', 'content_topics', 'topics_of_interest'],
    writing_rules: ['audience_writing_rules', 'writing_rules', 'rules', 'audience_rules']
  };
  const ICP_ALIAS_LOOKUP = (() => {
    const map = {};
    Object.keys(ICP_SECTION_ALIASES).forEach((canon) => {
      ICP_SECTION_ALIASES[canon].forEach((a) => {map[audNormalizeKey(a)] = canon;});
      map[audNormalizeKey(canon)] = canon;
    });
    return map;
  })();
  function audMatchHeading(line) {
    let s = String(line || '').trim();
    if (!s) return null;
    s = s.replace(/^#{1,6}\s*/, '').replace(/^\*\*(.+?)\*\*$/, '$1').replace(/^__(.+?)__$/, '$1');
    s = s.replace(/[:：]\s*$/, '').trim();
    if (!s || s.length > 60 || s.split(/\s+/).length > 8) return null;
    return ICP_ALIAS_LOOKUP[audNormalizeKey(s)] || null;
  }
  function audBulletLi(text) {
    const t = String(text || '').trim();
    if (!t) return '';
    const m = t.match(/^([^:]{1,60}):\s+(.*\S)$/);
    if (m) return '<li><strong>' + audEscape(m[1].trim()) + ':</strong> ' + audEscape(m[2].trim()) + '</li>';
    return '<li>' + audEscape(t) + '</li>';
  }

  /* Forgiving structured-text parser → { name, bodies, detected, missing }.
     Never trusts raw AI HTML: every value is escaped before insertion.
     'ICP Name / Role' is captured into `name` rather than a section body. */
  function audParseIcp(raw) {
    let text = String(raw == null ? '' : raw);
    text = text.replace(/```[a-z]*\n?/gi, '').replace(/```/g, '');
    if (audGenHtmlText(text).length < 30) return null;

    const lines = text.split(/\r?\n/);
    const bodies = {};
    const nameParts = [];
    let cur = null;
    let para = [], bullets = [], numbers = [];

    const push = (html) => {if (!cur || cur === 'icp_name' || !html) return;(bodies[cur] = bodies[cur] || []).push(html);};
    const flushPara = () => {
      if (!para.length) return;
      if (cur === 'icp_name') {nameParts.push(para.join(' '));} else {push('<p>' + audEscape(para.join(' ')) + '</p>');}
      para = [];
    };
    const flushBullets = () => {if (bullets.length) {push('<ul>\n' + bullets.join('\n') + '\n</ul>');bullets = [];}};
    const flushNumbers = () => {if (numbers.length) {push('<ol>\n' + numbers.join('\n') + '\n</ol>');numbers = [];}};
    const flush = () => {flushPara();flushBullets();flushNumbers();};

    for (const rawLine of lines) {
      const line = rawLine.trim();
      if (!line) {flush();continue;}
      const canon = audMatchHeading(line);
      if (canon) {flush();cur = canon;if (canon !== 'icp_name' && !bodies[canon]) bodies[canon] = [];continue;}
      const nm = line.match(/^\d{1,3}[.)]\s+(.*)$/);
      if (nm) {flushPara();flushBullets();const li = audBulletLi(nm[1]);if (li) numbers.push(li);continue;}
      const bm = line.match(/^(?:[-*•]|\u2013|\u2014)\s+(.*)$/);
      if (bm) {flushPara();flushNumbers();const li = audBulletLi(bm[1]);if (li) bullets.push(li);continue;}
      flushBullets();flushNumbers();
      para.push(line);
    }
    flush();

    let name = nameParts.join(' ').replace(/\s+/g, ' ').trim();
    name = name.replace(/^\*\*(.+?)\*\*$/, '$1').replace(/^["'\[]+|["'\]]+$/g, '').trim();
    if (name.length > 80) name = name.slice(0, 80).trim();

    const detected = ICP_SECTIONS.filter(([k]) => (bodies[k] || []).join('').trim().length > 0).map(([k]) => k);
    const missing = ICP_SECTIONS.filter(([k]) => detected.indexOf(k) === -1).map(([k]) => k);
    return { name, bodies, detected, missing };
  }

  /* Audience Writing Rules must always be a useful NUMBERED list — never left
     as "Not clearly found". If the model omits it, fall back to these generic
     but genuinely useful defaults (mirrors how PK guarantees mention rules). */
  const AUD_DEFAULT_WRITING_RULES = [
  'Focus on practical outcomes and concrete results, not vague benefits.',
  'Use examples and scenarios drawn from this person’s day-to-day work.',
  'Lead with the pains and goals that matter most to this role.',
  'Avoid overexplaining basics this person already understands.',
  'Back claims with specifics; do not overuse buzzwords or hype.'];
  function audDefaultWritingRulesHtml() {
    return '<ol>\n' + AUD_DEFAULT_WRITING_RULES.map((t) => '<li>' + audEscape(t) + '</li>').join('\n') + '\n</ol>';
  }
  /* Coerce whatever the model produced under Audience Writing Rules into ONE
     ordered list: gather every <li> across any number of <ol>/<ul> blocks (the
     parser emits a separate list per blank-line-separated group), else rebuild
     from numbered/paragraph lines. Always returns a single merged <ol>. */
  function audCoerceWritingRulesToOl(body) {
    const b = (body || '').trim();
    let items = [];
    if (b) {
      const liRe = /<li>([\s\S]*?)<\/li>/gi;
      let m;
      while (m = liRe.exec(b)) {const t = m[1].trim();if (t) items.push(t);}
      if (!items.length) {
        const txt = audGenHtmlText(b);
        items = txt.split(/\n+|(?<=[.!?])\s+/).map((s) => s.replace(/^\d+[.)]\s*/, '').trim()).filter((s) => s.length > 3).map((s) => audEscape(s));
      }
    }
    // Guarantee at least 4 rules — top up from the safe defaults (not dupes).
    if (items.length && items.length < 4) {
      for (const d of AUD_DEFAULT_WRITING_RULES) {
        if (items.length >= 4) break;
        if (!items.some((it) => audGenHtmlText(it).toLowerCase() === d.toLowerCase())) items.push(audEscape(d));
      }
    }
    if (!items.length) return null;
    return '<ol>\n' + items.map((x) => '<li>' + x + '</li>').join('\n') + '\n</ol>';
  }

  /* Assemble final editor HTML; empty sections get the placeholder. Audience
     Writing Rules is always coerced to a numbered list (default if empty).
     Preserves the required order. */
  function audAssembleIcpHtml(bodies) {
    return ICP_SECTIONS.map(([key, heading]) => {
      const body = (bodies[key] || []).join('\n').trim();
      const has = audGenHtmlText(body).length > 0;
      if (key === 'writing_rules') {
        const ol = has ? (audCoerceWritingRulesToOl(body) || audDefaultWritingRulesHtml()) : audDefaultWritingRulesHtml();
        return '<h2>' + heading + '</h2>\n' + ol;
      }
      return '<h2>' + heading + '</h2>\n' + (has ? body : '<p>' + audEscape(AUD_NOT_FOUND) + '</p>');
    }).join('\n');
  }

  const ICP_HEADING_BY_KEY = (() => {
    const m = {};
    ICP_SECTIONS.forEach(([k, h]) => {m[k] = h;});
    return m;
  })();

  /* ---- Lightweight document context detectors (safe metadata only) -------
     These help the prompt + diagnostics understand whether an uploaded
     document references a different company/product than saved knowledge, and
     which ICP sections the document itself already covers. Never log full
     document text — only candidate names / section keys. */
  const AUD_NAME_STOP = new Set(['The', 'This', 'That', 'They', 'Their', 'There', 'It', 'He', 'She', 'We', 'You',
  'And', 'Or', 'But', 'For', 'With', 'As', 'Is', 'Are', 'Was', 'Were', 'Persona', 'Profile', 'Role', 'Company',
  'Product', 'Products', 'Team', 'Teams', 'Sales', 'Marketing', 'Support', 'Operations', 'Customer', 'Customers',
  'Head', 'Director', 'Manager', 'Founder', 'Pains', 'Pain', 'Goals', 'Goal', 'Buying', 'Triggers', 'Objections',
  'Concerns', 'Decision', 'Criteria', 'Awareness', 'Messaging', 'Angles', 'Topics', 'Audience', 'Writing', 'Rules',
  'Overview', 'Process', 'ICP', 'Example', 'Description', 'Summary', 'Notes', 'Research', 'Document']);
  function audDetectCompanies(text) {
    const s = String(text || '');
    const counts = {};
    let m;
    const camel = /\b([A-Z][a-z0-9]+[A-Z][A-Za-z0-9]+)\b/g;       // AcmeFlow, DockFlow, RevOps
    while (m = camel.exec(s)) {counts[m[1]] = (counts[m[1]] || 0) + 3;}
    const cap = /\b([A-Z][a-zA-Z0-9]{2,})\b/g;
    while (m = cap.exec(s)) {const w = m[1];if (AUD_NAME_STOP.has(w)) continue;counts[w] = (counts[w] || 0) + 1;}
    const out = Object.keys(counts).filter((w) => /[a-z][A-Z]/.test(w) || counts[w] >= 2);
    out.sort((a, b) => counts[b] - counts[a]);
    return out.slice(0, 5);
  }
  function audDetectRoles(text) {
    const s = String(text || '').toLowerCase();
    const found = new Set();
    const pats = [/head of [a-z]+(?: [a-z]+)?/g, /vp of [a-z]+(?: [a-z]+)?/g, /vice president of [a-z]+/g,
    /director of [a-z]+(?: [a-z]+)?/g, /chief [a-z]+ officer/g, /[a-z]+ manager/g, /(?:co-)?founder/g,
    /\b(ceo|cmo|cto|cfo|coo|revops)\b/g, /product marketing(?: manager)?/g, /content marketing(?: manager)?/g];
    pats.forEach((p) => {let m;while (m = p.exec(s)) {found.add(m[0].trim());}});
    return Array.from(found).slice(0, 6);
  }
  function audDetectAdaptation(extra) {
    const s = String(extra || '').toLowerCase();
    if (!s.trim()) return false;
    return /\badapt\b|\brewrite (this )?(persona|icp|document)\b|\bapply (it|this|the (icp|persona|document)) to (our|my|your)\b|\bfit (my|our|your) (saved )?(product|company|brand)\b|\bfor our (product|company|brand)\b|\b(as a |as )?template.*(our|my|your)\b|\bmake it fit\b/.test(s);
  }
  const AUD_DOC_SECTION_HINTS = {
    audience_overview: ['overview', 'who they are', 'persona', 'profile', 'about the', 'background'],
    buying_role: ['buying process', 'decision maker', 'budget owner', 'influencer', 'champion', 'role in', 'evaluator'],
    pain_points: ['pain', 'pains', 'problem', 'frustration', 'challenge', 'struggle'],
    goals: ['goal', 'goals', 'outcome', 'objective', 'wants to', 'aims to'],
    buying_triggers: ['trigger', 'triggers', 'starts looking', 'prompts', ' event'],
    objections: ['objection', 'concern', 'worried', 'risk', 'hesitation'],
    decision_criteria: ['decision criteria', 'criteria', 'compares', 'evaluates', 'evaluation'],
    awareness_level: ['awareness', 'problem-aware', 'solution-aware', 'product-aware', 'comparing tools', 'ready to buy'],
    messaging_angles: ['messaging', 'angle', 'message', 'positioning', 'resonate'],
    topics: ['topics', 'themes', 'cares about', 'interested in', 'content'],
    writing_rules: ['writing rules', 'tone', 'style guide', 'how to write', 'do not', 'avoid']
  };
  function audDetectDocSections(text) {
    const s = String(text || '').toLowerCase();
    const detected = [];
    ICP_SECTIONS.forEach(([k]) => {
      const hints = AUD_DOC_SECTION_HINTS[k] || [];
      if (hints.some((h) => s.indexOf(h) !== -1)) detected.push(k);
    });
    return detected;
  }

  /* ---- Multi-persona detection ------------------------------------------
     Documents (especially PDFs) often hold several personas/ICPs. We split on
     PDF page markers and on inline "ICP N:" / "Persona: Name" / "Meet Name"
     headers, score each block for persona-style section labels, and treat
     blocks with enough signal as personas. When the user gives no instruction,
     the FIRST detected persona is used and the rest are EXCLUDED from the
     source so their details (budgets, revenue, examples) never blend in. */
  const AUD_PERSONA_LABELS = ['company description', 'persona description', 'buying role', 'buying roles',
  'challenges', 'seo budget', 'offer', 'website elements', 'goals', 'pain points', 'demographics',
  'about the company', 'about the persona', 'monthly traffic', 'monthly revenue'];
  const AUD_GLOBAL_HINTS = ['customer journey', 'cold outreach', 'outreach', 'journey', 'cover',
  'table of contents', 'introduction', 'overview of'];

  function audSplitPages(text) {
    const s = String(text || '');
    if (/---\s*PAGE\s+\d+\s*---/i.test(s)) {
      const parts = s.split(/---\s*PAGE\s+(\d+)\s*---/i);
      const pages = [];
      for (let i = 1; i < parts.length; i += 2) {
        pages.push({ page: parseInt(parts[i], 10), text: (parts[i + 1] || '').trim() });
      }
      if (pages.length) return pages;
    }
    return [{ page: 1, text: s.trim() }];
  }
  function audPersonaLabelScore(text) {
    const s = String(text || '').toLowerCase();
    let n = 0;
    AUD_PERSONA_LABELS.forEach((l) => {if (s.indexOf(l) !== -1) n += 1;});
    return n;
  }
  function audDetectPersonaName(text) {
    const head = String(text || '').split(/\n+/).map((l) => l.trim()).filter(Boolean).slice(0, 14);
    for (const l of head) {
      if (AUD_PERSONA_LABELS.some((lab) => l.toLowerCase().indexOf(lab) !== -1)) continue;
      const m = l.match(/^(?:meet\s+|persona[:\s-]+|name[:\s-]+|icp\s*\d+[:\s-]+)?([A-Z][a-z]{2,})(?:\s[A-Z][a-z]+)?$/);
      if (m) return m[1];
    }
    const m2 = String(text || '').match(/(?:persona|meet|name)[:\s-]+([A-Z][a-z]{2,})/i);
    if (m2) return m2[1];
    return null;
  }
  /* Break the document into candidate persona blocks (page-aware + inline
     headers). Returns every block; the caller filters by score. */
  function audPersonaBlocks(text) {
    const pages = audSplitPages(text);
    const blocks = [];
    const headerRe = /(^|\n)[ \t]*((?:ICP|Persona)\s*\d+\b[^\n]*|(?:ICP|Persona)[:\-\s]+[A-Z][a-z]+[^\n]*|Meet\s+[A-Z][a-z]+[^\n]*)/g;
    pages.forEach((pg) => {
      const idxs = [];
      let m;
      headerRe.lastIndex = 0;
      while (m = headerRe.exec(pg.text)) idxs.push(m.index + (m[1] ? m[1].length : 0));
      if (idxs.length >= 2) {
        for (let i = 0; i < idxs.length; i++) {
          const seg = pg.text.slice(idxs[i], i + 1 < idxs.length ? idxs[i + 1] : undefined).trim();
          if (seg) blocks.push({ name: audDetectPersonaName(seg), page: pg.page, text: seg });
        }
      } else {
        blocks.push({ name: audDetectPersonaName(pg.text), page: pg.page, text: pg.text });
      }
    });
    return blocks;
  }
  function audIsGlobalBlock(block) {
    const s = String(block.text || '').toLowerCase();
    if (AUD_GLOBAL_HINTS.some((h) => s.indexOf(h) !== -1) && audPersonaLabelScore(block.text) < 2) return true;
    // A short, low-signal first page reads as a cover.
    if (block.page === 1 && block.text.length < 400 && audPersonaLabelScore(block.text) < 2) return true;
    return false;
  }
  /* Detect personas → { personas:[{name,page,text,chars}], globals:[blocks] }. */
  function audDetectPersonas(text) {
    const blocks = audPersonaBlocks(text);
    const personas = [];
    const globals = [];
    blocks.forEach((b) => {
      const score = audPersonaLabelScore(b.text);
      if (audIsGlobalBlock(b)) {globals.push(b);return;}
      if (score >= 2 || (b.name && score >= 1)) {
        personas.push({ name: b.name || null, page: b.page, text: b.text, chars: b.text.length });
      }
    });
    return { personas, globals };
  }
  /* Pick the persona to use given extra instructions (none → first). */
  function audSelectPersona(personas, extra) {
    if (!personas.length) return null;
    const s = String(extra || '').toLowerCase();
    // Explicit name match.
    for (const p of personas) {
      if (p.name && s.indexOf(p.name.toLowerCase()) !== -1) return p;
    }
    // Ordinal-ish references.
    if (/\b(second|2nd|persona\s*2|icp\s*2)\b/.test(s) && personas[1]) return personas[1];
    if (/\b(third|3rd|persona\s*3|icp\s*3)\b/.test(s) && personas[2]) return personas[2];
    // "first" or empty → first actual persona.
    return personas[0];
  }

  /* ---- Section quality validation ---------------------------------------
     A section having SOME text isn't enough — it can be a placeholder, too
     thin, cut off mid-thought, or short on useful lines. Flags "present but
     weak" sections so a single targeted rewrite can fix only those, and can
     strip a trailing fragment (e.g. a dangling "Reduce") before applying. */
  const AUD_DANGLING = ['and', 'or', 'the', 'to', 'with', 'for', 'of', 'a', 'an', 'but', 'as', 'that',
  'which', 'connect', 'including', 'such', 'like', 'by', 'in', 'on', 'at', 'your', 'our', 'their'];
  /* Lone trailing verbs/connectors that signal an unfinished line. */
  const AUD_DANGLING_END = ['and', 'or', 'the', 'to', 'with', 'for', 'of', 'a', 'an', 'but', 'as', 'that',
  'which', 'by', 'in', 'on', 'at', 'your', 'our', 'their', 'including', 'such', 'like', 'when', 'while',
  'not', 'nor', 'yet', 'so', 'if', 'than', 'then', 'versus', 'vs', 'plus', 'because', 'since', 'unless',
  'reduce', 'connect', 'improve', 'help', 'give', 'make', 'show', 'use', 'focus', 'build', 'create',
  'increase', 'drive', 'enable', 'provide', 'deliver', 'support', 'grow', 'save', 'boost', 'streamline',
  'optimize', 'simplify', 'ensure', 'avoid', 'align'];
  /* Minimum useful lines per list-style section (used when enough source
     context exists). */
  const AUD_MIN_LINES = { messaging_angles: 4, topics: 6, pain_points: 4, goals: 3,
  buying_triggers: 3, objections: 3, decision_criteria: 4 };
  /* Adjectives/qualifiers that normally PRECEDE a noun — a line ending here is
     almost certainly cut off (e.g. "On-page and technical"). */
  const AUD_TRAILING_ADJ = ['technical', 'on-page', 'off-page', 'organic', 'strategic', 'digital',
  'paid', 'local', 'overall', 'general', 'various', 'related', 'etc', 'more', 'additional', 'further',
  'other', 'certain', 'specific', 'long-term', 'short-term', 'high-level', 'top-of-funnel'];

  /* Visible "lines" of a section body, in document order (each <li> and each
     <p>/<h3> as one unit). */
  function audBodyLines(body) {
    const div = document.createElement('div');
    div.innerHTML = body || '';
    const out = [];
    div.querySelectorAll('li, p, h3').forEach((el) => {
      const t = (el.textContent || '').replace(/\s+/g, ' ').trim();
      if (t) out.push({ text: t, li: el.tagName === 'LI' });
    });
    return out;
  }
  /* Is a single line an incomplete fragment? Short valid list items (e.g.
     "Marketing attribution") are NOT fragments; lone verbs, trailing
     connectors, and cut-off sentences are. */
  function audIsFragmentLine(line) {
    const t = String(line || '').trim();
    if (!t) return true;
    if (/[,:;]$/.test(t)) return true;
    if (/[-–—]$/.test(t)) return true;
    const words = t.split(/\s+/).filter(Boolean);
    const lastWord = (words[words.length - 1] || '').toLowerCase().replace(/[^a-z]/g, '');
    const lastWordHy = (words[words.length - 1] || '').toLowerCase().replace(/[^a-z-]/g, '');
    if (words.length === 1) return AUD_DANGLING_END.indexOf(lastWord) !== -1;
    if (AUD_DANGLING_END.indexOf(lastWord) !== -1) return true;
    // Ends on a qualifier that normally precedes a noun → cut off.
    if (AUD_TRAILING_ADJ.indexOf(lastWordHy) !== -1) return true;
    // Ends with a short dangling clause after a comma (e.g. "Collaboration, not",
    // "Partnership, not just"): a comma followed by ≤2 short trailing words that
    // do not themselves end the thought.
    const commaTail = t.match(/,\s*([\w-]+(?:\s+[\w-]+)?)\s*$/);
    if (commaTail) {
      const tailWords = commaTail[1].trim().split(/\s+/).filter(Boolean);
      const tailLast = (tailWords[tailWords.length - 1] || '').toLowerCase();
      if (tailWords.length <= 2 && (AUD_DANGLING_END.indexOf(tailLast) !== -1 || tailWords.length <= 1)) return true;
    }
    // Partial phrase after a conjunction: a short line ending "… and <word>"
    // (e.g. "On-page and technical", "Content and").
    const conj = t.match(/\b(and|or|with|for|to|not|but)\s+([\w-]+(?:\s+[\w-]+)?)\s*$/i);
    if (conj) {
      const tail = conj[2].trim().split(/\s+/).filter(Boolean);
      if (words.length <= 5 && tail.length <= 1) return true;
    }
    // A sentence-length line with no terminal punctuation that ends lowercase
    // is very likely cut off.
    if (words.length >= 6 && !/[.!?]["')\]]?$/.test(t) && /[a-z]$/.test(t)) return true;
    return false;
  }
  /* Count "useful" (complete, non-trivial) lines in a body. */
  function audUsefulLineCount(body) {
    return audBodyLines(body).filter((l) =>
      !audIsFragmentLine(l.text) && l.text.split(/\s+/).filter(Boolean).length >= 2).length;
  }
  function audSectionTextWeak(key, body) {
    const text = audGenHtmlText(body);
    if (!text) return true;
    if (/not clearly found/i.test(text)) return true;
    const words = text.split(/\s+/).filter(Boolean);
    if (key === 'awareness_level') {if (words.length < 3) return true;} else
    if (words.length < 6) return true;
    if (/[,;:]$/.test(text)) return true;
    return false;
  }
  function audWritingRulesWeak(body) {
    if (!body) return true;
    if (!/<ol[\s>]/i.test(body)) return true;
    return (body.match(/<li>/gi) || []).length < 4;
  }
  /* Full weak-section scan: placeholder/thin text, a trailing fragment on the
     last line, or too few useful lines for list-style sections. */
  function audWeakSections(bodies) {
    const weak = [];
    ICP_SECTIONS.forEach(([k]) => {
      const body = (bodies[k] || []).join('\n').trim();
      if (k === 'writing_rules') {if (audWritingRulesWeak(body)) weak.push(k);return;}
      if (audSectionTextWeak(k, body)) {weak.push(k);return;}
      const lines = audBodyLines(body);
      if (lines.length && audIsFragmentLine(lines[lines.length - 1].text)) {weak.push(k);return;}
      const min = AUD_MIN_LINES[k];
      if (min && audUsefulLineCount(body) < min) {weak.push(k);return;}
    });
    return weak;
  }
  /* Remove a clearly-fragmentary LAST line from a section's block array (drops
     the last <li>, or the whole trailing <p>). Returns { blocks, removed }. */
  function audStripTrailingFragment(blocks) {
    if (!blocks || !blocks.length) return { blocks: blocks || [], removed: false };
    const arr = blocks.slice();
    const div = document.createElement('div');
    div.innerHTML = arr[arr.length - 1] || '';
    const lis = Array.prototype.slice.call(div.querySelectorAll('li'));
    if (lis.length) {
      const lastLi = lis[lis.length - 1];
      if (audIsFragmentLine(lastLi.textContent || '')) {
        lastLi.parentNode.removeChild(lastLi);
        if (div.querySelectorAll('li').length === 0) arr.pop();
        else arr[arr.length - 1] = div.innerHTML;
        return { blocks: arr, removed: true };
      }
      return { blocks: arr, removed: false };
    }
    if (audIsFragmentLine(div.textContent || '')) {arr.pop();return { blocks: arr, removed: true };}
    return { blocks: arr, removed: false };
  }
  function audStripTrailingFragments(bodies) {
    let removed = 0;
    ICP_SECTIONS.forEach(([k]) => {
      if (k === 'writing_rules') return;
      const r = audStripTrailingFragment(bodies[k] || []);
      if (r.removed) {bodies[k] = r.blocks;removed += 1;}
    });
    return removed;
  }
  /* Deterministic Topics fallback, inferred from the selected persona source.
     Used ONLY when the AI's Topics section is still weak/cut-off after rewrite.
     Picks from a curated set based on signals present in the source text. */
  function audTopicsFallback(sourceText) {
    const s = String(sourceText || '').toLowerCase();
    const has = (re) => re.test(s);
    const picks = [];
    const add = (t) => {if (picks.indexOf(t) === -1) picks.push(t);};
    if (has(/content|blog|produc/)) add('Content consistency');
    if (has(/seo|rank|google|keyword|search/)) add('SEO strategy');
    if (has(/keyword|rank|search/)) add('Keyword research');
    if (has(/traffic|blog|visit/)) add('Blog traffic growth');
    if (has(/rank|google|serp/)) add('Google rankings');
    if (has(/lead|customer|convert|pipeline/)) add('Lead generation from content');
    if (has(/topic|plan|strategy|unsure/)) add('Content topic planning');
    if (has(/customer|organic|acqui/)) add('Organic customer acquisition');
    if (has(/roi|report|measure|prove|result/)) add('Content performance reporting');
    if (has(/agency|outsour|freelanc|partner|outreach/)) add('Working with an SEO/content agency');
    // Backfill from a generic content-marketing set to guarantee >= 6.
    const generic = ['Content consistency', 'SEO strategy', 'Keyword research', 'Blog traffic growth',
    'Google rankings', 'Lead generation from content', 'Content topic planning',
    'Organic customer acquisition', 'Content performance reporting', 'Working with an SEO/content agency'];
    for (const g of generic) {if (picks.length >= 8) break;add(g);}
    return '<ul>\n' + picks.slice(0, Math.max(6, Math.min(picks.length, 8))).map((t) => '<li>' + audEscape(t) + '</li>').join('\n') + '\n</ul>';
  }

  /* Deterministic Messaging Angles fallback, inferred from the selected persona
     source. Used ONLY when Messaging Angles is still weak/cut-off after rewrite.
     DOCUMENT MODE ONLY — these examples are content/SEO-flavored and must never
     run in website mode (see audDraftDerivedList for the source-agnostic path).
     Source-faithful; never invents timelines, "ranked", or guarantees. */
  function audMessagingFallback(sourceText) {
    const s = String(sourceText || '').toLowerCase();
    const has = (re) => re.test(s);
    const picks = [];
    const add = (t) => {if (picks.indexOf(t) === -1) picks.push(t);};
    if (has(/traffic/) && has(/customer|lead|convert/)) add('Turn existing website traffic into customers with a clearer SEO and content strategy.');
    if (has(/time|consisten|capacity|small team|1-3|lean/)) add('Publish consistent content without hiring a full-time marketing team.');
    if (has(/rank|keyword|google|search/)) add('Focus on topics and keywords that can rank and support customer acquisition.');
    if (has(/free post|trial|offer|low.?risk|testimonial/)) add('Use a low-risk starting offer to prove value before asking for a larger commitment.');
    if (has(/ceo|approv|budget|leadership/)) add('Help the Head of Marketing show clear content and SEO progress to the CEO.');
    if (has(/topic|strategy|unsure|plan/)) add('Replace guesswork with a focused content strategy built around proven topics.');
    const generic = [
    'Turn existing website traffic into customers with a clearer SEO and content strategy.',
    'Publish consistent content without hiring a full-time marketing team.',
    'Focus on topics and keywords that can rank and support customer acquisition.',
    'Use a low-risk starting offer to prove value before asking for a larger commitment.',
    'Help the Head of Marketing show clear content and SEO progress to the CEO.'];
    for (const g of generic) {if (picks.length >= 5) break;add(g);}
    return '<ul>\n' + picks.slice(0, Math.max(4, Math.min(picks.length, 6))).map((t) => '<li>' + audEscape(t) + '</li>').join('\n') + '\n</ul>';
  }

  /* Deterministic, source-faithful Audience Writing Rules fallback (numbered).
     Used ONLY when the rules are weak / fewer than 4 complete rules. */
  function audWritingRulesFallback(sourceText) {
    const rules = [
    'Focus on rankings, traffic, and customer acquisition — not vague SEO benefits.',
    'Mention the limited team size and lack of time when explaining the value of outside help.',
    'Use simple, concrete examples tied to content consistency, keyword research, and blog performance.',
    'Show how the offer reduces risk before the CEO approves a larger budget.',
    'Avoid hard timelines, guarantees, or unsupported ROI claims.'];
    return '<ol>\n' + rules.map((t) => '<li>' + audEscape(t) + '</li>').join('\n') + '\n</ol>';
  }

  /* Pull a labeled block out of the source (e.g. "Goals: a, b, c." or a
     "Challenges" heading) and split it into bullet <li>s. Returns null when the
     label isn't present, so we never fabricate beyond what the source says. */
  function audExtractLabeledList(sourceText, labels) {
    const src = String(sourceText || '');
    for (const label of labels) {
      const re = new RegExp('(?:^|\\n)\\s*' + label.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '\\s*[:\\-–]\\s*([^\\n]+)', 'i');
      const m = src.match(re);
      if (m && m[1]) {
        const parts = m[1].split(/[.;]\s+|,\s+(?=[a-z0-9])|\s+and\s+|•|\u2022/i)
          .map((s) => s.replace(/\s+/g, ' ').trim().replace(/[.;,]+$/, ''))
          .filter((s) => s.length >= 3);
        const items = [];
        parts.forEach((p) => {if (items.indexOf(p) === -1 && p.split(/\s+/).length >= 1) items.push(p);});
        if (items.length) {
          return '<ul>\n' + items.slice(0, 8).map((t) => '<li>' + audEscape(t.charAt(0).toUpperCase() + t.slice(1)) + '</li>').join('\n') + '\n</ul>';
        }
      }
    }
    return null;
  }
  /* Source labels mapped to each list-style ICP section, for the deterministic
     extraction fallback. */
  const AUD_SECTION_SOURCE_LABELS = {
    goals: ['Goals / Desired Outcomes', 'Goals', 'Desired Outcomes', 'Objectives'],
    buying_triggers: ['Buying Triggers', 'Triggers', 'Buying Trigger'],
    pain_points: ['Pain Points', 'Challenges', 'Pains', 'Problems'],
    objections: ['Objections / Concerns', 'Objections', 'Concerns'],
    decision_criteria: ['Decision Criteria', 'Criteria', 'Evaluation Criteria']
  };
  /* Inference fallback for Buying Triggers — persona docs rarely label these,
     so infer source-faithful trigger events from the persona's situation. */
  function audBuyingTriggersFallback(sourceText) {
    const s = String(sourceText || '').toLowerCase();
    const has = (re) => re.test(s);
    const picks = [];
    const add = (t) => {if (picks.indexOf(t) === -1) picks.push(t);};
    if (has(/no (new )?customer|no lead|not.*convert/)) add('Website traffic is not turning into new customers.');
    if (has(/not rank|does not rank|ranking|google/)) add('Content is not ranking or being found on Google.');
    if (has(/no time|consisten|capacity|small team|1-3|lean/)) add('The team cannot produce content consistently with current capacity.');
    if (has(/roi|prove|report|ceo|leadership|budget/)) add('Pressure to show marketing ROI or justify spend to leadership.');
    if (has(/unsure|which topic|strategy|plan/)) add('Uncertainty about which topics and keywords to prioritize.');
    if (has(/traffic/) && has(/grow|increase|drive/)) add('A goal to grow organic traffic without adding headcount.');
    const generic = [
    'Website traffic is not turning into new customers.',
    'Content is not ranking or being found on Google.',
    'The team cannot produce content consistently with current capacity.',
    'Pressure to show marketing ROI or justify spend to leadership.'];
    for (const g of generic) {if (picks.length >= 4) break;add(g);}
    return '<ul>\n' + picks.slice(0, Math.max(3, Math.min(picks.length, 6))).map((t) => '<li>' + audEscape(t) + '</li>').join('\n') + '\n</ul>';
  }

  /* ---- Website-mode source isolation + alignment ------------------------
     Document-mode fallbacks above are content/SEO-flavored and must NEVER run
     in website mode. Website mode uses: (a) a model-built source summary that
     anchors every section, (b) contamination detection against the live corpus,
     and (c) source-agnostic, draft-derived fallbacks so a weak section is
     repaired from THIS ICP's own on-topic content — never old examples. */

  /* Build a structured plain-text website source summary (one compact model
     call). Anchors every section AND powers deterministic section fallbacks, so
     it captures more than the prompt needs for prose. Labeled lines are parsed
     by audWebsiteSignals. Falls back to a corpus excerpt if the call fails. */
  async function audBuildWebsiteSummary(corpus, extra, operation = window.ClicklyxKnowledgeAccess.begin(true)) {
    operation.assert();
    const base = audTrim(corpus, 14000);
    if (audGenHtmlText(base).length < 200) return '';
    const prompt = 'From the website text below, write a SHORT plain-text source summary (no JSON, no ' +
      'HTML, no code fences) with EXACTLY these labeled lines, in this order:\n' +
      'Category: <company/product category>\n' +
      'Buyers: <main users or buyers the site targets>\n' +
      'Likely ICP roles: <2-4 likely buyer roles>\n' +
      'Product promise: <one-sentence main promise>\n' +
      'Use cases: <comma list of main product use cases>\n' +
      'Pains solved: <comma list of core pains the product solves>\n' +
      'Key features: <comma list of key features>\n' +
      'Outcomes: <comma list of business outcomes>\n' +
      'Buying concerns: <comma list of likely objections/concerns before buying>\n' +
      'Trigger events: <comma list of situations that make this buyer start looking>\n' +
      'Topics: <comma list of topics this buyer cares about>\n\n' +
      'For the comma-list lines give 4-8 concise items each. Use ONLY what the website supports; if a ' +
      'line is genuinely unknowable from the site, still give the best-supported inference for this ' +
      'category. Do not invent specific company names, prices, or timelines.\n\n' +
      (extra ? 'User focus: ' + extra + '\n\n' : '') + 'WEBSITE:\n' + base;
    try {
      const raw = await audCallIcpLLM(prompt, 'website_summary', operation);
      const txt = String(raw || '').replace(/```[a-z]*\n?/gi, '').replace(/```/g, '').trim();
      if (audGenHtmlText(txt).length >= 40) return txt.slice(0, 2600);
    } catch (e) {}
    return audTrim(corpus, 1200);
  }

  /* Parse the labeled summary into arrays of signals for deterministic
     fallbacks. Unknown lines are tolerated; missing lines yield []. */
  function audWebsiteSignals(summary) {
    const out = { category: '', buyers: '', roles: '', promise: '',
      use_cases: [], pains: [], features: [], outcomes: [], concerns: [], triggers: [], topics: [] };
    const map = [
    [/^category\s*[:\-]/i, 'category', false], [/^buyers?\s*[:\-]/i, 'buyers', false],
    [/^(likely )?icp roles?\s*[:\-]/i, 'roles', false], [/^product promise\s*[:\-]/i, 'promise', false],
    [/^use cases?\s*[:\-]/i, 'use_cases', true], [/^pains? (solved)?\s*[:\-]/i, 'pains', true],
    [/^key features?\s*[:\-]/i, 'features', true], [/^outcomes?\s*[:\-]/i, 'outcomes', true],
    [/^buying concerns?\s*[:\-]/i, 'concerns', true], [/^trigger events?\s*[:\-]/i, 'triggers', true],
    [/^topics?\s*[:\-]/i, 'topics', true]];
    String(summary || '').split(/\n+/).forEach((line) => {
      const l = line.trim();
      for (const [re, key, isList] of map) {
        if (re.test(l)) {
          const val = l.replace(re, '').trim();
          if (isList) {
            out[key] = val.split(/[,;]|\s+and\s+|•|\u2022/i).map((s) => s.replace(/\s+/g, ' ').trim().replace(/^[-–]\s*/, '').replace(/[.;]+$/, '')).filter((s) => s.length >= 3);
          } else {out[key] = val;}
          break;
        }
      }
    });
    return out;
  }
  function audSignalCount(sig) {
    return ['use_cases', 'pains', 'features', 'outcomes', 'concerns', 'triggers', 'topics']
      .reduce((n, k) => n + (sig[k] ? sig[k].length : 0), 0);
  }
  /* True when writing-rules text is the generic (non-source-specific) default —
     in website mode we want source-specific rules instead. */
  function audWritingRulesGeneric(body) {
    const t = audGenHtmlText(body || '').toLowerCase();
    if (!t) return true;
    let hits = 0;
    AUD_DEFAULT_WRITING_RULES.forEach((r) => {
      const key = audGenHtmlText(r).toLowerCase().slice(0, 28);
      if (key && t.indexOf(key) !== -1) hits += 1;
    });
    return hits >= 2;   // 2+ generic default rules present ⇒ treat as generic
  }
  const audCapFirst = (s) => {const t = String(s || '').trim();return t ? t.charAt(0).toUpperCase() + t.slice(1) : t;};
  const audSentence = (s) => {let t = audCapFirst(s);if (t && !/[.!?]$/.test(t)) t += '.';return t;};
  function audListHtml(items, ordered) {
    const tag = ordered ? 'ol' : 'ul';
    if (!items || !items.length) return null;
    return '<' + tag + '>\n' + items.map((t) => '<li>' + audEscape(t) + '</li>').join('\n') + '\n</' + tag + '>';
  }
  /* Build a section-specific, source-derived fallback from website signals.
     Returns HTML or null when the signals can't support the section. */
  function audWebsiteSectionFallback(key, sig, role) {
    const r = role && role.trim() ? role.trim() : 'this buyer';
    const uniq = (arr) => {const seen = new Set();const out = [];(arr || []).forEach((x) => {const k = x.toLowerCase();if (x && !seen.has(k)) {seen.add(k);out.push(x);}});return out;};
    if (key === 'pain_points') {
      let items = uniq((sig.pains || []).map(audCapFirst));
      if (items.length < 5) {
        const cat = (sig.category || '').toLowerCase();
        const generic = [
        'Customer data is fragmented across disconnected tools.',
        'Manual reporting and data reconciliation eat up time.',
        'Pipeline and revenue visibility is poor and hard to trust.',
        'Handoffs between marketing, sales, and service are inconsistent.',
        'Data quality and governance issues undermine decisions.',
        'Low tool adoption limits the value of existing systems.',
        'Implementation and integration complexity slows progress.'];
        items = uniq(items.concat(generic.map(audCapFirst)));
      }
      return audListHtml(items.slice(0, 7).map(audSentence), false);
    }
    if (key === 'goals') {
      const items = uniq((sig.outcomes || []).concat(sig.pains.map((p) => 'Resolve ' + p.toLowerCase())));
      return audListHtml(items.slice(0, 6).map(audSentence), false);
    }
    if (key === 'buying_triggers') {
      let items = uniq(sig.triggers);
      if (items.length < 3) items = uniq(items.concat(sig.pains.map((p) => audCapFirst(p) + ' becomes too costly to ignore.')));
      return audListHtml(items.slice(0, 6).map(audSentence), false);
    }
    if (key === 'objections') {
      let items = uniq(sig.concerns);
      if (items.length < 3) items = uniq(items.concat([
        'Migration may disrupt existing workflows.',
        'Implementation may take too long or need too many internal resources.',
        'Teams may resist switching from existing tools.',
        'Pricing, security, data governance, and integration depth must be clear.']));
      return audListHtml(items.slice(0, 6).map(audSentence), false);
    }
    if (key === 'decision_criteria') {
      // Phrase criteria as what the buyer is evaluating — never bare feature/
      // module names. Wrap each feature in an evaluation clause.
      const clause = (f) => {
        let x = f.toLowerCase().replace(/^the\s+/, '').replace(/\bcrm\b/g, 'CRM').replace(/\bai\b/g, 'AI').trim();
        return 'Whether the platform provides ' + x + ' that fits their workflows';
      };
      let items = uniq((sig.features || []).slice(0, 3).map(clause));
      const base = [
      'Ability to unify customer data across marketing, sales, and service',
      'Integration depth with the existing stack and migration support',
      'Reporting accuracy and pipeline visibility',
      'Workflow automation capabilities',
      'Security, governance, and admin controls',
      'Pricing clarity and scalability as the team grows',
      'Implementation speed and team adoption support'];
      items = uniq(items.concat(base));
      return audListHtml(items.slice(0, 7), false);
    }
    if (key === 'messaging_angles') {
      const items = [];
      if (sig.promise) items.push(audSentence(sig.promise));
      (sig.outcomes || []).slice(0, 3).forEach((o) => items.push(audSentence('Help ' + r + ' ' + o.toLowerCase().replace(/^to\s+/, ''))));
      (sig.use_cases || []).slice(0, 2).forEach((u) => items.push(audSentence(audCapFirst(u))));
      const out = uniq(items).slice(0, 6);
      return out.length >= 4 ? audListHtml(out, false) : audListHtml(uniq(items.concat((sig.pains || []).map((p) => audSentence('Address ' + p.toLowerCase())))).slice(0, 6), false);
    }
    if (key === 'topics') {
      let items = uniq((sig.topics || []).concat(sig.features || [], sig.use_cases || []).map(audCapFirst));
      return items.length >= 6 ? audListHtml(items.slice(0, 10), false) : null;
    }
    if (key === 'writing_rules') {
      const cat = sig.category ? sig.category.toLowerCase() : 'this product category';
      const rules = [
      'Focus on outcomes specific to ' + cat + (sig.outcomes && sig.outcomes.length ? ' such as ' + sig.outcomes.slice(0, 3).join(', ').toLowerCase() : '') + '.',
      (sig.use_cases && sig.use_cases.length ? 'Use concrete examples involving ' + sig.use_cases.slice(0, 3).join(', ').toLowerCase() + '.' : 'Use concrete examples drawn from ' + r + '\u2019s real workflows.'),
      'Connect every benefit to measurable value for ' + r + ', not generic productivity claims.',
      (sig.concerns && sig.concerns.length ? 'Address concerns like ' + sig.concerns.slice(0, 3).join(', ').toLowerCase() + ' directly.' : 'Address implementation, adoption, and pricing concerns directly.'),
      'Back claims with specifics; avoid hype, guarantees, and unsupported timelines.'];
      return audListHtml(rules, true);
    }
    return null;
  }

  /* Terms seen contaminating earlier (document/PDF) tests. In website mode each
     is suspicious ONLY if the live website corpus + summary does not support it
     (some sites really are SEO/content companies). Persona/brand names from the
     PDF test are always contamination in website mode. */
  const AUD_SUSPICIOUS_TERMS = ['seo strategy', 'keyword research', 'blog traffic', 'google ranking',
  'google rankings', 'content consistency', 'organic customer acquisition', 'content topic planning',
  '3 free posts', '30 topics', 'cold outreach', 'testimonial offer', 'free posts'];
  const AUD_ALWAYS_CONTAM = ['alice', 'derek', 'cody', 'rank lyx', 'ranklyx'];
  /* A suspicious term is supported if its key word(s) appear in the corpus/summary. */
  function audTermSupported(term, supportText) {
    const words = term.split(/\s+/).filter((w) => w.length >= 3 && ['the', 'and', 'for', 'with'].indexOf(w) === -1);
    if (!words.length) return false;
    return words.every((w) => supportText.indexOf(w) !== -1);
  }
  /* Returns the contaminated section keys for website mode. */
  function audContaminatedSections(appliedSections, corpus, summary) {
    const support = (String(corpus || '') + ' ' + String(summary || '')).toLowerCase();
    const out = [];
    ICP_SECTIONS.forEach(([k]) => {
      const text = audGenHtmlText((appliedSections[k] || []).join('\n')).toLowerCase();
      if (!text) return;
      let bad = false;
      AUD_ALWAYS_CONTAM.forEach((t) => {if (text.indexOf(t) !== -1) bad = true;});
      if (!bad) AUD_SUSPICIOUS_TERMS.forEach((t) => {
        if (text.indexOf(t) !== -1 && !audTermSupported(t, support)) bad = true;
      });
      if (bad) out.push(k);
    });
    return out;
  }

  /* Cross-section duplication: detect sections that copy Audience Overview or
     heavily overlap another section. Returns { dupSections:[keys], pairs:[..] }. */
  function audNormSentences(text) {
    return String(text || '').toLowerCase().replace(/\s+/g, ' ')
      .split(/(?<=[.!?])\s+/).map((s) => s.replace(/[^a-z0-9 ]/g, '').trim()).filter((s) => s.split(' ').length >= 4);
  }
  function audTextSimilarity(a, b) {
    const wa = new Set(String(a || '').toLowerCase().replace(/[^a-z0-9 ]/g, ' ').split(/\s+/).filter((w) => w.length >= 4));
    const wb = new Set(String(b || '').toLowerCase().replace(/[^a-z0-9 ]/g, ' ').split(/\s+/).filter((w) => w.length >= 4));
    if (!wa.size || !wb.size) return 0;
    let inter = 0;
    wa.forEach((w) => {if (wb.has(w)) inter += 1;});
    return inter / Math.min(wa.size, wb.size);
  }
  function audDuplicateSections(applied) {
    const texts = {};
    ICP_SECTIONS.forEach(([k]) => {texts[k] = audGenHtmlText((applied[k] || []).join('\n'));});
    const keys = ICP_SECTIONS.map(([k]) => k).filter((k) => texts[k] && texts[k].length > 0 && k !== 'writing_rules');
    const dup = new Set();
    const pairs = [];
    for (let i = 0; i < keys.length; i++) {
      for (let j = i + 1; j < keys.length; j++) {
        const a = keys[i], b = keys[j];
        const sa = audNormSentences(texts[a]), sb = audNormSentences(texts[b]);
        const sharedSentences = sa.filter((s) => sb.indexOf(s) !== -1).length;
        const sameStart = sa.length && sb.length && sa[0] === sb[0];
        // Real copying: ≥2 identical full sentences, identical opening sentence,
        // or near-identical text (≥0.72 word overlap). Plain shared domain
        // vocabulary between on-topic sections is NOT flagged (avoids endless
        // rewrites of legitimately related sections).
        const sim = audTextSimilarity(texts[a], texts[b]);
        if (sharedSentences >= 2 || sameStart || sim >= 0.72) {
          pairs.push(a + '~' + b);
          if (a === 'audience_overview') dup.add(b);
          else if (b === 'audience_overview') dup.add(a);
          else {dup.add(a);dup.add(b);}
        }
      }
    }
    return { dupSections: Array.from(dup), pairs };
  }

  /* Per-block (li/p/h3) text units of a section, with their source HTML, so we
     can surgically remove a copied-overview block while keeping good lines. */
  function audSectionUnits(blocks) {
    const div = document.createElement('div');
    div.innerHTML = (blocks || []).join('\n');
    const units = [];
    Array.prototype.slice.call(div.children).forEach((el) => {
      if (el.tagName === 'UL' || el.tagName === 'OL') {
        Array.prototype.slice.call(el.children).forEach((li) => {
          units.push({ tag: 'li', list: el.tagName.toLowerCase(), text: (li.textContent || '').replace(/\s+/g, ' ').trim(), html: li.outerHTML });
        });
      } else {
        units.push({ tag: el.tagName.toLowerCase(), text: (el.textContent || '').replace(/\s+/g, ' ').trim(), html: el.outerHTML });
      }
    });
    return units;
  }
  function audUnitsToHtml(units) {
    let out = '';
    let i = 0;
    while (i < units.length) {
      const u = units[i];
      if (u.tag === 'li') {
        const list = u.list || 'ul';
        let inner = '';
        while (i < units.length && units[i].tag === 'li' && (units[i].list || 'ul') === list) {inner += '<li>' + units[i].text + '</li>\n';i++;}
        out += '<' + list + '>\n' + inner + '</' + list + '>\n';
      } else {out += '<' + u.tag + '>' + u.text + '</' + u.tag + '>\n';i++;}
    }
    return out.trim();
  }
  /* Intra-section contamination: a section (with some valid content) also
     contains sentence(s)/paragraph(s) copied from Audience Overview, or a
     dangling-fragment unit. Removes the offending units, keeps the good ones.
     Returns { blocks, removedOverview, removedFragments } or null if unchanged. */
  function audCleanSectionUnits(blocks, overviewText) {
    const units = audSectionUnits(blocks);
    if (!units.length) return null;
    const ovSents = new Set(audNormSentences(overviewText));
    let removedOverview = 0, removedFragments = 0;
    const kept = units.filter((u) => {
      // Dangling fragment unit.
      if (audIsFragmentLine(u.text)) {removedFragments++;return false;}
      // Paragraph copied/near-copied from overview.
      if (u.tag === 'p' || u.tag === 'h3') {
        const sents = audNormSentences(u.text);
        const shared = sents.filter((s) => ovSents.has(s)).length;
        if (shared >= 1 || (overviewText && audTextSimilarity(u.text, overviewText) >= 0.6 && u.text.split(/\s+/).length >= 12)) {
          removedOverview++;return false;
        }
      } else {
        // A list item that is a whole copied overview sentence.
        if (ovSents.size && audNormSentences(u.text).some((s) => ovSents.has(s))) {removedOverview++;return false;}
      }
      return true;
    });
    if (!removedOverview && !removedFragments) return null;
    return { blocks: audUnitsToHtml(kept).split('\n'), removedOverview, removedFragments };
  }
  /* Does a section read as a bare product feature/module list rather than buyer
     decision criteria? True when most list items are short noun phrases with no
     evaluation verb/reason. */
  const AUD_CRITERIA_VERBS = ['ability', 'whether', 'how', 'support', 'depth', 'accuracy', 'clarity',
  'speed', 'integration', 'security', 'governance', 'pricing', 'cost', 'roi', 'scalab', 'adoption',
  'ease', 'quality', 'visibility', 'reliab', 'compliance', 'fit', 'need', 'must', 'control'];
  const AUD_MODULE_HINT = /\b(hub|agent|module|plan|tier|suite|crm|platform)\b/i;
  function audIsFeatureList(blocks) {
    const units = audSectionUnits(blocks).filter((u) => u.tag === 'li');
    if (units.length < 2) return false;
    let featureish = 0;
    units.forEach((u) => {
      const words = u.text.split(/\s+/).filter(Boolean);
      const low = u.text.toLowerCase();
      const hasCriterionWord = AUD_CRITERIA_VERBS.some((v) => low.indexOf(v) !== -1);
      // Short ( <6 words ) and either a module name or no criterion language.
      if (words.length < 6 && !hasCriterionWord) featureish++;
      else if (AUD_MODULE_HINT.test(u.text) && words.length < 8 && !hasCriterionWord) featureish++;
    });
    return featureish / units.length >= 0.5;
  }

  /* Source-agnostic, draft-derived fallback for a weak list section in website
     mode: builds bullets from THIS ICP's already-generated on-topic sections
     (overview, pains, goals, decision criteria) — never hardcoded examples. */
  function audDraftDerivedList(bodies, fromKeys, min) {
    const lines = [];
    fromKeys.forEach((k) => {
      audBodyLines((bodies[k] || []).join('\n')).forEach((l) => {
        if (!audIsFragmentLine(l.text) && l.text.split(/\s+/).length >= 2) {
          const clean = l.text.replace(/^(they|this icp|the icp)\s+/i, '').replace(/\s+/g, ' ').trim();
          const cap = clean.charAt(0).toUpperCase() + clean.slice(1);
          if (cap && lines.indexOf(cap) === -1) lines.push(cap);
        }
      });
    });
    if (lines.length < Math.max(2, min || 3)) return null;
    return '<ul>\n' + lines.slice(0, Math.max(min || 3, Math.min(lines.length, 8))).map((t) => '<li>' + audEscape(t) + '</li>').join('\n') + '\n</ul>';
  }

  /* Parse the FINAL assembled editor HTML back into per-key section blocks, so
     validation runs on exactly what will be inserted into the editor (not an
     intermediate draft). Splits on the <h2> headings in required order. */
  function audSectionsFromHtml(html) {
    const div = document.createElement('div');
    div.innerHTML = html || '';
    const nodes = Array.prototype.slice.call(div.childNodes);
    const out = {};
    let curKey = null;
    nodes.forEach((node) => {
      if (node.nodeType === 1 && node.tagName === 'H2') {
        const heading = (node.textContent || '').trim();
        const match = ICP_SECTIONS.find(([, h]) => h.toLowerCase() === heading.toLowerCase());
        curKey = match ? match[0] : null;
        if (curKey) out[curKey] = out[curKey] || [];
        return;
      }
      if (curKey && node.nodeType === 1) {(out[curKey] = out[curKey] || []).push(node.outerHTML);}
    });
    return out;
  }

  /* Money/number tokens (e.g. "$100k", "$6,000", "50k", "30k") normalized for
     comparison — used to catch revenue/budget figures that belong to OTHER
     personas leaking into the selected persona's output. */
  function audMoneyTokens(text) {
    const set = new Set();
    const re = /\$?\s?\d[\d,]*\s?k\b|\$\s?\d[\d,]{2,}\b|\b\d[\d,]*k\+?/gi;
    let m;
    while (m = re.exec(String(text || ''))) {
      const tok = m[0].toLowerCase().replace(/[$,\s+]/g, '');
      if (tok && /\d/.test(tok)) set.add(tok);
    }
    return set;
  }
  /* Sections whose text contains a figure unique to an excluded persona. */
  function audSectionsWithExcludedFigures(appliedSections, excludedFigures) {
    if (!excludedFigures || !excludedFigures.size) return [];
    const res = [];
    ICP_SECTIONS.forEach(([k]) => {
      const toks = audMoneyTokens(audGenHtmlText((appliedSections[k] || []).join('\n')));
      let hit = false;
      toks.forEach((t) => {if (excludedFigures.has(t)) hit = true;});
      if (hit) res.push(k);
    });
    return res;
  }

  /* Buying-role conflict: the source frames the persona as a recommender /
     evaluator / champion with a separate (e.g. CEO) final approver, but the
     output upgraded them to sole decision maker / budget owner. */
  function audBuyingRoleConflict(sourceText, outputBody) {
    const src = String(sourceText || '').toLowerCase();
    const out = audGenHtmlText(outputBody || '').toLowerCase();
    if (!out) return false;
    const srcRecommends = /\brecommend|\bsuggest|\bevaluat|\bchampion|\bproposes?\b|\bsubmits?\b/.test(src);
    const srcSeparateApprover = /\b(ceo|cfo|coo|founder|owner|leadership|board|exec\w*)\b[^.]{0,40}\bapprov/.test(src)
      || /\bapprov[^.]{0,40}\b(ceo|cfo|coo|founder|owner|leadership|board)\b/.test(src);
    if (!srcRecommends && !srcSeparateApprover) return false;
    const outSoleDM = /\b(primary|sole|final)\b[^.]{0,30}\bdecision\s*maker\b/.test(out)
      || /\bis the decision\s*maker\b/.test(out) || /\bbudget owner\b/.test(out)
      || /\bowns the budget\b/.test(out) || /\bfinal say\b/.test(out)
      || /\bmakes the final (decision|call)\b/.test(out);
    const outDropsApprover = srcSeparateApprover && !/\b(ceo|cfo|coo|founder|owner|leadership|board|exec\w*)\b/.test(out);
    return outSoleDM || outDropsApprover;
  }

  /* Names the explicit approver role found in the source (e.g. "CEO"), or null. */
  function audDetectApprover(sourceText) {
    const src = String(sourceText || '');
    const m = src.match(/\b(CEO|CFO|COO|founder|owner|board|leadership)\b[^.]{0,40}\bapprov/i)
      || src.match(/\bapprov[^.]{0,40}\b(CEO|CFO|COO|founder|owner|board|leadership)\b/i);
    if (!m) return null;
    const role = (m[1] || '').toUpperCase();
    return ['CEO', 'CFO', 'COO'].indexOf(role) !== -1 ? role : (m[1] || '').replace(/\b\w/g, (c) => c.toUpperCase());
  }
  /* True when the source names an explicit approver but the FINAL output omits
     that approver role — i.e. the explicit source detail was lost. */
  function audBuyingRoleMissingApprover(sourceText, outputBody) {
    const approver = audDetectApprover(sourceText);
    if (!approver) return false;
    const out = audGenHtmlText(outputBody || '');
    if (!out) return true;
    return !new RegExp('\\b' + approver + '\\b', 'i').test(out);
  }
  /* Deterministic, source-faithful Role-in-the-Buying-Process fallback. Uses
     the detected approver + role name; never invents budget ownership. */
  function audBuyingRoleFallback(sourceText, roleName) {
    const approver = audDetectApprover(sourceText) || 'the CEO';
    const role = (roleName && roleName.trim()) ? roleName.trim() : 'The Head of Marketing';
    const subj = /^the\b/i.test(role) ? role : 'The ' + role;
    return '<p>' + audEscape(subj + ' evaluates the content/SEO need, recommends the agency, and acts as the internal champion. ' +
      approver + ' approves the final decision and budget. This means ' + subj.charAt(0).toLowerCase() + subj.slice(1) +
      ' has strong influence over the evaluation, but ' + approver + ' must be convinced before the purchase moves forward.') + '</p>';
  }

  /* ---- Unsupported-claim cleanup (document-only mode) -------------------
     Strips hard claims the model added that the selected persona source never
     states: explicit timelines (60 days, 30/60/90 days, "within N days"),
     "guaranteed", "ranked" as a deliverable modifier, and budget-ownership /
     sole-decision-maker phrasing. Returns { removed:[phrases], changed:bool }. */
  function audCleanUnsupportedClaims(bodies, sourceText) {
    const src = String(sourceText || '').toLowerCase();
    const removed = [];
    const srcHas = (re) => re.test(src);
    // [label, matchRegex, replacement, allowedIfSource]
    const rules = [
    ['within N days', /\s*(?:in|within)\s+\d{1,3}\s*(?:to\s*\d{1,3}\s*)?[-–]?\s*days\b/gi, '', srcHas(/\d{1,3}\s*[-–to ]*\d{0,3}\s*days/)],
    ['30/60/90 days', /\s*(?:30|60|90)\s*[-/]\s*(?:60|90)\s*(?:[-/]\s*90\s*)?days\b/gi, '', srcHas(/(30|60|90)\s*[-/]/)],
    ['guaranteed', /\bguaranteed\b\s*/gi, '', srcHas(/guarantee/)],
    ['ranked (deliverable modifier)', /\branked\s+(topics|posts|articles|content)\b/gi, '$1', srcHas(/ranked\s+(topics|posts|articles|content)/)],
    ['final decision maker', /\b(?:the\s+)?(?:sole|primary|final)\s+decision[\s-]*maker\b/gi, 'internal champion and evaluator', srcHas(/decision[\s-]*maker/)],
    ['primary budget owner', /\b(?:the\s+)?(?:primary|sole)?\s*budget owner\b/gi, 'budget influencer', srcHas(/budget owner/)],
    ['owns the budget', /\bowns the (?:final )?budget\b/gi, 'influences the budget case', srcHas(/owns the (?:final )?budget/)]];
    let changed = false;
    ICP_SECTIONS.forEach(([k]) => {
      let blocks = bodies[k] || [];
      if (!blocks.length) return;
      let joined = blocks.join('\n');
      let touched = false;
      rules.forEach(([label, re, repl, allowed]) => {
        if (allowed) return;
        if (re.test(joined)) {
          joined = joined.replace(re, repl).replace(/\s{2,}/g, ' ').replace(/\s+([.,;:])/g, '$1');
          touched = true;
          if (removed.indexOf(label) === -1) removed.push(label);
        }
      });
      if (touched) {bodies[k] = joined.split('\n');changed = true;}
    });
    return { removed, changed };
  }

  /* Sections whose visible text mentions any of the given (excluded persona)
     names — used to detect cross-persona blending. */
  function audSectionsMentioningNames(bodies, names) {
    if (!names || !names.length) return [];
    const res = [];
    const lowered = names.map((n) => String(n).toLowerCase()).filter((n) => n.length >= 3);
    ICP_SECTIONS.forEach(([k]) => {
      const t = audGenHtmlText((bodies[k] || []).join('\n')).toLowerCase();
      if (lowered.some((n) => new RegExp('\\b' + n.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '\\b').test(t))) res.push(k);
    });
    return res;
  }
  /* Plain-text rendering of the current bodies, for the rewrite prompt's
     "existing draft" reference. */
  function audDraftText(bodies) {
    return ICP_SECTIONS.map(([k, h]) => {
      const t = audGenHtmlText((bodies[k] || []).join('\n'));
      return h + '\n' + (t || '(missing)');
    }).join('\n\n');
  }

  function audNormalizeUrl2(raw) {return /^https?:\/\//i.test((raw || '').trim()) ? (raw || '').trim() : 'https://' + (raw || '').trim();}
  function audTrim(s, n) {s = (s || '').replace(/\n{3,}/g, '\n\n').trim();return s.length > n ? s.slice(0, n) + '…' : s;}

  /* Audience-intent keywords for ICP page discovery / scoring. */
  const ICP_PRIORITY = ['customers', 'case-stud', 'case-studies', 'use-case', 'use-cases', 'usecases',
  'solutions', 'industr', 'teams', 'roles', 'persona', 'personas', 'audience', 'about',
  'product', 'products', 'features', 'platform', 'pricing', 'who-we-serve', 'for-'];
  const ICP_DIRECT_PATHS = ['/customers', '/case-studies', '/use-cases', '/solutions', '/industries',
  '/about', '/product', '/products', '/features', '/platform', '/pricing', '/teams', '/personas'];

  async function audFetchReadable(fullUrl, operation = window.ClicklyxKnowledgeAccess.begin(true)) {
    operation.assert();
    try {
      const txt = await operation.run(() => window.ClicklyxKnowledgeReader.read(fullUrl, operation));
      return txt && txt.trim().length ? txt : null;
    } catch (e) {return null;}
  }
  function audDiscoverPages(markdown, homeFullUrl) {
    let baseHost = '';
    try {baseHost = new URL(homeFullUrl).hostname.replace(/^www\./i, '');} catch (e) {return [];}
    const re = /\[([^\]]*)\]\((https?:\/\/[^)\s]+)\)/g;
    const seen = new Set();
    const out = [];
    let m;
    while (m = re.exec(markdown)) {
      const anchor = (m[1] || '').toLowerCase();
      let u;
      try {u = new URL(m[2]);} catch (e) {continue;}
      if (u.hostname.replace(/^www\./i, '') !== baseHost) continue;
      const path = (u.pathname || '/').replace(/\/+$/, '');
      if (!path) continue;
      if (/\.(png|jpe?g|gif|svg|webp|pdf|zip|css|js|ico|woff2?)$/i.test(path)) continue;
      const clean = u.origin + path;
      if (seen.has(clean)) continue;
      const hay = (path + ' ' + anchor).toLowerCase();
      let score = 0;
      for (const kw of ICP_PRIORITY) if (hay.indexOf(kw) !== -1) score += 1;
      if (score === 0) continue;
      seen.add(clean);
      out.push({ url: clean, score });
    }
    return out;
  }

  /* Crawl a site for audience signals → corpus string (cap ~20k). */
  async function audCrawlWebsite(url, onProgress, operation = window.ClicklyxKnowledgeAccess.begin(true)) {
    operation.assert();
    const full = audNormalizeUrl2(url);
    const tell = (m) => {operation.assert(); if (onProgress) onProgress(m);};
    audSafeDiag('source_read_started', { sourceType: 'website', hasUrl: !!url });
    console.info('[ICPGenerate] readStarted', { hasUrl: !!url });
    tell('Reading website…');
    const home = await audFetchReadable(full, operation);
    operation.assert();
    const homeLen = home ? home.replace(/\s+/g, ' ').trim().length : 0;
    if (homeLen < 300) {
      audSafeDiag('source_read_failed', { sourceType: 'website', issueCode: 'read-home', homeChars: homeLen });
      throw new Error('read-home');
    }

    const discovered = audDiscoverPages(home, full).sort((a, b) => b.score - a.score);
    let origin = full;
    try {origin = new URL(full).origin;} catch (e) {}
    const seen = new Set(discovered.map((d) => d.url));
    const candidates = discovered.slice(0, 6);
    for (const p of ICP_DIRECT_PATHS) {
      if (candidates.length >= 6) break;
      const u = origin + p;
      if (seen.has(u)) continue;
      seen.add(u);
      candidates.push({ url: u, score: 0 });
    }
    const selected = candidates.slice(0, 6);

    const fetchedUrls = [];
    const extracted = [];
    if (selected.length) {
      // Keep access checks sequential; ordinary unreadable pages remain skippable.
      for (const c of selected) {
        const txt = await audFetchReadable(c.url, operation);
        operation.assert();
        if (txt && txt.replace(/\s+/g, ' ').trim().length > 200) {
          extracted.push({ url: c.url, txt });
          fetchedUrls.push(c.url);
        }
      }
    }
    let corpus = 'HOMEPAGE:\n' + audTrim(home, 4000);
    for (const e of extracted) {
      let path = e.url;
      try {path = new URL(e.url).pathname;} catch (x) {}
      corpus += '\n\n----\nPAGE (' + path + '):\n' + audTrim(e.txt, 2600);
    }
    corpus = audTrim(corpus, 20000);
    console.info('[ICPGenerate] readCompleted', { fetchedPageCount: fetchedUrls.length, websiteCorpusChars: corpus.length });
    audSafeDiag('source_read_succeeded', { sourceType: 'website', fetchedPageCount: fetchedUrls.length, sourceChars: corpus.length });
    return corpus;
  }

  /* Pull readable text out of a saved Brand/Product knowledge object. */
  function audKnowledgeText(obj, cap) {
    if (!obj) return '';
    let s = '';
    if (typeof obj.brandName === 'string') s += obj.brandName + '\n';
    if (typeof obj.details === 'string') {
      /* Drop unchanged Brand Profile / Product Knowledge starter prompts so
         default writing guidance never pollutes the knowledge context
         (user-written content, including edited prompts, is kept). Both strips
         are safe to chain — each only removes its own exact-match helper text. */
      let details = obj.details;
      if (typeof window.bpStripTemplateHelpers === 'function') details = window.bpStripTemplateHelpers(details);
      if (typeof window.pkStripTemplateHelpers === 'function') details = window.pkStripTemplateHelpers(details);
      s += audGenHtmlText(details);
    }
    s = s.replace(/\s+/g, ' ').trim();
    return s.length > (cap || 4000) ? s.slice(0, cap || 4000) + '…' : s;
  }

  /* Build the generation prompt. PLAIN STRUCTURED TEXT only — no JSON/HTML. */
  function audBuildPrompt(ctx) {
    const headings = 'ICP Name / Role\nAudience Overview\nRole in the Buying Process\nPain Points\n' +
      'Goals / Desired Outcomes\nBuying Triggers\nObjections / Concerns\nDecision Criteria\n' +
      'Awareness Level\nMessaging Angles\nTopics They Care About\nAudience Writing Rules';
    let p = 'You are an expert B2B audience and ICP strategist helping build an internal ICP ' +
      'knowledge card. This card defines ONE Ideal Customer Profile — a single PERSON, ROLE, or ' +
      'BUYER PROFILE (for example: Head of Marketing, VP Sales, RevOps Manager, SaaS Founder, ' +
      'Customer Support Leader, Operations Manager). It will be used by future AI writing agents ' +
      'to decide who each article, section, example, pain point, and product mention should speak ' +
      'to.\n\n';
    p += 'CRITICAL: The ICP must be a person or role, NOT a company. Do NOT make the ICP about ' +
      'company size, industry, revenue, or firmographics. Never name the ICP something like ' +
      '"B2B SaaS companies", "Mid-market businesses", "Enterprise teams", "Agencies", or ' +
      '"Startups". The ICP Name / Role must be a human role. It is fine to mention company context ' +
      'inside the details, but the profile itself is a person.\n\n';

    if (ctx.sourceMode === 'document') {
      p += 'SOURCE PRIORITY (strict, in this order):\n' +
        '1) The uploaded / pasted ICP document (PRIMARY SOURCE OF TRUTH)\n' +
        '2) The user extra instructions\n' +
        '3) Saved Brand Profile (gap-fill only)\n' +
        '4) Saved Product Knowledge (gap-fill only)\n' +
        (ctx.websiteCorpus ? '5) Optional website context (gap-fill only)\n' : '') + '\n';
      p += 'Important: The uploaded ICP document is the main source. Preserve its company/product ' +
        'context unless the user explicitly asks you to adapt it to saved Brand/Product Knowledge. If ' +
        'the uploaded document and saved knowledge appear to reference different companies or products, ' +
        'PREFER THE UPLOADED DOCUMENT. Use saved Brand Profile and Product Knowledge only to fill ' +
        'missing details, not to replace the uploaded document’s context.\n\n';
      p += 'Do not inject product names, company names, features, or positioning from saved Product ' +
        'Knowledge unless they are needed to fill a genuinely missing section or the user explicitly ' +
        'asked you to adapt the document.\n\n';
      p += 'STAY CLOSE TO THE UPLOADED DOCUMENT. You may infer missing sections from the role, pains, ' +
        'goals, triggers, objections, and decision criteria, but do NOT add specific details like team ' +
        'size, reporting structure, named tools, budget ranges, or exact company stage unless they ' +
        'appear in the uploaded document or the user explicitly asks for that level of expansion. When ' +
        'filling gaps, use careful role-based inference — do not make the ICP feel like a different ' +
        'document. For example, it is fine to infer topics like campaign ROI, pipeline reporting, and ' +
        'marketing attribution from a Head of Marketing who struggles to prove ROI; it is NOT fine to ' +
        'state they report to the CMO, manage 3–20+ people, use tools like Asana/Monday/Jira, or are ' +
        'mid-market/enterprise unless the document says so.\n\n';
      if (ctx.adaptationRequested) {
        p += 'NOTE: The user HAS explicitly asked to adapt this ICP to saved Brand/Product Knowledge — ' +
          'you may align the company/product context accordingly while keeping the person/role and the ' +
          'document’s audience insight intact.\n\n';
      } else {
        p += 'NOTE: The user has NOT asked to adapt the ICP — keep the uploaded document’s own ' +
          'company/product context. Do not substitute a different company or product.\n\n';
        if (ctx.hasContextConflict) {
          p += 'CONTEXT CONFLICT DETECTED: the uploaded document and saved knowledge seem to mention ' +
            'different companies/products. Follow the uploaded document; treat saved knowledge as ' +
            'gap-fill only and do not introduce its company/product names.\n\n';
        }
      }
      if (ctx.selectedPersona) {
        const sp = ctx.selectedPersona;
        p += 'MULTIPLE PERSONAS DETECTED. Use ONLY the selected persona below' +
          (sp.name ? ' (' + sp.name + (sp.page ? ', page ' + sp.page : '') + ')' : '') + '. ' +
          (ctx.excludedPersonaNames && ctx.excludedPersonaNames.length
            ? 'Do NOT use these other personas or any of their details: ' + ctx.excludedPersonaNames.join(', ') + '. '
            : '') +
          'When the document contains multiple personas, use only the selected persona. Do not blend ' +
          'details from other personas. Do not merge revenue ranges, SEO budgets, traffic numbers, ' +
          'titles, examples, or personal details across personas. If a detail appears only in another ' +
          'persona, do not use it for the selected persona.\n\n';
      } else {
        p += 'If the document already contains an ICP or persona, EXTRACT and ORGANIZE that ICP — do ' +
          'not invent a different one. If it contains multiple ICPs and the user gave no instruction, ' +
          'use the FIRST actual persona only and do not blend personas. Produce ONLY ONE ICP card.\n\n';
      }
      if (ctx.documentOnly) {
        p += 'DOCUMENT-ONLY MODE: do not use any website, saved Brand Profile, or saved Product ' +
          'Knowledge. Still fill missing sections using CONTROLLED INFERENCE from the selected ' +
          'persona’s own content — its company description, persona description, challenges, goals, ' +
          'offer, website elements, buying roles, and customer journey. Only write "Not clearly found. ' +
          'Please add this manually." when the document truly lacks enough to infer a useful section.\n\n';
      } else {
        p += 'GAP FILLING: where a required section is missing from the document, fill it in this ' +
          'order — (a) careful inference from the selected persona’s own content, (b) the user extra ' +
          'instructions, (c) saved Brand/Product Knowledge ONLY if it does not conflict with the ' +
          'document, (d) optional website context if provided. Only write "Not clearly found. Please ' +
          'add this manually." when there is genuinely not enough information to infer a useful ' +
          'section.\n\n';
      }
      p += 'INFERENCE EXAMPLES: if the persona struggles to produce content, their blog does not drive ' +
        'traffic or rank, and they want more traffic and customers — Messaging Angles can be inferred ' +
        '(e.g. consistent content production, ranking for important keywords, turning the blog into a ' +
        'lead source) and Topics They Care About can be inferred (e.g. SEO strategy, keyword research, ' +
        'blog traffic, lead generation, content ROI). Do not leave Messaging Angles or Topics empty ' +
        'when the persona’s challenges and goals make them inferable.\n\n';
      if (ctx.detectedDocSections && ctx.detectedDocSections.length) {
        const names = ctx.detectedDocSections.map((k) => ICP_HEADING_BY_KEY[k]).filter(Boolean);
        if (names.length) p += 'The document appears to already cover: ' + names.join(', ') +
          '. Use the document’s own content for these — do not mark them missing.\n\n';
      }
      if (ctx.docCompanies && ctx.docCompanies.length && !ctx.adaptationRequested) {
        p += 'The uploaded document references these company/product names: ' + ctx.docCompanies.join(', ') +
          '. Keep them where they naturally fit (for example in Pain Points, Goals, Decision Criteria, ' +
          'or Topics) and do NOT replace them with company/product names from saved knowledge.\n\n';
      }
      p += 'NAME THE ICP BY ROLE, not by the persona’s personal name. Prefer a role such as ' +
        '"Head of Marketing / Marketing Director" or "Marketing Director". Keep company size and ' +
        'demographics inside Audience Overview, not in the role name. Only use a personal name if the ' +
        'document gives no role at all.\n\n';
      p += 'PRESERVE EXPLICIT BUYING ROLES. If the document contains explicit buying-role information, ' +
        'preserve it exactly. Do NOT upgrade a recommender, evaluator, or champion into a final ' +
        'decision maker or budget owner unless the document says so. If the document says one person ' +
        'recommends and another (e.g. a CEO) approves, keep BOTH roles. Example of the right framing: ' +
        '"The Head of Marketing recommends the agency, evaluates the offer, and acts as the internal ' +
        'champion. The CEO approves the final decision and budget." Do not write "she is the primary ' +
        'decision maker and budget owner" when the document only says she recommends.\n\n';
      p += 'REDUCE UNSUPPORTED CERTAINTY. Do not assert "guaranteed ROI", "guaranteed results", ' +
        '"primary budget owner", "final decision maker", or hard timelines like "must prove within ' +
        '60–90 days" unless the selected persona source states them. Prefer supported framings such as ' +
        '"needs proof", "wants early evidence", "needs a low-risk way to evaluate the offer", ' +
        '"CEO approval matters", or "budget must be justified".\n\n';
      p += (ctx.selectedPersona ? 'SELECTED PERSONA (primary source):\n' + audTrim(ctx.documentText, 18000) + '\n\n'
        : 'UPLOADED ICP DOCUMENT (primary source):\n' + audTrim(ctx.documentText, 22000) + '\n\n');
      if (ctx.globalContext) p += 'SHARED / GLOBAL DOCUMENT CONTEXT (use only if clearly global):\n' + audTrim(ctx.globalContext, 5000) + '\n\n';
      if (ctx.extra) p += 'USER EXTRA INSTRUCTIONS (follow closely):\n' + ctx.extra + '\n\n';
      if (ctx.brandText) p += 'SAVED BRAND PROFILE (gap-fill only):\n' + ctx.brandText + '\n\n';
      if (ctx.productText) p += 'SAVED PRODUCT KNOWLEDGE (gap-fill only — do not impose its company/product on the ICP):\n' + ctx.productText + '\n\n';
      if (ctx.websiteCorpus) p += 'OPTIONAL WEBSITE CONTEXT (gap-fill only):\n' + audTrim(ctx.websiteCorpus, 8000) + '\n\n';
    } else {
      p += 'PRIMARY SOURCE — the company website text below. Infer the most important ICP this company ' +
        'sells to, prioritizing audience, customers, use cases, roles, and industries signals.\n\n';
      if (ctx.websiteSummary) {
        p += 'WEBSITE SOURCE SUMMARY (anchor EVERY section to this; do not drift into unrelated ' +
          'topics). Every section — Pain Points, Goals, Buying Triggers, Objections, Decision Criteria, ' +
          'Messaging Angles, Topics They Care About, and Audience Writing Rules — must stay within the ' +
          'world described here:\n' + ctx.websiteSummary + '\n\n';
      }
      p += 'WEBSITE:\n' + audTrim(ctx.websiteCorpus, 20000) + '\n\n';
      p += 'IMPORTANT: use ONLY this website (and any saved knowledge below) as the source. Do not ' +
        'introduce SEO/content-marketing, blog, keyword, cold-outreach, or persona examples unless this ' +
        'specific website is actually about them.\n\n';
      if (ctx.brandText) p += 'SAVED BRAND PROFILE (supporting context):\n' + ctx.brandText + '\n\n';
      if (ctx.productText) p += 'SAVED PRODUCT KNOWLEDGE (supporting context):\n' + ctx.productText + '\n\n';
      if (ctx.extra) p += 'USER EXTRA INSTRUCTIONS (follow these closely):\n' + ctx.extra + '\n\n';
    }

    p += 'Return PLAIN STRUCTURED TEXT only. Do NOT return JSON. Do NOT return HTML. Do NOT use code ' +
      'fences. Use EXACTLY these section headings, each on its own line, in this order:\n' + headings + '\n\n';
    p += 'Formatting rules:\n' +
      '- After "ICP Name / Role", put the short role name on the next line (e.g. "Head of Marketing").\n' +
      '- Audience Overview: 2 to 3 short paragraphs on who this person is, what they are responsible ' +
      'for, and why they matter to the buying process.\n' +
      '- Role in the Buying Process: state whether they are the decision maker, budget owner, ' +
      'influencer, user, evaluator, internal champion, or blocker, and explain briefly.\n' +
      '- Pain Points, Goals / Desired Outcomes, Buying Triggers, Objections / Concerns, Decision ' +
      'Criteria, Messaging Angles, Topics They Care About: use bullet lines (one per line, starting ' +
      'with "- ") whenever possible.\n' +
      '- Awareness Level: state whether they are problem-aware, solution-aware, product-aware, or ' +
      'ready to buy, and explain briefly.\n' +
      '- Audience Writing Rules: ALWAYS a numbered list (1. 2. 3.), 3 to 6 concrete rules guiding ' +
      'future AI writing for this ICP.\n\n';
    p += 'Quality: be practical and specific. Use concrete pains, goals, objections, and decision ' +
      'criteria. Avoid vague filler like "wants to save time". Do not overuse buzzwords. Write every ' +
      'section; only when there is genuinely no supporting basis, write the single line "Not clearly ' +
      'found. Please add this manually." for that section. Output ALL headings in order, every time.\n\n';
    p += 'VOICE: write this as internal knowledge ABOUT the ICP, in the THIRD PERSON. Use "This ICP…", ' +
      '"The Head of Marketing…", or "They…". Do NOT address the reader as "You are…" or "Your ' +
      'company…" — this document is internal knowledge for the AI, not copy written to the persona.';
    return p;
  }

  /* Targeted rewrite prompt — regenerate ONLY the weak/incomplete sections,
     keeping the same strict source priority. */
  function audBuildRewritePrompt(ctx, weakKeys) {
    const headingList = weakKeys.map((k) => ICP_HEADING_BY_KEY[k]).join('\n');
    let p = 'You previously drafted an internal ICP knowledge card. These sections are weak, ' +
      'incomplete, or cut off and must be rewritten: ' + weakKeys.map((k) => ICP_HEADING_BY_KEY[k]).join(', ') + '.\n\n';
    p += 'Rewrite ONLY these sections. Use the EXACT headings below, each on its own line, in this ' +
      'order:\n' + headingList + '\n\n';
    p += 'Do not repeat or include any other sections. Do NOT return JSON, HTML, or code fences. ' +
      'Be specific and complete. The previous version of these sections appears incomplete or cut ' +
      'off — rewrite each with COMPLETE lines only and do NOT include any trailing fragments or ' +
      'unfinished sentences. Never end a section on a lone word like "Reduce" or "Connect".\n\n';
    p += 'CRITICAL: each section must be SECTION-SPECIFIC. Do NOT copy the Audience Overview into ' +
      'these sections, and do not reuse the same sentences across sections. Section meanings:\n' +
      '- Goals / Desired Outcomes = the outcomes this ICP wants to achieve.\n' +
      '- Buying Triggers = events or situations that make this ICP start looking for the product.\n' +
      '- Objections / Concerns = concerns this ICP has before buying.\n' +
      '- Decision Criteria = what this ICP compares/evaluates when choosing.\n' +
      '- Awareness Level = how aware this ICP is of the problem, the solution category, and the ' +
      'product (problem-aware / solution-aware / product-aware / ready to buy), explained briefly.\n' +
      '- Messaging Angles = positioning angles for selling the product to this ICP.\n' +
      '- Topics They Care About = topics/themes this ICP cares about.\n' +
      '- Audience Writing Rules = writing guidance for future AI content for this ICP.\n\n';
    if (weakKeys.indexOf('messaging_angles') !== -1) {
      p += 'Messaging Angles: give 4 to 6 complete messaging angles, each as one complete line ' +
        'starting with "- ". No fragments, no unfinished sentence.\n\n';
    }
    if (weakKeys.indexOf('topics') !== -1) {
      p += 'Topics They Care About: give at least 6 COMPLETE topic lines starting with "- ", inferred ' +
        'from the role, pains, goals, triggers, and objections. Each must be a complete topic phrase ' +
        '(e.g. "On-page and technical SEO", not "On-page and technical").\n\n';
    }
    if (weakKeys.indexOf('buying_role') !== -1) {
      p += 'Role in the Buying Process: preserve the document’s explicit buying roles exactly. If the ' +
        'document says this person recommends/evaluates/champions and a separate person (e.g. the CEO) ' +
        'approves the final decision and budget, keep BOTH. Do NOT call this person the sole/primary ' +
        'decision maker or budget owner unless the document says so.\n\n';
    }
    if (ctx.sourceMode === 'document') {
      if (ctx.selectedPersona) {
        p += 'Use ONLY the selected persona below as the source' +
          (ctx.selectedPersona.name ? ' (' + ctx.selectedPersona.name + ')' : '') + '. ' +
          (ctx.excludedPersonaNames && ctx.excludedPersonaNames.length
            ? 'Do NOT use these other personas or any of their details: ' + ctx.excludedPersonaNames.join(', ') + '. '
            : '') +
          'Do not blend revenue ranges, SEO budgets, traffic numbers, titles, or examples across ' +
          'personas. If a detail appears only in another persona, do not use it.\n\n';
      }
      p += 'SOURCE PRIORITY (strict): 1) the uploaded ICP document, 2) the user extra instructions' +
        (ctx.documentOnly ? '. Do NOT use website or saved knowledge (document-only mode); still ' +
          'infer missing sections from the selected persona’s own content.' :
          ', 3) saved Brand Profile, 4) saved Product Knowledge' + (ctx.websiteCorpus ? ', 5) optional website context' : '') + '.') +
        ' The uploaded document is the PRIMARY source — preserve its company/product context. Do not ' +
        'inject company or product names from saved knowledge unless filling a genuinely missing ' +
        'detail or the user explicitly asked to adapt.\n\n';
      if (!ctx.adaptationRequested && ctx.hasContextConflict) {
        p += 'The document and saved knowledge reference different companies/products — follow the ' +
          'document and do not introduce saved knowledge’s company/product names.\n\n';
      }
      p += (ctx.selectedPersona ? 'SELECTED PERSONA (primary source):\n' : 'UPLOADED ICP DOCUMENT (primary source):\n') + audTrim(ctx.documentText, 16000) + '\n\n';
      if (ctx.globalContext) p += 'SHARED / GLOBAL DOCUMENT CONTEXT (use only if clearly global):\n' + audTrim(ctx.globalContext, 4000) + '\n\n';
    } else {
      p += 'Use the company website text as the primary source.\n';
      if (ctx.websiteSummary) p += 'WEBSITE SOURCE SUMMARY (anchor every rewritten section to this; do not drift):\n' + ctx.websiteSummary + '\n\n';
      p += 'WEBSITE:\n' + audTrim(ctx.websiteCorpus, 12000) + '\n\n' +
        'Do not introduce SEO/content, blog, keyword, cold-outreach, persona, or document examples ' +
        'unless this specific website is actually about them.\n\n';
    }
    p += 'EXISTING DRAFT (for reference; rewrite only the listed sections):\n' + ctx.existingDraftText + '\n\n';
    if (ctx.extra) p += 'USER EXTRA INSTRUCTIONS:\n' + ctx.extra + '\n\n';
    if (ctx.brandText) p += 'SAVED BRAND PROFILE (gap-fill only):\n' + ctx.brandText + '\n\n';
    if (ctx.productText) p += 'SAVED PRODUCT KNOWLEDGE (gap-fill only):\n' + ctx.productText + '\n\n';
    if (weakKeys.indexOf('writing_rules') !== -1) {
      p += 'Audience Writing Rules MUST be a numbered list (1. 2. 3. 4.) with at least 4 concrete, ' +
        'practical rules guiding future AI writing for this ICP.\n';
    }
    p += 'For list-style sections (Pain Points, Goals / Desired Outcomes, Buying Triggers, ' +
      'Objections / Concerns, Decision Criteria, Messaging Angles, Topics They Care About) use bullet ' +
      'lines starting with "- ". Write in the THIRD PERSON ("This ICP…", "They…"), never "You…".';
    return p;
  }

  /* Full per-card generation. Returns { name, html, detected, missing }. */
  async function audGenerateIcp(payload, onProgress, operation = window.ClicklyxKnowledgeAccess.begin(true)) {
    operation.assert();
    const tell = (m) => {operation.assert(); if (onProgress) onProgress(m);};
    const brand = payload.savedBrandProfile || null;
    const product = payload.savedProductKnowledge || null;
    const brandText = audKnowledgeText(brand, 3500);
    const productText = audKnowledgeText(product, 3500);
    console.info('[ICPGenerate] generationStarted', {
      sourceMode: payload.sourceMode, hasBrandProfile: !!brand, hasProductKnowledge: !!product,
      brandProfileIsEmpty: !audGenHtmlText(brandText), productKnowledgeIsEmpty: !audGenHtmlText(productText),
      websiteCorpusChars: 0,
      hasExtraInstructions: !!(payload.extraInstructions && payload.extraInstructions.trim())
    });

    let websiteCorpus = '';
    let documentText = '';
    let websiteSummary = '';
    if (payload.sourceMode === 'website') {
      // WEBSITE MODE: ignore any document/persona payload entirely — only the
      // live website corpus (+ relevant saved knowledge) may be used.
      websiteCorpus = await audCrawlWebsite(payload.websiteUrl, tell, operation);
      if (audGenHtmlText(websiteCorpus).length < 400) {
        audSafeDiag('source_read_failed', { sourceType: 'website', issueCode: 'read-corpus', sourceChars: audGenHtmlText(websiteCorpus).length });
        throw new Error('read-corpus');
      }
      tell('Reviewing the website…');
      websiteSummary = await audBuildWebsiteSummary(websiteCorpus, (payload.extraInstructions || '').trim(), operation);
      console.info('[ICPGenerate] websiteSourceSummaryCreated', { websiteSourceSummaryCreated: !!websiteSummary, websiteSourceSummaryChars: websiteSummary.length });
      console.info('[ICPGenerate] documentTextIgnoredForWebsiteMode', { documentTextIgnoredForWebsiteMode: true });
      console.info('[ICPGenerate] selectedPersonaIgnoredForWebsiteMode', { selectedPersonaIgnoredForWebsiteMode: true });
      console.info('[ICPGenerate] previousDocumentStateCleared', { previousDocumentStateCleared: true });
      tell('Reviewing saved knowledge…');
    } else {
      tell('Reading ICP source…');
      documentText = String(payload.documentText || '');
      audSafeDiag('source_read_started', { sourceType: 'document', documentName: payload.documentName || null });
      console.info('[ICPGenerate] documentChars', { documentChars: documentText.length });
      if (documentText.replace(/\s+/g, ' ').trim().length < AUD_MIN_DOC_CHARS) {
        audSafeDiag('source_read_failed', { sourceType: 'document', issueCode: 'thin-doc', sourceChars: documentText.length });
        throw new Error('thin-doc');
      }
      audSafeDiag('source_read_succeeded', { sourceType: 'document', sourceChars: documentText.length });
      if (payload.useWebsiteAndSavedKnowledgeForGaps && payload.websiteUrlForGaps) {
        try {websiteCorpus = await audCrawlWebsite(payload.websiteUrlForGaps, tell, operation);} catch (e) {websiteCorpus = '';}
      }
      tell('Reviewing saved knowledge…');
    }

    const extra = (payload.extraInstructions || '').trim();
    const isDoc = payload.sourceMode === 'document';
    const isWebsite = payload.sourceMode === 'website';
    const documentOnly = isDoc && !payload.useWebsiteAndSavedKnowledgeForGaps;
    const gapFillMode = documentOnly ? 'document-only' : 'document-plus-saved-knowledge';
    // Document-only mode: do not feed saved knowledge or website context (but
    // STILL infer missing sections from the document — handled in the prompt).
    const effBrandText = documentOnly ? '' : brandText;
    const effProductText = documentOnly ? '' : productText;
    const effWebsiteCorpus = documentOnly ? '' : websiteCorpus;

    // --- Multi-persona detection + selection (document mode) -------------
    let selectedPersona = null;
    let excludedPersonaNames = [];
    let excludedFigures = new Set();   // money/number tokens unique to OTHER personas
    let globalContext = '';
    let documentForPrompt = documentText;
    if (isDoc) {
      const det = audDetectPersonas(documentText);
      console.info('[ICPGenerate] pdfPagesExtracted', { pdfPagesExtracted: audSplitPages(documentText).length });
      if (det.personas.length >= 2) {
        const sel = audSelectPersona(det.personas, extra);
        selectedPersona = sel ? { name: sel.name, page: sel.page } : null;
        excludedPersonaNames = det.personas.filter((pp) => pp !== sel && pp.name).map((pp) => pp.name);
        globalContext = det.globals.map((g) => g.text).join('\n\n');
        documentForPrompt = sel ? sel.text : documentText;
        // Figures (e.g. $100k, $6,000) that appear ONLY in the other personas —
        // used to catch revenue/budget-range blending in the final output.
        if (sel) {
          const selFigs = audMoneyTokens(sel.text);
          const exclFigs = new Set();
          det.personas.filter((pp) => pp !== sel).forEach((pp) => {
            audMoneyTokens(pp.text).forEach((f) => {if (!selFigs.has(f)) exclFigs.add(f);});
          });
          excludedFigures = exclFigs;
        }
        console.info('[ICPGenerate] persona ' + JSON.stringify({
          detectedPersonaCount: det.personas.length,
          detectedPersonaNames: det.personas.map((pp) => pp.name || '(unnamed)'),
          detectedPersonaPages: det.personas.map((pp) => pp.page),
          selectedPersonaName: sel ? (sel.name || '(unnamed)') : null,
          selectedPersonaPage: sel ? sel.page : null,
          excludedPersonaNames: excludedPersonaNames,
          selectedPersonaSourceChars: sel ? sel.text.length : 0
        }));
      } else {
        console.info('[ICPGenerate] persona ' + JSON.stringify({ detectedPersonaCount: det.personas.length }));
      }
    }

    // --- Document context detection (safe metadata only) -----------------
    const docCompanies = isDoc ? audDetectCompanies(documentForPrompt) : [];
    const docRoles = isDoc ? audDetectRoles(documentForPrompt) : [];
    const savedCompanies = documentOnly ? [] : audDetectCompanies(
      (brand && brand.brandName ? brand.brandName + ' ' : '') + brandText + ' ' + productText);
    const adaptationRequested = isDoc ? audDetectAdaptation(extra) : false;
    const lowerDoc = new Set(docCompanies.map((c) => c.toLowerCase()));
    const overlap = savedCompanies.some((c) => lowerDoc.has(c.toLowerCase()));
    const hasContextConflict = isDoc && !documentOnly && docCompanies.length > 0 && savedCompanies.length > 0 && !overlap;
    const detectedDocSections = isDoc ? audDetectDocSections(documentForPrompt) : [];
    const missingDocumentSections = isDoc
      ? ICP_SECTIONS.map(([k]) => k).filter((k) => detectedDocSections.indexOf(k) === -1) : [];

    if (isDoc) console.info('[ICPGenerate] documentContext', {
      detectedDocumentSections: detectedDocSections,
      missingDocumentSections: missingDocumentSections,
      documentCompanyCandidates: docCompanies,
      documentRoleCandidates: docRoles,
      savedKnowledgeCompanyCandidates: savedCompanies,
      hasContextConflict: hasContextConflict,
      adaptationRequested: adaptationRequested,
      gapFillMode: gapFillMode,
      documentPrimarySourceUsed: true
    });

    const promptCtx = {
      sourceMode: payload.sourceMode, websiteCorpus: effWebsiteCorpus, documentText: documentForPrompt,
      brandText: effBrandText, productText: effProductText, extra, websiteSummary,
      detectedDocSections, hasContextConflict, adaptationRequested, docCompanies,
      selectedPersona, excludedPersonaNames, globalContext, documentOnly
    };
    const prompt = audBuildPrompt(promptCtx);

    tell('Creating ICP draft…');
    console.info('[ICPGenerate] aiCallStarted', { sourceMode: payload.sourceMode, promptChars: prompt.length });
    let raw;
    try {
      raw = await audCallIcpLLM(prompt, 'icp_draft', operation);
    } catch (e) {
      console.warn('[ICPGenerate] generationFailed', { stage: 'ai-call' });
      throw new Error('ai-failed');
    }
    const rawLen = raw ? String(raw).trim().length : 0;
    console.info('[ICPGenerate] aiCallCompleted', { aiRawChars: rawLen });
    if (!rawLen) throw new Error('ai-empty');

    const parsed = audParseIcp(raw);
    if (!parsed) {
      audSafeDiag('response_parse_failed', { sourceMode: payload.sourceMode, responseFormat: typeof raw, responseChars: rawLen });
      console.warn('[ICPGenerate] generationFailed', { stage: 'output' });
      throw new Error('parse-failed');
    }
    const bodies = parsed.bodies;
    audSafeDiag('generation_request_succeeded', {
      stage: 'icp_draft_parsed',
      sourceMode: payload.sourceMode,
      responseFormat: typeof raw,
      detectedSectionCount: parsed.detected.length,
      missingSectionCount: parsed.missing.length
    });
    console.info('[ICPGenerate] detectedSections', { detected: parsed.detected });
    console.info('[ICPGenerate] missingSections', { missing: parsed.missing });

    // Strip clearly-fragmentary trailing lines (e.g. a dangling "Reduce")
    // BEFORE weak detection, so the rewrite repairs the section cleanly.
    const trailingFragmentsRemoved = audStripTrailingFragments(bodies);
    console.info('[ICPGenerate] trailingFragmentsRemoved', { trailingFragmentsRemoved: trailingFragmentsRemoved });

    // Shared rewrite helper — regenerate ONLY the given weak sections, merge in
    // any non-empty results. Returns the detected sections from the pass.
    const rewriteCtx = {
      sourceMode: payload.sourceMode, websiteCorpus: effWebsiteCorpus, documentText: documentForPrompt,
      brandText: effBrandText, productText: effProductText, extra, websiteSummary,
      hasContextConflict, adaptationRequested,
      selectedPersona, excludedPersonaNames, globalContext, documentOnly
    };
    const runRewrite = async (weakKeys) => {
      operation.assert();
      const rwPrompt = audBuildRewritePrompt(Object.assign({}, rewriteCtx, { existingDraftText: audDraftText(bodies) }), weakKeys);
      let raw2 = null;
      try {raw2 = await audCallIcpLLM(rwPrompt, 'icp_rewrite', operation);} catch (e) {raw2 = null;}
      operation.assert();
      if (!raw2) return [];
      const rw = audParseIcp(raw2);
      if (!rw) return [];
      weakKeys.forEach((k) => {
        let nbBlocks = rw.bodies[k] || [];
        const stripped = audStripTrailingFragment(nbBlocks);
        nbBlocks = stripped.blocks;
        if (audGenHtmlText(nbBlocks.join('\n')).length === 0) return;
        // For list-min sections, keep whichever version has more useful lines
        // so a thinner rewrite never downgrades a stronger original.
        if (AUD_MIN_LINES[k]) {
          const oldCount = audUsefulLineCount((bodies[k] || []).join('\n'));
          const newCount = audUsefulLineCount(nbBlocks.join('\n'));
          if (newCount >= oldCount) bodies[k] = nbBlocks;
        } else {
          bodies[k] = nbBlocks;
        }
      });
      return rw.detected.filter((k) => weakKeys.indexOf(k) !== -1);
    };

    // --- Quality validation + up to ONE targeted rewrite pass --------------
    // Cross-persona blending: any section mentioning an EXCLUDED persona name
    // is forced into the rewrite set (rewrite uses only the selected persona).
    const blendSections = audSectionsMentioningNames(bodies, excludedPersonaNames);
    const crossPersonaBlendDetected = blendSections.length > 0;
    console.info('[ICPGenerate] crossPersonaBlend', { crossPersonaBlendDetected: crossPersonaBlendDetected, blendSections: blendSections });
    // Buying-role faithfulness: source frames the persona as recommender +
    // separate approver, but output upgraded them to sole decision maker.
    const explicitBuyingRolesDetected = isDoc && !!audDetectApprover(documentForPrompt);
    console.info('[ICPGenerate] explicitBuyingRolesDetected', { explicitBuyingRolesDetected: explicitBuyingRolesDetected });
    const buyingRoleConflictDetected = isDoc && (
      audBuyingRoleConflict(documentForPrompt, (bodies['buying_role'] || []).join('\n')) ||
      audBuyingRoleMissingApprover(documentForPrompt, (bodies['buying_role'] || []).join('\n')));
    console.info('[ICPGenerate] buyingRoleConflictDetected', { buyingRoleConflictDetected: buyingRoleConflictDetected });
    const initialWeak = Array.from(new Set(
      audWeakSections(bodies).concat(blendSections).concat(buyingRoleConflictDetected ? ['buying_role'] : [])));
    console.info('[ICPGenerate] weakSectionsBeforeRewrite', { weakSectionsBeforeRewrite: initialWeak });
    console.info('[ICPGenerate] initialWeakSections', { initialWeakSections: initialWeak });
    let rewriteRan = false;
    if (initialWeak.length) {
      tell('Improving the draft…');
      if (buyingRoleConflictDetected) console.info('[ICPGenerate] buyingRoleRewriteStarted', { buyingRoleRewriteStarted: true });
      console.info('[ICPGenerate] qualityRewriteStarted', { qualityRewriteRequestedSections: initialWeak });
      const rwDetected = await runRewrite(initialWeak);
      rewriteRan = true;
      console.info('[ICPGenerate] qualityRewriteCompleted', { qualityRewriteDetectedSections: rwDetected });
      // Clean any new trailing fragments the rewrite may have introduced.
      audStripTrailingFragments(bodies);
    }

    // --- Final quality gate -----------------------------------------------
    const buildEffective = () => {
      const eff = {};
      ICP_SECTIONS.forEach(([k]) => {eff[k] = bodies[k];});
      const wrBody = (bodies['writing_rules'] || []).join('\n').trim();
      eff['writing_rules'] = [wrBody ? (audCoerceWritingRulesToOl(wrBody) || audDefaultWritingRulesHtml()) : audDefaultWritingRulesHtml()];
      return eff;
    };
    const stillWeakSet = () => {
      const set = new Set(audWeakSections(buildEffective()));
      if (isDoc && (audBuyingRoleConflict(documentForPrompt, (bodies['buying_role'] || []).join('\n')) ||
        audBuyingRoleMissingApprover(documentForPrompt, (bodies['buying_role'] || []).join('\n')))) set.add('buying_role');
      return Array.from(set);
    };
    let finalWeak = stillWeakSet();
    // If still weak after the first pass (or none ran), attempt one more.
    if (finalWeak.length) {
      tell('Improving the draft…');
      console.info('[ICPGenerate] qualityRewriteStarted', { qualityRewriteRequestedSections: finalWeak });
      const rwDetected = await runRewrite(finalWeak);
      console.info('[ICPGenerate] qualityRewriteCompleted', { qualityRewriteDetectedSections: rwDetected });
      audStripTrailingFragments(bodies);
      finalWeak = stillWeakSet();
    }

    // Deterministic Topics fallback — DOCUMENT MODE ONLY (the website path uses
    // source-aware repair in the final validation loop below).
    let topicsFallbackUsed = false;
    if (isDoc && finalWeak.indexOf('topics') !== -1) {
      bodies['topics'] = [audTopicsFallback(documentForPrompt || (effBrandText + ' ' + effProductText))];
      topicsFallbackUsed = true;
      finalWeak = stillWeakSet();
    }
    console.info('[ICPGenerate] topicsFallbackUsed', { topicsFallbackUsed: topicsFallbackUsed });

    // --- Unsupported-claim cleanup (document-only mode) -------------------
    // Strip hard claims the model added that the persona source never states
    // (timelines like "60 days", "ranked topics", budget-ownership phrasing).
    let unsupportedClaimsDetected = false;
    let unsupportedClaimsRemoved = [];
    if (isDoc && documentOnly) {
      const clean = audCleanUnsupportedClaims(bodies, documentForPrompt);
      unsupportedClaimsRemoved = clean.removed;
      unsupportedClaimsDetected = clean.removed.length > 0;
      if (clean.changed) audStripTrailingFragments(bodies);
    }
    console.info('[ICPGenerate] unsupportedClaimsDetected', { unsupportedClaimsDetected: unsupportedClaimsDetected });
    console.info('[ICPGenerate] unsupportedClaimsRemoved', { unsupportedClaimsRemoved: unsupportedClaimsRemoved });

    // --- Deterministic buying-role fallback -------------------------------
    // If the source names an explicit approver but the final Role section still
    // omits it, write a safe source-faithful version (never invents budget
    // ownership).
    let buyingRoleFallbackUsed = false;
    if (isDoc && explicitBuyingRolesDetected &&
        audBuyingRoleMissingApprover(documentForPrompt, (bodies['buying_role'] || []).join('\n'))) {
      bodies['buying_role'] = [audBuyingRoleFallback(documentForPrompt, parsed.name || (selectedPersona && selectedPersona.name) || '')];
      buyingRoleFallbackUsed = true;
      finalWeak = stillWeakSet();
    }
    console.info('[ICPGenerate] buyingRoleFallbackUsed', { buyingRoleFallbackUsed: buyingRoleFallbackUsed });
    const finalBuyingRolesPreserved = !isDoc || !explicitBuyingRolesDetected ||
      !audBuyingRoleMissingApprover(documentForPrompt, (bodies['buying_role'] || []).join('\n'));
    console.info('[ICPGenerate] finalBuyingRolesPreserved', { finalBuyingRolesPreserved: finalBuyingRolesPreserved });

    // ============ FINAL APPLIED-CONTENT VALIDATION =======================
    // Validate the EXACT HTML/text that will be inserted into the editor — not
    // the raw AI response, a mock, or an intermediate draft. Assemble → parse
    // back by section → catch any trailing fragment / below-minimum section →
    // repair deterministically → re-assemble. Loops until clean or capped.
    console.info('[ICPGenerate] finalAppliedContentValidationStarted', { finalAppliedContentValidationStarted: true });
    const srcForFallback = documentForPrompt || (effBrandText + ' ' + effProductText);
    const webSignals = isWebsite ? audWebsiteSignals(websiteSummary) : null;
    const webRole = (parsed.name || '').trim();
    if (isWebsite) console.info('[ICPGenerate] websiteSourceSummarySignals', {
      websiteSourceSummarySignals: webSignals ? {
        category: !!webSignals.category, roles: !!webSignals.roles,
        useCases: webSignals.use_cases.length, pains: webSignals.pains.length,
        features: webSignals.features.length, outcomes: webSignals.outcomes.length,
        concerns: webSignals.concerns.length, triggers: webSignals.triggers.length, topics: webSignals.topics.length
      } : null
    });
    let html = audAssembleIcpHtml(bodies);
    let finalAppliedFragmentsDetected = false;
    let finalAppliedFragmentsRemoved = 0;
    let messagingAnglesFallbackUsed = false;
    let audienceWritingRulesFallbackUsed = false;
    let websiteFallbackSectionsUsed = [];
    let duplicateSectionsDetected = false;
    let duplicateSectionPairs = [];
    let intraSectionDuplicationDetected = false;
    let copiedOverviewBlocksRemoved = 0;
    let danglingFragmentsRemoved = 0;
    let decisionCriteriaFeatureListDetected = false;
    let painPointsFallbackUsed = false;
    let decisionCriteriaFallbackUsed = false;

    // Weak detection over the APPLIED (post-assembly) section text. In website
    // mode, contaminated sections (terms unsupported by the live corpus) AND
    // sections that duplicate Audience Overview / another section count as weak.
    const weakInApplied = (applied) => {
      const weak = new Set();
      const figLeak = audSectionsWithExcludedFigures(applied, excludedFigures);
      const contam = isWebsite ? audContaminatedSections(applied, websiteCorpus, websiteSummary) : [];
      if (isWebsite) {
        const dup = audDuplicateSections(applied);
        dup.dupSections.forEach((k) => weak.add(k));
        if (dup.dupSections.length) {duplicateSectionsDetected = true;duplicateSectionPairs = dup.pairs;}
      }
      ICP_SECTIONS.forEach(([k]) => {
        const body = (applied[k] || []).join('\n');
        if (figLeak.indexOf(k) !== -1) {weak.add(k);return;}   // excluded-persona figure leaked in
        if (contam.indexOf(k) !== -1) {weak.add(k);return;}    // website contamination
        if (k === 'writing_rules') {
          if (audWritingRulesWeak(body)) {weak.add(k);return;}
          // Website mode: generic default rules aren't source-specific — replace
          // them when the summary has enough signal to build better ones.
          if (isWebsite && webSignals && audSignalCount(webSignals) >= 4 && audWritingRulesGeneric(body)) weak.add(k);
          return;
        }
        if (audSectionTextWeak(k, body)) {weak.add(k);return;}
        // Website mode: a section that copies Audience Overview content or reads
        // as a bare feature/module list (Decision Criteria) is weak.
        if (isWebsite) {
          const ovText = audGenHtmlText((applied['audience_overview'] || []).join('\n'));
          if (k !== 'audience_overview' && ovText) {
            const sents = audNormSentences(body);
            const ovSents = new Set(audNormSentences(ovText));
            const shared = sents.filter((s) => ovSents.has(s)).length;
            if (shared >= 2) {weak.add(k);intraSectionDuplicationDetected = true;return;}
          }
          if (k === 'decision_criteria' && audIsFeatureList(applied[k] || [])) {weak.add(k);decisionCriteriaFeatureListDetected = true;return;}
        }
        const lines = audBodyLines(body);
        if (lines.length && audIsFragmentLine(lines[lines.length - 1].text)) {weak.add(k);return;}
        const min = AUD_MIN_LINES[k];
        if (min && audUsefulLineCount(body) < min) weak.add(k);
      });
      return Array.from(weak);
    };

    for (let iter = 0; iter < 3; iter++) {
      const applied = audSectionsFromHtml(html);
      const weak = weakInApplied(applied);
      if (!weak.length) break;
      // 1) Strip trailing fragments from each weak section's APPLIED content.
      weak.forEach((k) => {
        const r = audStripTrailingFragment(applied[k] || []);
        if (r.removed) {finalAppliedFragmentsDetected = true;finalAppliedFragmentsRemoved += 1;bodies[k] = r.blocks;}
      });
      // 1.5) Website mode: surgically remove copied-overview blocks / dangling
      //      fragments from WITHIN a section, keeping its good lines, before any
      //      rewrite. This catches an overview paragraph pasted after valid bullets.
      if (isWebsite) {
        const ovText = audGenHtmlText((audSectionsFromHtml(html)['audience_overview'] || []).join('\n'));
        weak.forEach((k) => {
          if (k === 'audience_overview' || k === 'writing_rules') return;
          const cleaned = audCleanSectionUnits(bodies[k] || [], ovText);
          if (cleaned) {
            bodies[k] = cleaned.blocks;
            copiedOverviewBlocksRemoved += cleaned.removedOverview;
            danglingFragmentsRemoved += cleaned.removedFragments;
            if (cleaned.removedOverview) intraSectionDuplicationDetected = true;
          }
        });
        html = audAssembleIcpHtml(bodies);
      }
      html = audAssembleIcpHtml(bodies);
      // 2) Re-validate after fragment removal.
      const stillWeak = weakInApplied(audSectionsFromHtml(html));
      if (!stillWeak.length) break;
      // 3) Repair. WEBSITE MODE is source-aware: never apply document/SEO
      //    fallbacks — rewrite from the website source, else derive from this
      //    ICP's own on-topic sections; never from old examples.
      const remaining = [];
      if (isWebsite) {
        if (iter === 0) {
          // Prefer a website-source-anchored rewrite for everything weak.
          await runRewrite(stillWeak);
          audStripTrailingFragments(bodies);
          html = audAssembleIcpHtml(bodies);
        } else {
          // Last resort: build section-specific content from the website source
          // SIGNALS (never document/SEO examples); fall back to draft-derived.
          weakInApplied(audSectionsFromHtml(html)).forEach((k) => {
            let fb = webSignals ? audWebsiteSectionFallback(k, webSignals, webRole) : null;
            if (!fb && k !== 'writing_rules') {
              fb = audDraftDerivedList(bodies, ['pain_points', 'goals', 'decision_criteria', 'audience_overview'], AUD_MIN_LINES[k] || 3);
            }
            if (!fb && k === 'writing_rules') fb = audDefaultWritingRulesHtml();
            if (fb) {
              bodies[k] = [fb];
              if (websiteFallbackSectionsUsed.indexOf(k) === -1) websiteFallbackSectionsUsed.push(k);
              if (k === 'messaging_angles') messagingAnglesFallbackUsed = true;
              if (k === 'topics') topicsFallbackUsed = true;
              if (k === 'writing_rules') audienceWritingRulesFallbackUsed = true;
              if (k === 'pain_points') painPointsFallbackUsed = true;
              if (k === 'decision_criteria') decisionCriteriaFallbackUsed = true;
            }
          });
          html = audAssembleIcpHtml(bodies);
          break;
        }
      } else {
        // DOCUMENT MODE: existing source-faithful deterministic fallbacks.
        stillWeak.forEach((k) => {
          if (k === 'messaging_angles') {bodies[k] = [audMessagingFallback(srcForFallback)];messagingAnglesFallbackUsed = true;}
          else if (k === 'topics') {bodies[k] = [audTopicsFallback(srcForFallback)];topicsFallbackUsed = true;}
          else if (k === 'writing_rules') {bodies[k] = [audWritingRulesFallback(srcForFallback)];audienceWritingRulesFallbackUsed = true;}
          else if (k === 'buying_triggers') {
            const ext = audExtractLabeledList(srcForFallback, AUD_SECTION_SOURCE_LABELS[k]);
            bodies[k] = [ext || audBuyingTriggersFallback(srcForFallback)];
          }
          else if (AUD_SECTION_SOURCE_LABELS[k]) {
            const ext = audExtractLabeledList(srcForFallback, AUD_SECTION_SOURCE_LABELS[k]);
            if (ext) bodies[k] = [ext];
            else remaining.push(k);
          }
          else remaining.push(k);
        });
        html = audAssembleIcpHtml(bodies);
        // 4) Targeted rewrite (once) for sections with no deterministic fallback.
        if (remaining.length && iter === 0) {await runRewrite(remaining);audStripTrailingFragments(bodies);html = audAssembleIcpHtml(bodies);}
        else if (remaining.length) break;
      }
    }
    if (audGenHtmlText(html).length < 40) throw new Error('bad-output');

    // Final read of the APPLIED content for the verdict.
    const appliedFinal = audSectionsFromHtml(html);
    const finalAppliedWeakSections = weakInApplied(appliedFinal);
    const finalBlend = audSectionsMentioningNames(appliedFinal, excludedPersonaNames);
    const contaminatedSections = isWebsite ? audContaminatedSections(appliedFinal, websiteCorpus, websiteSummary) : [];
    const sourceContaminationDetected = contaminatedSections.length > 0;
    const finalMissing = ICP_SECTIONS.map(([k]) => k).filter((k) => audGenHtmlText((appliedFinal[k] || []).join('\n')).length === 0);
    const finalWeakSections = finalAppliedWeakSections;
    const finalAppliedContentValidationPassed = finalAppliedWeakSections.length === 0 && finalBlend.length === 0 && !sourceContaminationDetected;
    const finalSourceFaithfulnessPassed = finalBuyingRolesPreserved && finalBlend.length === 0 && finalAppliedWeakSections.length === 0;
    const successStateAllowed = finalAppliedContentValidationPassed && finalSourceFaithfulnessPassed && finalMissing.length === 0;
    const finalAppliedWithWarning = !successStateAllowed;
    const warningStateShown = finalAppliedWithWarning;
    console.info('[ICPGenerate] sourceContaminationDetected', { sourceContaminationDetected: sourceContaminationDetected });
    console.info('[ICPGenerate] contaminatedSections', { contaminatedSections: contaminatedSections });

    // Role-name fallback: if the model named the ICP by a persona's personal
    // name, prefer a role pulled from the selected persona's text.
    let finalName = parsed.name;
    if (isDoc && finalName) {
      const personal = [].concat(
        selectedPersona && selectedPersona.name ? [selectedPersona.name] : [],
        excludedPersonaNames).map((n) => n.toLowerCase());
      if (personal.indexOf(finalName.toLowerCase()) !== -1) {
        const roles = audDetectRoles(documentForPrompt);
        if (roles.length) finalName = roles[0].replace(/\b\w/g, (c) => c.toUpperCase());
      }
    }

    console.info('[ICPGenerate] finalAppliedFragmentsDetected', { finalAppliedFragmentsDetected: finalAppliedFragmentsDetected });
    console.info('[ICPGenerate] finalAppliedFragmentsRemoved', { finalAppliedFragmentsRemoved: finalAppliedFragmentsRemoved });
    console.info('[ICPGenerate] messagingAnglesFallbackUsed', { messagingAnglesFallbackUsed: messagingAnglesFallbackUsed });
    console.info('[ICPGenerate] audienceWritingRulesFallbackUsed', { audienceWritingRulesFallbackUsed: audienceWritingRulesFallbackUsed });
    console.info('[ICPGenerate] finalAppliedWeakSections', { finalAppliedWeakSections: finalAppliedWeakSections });
    console.info('[ICPGenerate] finalMissingSections', { finalMissingSections: finalMissing });
    console.info('[ICPGenerate] finalWeakSections', { finalWeakSections: finalWeakSections });
    console.info('[ICPGenerate] crossPersonaBlendDetected', { crossPersonaBlendDetected: finalBlend.length > 0 });
    console.info('[ICPGenerate] finalAppliedContentValidationPassed', { finalAppliedContentValidationPassed: finalAppliedContentValidationPassed });
    console.info('[ICPGenerate] intraSectionDuplication', { intraSectionDuplicationDetected: intraSectionDuplicationDetected, copiedOverviewBlocksRemoved: copiedOverviewBlocksRemoved, danglingFragmentsRemoved: danglingFragmentsRemoved });
    console.info('[ICPGenerate] decisionCriteria', { decisionCriteriaFeatureListDetected: decisionCriteriaFeatureListDetected, decisionCriteriaFallbackUsed: decisionCriteriaFallbackUsed });
    console.info('[ICPGenerate] painPointsFallbackUsed', { painPointsFallbackUsed: painPointsFallbackUsed });
    console.info('[ICPGenerate] finalSourceFaithfulnessPassed', { finalSourceFaithfulnessPassed: finalSourceFaithfulnessPassed });
    console.info('[ICPGenerate] successStateAllowed', { successStateAllowed: successStateAllowed });
    console.info('[ICPGenerate] warningStateShown', { warningStateShown: warningStateShown });
    console.info('[ICPGenerate] duplicateSectionsDetected', { duplicateSectionsDetected: duplicateSectionsDetected });
    console.info('[ICPGenerate] duplicateSectionPairs', { duplicateSectionPairs: duplicateSectionPairs });
    console.info('[ICPGenerate] websiteFallbackSectionsUsed', { websiteFallbackSectionsUsed: websiteFallbackSectionsUsed });
    console.info('[ICPGenerate] finalAppliedWithWarning', { finalAppliedWithWarning: finalAppliedWithWarning });
    if (!successStateAllowed) {
      audSafeDiag('validation_failed', {
        sourceMode: payload.sourceMode,
        missingSchemaFields: finalMissing,
        validationIssueCodes: finalWeakSections,
        sourceContaminationDetected,
        crossPersonaBlendDetected: finalBlend.length > 0,
        finalSourceFaithfulnessPassed
      });
      throw new Error('validation-failed');
    }
    console.info('[ICPGenerate] generatedIcpName', { hasName: !!finalName, sourceMode: payload.sourceMode });
    audSafeDiag('completed', {
      sourceMode: payload.sourceMode,
      hasName: !!finalName,
      htmlChars: html.length,
      detectedSectionCount: parsed.detected.length,
      missingSectionCount: finalMissing.length
    });
    operation.assert();
    return { name: finalName, html: html, detected: parsed.detected, missing: finalMissing, warning: finalAppliedWithWarning };
  }

  function GenerateIcpModal({ icpId, icpName, currentName, getCurrentDetails, onGenerated, onClose }) {
    const generationScope = useRef(null);
    const access = window.ClicklyxKnowledgeAccess.useAccess(() => {
      const scope = generationScope.current;
      const state = window.ClicklyxWorkspaceAccess.getState();
      generationScope.current = null;
      const unavailable = scope && scope.workspaceId === state.workspaceId && scope.epoch === state.epoch
        && state.status === 'access_unavailable' && state.errorCode === 'workspace_access_unavailable'
        && workspaceRequestIsCurrent();
      pendingPayloadRef.current = null;
      setPhase(unavailable ? 'error' : 'form');
      setGenError(unavailable ? AUD_ERR_ACCESS : '');
      setProgress('');
      setExState(current => current === 'extracting' ? 'waiting' : current);
    });
    const [source, setSource] = useState('website');   // 'website' | 'upload'
    const [websiteUrl, setWebsiteUrl] = useState('');
    const [fillGaps, setFillGaps] = useState(true);
    const [gapUrl, setGapUrl] = useState('');
    const [instructions, setInstructions] = useState('');
    const [pasted, setPasted] = useState('');
    /* File + extraction state (text kept in memory only). */
    const [file, setFile] = useState(null);            // { name, type, size }
    const [pendingFile, setPendingFile] = useState(null); // local File, never uploaded
    const [exState, setExState] = useState('idle');    // idle | waiting | extracting | ready | error
    const [exText, setExText] = useState('');
    const [exChars, setExChars] = useState(0);
    const [exError, setExError] = useState('');
    const [libMissing, setLibMissing] = useState(false);
    /* Validation + generation phase. */
    const [validation, setValidation] = useState('');
    const [phase, setPhase] = useState('form');      // form | confirm | busy | success | error
    const [progress, setProgress] = useState('');
    const [genError, setGenError] = useState('');
    const [genWarn, setGenWarn] = useState(false);   // non-blocking "may need review" notice
    const fileRef = useRef(null);
    const pendingPayloadRef = useRef(null);
    const knowledgeEpochRef = useRef(
      window.RankLyxCloudKnowledge && typeof window.RankLyxCloudKnowledge.getRequestEpoch === 'function'
        ? window.RankLyxCloudKnowledge.getRequestEpoch()
        : null
    );
    const workspaceRequestIsCurrent = useCallback(() => {
      const cloud = window.RankLyxCloudKnowledge;
      return knowledgeEpochRef.current === null || !cloud || typeof cloud.getRequestEpoch !== 'function' ||
        cloud.getRequestEpoch() === knowledgeEpochRef.current;
    }, []);

    /* During generation + the success beat, the modal is locked: no scrim
       close, no X, no Escape, no Cancel — so a draft is never lost mid-flight. */
    const busy = phase === 'busy' || phase === 'success';
    const guardedClose = useCallback(() => {if (!busy) onClose();}, [busy, onClose]);

    const clearOutcome = () => {setValidation('');if (phase === 'error') {setPhase('form');setGenError('');}};

    useEffect(() => {
      const onKey = (e) => {
        if (e.key !== 'Escape') return;
        e.preventDefault();e.stopPropagation();
        if (busy) return;                  // locked during generation/success
        if (phase === 'confirm') {setPhase('form');return;}
        onClose();
      };
      document.addEventListener('keydown', onKey, true);
      return () => document.removeEventListener('keydown', onKey, true);
    }, [onClose, busy, phase]);

    const resetFile = useCallback(() => {
      if (!access.canAi()) return;
      setPendingFile(null);
      setFile(null);setExState('idle');setExText('');setExChars(0);setExError('');setLibMissing(false);
      if (fileRef.current) fileRef.current.value = '';
    }, []);

    const onPickFile = useCallback((e) => {
      const f = e.target.files && e.target.files[0];
      if (!f) return;
      const state = window.ClicklyxWorkspaceAccess.getState();
      const origin = access.getOrigin();
      const scope = window.ClicklyxWebsiteContext;
      if (state.status !== 'full' || !state.canUseAi || !state.canMutateWorkspaceContent || state.errorCode
          || origin === null || origin && (!scope || !scope.isCurrent(origin))) return;
      clearOutcome();
      setPendingFile(null);
      // Record the native selection before the focus-triggered Website refresh
      // finishes. Extraction still requires a fresh authorized operation below.
      if (fileRef.current) fileRef.current.value = '';
      // Size guard.
      if (f.size > AUD_MAX_FILE_BYTES) {
        setFile({ name: f.name, type: f.type, size: f.size });
        setExState('error');setExText('');setExChars(0);setLibMissing(false);
        setExError('This file is too large. Please upload a document under 10MB.');
        if (fileRef.current) fileRef.current.value = '';
        return;
      }
      const ext = audFileExt(f.name);
      const okExt = ['pdf', 'docx', 'txt', 'md', 'markdown'].indexOf(ext) !== -1;
      setFile({ name: f.name, type: f.type, size: f.size });
      setExText('');setExChars(0);setExError('');setLibMissing(false);
      // Safe diagnostics — metadata only, never document text.
      console.info('[ICPGenerate] document selected', { fileType: ext, fileSize: f.size });
      if (!okExt) {
        setExState('error');
        setExError('We couldn’t read this document. Try another file or paste the text manually.');
        if (fileRef.current) fileRef.current.value = '';
        return;
      }
      setPendingFile({ file: f, origin, workspaceId: state.workspaceId, epoch: state.epoch });
      setExState('waiting');
    }, []);

    const uploadOrigin = access.getOrigin();
    const canExtract = access.canAi();
    useEffect(() => {
      if (!pendingFile) return;
      const state = window.ClicklyxWorkspaceAccess.getState();
      const scope = window.ClicklyxWebsiteContext;
      if (state.workspaceId !== pendingFile.workspaceId || state.epoch !== pendingFile.epoch
          || pendingFile.origin && (!scope || !scope.samePageFamily(pendingFile.origin, uploadOrigin))) {
        setPendingFile(null);setFile(null);setExText('');setExChars(0);setExState('error');
        setExError('Website access changed. Select the document again in the intended Website.');
        return;
      }
      if (!canExtract) return;
      const operation = access.capture(true);
      if (!operation) return;
      let cancelled = false;
      const current = () => !cancelled && operation.current();
      const f = pendingFile.file;
      setExState('extracting');
      console.info('[ICPGenerate] extraction started', { fileType: audFileExt(f.name), fileSize: f.size });
      (async () => {
        try {
          const text = await audExtractFile(f, operation);
          if (!current()) return;
          if (!text) throw new Error('empty');
          setExText(text);setExChars(text.length);setExState('ready');setPendingFile(null);
          console.info('[ICPGenerate] extraction completed', { extractedChars: text.length });
        } catch (err) {
          if (!current()) return;
          const missing = err && (err.message === 'no-pdf-lib' || err.message === 'no-docx-lib');
          setPendingFile(null);setExState('error');setLibMissing(!!missing);
          setExError(missing ? 'Document extraction is unavailable. Paste the document text below or try again.'
            : 'We couldn’t read this document. Try another file or paste the text manually.');
        }
      })();
      return () => {cancelled = true;operation.dispose();};
    }, [pendingFile, uploadOrigin, canExtract]);

    /* Build + validate the generation payload (no AI call). Returns the
       payload, or null after setting a validation message. */
    const buildPayload = useCallback(() => {
      if (!access.canAi()) return;
      setValidation('');
      const extra = instructions.trim();

      if (source === 'website') {
        if (!websiteUrl.trim()) {setValidation('Please enter a website URL.');return null;}
        if (!audIsValidUrl(websiteUrl)) {setValidation('Please enter a valid website URL.');return null;}
        return {
          currentIcpId: icpId,
          sourceMode: 'website',
          websiteUrl: audNormalizeUrl(websiteUrl),
          extraInstructions: extra
        };
      }

      // Upload / document mode. Prefer extracted file text; else pasted text.
      const fileText = exState === 'ready' ? exText : '';
      const pasteText = pasted.trim();
      const docText = fileText || pasteText;
      const usingFile = !!fileText;
      if (!docText) {
        if (exState === 'error' && exError && !pasteText) {setValidation(exError);return null;}
        setValidation('Upload an ICP document or paste document text.');
        return null;
      }
      if (docText.length < AUD_MIN_DOC_CHARS) {
        setValidation('This document does not contain enough readable text.');
        return null;
      }
      return {
        currentIcpId: icpId,
        sourceMode: 'document',
        documentName: usingFile && file ? file.name : 'Pasted text',
        documentText: docText,
        documentTextChars: docText.length,
        extraInstructions: extra,
        useWebsiteAndSavedKnowledgeForGaps: fillGaps,
        websiteUrlForGaps: (fillGaps && gapUrl.trim()) ? audNormalizeUrl(gapUrl) : undefined
      };
    }, [source, websiteUrl, instructions, exState, exText, pasted, exError, file, fillGaps, gapUrl, icpId]);

    /* Run the real generation, then hand the draft back to the edit modal.
       Only ever applies to the current ICP — never the dashboard or others. */
    const runGeneration = useCallback(async (payload) => {
      const operation = access.capture(true);
      if (!operation) return;
      const state = window.ClicklyxWorkspaceAccess.getState();
      const scope = { workspaceId: state.workspaceId, epoch: state.epoch };
      generationScope.current = scope;
      setPhase('busy');
      setProgress(payload.sourceMode === 'document' ? 'Reading ICP source…' : 'Reading website…');
      setGenError('');
      setGenWarn(false);
      try {
        // Fetch current Workspace Knowledge at action time, never legacy local
        // keys or a payload captured before a switch/replacement confirmation.
        const currentPayload = { ...payload, savedBrandProfile: undefined, savedProductKnowledge: undefined };
        if (payload.sourceMode === 'website' || payload.useWebsiteAndSavedKnowledgeForGaps) {
          const cloud = window.RankLyxCloudKnowledge;
          if (!cloud || typeof cloud.getKnowledgeSnapshot !== 'function') throw new Error('knowledge-unavailable');
          const snapshot = await operation.run(() => cloud.getKnowledgeSnapshot({ origin: operation.origin }));
          if (!snapshot.ok || snapshot.stale || !snapshot.knowledge) throw new Error('knowledge-unavailable');
          currentPayload.savedBrandProfile = snapshot.knowledge.brandProfile || undefined;
          currentPayload.savedProductKnowledge = snapshot.knowledge.productKnowledge || undefined;
        }
        const result = await audGenerateIcp(currentPayload, (msg) => {if (operation.current()) setProgress(msg);}, operation);
        if (!operation.current() || !workspaceRequestIsCurrent()) return;
        // Apply to the CURRENT ICP edit modal draft only.
        try {
          onGenerated(result.name, result.html);
        } catch (saveErr) {
          audSafeDiag('save_failed', {
            sourceMode: payload.sourceMode,
            currentIcpId: payload.currentIcpId,
            errorMessage: saveErr && saveErr.message ? saveErr.message : 'Could not apply generated ICP.'
          });
          throw new Error('save-failed');
        }
        console.info('[ICPGenerate] appliedToCurrentIcpOnly', { currentIcpId: payload.currentIcpId });
        setGenWarn(!!result.warning);
        setPhase('success');
        access.schedule(() => {if (operation.current() && workspaceRequestIsCurrent()) onClose();}, result.warning ? 1500 : 1050);
      } catch (err) {
        if (!operation.current() || !workspaceRequestIsCurrent()) return;
        console.warn('[ICPGenerate] generationFailed', { code: (err && err.message) || 'unknown' });
        setGenError(audGenerationErrorMessage(err));
        setPhase('error');
      } finally {
        if (generationScope.current === scope) generationScope.current = null;
      }
    }, [onGenerated, onClose, workspaceRequestIsCurrent]);

    /* Does the current ICP draft hold meaningful (non-default) content? If so,
       generating would replace it → show the replacement confirmation first. */
    const currentIsMeaningful = useCallback(() => {
      if ((currentName || '').trim()) return true;
      const html = typeof getCurrentDetails === 'function' ? getCurrentDetails() : '';
      return audNormHtml(html) !== audNormHtml(AUD_DEFAULT_DETAILS);
    }, [currentName, getCurrentDetails]);

    const onGenerateClick = useCallback(() => {
      if (!access.canAi()) return;
      const payload = buildPayload();
      if (!payload) return;
      pendingPayloadRef.current = payload;
      if (currentIsMeaningful()) {setPhase('confirm');return;}
      runGeneration(payload);
    }, [buildPayload, currentIsMeaningful, runGeneration]);

    const onConfirmReplace = useCallback(() => {
      if (!access.canAi()) return;
      const payload = pendingPayloadRef.current;
      if (payload) runGeneration(payload);
    }, [runGeneration]);

    const SourceOpt = ({ value, icon, label, help }) => (
      <button
        type="button"
        className={`aud-src ${source === value ? 'aud-src--on' : ''}`}
        aria-pressed={source === value}
        disabled={!access.canAi()} onClick={access.guard(() => {setSource(value);clearOutcome();}, true)}>
        <span className="aud-src__radio" aria-hidden="true"></span>
        <span className="aud-src__ic">{icon}</span>
        <span className="aud-src__text">
          <span className="aud-src__label">{label}</span>
          <span className="aud-src__help">{help}</span>
        </span>
      </button>);

    const bothSources = exState === 'ready' && exText && pasted.trim();
    const docName = (exState === 'ready' && file) ? file.name : (pasted.trim() ? 'Pasted text' : 'your document');

    return (
      <div className="bp-modal-scrim aud-gen-scrim" onMouseDown={busy ? undefined : onClose}>
        <div className="bp-modal aud-genmodal" role="dialog" aria-modal="true" aria-labelledby="aud-gen-title" onMouseDown={(e) => e.stopPropagation()}>
          <button type="button" className="bp-modal__x" onClick={guardedClose} aria-label="Close" disabled={busy} style={busy ? { opacity: 0.4, cursor: 'default' } : undefined}>
            <AudIconClose />
          </button>

          <div className="bp-modal__hd aud-genmodal__hd">
            <span className="bp-modal__icon"><AudIconSparkles /></span>
            <h2 id="aud-gen-title" className="bp-modal__title">Generate ICP</h2>
            <p className="bp-modal__sub">
              Use your website, saved knowledge, or an ICP document to create a
              draft for this audience profile.
            </p>
            <div className="aud-genmodal__scope">
              <AudIconUsers />
              <span>Only affects {icpName ? <>“{icpName}”</> : 'the ICP you are currently editing'} — your other ICP cards stay untouched.</span>
            </div>
          </div>

          <div className="bp-modal__body aud-genmodal__body">
            {phase === 'busy' ?
              <div className="aud-genstate">
                <div className="aud-genstate__spinner"><span className="bp-spinner bp-spinner--lg"></span></div>
                <div className="aud-genstate__title">Generating ICP…</div>
                <div className="aud-genstate__msg">{progress || 'Working…'}</div>
                <div className="aud-genstate__note">This only affects {icpName ? <>“{icpName}”</> : 'the ICP you are editing'}.</div>
              </div> :
            phase === 'success' ?
              <div className="aud-genstate aud-genstate--ok">
                <div className="aud-genstate__check"><AudIconCheckCircle /></div>
                <div className="aud-genstate__title">ICP generated</div>
                <div className="aud-genstate__msg">
                  {genWarn
                    ? 'Draft generated, but a few sections may need review.'
                    : 'Your new draft is ready. Review it before saving.'}
                </div>
              </div> :
            phase === 'confirm' ?
              <div className="aud-genconfirm">
                <span className="aud-genconfirm__ic"><AudIconAlert /></span>
                <p className="aud-genconfirm__text">
                  This will replace the current ICP draft in this card only. Other ICP cards will not be changed.
                </p>
              </div> :
            <React.Fragment>
            <div className="aud-genmodal__field">
              <div className="aud-card__label">Source</div>
              <div className="aud-src-list">
                <SourceOpt
                  value="website"
                  icon={<AudIconGlobe />}
                  label="Website + saved knowledge"
                  help="Use the website, Brand Profile, and Product Knowledge to infer this ICP." />
                <SourceOpt
                  value="upload"
                  icon={<AudIconUpload />}
                  label="Upload ICP document"
                  help="Use an existing ICP, persona, or audience document as the main source." />
              </div>
            </div>

            {source === 'website' &&
              <div className="aud-genmodal__field">
                <label className="aud-card__label" htmlFor="aud-gen-url">Website URL</label>
                <input readOnly={!access.canAi()}
                  id="aud-gen-url"
                  className={`bp-input ${validation && source === 'website' ? 'bp-input--err' : ''}`}
                  type="url"
                  value={websiteUrl}
                  onChange={access.guard((e) => {setWebsiteUrl(e.target.value);clearOutcome();}, true)}
                  placeholder="https://example.com"
                  autoComplete="off" />
              </div>}

            {source === 'upload' &&
              <React.Fragment>
                <div className="aud-genmodal__field">
                  {exState === 'ready' || exState === 'waiting' ?
                    <div className="aud-upload aud-upload--ready">
                      <span className="aud-upload__ic aud-upload__ic--ok"><AudIconCheckCircle /></span>
                      <span className="aud-upload__main">
                        <span className="aud-upload__title">{file ? file.name : 'Document'}</span>
                        <span className="aud-upload__status aud-upload__status--ok">
                          {exState === 'waiting' ? 'Document selected · waiting for Website access' : <>Document ready · {audFormatNum(exChars)} characters extracted</>}
                        </span>
                      </span>
                      <button type="button" className="aud-upload__remove" disabled={!access.canAi()} onClick={resetFile} aria-label="Remove file" title="Remove file">
                        <AudIconClose />
                      </button>
                    </div> :
                  exState === 'extracting' ?
                    <div className="aud-upload aud-upload--busy">
                      <span className="aud-upload__ic"><span className="bp-spinner"></span></span>
                      <span className="aud-upload__main">
                        <span className="aud-upload__title">{file ? file.name : 'Document'}</span>
                        <span className="aud-upload__status">Extracting document…</span>
                      </span>
                    </div> :
                  exState === 'error' ?
                    <div className="aud-upload aud-upload--err">
                      <span className="aud-upload__ic aud-upload__ic--err"><AudIconAlert /></span>
                      <span className="aud-upload__main">
                        <span className="aud-upload__title">{file ? file.name : 'Document'}</span>
                        <span className="aud-upload__status aud-upload__status--err">{exError}</span>
                      </span>
                      <button type="button" className="aud-upload__remove" disabled={!access.canAi()} onClick={resetFile} aria-label="Remove file" title="Remove file">
                        <AudIconClose />
                      </button>
                    </div> :
                    <button type="button" className="aud-upload" disabled={!access.canAi()} onClick={access.guard(() => {if (fileRef.current) fileRef.current.click();}, true)}>
                      <span className="aud-upload__ic"><AudIconUpload /></span>
                      <span className="aud-upload__main">
                        <span className="aud-upload__title">Upload document</span>
                        <span className="aud-upload__fmt">Supported formats: PDF, DOCX, TXT, or Markdown</span>
                      </span>
                    </button>}
                  <input readOnly={!access.canAi()}
                    ref={fileRef}
                    type="file"
                    accept={AUD_ACCEPT}
                    style={{ display: 'none' }}
                    disabled={!access.canAi()} onChange={onPickFile} />

                  {/* Manual paste fallback */}
                  <div className="aud-paste">
                    <label className="aud-card__label aud-paste__label" htmlFor="aud-gen-paste">Paste document text instead</label>
                    <textarea readOnly={!access.canAi()}
                      id="aud-gen-paste"
                      className="bp-textarea"
                      value={pasted}
                      onChange={access.guard((e) => {setPasted(e.target.value);clearOutcome();}, true)}
                      placeholder="Paste ICP, persona, or audience research notes here." />
                    {bothSources &&
                      <div className="aud-genmodal__filenote">
                        The uploaded document will be used as the main source. Pasted text will be ignored unless the file is removed.
                      </div>}
                  </div>
                </div>

                <div className="aud-genmodal__field">
                  <label className="aud-check">
                    <input disabled={!access.canAi()} type="checkbox" checked={fillGaps} onChange={access.guard((e) => {setFillGaps(e.target.checked);clearOutcome();}, true)} />
                    <span className="aud-check__box" aria-hidden="true"><AudIconCheck /></span>
                    <span className="aud-check__text">
                      <span className="aud-check__label">Use website and saved knowledge to fill gaps</span>
                      <span className="aud-check__help">The uploaded document stays the main source. Website, Brand Profile, and Product Knowledge will only help fill missing details later.</span>
                    </span>
                  </label>
                  {fillGaps &&
                    <div className="aud-gapurl">
                      <label className="aud-card__label" htmlFor="aud-gen-gapurl">Website URL for extra context</label>
                      <input readOnly={!access.canAi()}
                        id="aud-gen-gapurl"
                        className="bp-input"
                        type="url"
                        value={gapUrl}
                        onChange={access.guard((e) => {setGapUrl(e.target.value);clearOutcome();}, true)}
                        placeholder="https://example.com"
                        autoComplete="off" />
                    </div>}
                </div>
              </React.Fragment>}

            <div className="aud-genmodal__field">
              <label className="aud-card__label" htmlFor="aud-gen-ctx">Extra instructions</label>
              <textarea readOnly={!access.canAi()}
                id="aud-gen-ctx"
                className="bp-textarea"
                value={instructions}
                onChange={access.guard((e) => {setInstructions(e.target.value);clearOutcome();}, true)}
                placeholder="Example: Generate this ICP from the first persona in the document, or focus on sales leaders only." />
            </div>

            <div className="aud-genmodal__hint">
              In the next step, this will generate only the ICP card you are currently editing.
            </div>

            {validation &&
              <div className="bp-modal__error aud-genmodal__validation" role="alert">
                <AudIconAlert />
                <span>{validation}</span>
              </div>}
            {phase === 'error' && genError &&
              <div className="bp-modal__error aud-genmodal__validation" role="alert">
                <AudIconAlert />
                <span>{genError}</span>
              </div>}
            </React.Fragment>}
          </div>

          {phase === 'busy' || phase === 'success' ?
            <div className="bp-modal__ft">
              <button type="button" className="rl-btn rl-btn--secondary bp-btn" disabled={true} style={{ opacity: 0.5, cursor: 'default' }}>Cancel</button>
              <button type="button" className="rl-btn rl-btn--primary bp-btn" disabled={true}>
                {phase === 'success'
                  ? <React.Fragment><AudIconCheck /><span>Done</span></React.Fragment>
                  : <React.Fragment><span className="bp-spinner bp-spinner--light"></span><span>Generating…</span></React.Fragment>}
              </button>
            </div> :
          phase === 'confirm' ?
            <div className="bp-modal__ft">
              <button type="button" className="rl-btn rl-btn--secondary bp-btn" onClick={() => setPhase('form')}>Cancel</button>
              <button type="button" className="rl-btn rl-btn--primary bp-btn aud-danger-btn" disabled={!access.canAi()} onClick={onConfirmReplace}>
                <AudIconSparkles /><span>Replace and generate</span>
              </button>
            </div> :
            <div className="bp-modal__ft">
              <button type="button" className="rl-btn rl-btn--secondary bp-btn" onClick={onClose}>Cancel</button>
              <button type="button" className="rl-btn rl-btn--primary bp-btn" onClick={onGenerateClick} disabled={!access.canAi() || exState === 'waiting' || exState === 'extracting'}>
                <AudIconSparkles /><span>{phase === 'error' ? 'Try again' : 'Generate ICP'}</span>
              </button>
            </div>}
        </div>
      </div>);
  }

  /* ------------------------------------------------------------------ */
  /* ------------------------------------------------------------------ */
  /* Restore starter template — confirmation modal for one ICP card. Replaces
     the open card's ICP details with the starter template + writing prompts.
     Never auto-saves and never touches the ICP name / role. */
  function IcpRestoreModal({ open, onClose, onConfirm }) {
    const access = window.ClicklyxKnowledgeAccess.useAccess();
    useEffect(() => {
      if (!open) return;
      const onKey = (e) => {if (e.key === 'Escape') {e.preventDefault();e.stopPropagation();onClose();}};
      document.addEventListener('keydown', onKey, true);
      return () => document.removeEventListener('keydown', onKey, true);
    }, [open, onClose]);

    if (!open) return null;

    return (
      <div className="bp-modal-scrim" onMouseDown={onClose}>
        <div
          className="bp-modal bp-modal--confirm"
          role="dialog"
          aria-modal="true"
          aria-labelledby="aud-restore-title"
          onMouseDown={(e) => e.stopPropagation()}>
          <button type="button" className="bp-modal__x" onClick={onClose} aria-label="Close">
            <AudIconClose />
          </button>

          <div className="bp-modal__hd">
            <span className="bp-modal__icon"><AudIconReset /></span>
            <h2 id="aud-restore-title" className="bp-modal__title">Restore starter template?</h2>
            <p className="bp-modal__sub">
              This will replace the current ICP details with the original starter
              template and writing prompts for this card only. Your changes will
              not be applied until you click Done editing.
            </p>
          </div>

          <div className="bp-modal__ft">
            <button type="button" className="rl-btn rl-btn--secondary bp-btn" onClick={onClose}>
              Cancel
            </button>
            <button type="button" className="rl-btn rl-btn--primary bp-btn" disabled={!access.canMutate()} onClick={access.guard(onConfirm)}>
              <AudIconReset />
              <span>Restore template</span>
            </button>
          </div>
        </div>
      </div>);
  }

  /* Edit ICP — large centered modal. Owns a LOCAL working copy of the ICP
     (name + editor HTML) plus its own undo/redo history. Nothing here touches
     localStorage. "Done editing" lifts the working copy up via onApply (page
     draft → unsaved). "Discard edits" closes without applying. */
  function IcpEditModal({ icp, onApply, onClose }) {
    const access = window.ClicklyxKnowledgeAccess.useAccess(() => { if (commitTimerRef.current) access.clearTimer(commitTimerRef.current); });
    const editorRef = useRef(null);
    const undoStackRef = useRef([]);
    const redoStackRef = useRef([]);
    const lastHtmlRef = useRef(icp.details || '');
    const commitTimerRef = useRef(null);
    /* Snapshot of the card's state when the modal opened — the baseline for
       "has unsaved modal edits" and for the close confirmation. */
    const snapRef = useRef({ name: icp.name || '', details: icp.details || '' });
    const initialSourceRef = useRef(icp.source === 'ai' ? 'ai' : 'manual');
    const sourceRef = useRef(initialSourceRef.current);

    const [name, setName] = useState(icp.name || '');
    const [canUndo, setCanUndo] = useState(false);
    const [canRedo, setCanRedo] = useState(false);
    const [confirmClose, setConfirmClose] = useState(false);
    const [genOpen, setGenOpen] = useState(false);   // per-card Generate ICP panel
    const [restoreOpen, setRestoreOpen] = useState(false);   // per-card Restore confirm

    const getHtml = useCallback(
      () => (editorRef.current ? editorRef.current.innerHTML : snapRef.current.details), []);

    /* Seed the editor once on mount; clean history baseline. */
    useEffect(() => {
      const el = editorRef.current;
      if (el) {
        el.innerHTML = icp.details || '';
        const scroll = el.closest('.aud-editor__scroll');
        if (scroll) scroll.scrollTop = 0;
      }
      lastHtmlRef.current = icp.details || '';
      undoStackRef.current = [];
      redoStackRef.current = [];
      setCanUndo(false);
      setCanRedo(false);
      const t = setTimeout(() => {if (editorRef.current) editorRef.current.focus();}, 80);
      return () => clearTimeout(t);
      // eslint-disable-next-line
    }, []);

    const commitEdit = useCallback(() => {
      if (!access.canMutate()) return;
      if (commitTimerRef.current) {access.clearTimer(commitTimerRef.current);commitTimerRef.current = null;}
      const cur = getHtml();
      if (cur === lastHtmlRef.current) return;
      undoStackRef.current.push(lastHtmlRef.current);
      if (undoStackRef.current.length > AUD_HISTORY_MAX) undoStackRef.current.shift();
      redoStackRef.current = [];
      lastHtmlRef.current = cur;
      setCanUndo(true);
      setCanRedo(false);
    }, [getHtml]);

    const onEditorInput = useCallback(() => {
      if (!access.canMutate()) return;
      if (commitTimerRef.current) access.clearTimer(commitTimerRef.current);
      commitTimerRef.current = access.schedule(commitEdit, 500);
    }, [commitEdit]);

    const undo = useCallback(() => {
      if (!access.canMutate()) return;
      commitEdit();
      if (!undoStackRef.current.length) return;
      const cur = getHtml();
      const prev = undoStackRef.current.pop();
      redoStackRef.current.push(cur);
      if (redoStackRef.current.length > AUD_HISTORY_MAX) redoStackRef.current.shift();
      if (editorRef.current) editorRef.current.innerHTML = prev;
      lastHtmlRef.current = prev;
      setCanUndo(undoStackRef.current.length > 0);
      setCanRedo(true);
    }, [commitEdit, getHtml]);

    const redo = useCallback(() => {
      if (!access.canMutate()) return;
      if (!redoStackRef.current.length) return;
      const cur = getHtml();
      const next = redoStackRef.current.pop();
      undoStackRef.current.push(cur);
      if (undoStackRef.current.length > AUD_HISTORY_MAX) undoStackRef.current.shift();
      if (editorRef.current) editorRef.current.innerHTML = next;
      lastHtmlRef.current = next;
      setCanRedo(redoStackRef.current.length > 0);
      setCanUndo(true);
    }, [getHtml]);

    /* Apply an AI-generated draft to THIS ICP editor only: replace the editor
       content, update the name if a useful one came back, clear undo/redo
       history, and treat the generated draft as the new undo baseline. The
       modal stays open (caller closes the generate panel) and is now "changed"
       vs. the opening snapshot, so Done editing will push it to the dashboard. */
    const applyGenerated = useCallback((newName, html) => {
      if (!access.canAi()) return;
      sourceRef.current = 'ai';
      if (typeof newName === 'string' && newName.trim()) setName(newName.trim());
      const el = editorRef.current;
      if (el) {
        el.innerHTML = html || '';
        const scroll = el.closest('.aud-editor__scroll');
        if (scroll) scroll.scrollTop = 0;
      }
      if (commitTimerRef.current) {access.clearTimer(commitTimerRef.current);commitTimerRef.current = null;}
      lastHtmlRef.current = html || '';
      undoStackRef.current = [];
      redoStackRef.current = [];
      setCanUndo(false);
      setCanRedo(false);
    }, []);

    /* Restore the starter template + writing prompts into THIS ICP editor only.
       Keeps the ICP name / role unchanged, leaves the dashboard card untouched
       (Done editing applies it) and saves nothing. Like a generated draft it
       becomes the new undo baseline, and the modal is now "changed" vs. the
       opening snapshot so Done editing will push it to the dashboard. */
    const applyRestore = useCallback(() => {
      if (!access.canMutate()) return;
      sourceRef.current = initialSourceRef.current;
      const el = editorRef.current;
      if (el) {
        el.innerHTML = AUD_DEFAULT_DETAILS;
        const scroll = el.closest('.aud-editor__scroll');
        if (scroll) scroll.scrollTop = 0;
        el.scrollTop = 0;
      }
      if (commitTimerRef.current) {access.clearTimer(commitTimerRef.current);commitTimerRef.current = null;}
      lastHtmlRef.current = AUD_DEFAULT_DETAILS;
      undoStackRef.current = [];
      redoStackRef.current = [];
      setCanUndo(false);
      setCanRedo(false);
      setRestoreOpen(false);
    }, []);

    /* True when the modal holds edits not yet applied vs. the opening snapshot. */
    const hasModalEdits = useCallback(() => {
      const snap = snapRef.current;
      if ((name || '').trim() !== (snap.name || '').trim()) return true;
      return audNormHtml(getHtml()) !== audNormHtml(snap.details);
    }, [name, getHtml]);

    const doApply = useCallback(() => {
      if (!access.canMutate()) return;
      onApply(icp.id, name, getHtml(), sourceRef.current);
      onClose();
    }, [icp.id, name, getHtml, onApply, onClose]);

    /* X / Escape: guard against accidental loss of modal edits. */
    const attemptClose = useCallback(() => {
      if (hasModalEdits()) {setConfirmClose(true);return;}
      onClose();
    }, [hasModalEdits, onClose]);

    useEffect(() => {
      const onKey = (e) => {if (e.key === 'Escape' && !genOpen && !restoreOpen) {e.preventDefault();attemptClose();}};
      document.addEventListener('keydown', onKey);
      return () => document.removeEventListener('keydown', onKey);
    }, [attemptClose, genOpen, restoreOpen]);

    const titleName = (name || '').trim();

    return (
      <React.Fragment>
      <div className="bp-modal-scrim aud-modal-scrim">
        {/* Scrim intentionally does NOT close — accidental-close protection. */}
        <div className="bp-modal aud-emodal" role="dialog" aria-modal="true" aria-labelledby="aud-emodal-title" onMouseDown={(e) => e.stopPropagation()}>
          <button type="button" className="bp-modal__x" onClick={attemptClose} aria-label="Close">
            <AudIconClose />
          </button>

          <div className="bp-modal__hd aud-emodal__hd">
            <span className="bp-modal__icon"><AudIconUsers /></span>
            <h2 id="aud-emodal-title" className="bp-modal__title">
              {titleName ? <>{access.canMutate() ? 'Edit ICP' : 'ICP'}: <span className="aud-emodal__titlename">{titleName}</span></> : 'Edit ICP'}
            </h2>
          </div>

          {confirmClose ?
            <React.Fragment>
              <div className="bp-modal__body aud-emodal__body">
                <div className="bp-modal__confirm">
                  <span className="bp-modal__confirm-ic"><AudIconAlert /></span>
                  <p>You have unsaved edits in this ICP. Discard them?</p>
                </div>
              </div>
              <div className="bp-modal__ft">
                <button type="button" className="rl-btn rl-btn--secondary bp-btn" onClick={() => setConfirmClose(false)}>
                  Keep editing
                </button>
                <button type="button" className="rl-btn rl-btn--primary bp-btn aud-danger-btn" onClick={onClose}>
                  Discard edits
                </button>
              </div>
            </React.Fragment> :
            <React.Fragment>
              <div className="bp-modal__body aud-emodal__body">
                <div className="aud-emodal__field">
                  <label className="aud-card__label" htmlFor="aud-emodal-name">ICP name / role</label>
                  <input readOnly={!access.canMutate()}
                    id="aud-emodal-name"
                    className="bp-input"
                    type="text"
                    value={name}
                    onChange={access.guard((e) => setName(e.target.value))}
                    placeholder="e.g. Head of Marketing"
                    autoComplete="off" />
                </div>
                <div className="aud-emodal__field">
                  <div className="aud-field-row">
                    <label className="aud-card__label">ICP details</label>
                    <button type="button" className="bp-gen-btn bp-gen-btn--tool" disabled={!access.canAi()} onClick={access.guard(() => setGenOpen(true), true)}>
                      <AudIconSparkles /><span>Generate ICP</span>
                    </button>
                  </div>
                  <AudEditor
                    editorRef={editorRef}
                    onInput={onEditorInput}
                    onRestore={access.guard(() => setRestoreOpen(true))}
                    canUndo={canUndo}
                    canRedo={canRedo}
                    onUndo={undo}
                    onRedo={redo} />
                </div>
                <div className="bp-ai-note aud-card__note">
                  <AudIconAlert />
                  <span>AI can make mistakes. Review important details before saving.</span>
                </div>
              </div>
              <div className="bp-modal__ft">
                <button type="button" className="rl-btn rl-btn--secondary bp-btn" onClick={onClose}>
                  Discard edits
                </button>
                <button type="button" className="rl-btn rl-btn--primary bp-btn" disabled={!access.canMutate()} onClick={doApply}>
                  <AudIconCheck /><span>Done editing</span>
                </button>
              </div>
            </React.Fragment>}
        </div>
      </div>
      {genOpen && <GenerateIcpModal
        icpId={icp.id}
        icpName={titleName}
        currentName={name}
        getCurrentDetails={getHtml}
        onGenerated={applyGenerated}
        onClose={() => setGenOpen(false)} />}
      <IcpRestoreModal
        open={restoreOpen}
        onClose={() => setRestoreOpen(false)}
        onConfirm={applyRestore} />
      </React.Fragment>);
  }

  /* ------------------------------------------------------------------ */
  /* Filled ICP card (compact, clickable). */
  function IcpCard({ icp, index, onOpen, onDelete }) {
    const access = window.ClicklyxKnowledgeAccess.useAccess();
    const displayName = (icp.name || '').trim() || 'Untitled ICP';
    const isUntitled = !(icp.name || '').trim();
    const numLabel = String(index + 1).padStart(2, '0');
    const preview = audPreview(icp.details) ||
      'Add pain points, goals, buying triggers, and writing rules for this ICP.';

    return (
      <div
        className="aud-icard"
        role="button"
        tabIndex={0}
        onClick={() => onOpen(icp.id)}
        onKeyDown={(e) => {if (e.key === 'Enter' || e.key === ' ') {e.preventDefault();onOpen(icp.id);}}}>
        <div className="aud-icard__top">
          <span className="aud-card__num">{numLabel}</span>
          <button
            type="button"
            className="aud-icard__del"
            title="Delete ICP"
            aria-label="Delete ICP"
            disabled={!access.canMutate()} onClick={(e) => {e.stopPropagation();if (access.canMutate()) onDelete(icp.id);}}>
            <AudIconTrash />
          </button>
        </div>
        <div className={`aud-icard__name ${isUntitled ? 'aud-icard__name--ph' : ''}`}>{displayName}</div>
        <div className="aud-icard__preview">{preview}</div>
        <div className="aud-icard__edit">
          <AudIconEdit /><span>{access.canMutate() ? 'Edit' : 'View'}</span>
        </div>
      </div>);
  }

  /* Empty "Add ICP" placeholder slot. */
  function IcpPlaceholder({ onAdd }) {
    const access = window.ClicklyxKnowledgeAccess.useAccess();
    return (
      <button type="button" className="aud-pcard" disabled={!access.canMutate()} onClick={access.guard(onAdd)}>
        <span className="aud-pcard__plus"><AudIconPlus /></span>
        <span className="aud-pcard__label">Add ICP</span>
        <span className="aud-pcard__help">Create another audience profile</span>
      </button>);
  }

  /* ------------------------------------------------------------------ */
  /* ICP Knowledge page (dashboard). */
  function IcpKnowledge({ briefReturnContext, onReturnToBrief }) {
    const access = window.ClicklyxKnowledgeAccess.useAccess(() => { setStatus(current => current === 'saving' ? 'idle' : current); });
    const pageOrigin = access.getOrigin();
    const previousLoadOriginRef = useRef(pageOrigin);
    const savedRef = useRef([]);          // last cloud baseline (source of truth for Discard)
    const controllerRef = useRef(null);
    const draftRevisionRef = useRef(0);

    const [icps, setIcps] = useState([]);
    const [dirty, setDirty] = useState(false);
    const [status, setStatus] = useState('idle');   // idle | saving | saved | error | conflict
    const [saveError, setSaveError] = useState('');
    const [loadState, setLoadState] = useState('loading');   // loading | ready | error
    const [editing, setEditing] = useState(null);
    const [confirmDeleteId, setConfirmDeleteId] = useState(null);

    const ensureController = useCallback(() => {
      if (!controllerRef.current) {
        const cloud = window.RankLyxCloudKnowledge;
        if (cloud && typeof cloud.createIcpCollectionPageController === 'function') {
          controllerRef.current = cloud.createIcpCollectionPageController({ getOrigin: access.getOrigin });
        }
      }
      return controllerRef.current;
    }, []);

    const applyCloudBaseline = useCallback((profiles) => {
      const next = audClone(profiles);
      savedRef.current = next;
      setIcps(next);
      setEditing(null);
      setConfirmDeleteId(null);
      draftRevisionRef.current += 1;
      setDirty(false);
      setStatus('idle');
      setSaveError('');
      setLoadState('ready');
    }, []);

    const loadCloudCollection = useCallback(async () => {
      setLoadState('loading');
      setSaveError('');
      const controller = ensureController();
      const result = controller ? await controller.load() : null;
      if (result && result.stale) return;
      if (!result || !result.ok) {
        setLoadState('error');
        return;
      }
      applyCloudBaseline(result.profiles);
    }, [ensureController, applyCloudBaseline]);

    useEffect(() => {
      const onWorkspaceSwitching = () => {
        access.cancel();
        if (controllerRef.current) controllerRef.current.invalidate();
        savedRef.current = [];
        setIcps([]);
        setEditing(null);
        setConfirmDeleteId(null);
        draftRevisionRef.current += 1;
        setDirty(false);
        setStatus('idle');
        setSaveError('');
        setLoadState('loading');
      };
      window.addEventListener('ranklyx:workspace-switching', onWorkspaceSwitching);
      loadCloudCollection();
      return () => {
        window.removeEventListener('ranklyx:workspace-switching', onWorkspaceSwitching);
        if (controllerRef.current) controllerRef.current.dispose();
      };
    }, [loadCloudCollection]);

    // Cached Website pages survive navigation. A stale pending read must be
    // replaced when the page becomes current again, without losing saved or
    // unsaved drafts that already finished hydrating.
    useEffect(() => {
      if (previousLoadOriginRef.current === pageOrigin) return;
      previousLoadOriginRef.current = pageOrigin;
      const scope = window.ClicklyxWebsiteContext;
      if (!pageOrigin || !scope || !scope.isCurrent(pageOrigin)) return;
      if (controllerRef.current && !controllerRef.current.isHydrated()) loadCloudCollection();
    }, [pageOrigin, loadCloudCollection]);

    const markDirty = useCallback(() => {
      if (!access.canMutate()) return;
      draftRevisionRef.current += 1;
      setDirty(true);
      setSaveError('');
      setStatus((current) => current === 'saved' || current === 'error' || current === 'conflict' ? 'idle' : current);
    }, []);

    /* A new card exists only in the edit modal until Done editing. */
    const openNew = useCallback(() => {
      if (!access.canMutate()) return;
      if (icps.length >= AUD_MAX) return;
      const cloud = window.RankLyxCloudKnowledge;
      let id = '';
      try {
        id = cloud && typeof cloud.createIcpDraftId === 'function'
          ? cloud.createIcpDraftId(icps.map((profile) => profile.id))
          : '';
      } catch (e) {id = '';}
      if (!id) {
        setStatus('error');
        setSaveError("Couldn't create a new ICP draft. Please try again.");
        return;
      }
      setConfirmDeleteId(null);
      setEditing({
        id,
        name: '',
        details: AUD_DEFAULT_DETAILS,
        position: icps.length,
        source: 'manual',
        metadata: {},
        createdAt: null,
        updatedAt: null
      });
    }, [icps]);

    const briefReturnTokenRef = useRef(null);
    useEffect(() => {
      if (loadState !== 'ready' || !briefReturnContext || briefReturnContext.source !== 'brief' || !briefReturnContext.websiteId || briefReturnTokenRef.current === briefReturnContext.token) return;
      briefReturnTokenRef.current = briefReturnContext.token;
      openNew();
    }, [loadState, briefReturnContext && briefReturnContext.token, openNew]);

    const onOpen = useCallback((id) => {
      setConfirmDeleteId(null);
      setEditing(icps.find((profile) => profile.id === id) || null);
    }, [icps]);

    const onApply = useCallback((id, name, details, sourceValue) => {
      if (!access.canMutate()) return;
      setIcps((list) => {
        const source = sourceValue === 'ai' ? 'ai' : 'manual';
        if (list.some((profile) => profile.id === id)) {
          return list.map((profile) => profile.id === id
            ? { ...profile, name, details, source }
            : profile);
        }
        if (list.length >= AUD_MAX) return list;
        return list.concat([{
          id,
          name,
          details,
          position: list.length,
          source,
          metadata: {},
          createdAt: null,
          updatedAt: null
        }]);
      });
      markDirty();
    }, [markDirty]);

    const closeModal = useCallback(() => setEditing(null), []);

    const performDelete = useCallback((id) => {
      if (!access.canMutate()) return;
      setIcps((list) => list.filter((profile) => profile.id !== id));
      setConfirmDeleteId(null);
      markDirty();
    }, [markDirty]);

    const onDelete = useCallback((id) => {
      if (!access.canMutate()) return;
      const card = icps.find((profile) => profile.id === id);
      if (card && audIsMeaningful(card)) {setConfirmDeleteId(id);return;}
      performDelete(id);
    }, [icps, performDelete]);

    const saveIcpKnowledge = useCallback(async (afterSave) => {
      const operation = access.capture(false);
      if (!operation) return;
      const controller = controllerRef.current;
      if (!controller || loadState !== 'ready' || status === 'saving' || status === 'conflict') return;
      if (icps.some((profile) => !(profile.name || '').trim() || !(profile.details || '').trim())) {
        setStatus('error');
        setSaveError('Add a name and details to every ICP before saving.');
        return;
      }

      const revision = draftRevisionRef.current;
      const draft = audClone(icps);
      setStatus('saving');
      setSaveError('');
      const result = await controller.save(draft);
      if (!operation.current()) return;
      const conflict = !!(result && result.status === 409 && result.error && result.error.code === 'knowledge_conflict');
      if (conflict) {
        setStatus('conflict');
        setSaveError('This ICP collection changed elsewhere. Reload the latest cloud version before saving again.');
        return;
      }
      if (result && result.stale) return;
      if (!result || !result.ok) {
        setStatus('error');
        setSaveError("Couldn't save. Please try again.");
        return;
      }

      const next = audClone(result.profiles);
      savedRef.current = next;
      if (draftRevisionRef.current === revision) {
        setIcps(next);
        setDirty(false);
        setStatus('saved');
        if (typeof afterSave === 'function') {
          const named = next.filter((profile) => String(profile.name || '').trim());
          const selected = named[named.length - 1] || next[next.length - 1] || null;
          afterSave({ type: 'icp', id: selected && selected.id || '' });
        }
      } else {
        const returnedById = {};
        next.forEach((profile) => {returnedById[profile.id] = profile;});
        const correlations = result.correlations || {};
        setIcps((current) => current.map((profile, index) => {
          const authoritativeId = correlations[profile.id] || profile.id;
          const authoritative = returnedById[authoritativeId];
          if (!authoritative) return { ...profile, position: index };
          return {
            ...authoritative,
            name: profile.name,
            details: profile.details,
            source: profile.source,
            position: index
          };
        }));
        setDirty(true);
        setStatus('idle');
      }
    }, [icps, loadState, status]);

    const onSave = useCallback(() => {
      saveIcpKnowledge();
    }, [saveIcpKnowledge]);
    const saveAndReturnToBrief = useCallback(() => {
      saveIcpKnowledge((payload) => {
        if (onReturnToBrief) onReturnToBrief(payload);
      });
    }, [saveIcpKnowledge, onReturnToBrief]);
    const returnToBrief = useCallback(() => {
      const named = icps.filter((profile) => String(profile.name || '').trim());
      const selected = named[named.length - 1] || icps[icps.length - 1] || null;
      if (onReturnToBrief) onReturnToBrief({ type: 'icp', id: selected && selected.id || '' });
    }, [icps, onReturnToBrief]);

    const onDiscard = useCallback(() => {
      const controller = controllerRef.current;
      const baseline = controller && controller.isHydrated() ? controller.restore() : savedRef.current;
      const next = audClone(baseline);
      savedRef.current = next;
      setIcps(next);
      setEditing(null);
      setConfirmDeleteId(null);
      draftRevisionRef.current += 1;
      setDirty(false);
      setStatus('idle');
      setSaveError('');
    }, []);

    const reloadLatest = useCallback(() => {
      loadCloudCollection();
    }, [loadCloudCollection]);

    if (loadState !== 'ready') {
      return (
        <div className={"rl-page bp-page aud-page" + (loadState === 'error' ? '' : ' c5-knowledge-loading')} data-screen-label={loadState === 'error' ? 'ICP Knowledge unavailable' : 'Loading ICP Knowledge'}>
          <div className="rl-ph" style={{ maxWidth: 560 }}>
            <span className="rl-ph__icon">
              {loadState === 'error' ? <AudIconAlert /> : <span className="bp-spinner"></span>}
            </span>
            <h2 className="rl-ph__title">{loadState === 'error' ? "We couldn't load ICP Knowledge" : 'Loading ICP Knowledge'}</h2>
            <p className="rl-ph__desc">{loadState === 'error' ? 'Your cloud ICP collection is still safe. Try loading it again.' : 'Loading the latest Workspace version...'}</p>
            {loadState === 'error' &&
              <button type="button" className="rl-btn rl-btn--secondary" onClick={loadCloudCollection}>Try again</button>}
          </div>
        </div>);
    }

    const slots = [];
    for (let i = 0; i < AUD_MAX; i++) slots.push(icps[i] || null);
    const editingIcp = editing;
    const deletingIcp = confirmDeleteId ? icps.find((profile) => profile.id === confirmDeleteId) : null;
    const cameFromBrief = !!(briefReturnContext && briefReturnContext.source === 'brief' && onReturnToBrief);

    return (
      <div className="rl-page bp-page aud-page" data-screen-label="ICP Knowledge">
        <div className="bp-wrap">
          <header className="bp-head">
            <div className="bp-eyebrow"><AudIconUsers /><span>Knowledge</span></div>
            <h1 className="bp-title">ICP Knowledge</h1>
            <p className="bp-lede">
              Add the audience profiles your content should speak to. ICP is your
              Ideal Customer Profile, the target person, buyer, or decision-maker
              your content is written for.
            </p>
          </header>

          <div className="aud-controls">
            <span className="aud-limit">
              {'You can add up to 3 ICP profiles. ' + icps.length + ' of ' + AUD_MAX + ' used.'}
            </span>
          </div>

          <div className="aud-grid">
            {slots.map((profile, index) =>
              profile
                ? <IcpCard key={profile.id} icp={profile} index={index} onOpen={onOpen} onDelete={onDelete} />
                : <IcpPlaceholder key={'slot-' + index} onAdd={openNew} />
            )}
          </div>

          <div className="bp-actions aud-actions">
            <div className="bp-actions__status" role="status" aria-live="polite">
              {status === 'saving' &&
                <span className="bp-status bp-status--muted"><span className="bp-spinner"></span><span>Saving...</span></span>}
              {status === 'saved' &&
                <span className="bp-status bp-status--ok"><AudIconCheckCircle /><span>ICP knowledge saved</span></span>}
              {status === 'error' &&
                <span className="bp-status bp-status--err"><AudIconAlert /><span>{saveError || "Couldn't save. Please try again."}</span></span>}
              {status === 'conflict' &&
                <span className="bp-status bp-status--err"><AudIconAlert /><span>{saveError}</span></span>}
              {status === 'idle' && dirty &&
                <span className="bp-status bp-status--muted"><span className="bp-status__dot"></span><span>Unsaved changes</span></span>}
            </div>
            <div className="bp-actions__btns">
              {status === 'conflict' &&
                <button type="button" className="rl-btn rl-btn--secondary bp-btn" onClick={reloadLatest}>
                  <span>Reload latest</span>
                </button>}
              {cameFromBrief && !dirty && status !== 'saving' &&
                <button type="button" className="rl-btn rl-btn--secondary bp-btn" onClick={returnToBrief}>
                  <span>Return to brief</span>
                </button>}
              <button type="button" className="rl-btn rl-btn--secondary bp-btn" onClick={onDiscard} disabled={!dirty || status === 'saving'}>
                <AudIconReset /><span>Discard unsaved changes</span>
              </button>
              <button type="button" className="rl-btn rl-btn--primary bp-btn" onClick={cameFromBrief ? saveAndReturnToBrief : onSave} disabled={!access.canMutate() || status === 'saving' || status === 'conflict'}>
                {status === 'saving'
                  ? <React.Fragment><span className="bp-spinner bp-spinner--light"></span><span>Saving...</span></React.Fragment>
                  : <React.Fragment><AudIconCheck /><span>{cameFromBrief ? 'Save and return to brief' : 'Save ICP Knowledge'}</span></React.Fragment>}
              </button>
            </div>
          </div>
        </div>

        {editingIcp &&
          <IcpEditModal
            key={editingIcp.id}
            icp={editingIcp}
            onApply={onApply}
            onClose={closeModal} />}

        {deletingIcp &&
          <div className="bp-modal-scrim" onMouseDown={() => setConfirmDeleteId(null)}>
            <div className="bp-modal aud-confirm-modal" role="dialog" aria-modal="true" onMouseDown={(e) => e.stopPropagation()}>
              <div className="bp-modal__hd">
                <span className="bp-modal__icon aud-icon-danger"><AudIconTrash /></span>
                <h2 className="bp-modal__title">Delete this ICP?</h2>
                <p className="bp-modal__sub">
                  {(deletingIcp.name || '').trim()
                    ? <>&ldquo;{(deletingIcp.name || '').trim()}&rdquo; and its details will be removed from this draft. You can still discard unsaved changes to bring it back until you save.</>
                    : <>This ICP and its details will be removed from this draft. You can still discard unsaved changes to bring it back until you save.</>}
                </p>
              </div>
              <div className="bp-modal__ft">
                <button type="button" className="rl-btn rl-btn--secondary bp-btn" onClick={() => setConfirmDeleteId(null)}>Keep ICP</button>
                <button type="button" className="rl-btn rl-btn--primary bp-btn aud-danger-btn" disabled={!access.canMutate()} onClick={() => performDelete(deletingIcp.id)}>Delete ICP</button>
              </div>
            </div>
          </div>}
      </div>);
  }

  window.IcpKnowledge = IcpKnowledge;
  /* Back-compat alias so existing wiring that referenced the old name keeps
     working during the rename. */
  window.AudienceIcp = IcpKnowledge;
})();
