/* Rank Lyx — Knowledge / Product Knowledge

   The second Knowledge page. Lets a user teach the AI what their company
   sells — products, services, features, use cases, and offers — as an
   editable "product knowledge document" rather than a stiff form:
     • Card 1 — Product details (rich text editor, stores HTML)

   This knowledge later helps the Outline Agent, Research Agent, Writing
   Agent, and Editor create more accurate product-led content.

   "Generate from website" mirrors the Brand Profile approach exactly: a reader
   proxy fetches the real homepage + priority internal pages, the model returns
   PLAIN STRUCTURED TEXT (never JSON / HTML / code fences), and a forgiving
   parser converts that into escaped editor HTML. Nothing is auto-saved.

   Persistence: Workspace-scoped cloud storage through RankLyxCloudKnowledge.
   Generated and manually edited drafts remain local to the page until Save.
*/

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


  /* Starter Product Knowledge template — the section headings plus a short
     writing prompt under each. This is both the editable default shown when no
     Product Knowledge is saved yet AND the content restored on demand via the
     toolbar's "Restore" button. Each prompt is tagged data-template-helper so
     pkStripTemplateHelpers (below) can keep unchanged guidance out of the AI
     knowledge context. Product Mention Rules restores as a numbered list. */
  const PK_TEMPLATE_SECTIONS = [
    ['Product / Service Overview', 'Explain what the product or service is, who it is for, and the main problem it solves.'],
    ['Core Products / Services', 'List the main products, services, packages, or offers. Briefly explain what each one includes.'],
    ['Core Features', 'Describe the most important features, capabilities, or service components customers should know about.'],
    ['Use Cases', 'List the main situations where customers use the product or service.'],
    ['Problems Solved', 'Describe the pain points, bottlenecks, risks, or frustrations the product or service helps customers fix.'],
    ['Benefits / Outcomes', 'List the results customers can expect, such as saved time, better performance, more revenue, lower costs, fewer errors, or clearer workflows.'],
    ['Best-Fit Customers', 'Describe who the product or service is best for. Mention roles, company types, industries, team sizes, or maturity levels where relevant.'],
    ['Not a Good Fit For', 'Explain who the product or service is not ideal for, or which situations it should not be positioned for.'],
    ['How It Works', 'Explain the process, workflow, setup, onboarding, delivery model, or customer journey.'],
    ['Pricing / Plans', 'Add pricing, plan names, package details, contract terms, or billing notes if available. If pricing is not public, explain how pricing should be discussed.']
  ];
  /* Product Mention Rules restores as a numbered list of example rules. */
  const PK_MENTION_RULE_HELPERS = [
    'Mention the product only when it naturally fits the search intent.',
    'Do not force the product into educational sections.',
    'Use practical use cases instead of hype.',
    'Avoid making unsupported claims or guarantees.'
  ];

  const PK_DEFAULT_DETAILS =
    PK_TEMPLATE_SECTIONS
      .map(([heading, prompt]) => '<h2>' + heading + '</h2>\n<p data-template-helper="1">' + prompt + '</p>')
      .join('\n') +
    '\n<h2>Product Mention Rules</h2>\n<ol data-template-helper="1">\n' +
    PK_MENTION_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
     mention rules), used to detect guidance the user left untouched. */
  const PK_HELPER_NORM_SET = new Set(
    PK_TEMPLATE_SECTIONS.map(([, prompt]) => prompt)
      .concat(PK_MENTION_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 Product Mention Rules example <li>s
     (a list left fully default is emptied and then removed). Exposed on window
     so knowledge consumers (e.g. ICP generation) can call it when preparing
     Product Knowledge context. */
  function pkStripTemplateHelpers(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 && PK_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 && PK_HELPER_NORM_SET.has(t)) p.remove();
      });
      return tmp.innerHTML;
    } catch (e) {
      return s;
    }
  }
  window.pkStripTemplateHelpers = pkStripTemplateHelpers;

  /* Inline SVG icons (same set/visual language as Brand Profile). Inline SVG
     rather than lucide rewriting so mount/unmount can't throw removeChild. */
  function PkIconCheck() {
    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 PkIconCheckCircle() {
    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 PkIconAlert() {
    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 PkIconReset() {
    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 PkIconSparkles() {
    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 PkIconClose() {
    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 PkIconUndo() {
    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 PkIconRedo() {
    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>);
  }

  /* ================================================================== */
  /* "Generate from website" — real website analysis (same flow as Brand
     Profile). Page text comes through the authenticated Clicklyx Reader route.
     Only safely fetched static content is available; no rendering fallback. */
  const PK_NOT_FOUND = 'Not clearly found on the website. Please add this manually.';
  /* Product-led priority paths, per spec. */
  const PK_PRIORITY = [
  'product', 'products', 'features', 'service', 'services', 'solution',
  'solutions', 'use-case', 'use-cases', 'usecases', 'platform', 'pricing',
  'plans', 'integration', 'integrations', 'customer', 'customers',
  'case-stud', 'case-studies', 'demo', 'how-it-works', 'how-it-work'];

  /* Stage-specific failure messages (per spec). */
  const PK_ERR_READ = 'We couldn’t read enough content from this website. You can try another URL, add extra context, or fill the Product Knowledge manually.';
  const PK_ERR_AI = 'We could read the website, but couldn’t generate Product Knowledge from it. Please try again or add extra context.';
  const PK_ERR_OUTPUT = 'We generated a draft, but couldn’t format it safely for the editor. Please try again.';
  const PK_ERR_ACCESS = 'Product Knowledge generation stopped because Workspace access is temporarily unavailable. Your existing content has not changed. Try again once access is restored.';
  const PK_ERR_URL = 'Please enter a valid website URL.';
  const PK_ERR_UNEXPECTED = 'Something went wrong while generating Product Knowledge. Please try again.';
  /* Map an explicit error code → the honest user message. Reading-stage codes
     map to the reading error; AI/output codes to theirs; ANYTHING ELSE (a
     TypeError, undefined variable, parser/second-pass bug, etc.) maps to the
     generic unexpected error — never silently to the reading error. */
  const PK_READ_CODES = ['no-content', 'read-home', 'read-corpus', 'network', 'empty'];
  function pkErrorMessage(err) {
    const code = err && err.message ? err.message : '';
    if (code === 'invalid-url') return PK_ERR_URL;
    if (PK_READ_CODES.indexOf(code) !== -1) return PK_ERR_READ;
    if (code === 'ai-failed' || code === 'ai-empty') return PK_ERR_AI;
    if (code === 'bad-output') return PK_ERR_OUTPUT;
    return PK_ERR_UNEXPECTED;
  }

  function pkNormalizeUrl(raw) {
    const s = (raw || '').trim();
    return /^https?:\/\//i.test(s) ? s : 'https://' + s;
  }
  function pkIsValidUrl(raw) {
    if (!raw || !raw.trim()) return false;
    try {
      const u = new URL(pkNormalizeUrl(raw));
      return !!u.hostname && u.hostname.indexOf('.') > 0;
    } catch (e) {return false;}
  }
  function pkEscape(s) {
    return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  }

  /* Fetch one page through the shared, bounded Clicklyx Reader transport. */
  async function pkFetchReadable(fullUrl, operation = window.ClicklyxKnowledgeAccess.begin(true)) {
    operation.assert();
    try {
      const text = await operation.run(() => window.ClicklyxKnowledgeReader.read(fullUrl, operation));
      return text && text.trim().length ? text : null;
    } catch (e) {
      return null;
    }
  }

  /* Intent buckets for Product Knowledge. Each maps to keyword fragments
     matched against a candidate URL's path + anchor text — first match wins.
     Bucketing (vs. one global score) lets us select a BALANCED mix of page
     types instead of, say, ten product links and zero pricing pages. */
  const PK_BUCKETS = [
  ['pricingPages', ['pricing', 'prices', '/cost', 'cost-']],
  ['planPages', ['plans', '/plan', 'packages', 'editions', 'tiers']],
  ['productPages', ['/product', '/products']],
  ['featurePages', ['/feature', '/features', 'capabilit']],
  ['platformPages', ['/platform']],
  ['solutionPages', ['/solution', '/solutions']],
  ['useCasePages', ['use-case', 'use-cases', 'usecases', 'use_case']],
  ['integrationPages', ['integration', 'integrations', 'app-marketplace', 'marketplace']],
  ['customerPages', ['/customers', 'case-stud', 'case-studies', 'customer-stor']],
  ['demoOrHowItWorksPages', ['/demo', 'how-it-works', 'how-it-work', 'how_it_works', '/tour', 'get-started']]];

  function pkBucketFor(hay) {
    const s = String(hay || '').toLowerCase();
    for (const [bucket, kws] of PK_BUCKETS) {
      for (const kw of kws) if (s.indexOf(kw) !== -1) return bucket;
    }
    return null;
  }

  /* Common product/pricing paths to try DIRECTLY, even when the homepage
     doesn't link them. Kept only if the reader proxy returns useful text. */
  const PK_DIRECT_PATHS = [
  '/pricing', '/plans', '/products', '/product', '/features', '/platform',
  '/solutions', '/use-cases', '/customers', '/integrations', '/demo', '/how-it-works'];

  /* Pull same-origin candidate links out of the reader's markdown, classified
     into intent buckets and scored by keyword density within the bucket. */
  function pkDiscoverInternalPages(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();
      const bucket = pkBucketFor(hay);
      if (!bucket) continue;
      let score = 0;
      for (const kw of PK_PRIORITY) if (hay.indexOf(kw) !== -1) score += 1;
      seen.add(clean);
      out.push({ url: clean, bucket, score, source: 'discovered' });
    }
    return out;
  }

  /* Per-type character cap for the corpus — pricing/plans get the most room so
     they're never starved by generic product/resource links. */
  function pkTypeCap(bucket) {
    if (bucket === 'pricingPages' || bucket === 'planPages') return 5000;
    if (bucket === 'productPages' || bucket === 'featurePages' || bucket === 'platformPages') return 2000;
    return 1500; // solutions / use-cases / customers / integrations / demo
  }

  /* Order pages in the corpus so pricing/plans sit right after the homepage and
     can't be truncated away by the total cap. */
  const PK_CORPUS_ORDER = ['pricingPages', 'planPages', 'productPages', 'featurePages',
  'platformPages', 'solutionPages', 'useCasePages', 'customerPages',
  'integrationPages', 'demoOrHowItWorksPages'];

  function pkTrim(s, n) {
    s = (s || '').replace(/\n{3,}/g, '\n\n').trim();
    return s.length > n ? s.slice(0, n) + '…' : s;
  }

  /* The 11 sections, in order: [key, display heading]. */
  const PK_SECTIONS = [
  ['product_overview', 'Product / Service Overview'],
  ['core_products', 'Core Products / Services'],
  ['core_features', 'Core Features'],
  ['use_cases', 'Use Cases'],
  ['problems_solved', 'Problems Solved'],
  ['benefits_outcomes', 'Benefits / Outcomes'],
  ['best_fit', 'Best-Fit Customers'],
  ['not_fit', 'Not a Good Fit For'],
  ['how_it_works', 'How It Works'],
  ['pricing', 'Pricing / Plans'],
  ['mention_rules', 'Product Mention Rules']];

  function pkNormalizeKey(value) {
    return String(value == null ? '' : value).
    toLowerCase().
    replace(/&/g, ' and ').
    replace(/[^a-z0-9]+/g, ' ').
    replace(/([a-z])([0-9])/g, '$1 $2').
    trim().
    replace(/\s+/g, '_');
  }
  /* Canonical key → accepted aliases (compared after pkNormalizeKey). */
  const PK_SECTION_ALIASES = {
    product_overview: ['product_overview', 'product_service_overview', 'product / service overview',
    'products / services overview', 'service_overview', 'overview', 'product_and_service_overview'],
    core_products: ['core_products', 'core_products_services', 'core products / services',
    'core_products_and_services', 'products', 'services', 'products_and_services',
    'core_services', 'core_offerings', 'offerings', 'product_lineup', 'modules', 'hubs'],
    core_features: ['core_features', 'features', 'key_features', 'capabilities', 'main_features'],
    use_cases: ['use_cases', 'use_case', 'usecases', 'use cases', 'scenarios'],
    problems_solved: ['problems_solved', 'problems', 'problem_solved', 'pains_solved', 'pain_points',
    'problems_we_solve', 'challenges_solved'],
    benefits_outcomes: ['benefits_outcomes', 'benefits / outcomes', 'benefits_and_outcomes',
    'benefits', 'outcomes', 'results', 'value', 'customer_benefits'],
    best_fit: ['best_fit', 'best_fit_customers', 'best-fit customers', 'ideal_customers',
    'who_its_for', 'who_it_is_for', 'best_for', 'target_customers'],
    not_fit: ['not_fit', 'not_a_good_fit', 'not a good fit for', 'not_a_good_fit_for',
    'who_its_not_for', 'not_for', 'poor_fit', 'not_ideal_for'],
    how_it_works: ['how_it_works', 'how it works', 'how_we_work', 'process', 'workflow', 'how-it-works'],
    pricing: ['pricing', 'pricing_plans', 'pricing / plans', 'plans', 'packages', 'pricing_and_plans',
    'price', 'offers'],
    mention_rules: ['mention_rules', 'product_mention_rules', 'product mention rules',
    'mention_guidelines', 'mention_guidance', 'when_to_mention']
  };
  const PK_ALIAS_LOOKUP = (() => {
    const map = {};
    Object.keys(PK_SECTION_ALIASES).forEach((canon) => {
      PK_SECTION_ALIASES[canon].forEach((alias) => {map[pkNormalizeKey(alias)] = canon;});
      map[pkNormalizeKey(canon)] = canon;
    });
    return map;
  })();

  const PK_NOT_FOUND_P = '<p>' + pkEscape(PK_NOT_FOUND) + '</p>';

  function pkHtmlText(html) {
    return String(html || '').replace(/<[^>]*>/g, ' ').replace(/&[a-z]+;/gi, ' ').
    replace(/\s+/g, ' ').trim();
  }
  /* One "Label: explanation" bullet → <li><strong>Label:</strong> …</li>. */
  function pkBulletLi(text) {
    const t = String(text || '').trim();
    if (!t) return '';
    const m = t.match(/^([^:]{1,60}):\s+(.*\S)$/);
    if (m) return '<li><strong>' + pkEscape(m[1].trim()) + ':</strong> ' + pkEscape(m[2].trim()) + '</li>';
    return '<li>' + pkEscape(t) + '</li>';
  }
  /* Detect a MAIN section heading line → canonical key, else null. */
  function pkMatchHeading(line) {
    let s = String(line || '').trim();
    if (!s) return null;
    s = s.replace(/^#{1,6}\s*/, '');
    s = s.replace(/^\*\*(.+?)\*\*$/, '$1').replace(/^__(.+?)__$/, '$1');
    s = s.replace(/[:：]\s*$/, '').trim();
    if (!s || s.length > 60 || s.split(/\s+/).length > 7) return null;
    return PK_ALIAS_LOOKUP[pkNormalizeKey(s)] || null;
  }

  /* Forgiving structured-text parser. Returns { bodies, detected, missing,
     fallbackUsed } — bodies maps each canonical section key → an array of block
     HTML strings — or null when the response is genuinely empty/unusable. It
     does NOT assemble final HTML or fill placeholders, so a second pass can be
     merged in before assembly. `allowFallback` (first pass only) dumps the
     whole response under Product / Service Overview when almost nothing
     matched. */
  function pkParseSections(raw, allowFallback) {
    let text = String(raw == null ? '' : raw);
    text = text.replace(/```[a-z]*\n?/gi, '').replace(/```/g, '');
    if (pkHtmlText(text).length < 40) return null;

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

    const push = (html) => {if (!cur || !html) return;(bodies[cur] = bodies[cur] || []).push(html);};
    const flushPara = () => {if (para.length) {push('<p>' + pkEscape(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;}

      // 1) Main section heading?
      const canon = pkMatchHeading(line);
      if (canon) {flush();cur = canon;if (!bodies[cur]) bodies[cur] = [];continue;}

      // 2) Product/feature subsection: a line starting with ### (not a main heading).
      if (/^#{3,}\s+/.test(line)) {
        flush();
        const name = line.replace(/^#{1,6}\s*/, '').replace(/^\*\*(.+?)\*\*$/, '$1').trim();
        if (name) push('<h3>' + pkEscape(name) + '</h3>');
        continue;
      }

      // 3) Numbered line: "1. ", "2) " → ordered list item.
      const nm = line.match(/^\d{1,3}[.)]\s+(.*)$/);
      if (nm) {flushPara();flushBullets();const li = pkBulletLi(nm[1]);if (li) numbers.push(li);continue;}

      // 4) Bullet line: "- ", "* ", "• " (single marker + space; "**" excluded).
      const bm = line.match(/^(?:[-*•]|\u2013|\u2014)\s+(.*)$/);
      if (bm) {flushPara();flushNumbers();const li = pkBulletLi(bm[1]);if (li) bullets.push(li);continue;}

      // 5) Otherwise paragraph text.
      flushBullets();flushNumbers();
      para.push(line);
    }
    flush();

    const detected = PK_SECTIONS.filter(([k]) => (bodies[k] || []).join('').trim().length > 0).map(([k]) => k);
    const missing = PK_SECTIONS.filter(([k]) => detected.indexOf(k) === -1).map(([k]) => k);

    // Fallback (first pass only): too few sections matched → dump whole escaped
    // response as paragraphs under Product / Service Overview.
    let fallbackUsed = false;
    if (allowFallback && detected.length < 5 && pkHtmlText((bodies.product_overview || []).join('')).length < 40) {
      fallbackUsed = true;
      const paras = text.split(/\n{2,}/).map((p) => p.replace(/\s+/g, ' ').trim()).filter(Boolean).
      map((p) => '<p>' + pkEscape(p) + '</p>').join('\n');
      bodies.product_overview = [paras || '<p>' + pkEscape(text.trim()) + '</p>'];
      if (detected.indexOf('product_overview') === -1) detected.push('product_overview');
      const i = missing.indexOf('product_overview');
      if (i !== -1) missing.splice(i, 1);
    }

    return { bodies, detected, missing, fallbackUsed };
  }

  /* Canonical key → display heading. */
  const PK_HEADING_BY_KEY = (() => {
    const m = {};
    PK_SECTIONS.forEach(([k, h]) => {m[k] = h;});
    return m;
  })();

  /* Assemble final editor HTML from a merged bodies map; sections with no
     content get the "Not clearly found" placeholder. Preserves section order. */
  function pkAssembleHtml(bodies) {
    return PK_SECTIONS.map(([key, heading]) => {
      const body = (bodies[key] || []).join('\n').trim();
      return '<h2>' + heading + '</h2>\n' + (pkHtmlText(body).length > 0 ? body : PK_NOT_FOUND_P);
    }).join('\n');
  }

  /* Sections still empty in a merged bodies map, in canonical order. */
  function pkMissingSections(bodies) {
    return PK_SECTIONS.
    filter(([k]) => pkHtmlText((bodies[k] || []).join('\n')).length === 0).
    map(([k]) => k);
  }

  /* Deterministic, safe Product Mention Rules — the last-resort fallback so this
     section is NEVER left as "Not clearly found". Generic but genuinely useful,
     derived from how the product knowledge is meant to be applied in content. */
  const PK_DEFAULT_MENTION_RULES = [
  'Mention the product when the article discusses pains, workflows, or use cases the product clearly solves.',
  'Avoid forcing product mentions in purely educational sections.',
  'Mention pricing only when the article is about pricing, plans, comparisons, or buying decisions.',
  'Do not claim unsupported features, guarantees, metrics, or customer results.',
  'Use product mentions as helpful context, not as salesy interruptions.',
  'Prefer specific product or service mentions over generic brand mentions when a section maps to a clear feature or use case.'];
  function pkDefaultMentionRulesHtml() {
    return '<ol>\n' + PK_DEFAULT_MENTION_RULES.map((t) => '<li>' + pkEscape(t) + '</li>').join('\n') + '\n</ol>';
  }
  /* Product Mention Rules is ALWAYS rendered as a numbered list. Coerce whatever
     the model returned (bullets, paragraphs, or already-numbered lines) into a
     single <ol>. Content arriving here is already escaped editor HTML, so we
     never re-escape list/paragraph items (only the plain-text fallback path). */
  function pkSplitSentences(text) {
    const m = String(text || '').match(/[^.!?]+[.!?]+["')\]]*/g);
    if (m && m.length) return m.map((s) => s.trim()).filter(Boolean);
    const t = String(text || '').trim();
    return t ? [t] : [];
  }
  function pkToOrderedRules(html) {
    const s = String(html || '').trim();
    if (!s) return '';
    // Already has list items (from <ul>/<ol>) → reuse them as an ordered list.
    const lis = s.match(/<li>[\s\S]*?<\/li>/gi);
    if (lis && lis.length) return '<ol>\n' + lis.join('\n') + '\n</ol>';
    // Paragraph blocks → one rule per paragraph, or split a lone paragraph into
    // sentence-style rules when it clearly holds several.
    const paras = (s.match(/<p>[\s\S]*?<\/p>/gi) || []).
    map((p) => p.replace(/<\/?p>/gi, '').trim()).filter(Boolean);
    let items;
    if (paras.length > 1) {
      items = paras;
    } else if (paras.length === 1) {
      const sent = pkSplitSentences(paras[0]);
      items = sent.length > 1 ? sent : paras;
    } else {
      // No <p>/<li> at all — fall back to visible text (needs escaping).
      const sent = pkSplitSentences(pkHtmlText(s));
      items = (sent.length ? sent : [pkHtmlText(s)]).map((t) => pkEscape(t));
    }
    return '<ol>\n' + items.map((it) => '<li>' + it + '</li>').join('\n') + '\n</ol>';
  }
  /* When a pricing/plans page was fetched but exact details aren't safely
     readable, this honest pointer beats "Not clearly found" and invents no
     prices or plan names. */
  const PK_PRICING_UNCLEAR = 'Pricing information appears to be available on the pricing page, but exact plan details should be confirmed there before use in content.';

  /* Shared directive: Product Mention Rules must always come back as a numbered
     list. Injected into every generation prompt that can produce the section. */
  const PK_MENTION_RULES_DIRECTIVE =
  'Always format Product Mention Rules as a NUMBERED LIST (1. 2. 3.), one rule ' +
  'per line, practical and specific. Cover: when to mention the product or ' +
  'service, when not to force a mention, which product names or features to ' +
  'use, pricing mention rules, claims to avoid, unsupported guarantees, ' +
  'results, or features to avoid, and comparison-content rules when relevant.';

  /* ---- Pricing signal extraction -----------------------------------
     Pricing/plans pages often bury the actual plan names and prices deep in the
     page, where the per-page corpus trim can drop them. extractPricingSignals
     pulls only the pricing-relevant lines (plus a one-line window around each)
     out of the FULL fetched page text, dedupes them, and returns a compact
     string we put near the TOP of the corpus so the model always sees real
     pricing before any cap kicks in. Returns counts + matched terms for
     diagnostics — never the user's keys/tokens or any private data. */
  const PK_PRICING_TERMS = [
  'pricing', 'plans', 'plan', 'free', 'starter', 'professional', 'pro', 'business',
  'enterprise', 'team', 'scale', 'plus', 'premium', 'custom', 'contact sales',
  'per user', 'per seat', 'per record', 'per month', 'monthly', 'annually', 'annual',
  'billed', 'seat', 'user', 'credits', 'included', 'add-on', 'add on', 'trial',
  '/mo', '/month', '$', '£', '€'];
  /* Short alpha terms get a word-boundary test (so "pro" doesn't match
     "product"); everything else is a plain substring/symbol test. */
  const PK_PRICING_WORD_TERMS = new Set(['plan', 'plans', 'free', 'pro', 'team', 'plus',
  'scale', 'seat', 'user', 'trial', 'business', 'starter', 'premium', 'enterprise',
  'professional', 'annual', 'monthly', 'annually', 'billed', 'included', 'credits', 'custom']);

  function extractPricingSignals(text) {
    const raw = String(text || '');
    if (!raw.trim()) return { signals: '', matchedTerms: [], rawChars: 0 };
    const lines = raw.replace(/\r/g, '').split('\n').
    map((l) => l.replace(/[ \t]+/g, ' ').trim()).filter(Boolean);
    const matched = new Set();
    const hit = (line) => {
      const l = line.toLowerCase();
      let any = false;
      for (const term of PK_PRICING_TERMS) {
        let found;
        if (PK_PRICING_WORD_TERMS.has(term)) {
          found = new RegExp('\\b' + term.replace(/[-]/g, '\\-') + '\\b').test(l);
        } else {
          found = l.indexOf(term) !== -1;
        }
        if (found) {matched.add(term);any = true;}
      }
      return any;
    };
    // Capture each hit line plus a one-line window on either side.
    const keep = new Set();
    for (let i = 0; i < lines.length; i++) {
      if (hit(lines[i])) {
        keep.add(i);
        if (i > 0) keep.add(i - 1);
        if (i + 1 < lines.length) keep.add(i + 1);
      }
    }
    const ordered = [...keep].sort((a, b) => a - b);
    const seen = new Set();
    const out = [];
    for (const i of ordered) {
      const ln = lines[i];
      const key = ln.toLowerCase();
      if (ln.length < 2 || seen.has(key)) continue; // drop dupes + noise
      seen.add(key);
      out.push(ln);
    }
    let signals = out.join('\n');
    if (signals.length > 9000) signals = signals.slice(0, 9000) + '…';
    return { signals, matchedTerms: [...matched], rawChars: raw.length };
  }

  /* ---- Pricing plan candidate detection ----------------------------
     Pull likely plan NAMES out of the pricing signals so we can check whether
     the generated Pricing / Plans section actually covers every plan (not just
     the first one or two). Returns names + count + whether exact prices /
     contact-sales appear. Never logs the full pricing text. */
  const PK_PLAN_NAME_WORDS = ['free', 'starter', 'plus', 'pro', 'professional',
  'business', 'team', 'scale', 'enterprise', 'custom', 'trial', 'growth',
  'premium', 'basic', 'standard', 'advanced', 'essentials', 'essential', 'ultimate'];
  function extractPricingPlanCandidates(pricingSignals) {
    const text = String(pricingSignals || '');
    if (!text.trim()) return { planNames: [], planCount: 0, hasExactPrices: false, hasContactSales: false };
    const lines = text.split('\n').map((l) => l.trim()).filter(Boolean);
    const priceCue = /([$£€]\s?\d|\/mo\b|\/month\b|per (?:user|seat)|per month|monthly|annual(?:ly)?|billed|includes|everything in|contact sales|custom pricing)/i;
    const nameRe = new RegExp('\\b(' + PK_PLAN_NAME_WORDS.join('|') + ')\\b', 'i');
    const names = [];
    const seen = new Set();
    for (let i = 0; i < lines.length; i++) {
      const line = lines[i];
      const m = line.match(nameRe);
      if (!m) continue;
      const looksLikeName = line.split(/\s+/).length <= 4; // "Free", "Plus plan"
      const nearPrice = priceCue.test(line) || priceCue.test(lines[i + 1] || '');
      if (!looksLikeName && !nearPrice) continue;
      const canon = m[1].charAt(0).toUpperCase() + m[1].slice(1).toLowerCase();
      if (seen.has(canon.toLowerCase())) continue;
      seen.add(canon.toLowerCase());
      names.push(canon);
    }
    return {
      planNames: names,
      planCount: names.length,
      hasExactPrices: /[$£€]\s?\d/.test(text),
      hasContactSales: /(contact sales|custom pricing|talk to sales)/i.test(text)
    };
  }

  /* ---- Section quality validation ----------------------------------
     A section having SOME text isn't enough — it can be cut off mid-word, too
     thin, a vague pricing punt, or generic mention rules. These checks flag
     "present but weak" sections so a targeted rewrite can fix only those. */
  const PK_MIN_WORDS = {
    core_features: 16, use_cases: 16, problems_solved: 16,
    benefits_outcomes: 16, best_fit: 14, how_it_works: 16
  };
  function pkWordCount(text) {
    const t = String(text || '').trim();
    return t ? t.split(/\s+/).filter(Boolean).length : 0;
  }
  /* A dangling 1–2 word tail with no terminal punctuation reads as cut off
     (e.g. a Benefits list ending on the lone word "Reduced"). */
  function pkLooksCutOff(text) {
    const t = String(text || '').trim();
    if (!t) return false;
    if (/[.!?)\]"”'…]$/.test(t)) return false;
    const tail = t.split(/[.!?:;\n]+/).map((s) => s.trim()).filter(Boolean).pop() || '';
    const words = tail.split(/\s+/).filter(Boolean);
    return words.length > 0 && words.length <= 2;
  }
  function pkCountRules(html) {
    const lis = (String(html || '').match(/<li/gi) || []).length;
    if (lis) return lis;
    const txt = pkHtmlText(html);
    if (!txt) return 0;
    return txt.split(/[\n.]+/).filter((s) => pkWordCount(s) >= 4).length;
  }
  /* Pricing is weak when signals exist but the section punts ("confirm on the
     pricing page", "not fully detailed") without naming a single concrete plan
     or price. With no signals we can't expect better, so it's not flagged. */
  function pkPricingIsVague(html, hasSignals) {
    const text = pkHtmlText(html);
    if (!text) return !!hasSignals;
    if (!hasSignals) return false;
    const punts = /(should be confirmed|confirm[^.]{0,30}pricing page|not (?:fully )?detailed|are not (?:fully )?detailed|aren'?t (?:fully )?detailed|not (?:clearly )?(?:readable|available))/i.test(text);
    const hasPlanOrPrice = /[$£€]\s?\d|\d+\s?(?:\/mo|\/month|per month|per user|per seat)|\b(?:free|starter|professional|business|enterprise|team|scale|plus|premium)\b\s+(?:plan|tier)/i.test(text);
    return punts && !hasPlanOrPrice;
  }
  /* Spelled-out / numeric plan-count claim in the output ("four plans"). */
  const PK_NUM_WORDS = { one: 1, two: 2, three: 3, four: 4, five: 5, six: 6,
    seven: 7, eight: 8, nine: 9, ten: 10 };
  function pkClaimedPlanCount(text) {
    const m = String(text || '').toLowerCase().
    match(/\b(one|two|three|four|five|six|seven|eight|nine|ten|\d{1,2})\s+(?:pricing\s+|paid\s+)?(?:plans|tiers|editions|packages)\b/);
    if (!m) return 0;
    return PK_NUM_WORDS[m[1]] || parseInt(m[1], 10) || 0;
  }
  /* Which candidate plan names actually appear in the output text. */
  function pkPlansMentionedInOutput(text, planNames) {
    const l = String(text || '').toLowerCase();
    const found = [];
    for (const name of planNames || []) {
      const esc = name.toLowerCase().replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&');
      if (new RegExp('\\b' + esc + '\\b').test(l)) found.push(name);
    }
    return found;
  }
  /* Pricing completeness: signals show more plans than the section covers, or
     the section claims N plans but describes fewer. Emptiness is handled by the
     missing/safety passes, so an empty section is not flagged here. */
  function pkPricingCompletenessWeak(html, pricingInfo) {
    if (!pricingInfo || !pricingInfo.included) return false;
    const text = pkHtmlText(html);
    if (!text) return false;
    const candidateCount = pricingInfo.planCount || (pricingInfo.planNames || []).length;
    const outputCount = pkPlansMentionedInOutput(text, pricingInfo.planNames).length;
    const claimed = pkClaimedPlanCount(text);
    if (candidateCount >= 3 && outputCount < candidateCount) return true; // signals show more than covered
    if (claimed >= 2 && outputCount < claimed) return true; // claims N, describes fewer
    if (candidateCount >= 2 && outputCount <= 1) return true; // only one plan covered
    return false;
  }
  /* Normalize the pricing context arg (accepts a boolean or a rich object). */
  function pkPricingInfoOf(arg) {
    if (arg && typeof arg === 'object') return arg;
    return { included: !!arg, planNames: [], planCount: 0 };
  }
  /* True when a section is genuinely useful (not just non-empty). */
  function isSectionUseful(key, html, pricingInfo) {
    const text = pkHtmlText(html);
    if (!text) return false;
    if (text.indexOf(PK_NOT_FOUND) !== -1 && pkWordCount(text) <= pkWordCount(PK_NOT_FOUND) + 4) return false;
    if (key === 'pricing') {
      const info = pkPricingInfoOf(pricingInfo);
      if (pkPricingIsVague(html, info.included)) return false;
      if (pkPricingCompletenessWeak(html, info)) return false;
      return true;
    }
    if (key === 'mention_rules') return pkCountRules(html) >= 4;
    if (pkLooksCutOff(text)) return false;
    const min = PK_MIN_WORDS[key];
    if (min && pkWordCount(text) < min) return false;
    return true;
  }
  /* Present-but-weak sections (skips empty ones — those are handled by the
     missing-section passes / safety fills). */
  function pkWeakSections(bodies, pricingInfo) {
    return PK_SECTIONS.
    filter(([k]) => pkHtmlText((bodies[k] || []).join('\n')).length > 0).
    filter(([k]) => !isSectionUseful(k, (bodies[k] || []).join('\n'), pricingInfo)).
    map(([k]) => k);
  }

  /* Real analysis pipeline. onProgress(msg) fires at each real step. */
  async function generateProductKnowledgeFromWebsite({ url, extraContext, brandName, onProgress, operation = window.ClicklyxKnowledgeAccess.begin(true) }) {
    operation.assert();
    if (!pkIsValidUrl(url)) throw new Error('invalid-url');
    const full = pkNormalizeUrl(url);
    const tell = (msg) => { operation.assert(); if (onProgress) onProgress(msg);};

    // 1 — read the homepage.
    console.info('[ProductKnowledge] readStageStarted');
    tell('Reading homepage…');
    const home = await pkFetchReadable(full, operation);
    operation.assert();
    const homeLen = home ? home.replace(/\s+/g, ' ').trim().length : 0;
    if (homeLen < 350) {
      console.warn('[ProductKnowledge] failureStage=read-home; readableChars=' + homeLen);
      throw new Error('read-home');
    }

    // 2 — discover internal pages from homepage links, classified by intent,
    // and add direct common-path candidates (pricing/plans/products/…).
    tell('Looking for product and service pages…');
    const discovered = pkDiscoverInternalPages(home, full);

    let origin = full;
    try {origin = new URL(full).origin;} catch (e) {}
    const discoveredSet = new Set(discovered.map((d) => d.url));
    const directCandidates = [];
    for (const p of PK_DIRECT_PATHS) {
      const u = origin + p;
      if (discoveredSet.has(u)) continue;
      directCandidates.push({ url: u, bucket: pkBucketFor(p) || 'productPages', score: 0, source: 'direct' });
    }

    // Group every candidate by bucket (best in-bucket score first).
    const byBucket = {};
    discovered.concat(directCandidates).forEach((c) => {
      (byBucket[c.bucket] = byBucket[c.bucket] || []).push(c);
    });
    Object.keys(byBucket).forEach((b) => byBucket[b].sort((a, z) => z.score - a.score));

    // Balanced selection: pricing + plans are MUST-TRY first (so they can't be
    // pushed out by generic links), then round-robin the remaining buckets so
    // no single page type dominates.
    const MAX_PAGES = 6;
    const selected = [];
    const selSet = new Set();
    const take = (c) => {
      if (c && !selSet.has(c.url) && selected.length < MAX_PAGES) {selSet.add(c.url);selected.push(c);}
    };
    ['pricingPages', 'planPages'].forEach((b) => (byBucket[b] || []).slice(0, 2).forEach(take));
    const idx = {};
    let added = true;
    while (added && selected.length < MAX_PAGES) {
      added = false;
      for (const b of PK_CORPUS_ORDER) {
        const list = byBucket[b] || [];
        let i = idx[b] || 0;
        while (i < list.length && selSet.has(list[i].url)) i++;
        if (i < list.length) {take(list[i]);idx[b] = i + 1;added = true;} else
        idx[b] = i;
        if (selected.length >= MAX_PAGES) break;
      }
    }

    // 3 — read pages sequentially so their access checks cannot supersede each other.
    // Keep useful text and skip ordinary unreadable pages, including direct paths that 404.
    const extracted = [];
    const fetchedUrls = [];
    const failedUrls = [];
    if (selected.length) {
      tell('Extracting product details…');
      for (const c of selected) {
        const txt = await pkFetchReadable(c.url, operation);
        operation.assert();
        if (txt && txt.replace(/\s+/g, ' ').trim().length > 200) {
          extracted.push(Object.assign({}, c, { txt }));
          fetchedUrls.push(c.url);
        } else {
          failedUrls.push(c.url);
        }
      }
    }

    // 4 — build the corpus, ordered so pricing/plans survive the total cap, and
    // with per-type caps so detail-rich pages get more room than nav text.
    extracted.sort((a, b) => PK_CORPUS_ORDER.indexOf(a.bucket) - PK_CORPUS_ORDER.indexOf(b.bucket));

    // Pricing signals: pull real plan/price lines from the FULL pricing/plans
    // page text (before per-page trim) and place them near the top of the
    // corpus so the model sees them first. Priority order in the corpus:
    //   homepage → pricing signals → pricing/plans pages → product/features/
    //   platform → use-case/solution/customer/integration.
    const pricingExtracted = extracted.filter(
      (e) => e.bucket === 'pricingPages' || e.bucket === 'planPages'
    );
    const pricingPageUrls = pricingExtracted.map((e) => e.url);
    const pricingRaw = pricingExtracted.map((e) => e.txt || '').join('\n\n');
    const pricingSig = extractPricingSignals(pricingRaw);
    const pricingSignals = pricingSig.signals;
    const pricingSignalMatchedTerms = pricingSig.matchedTerms;
    const pricingRawChars = pricingSig.rawChars;
    const pricingSignalChars = pricingSignals.length;
    const pricingSignalsIncluded = pricingSignals.trim().length > 0;
    // Plan candidates detected from the pricing signals (names + counts), used
    // both for completeness validation and the pricing rewrite prompt.
    const pricingPlanCandidates = extractPricingPlanCandidates(pricingSignals);
    const pricingInfo = {
      included: pricingSignalsIncluded,
      planNames: pricingPlanCandidates.planNames,
      planCount: pricingPlanCandidates.planCount,
      hasExactPrices: pricingPlanCandidates.hasExactPrices,
      hasContactSales: pricingPlanCandidates.hasContactSales
    };

    let corpus = 'HOMEPAGE:\n' + pkTrim(home, 3000);
    if (pricingSignalsIncluded) {
      corpus += '\n\n----\nPRICING SIGNALS (extracted from pricing/plans pages):\n' + pricingSignals;
    }
    for (const e of extracted) {
      let path = e.url;
      try {path = new URL(e.url).pathname;} catch (x) {}
      corpus += '\n\n----\nPAGE [' + e.bucket + '] (' + path + '):\n' + pkTrim(e.txt, pkTypeCap(e.bucket));
    }
    // Total cap trims from the END, so lower-priority pages are dropped before
    // the homepage, pricing signals, and pricing pages near the front.
    corpus = pkTrim(corpus, 26000);

    // Counts only: target URLs can contain private query strings.
    console.info('[ProductKnowledge] crawl ' + JSON.stringify({
      discoveredCandidateCount: discovered.length,
      selectedPageCount: selected.length,
      fetchedPageCount: fetchedUrls.length,
      failedPageCount: failedUrls.length,
      pricingPageCount: pricingPageUrls.length,
      pricingRawChars: pricingRawChars,
      pricingSignalChars: pricingSignalChars,
      pricingSignalMatchedTerms: pricingSignalMatchedTerms,
      pricingSignalsIncluded: pricingSignalsIncluded,
      corpusChars: corpus.length
    }));

    const corpusTextLen = corpus.replace(/\s+/g, ' ').trim().length;
    console.info('[ProductKnowledge] stage=read-ok pagesFetched=' + (1 + extracted.length) +
    ' corpusChars=' + corpus.length + ' corpusTextChars=' + corpusTextLen);
    if (corpusTextLen < 400) {
      console.warn('[ProductKnowledge] failureStage=read-corpus; corpusTextChars=' + corpusTextLen);
      throw new Error('read-corpus');
    }
    console.info('[ProductKnowledge] readStagePassed');

    // 5 — hand the real text + user context to the model under strict rules.
    tell('Preparing your Product Knowledge draft…');
    const ctx = (extraContext || '').trim();
    const brand = (brandName || '').trim();
    // Extra pricing instruction, added only when real pricing signals exist.
    const pricingPromptAddon = pricingSignalsIncluded ?
    '\n\nImportant: Pricing-specific snippets were extracted from pricing/plans ' +
    'pages and placed under PRICING SIGNALS. Use those snippets first when ' +
    'writing Pricing / Plans. If plan names, tiers, exact prices, or billing ' +
    'terms are present there, include them carefully. Do not replace available ' +
    'pricing details with a vague "confirm pricing page" sentence. Only say ' +
    'exact pricing should be confirmed when pricing varies, is incomplete, or ' +
    'is unclear.' : '';
    const prompt =
    'You are generating Product Knowledge for an AI writing software. This is ' +
    'an internal knowledge document that future AI agents (an Outline Agent, ' +
    'Research Agent, Writing Agent, and Editor) will use to write product-led ' +
    'content, examples, CTAs, comparisons, use case sections, and product ' +
    'mentions.\n\n' +
    'Analyze the provided website text and optional user context. Write from ' +
    'the brand’s own point of view using "we," "our," and "us." ' + (
    brand ?
    'The brand is "' + brand + '"; use this name naturally when useful, ' +
    'such as "At ' + brand + ', we…". Do not repeat it in every sentence.\n\n' :
    'Use the brand name naturally when useful.\n\n') +
    'Return PLAIN STRUCTURED TEXT only. Do NOT return JSON. Do NOT return ' +
    'HTML. Do NOT use code fences.\n\n' +
    'Use exactly these section headings, each on its own line, in this ' +
    'order:\n' +
    'Product / Service Overview\nCore Products / Services\nCore Features\n' +
    'Use Cases\nProblems Solved\nBenefits / Outcomes\nBest-Fit Customers\n' +
    'Not a Good Fit For\nHow It Works\nPricing / Plans\nProduct Mention ' +
    'Rules\n\n' +
    'Give useful detail. Do not write a shallow summary. For Core Products / ' +
    'Services, if the company has multiple products, services, modules, hubs, ' +
    'or offers, use subsections in this exact format:\n' +
    '### Product or Service Name\n' +
    'Description of what it does, who it helps, and why it matters.\n\n' +
    'For Core Features, use bullet lines (one per line) or ### subsections ' +
    'when useful. For Benefits / Outcomes, use bullet lines when there are ' +
    'multiple benefits, in the form:\n* Label: explanation\n\n' +
    'For Product Mention Rules, write practical rules for future AI content ' +
    'generation, such as when to mention the product (specific pains / ' +
    'problems / use cases), when to avoid forcing mentions in purely ' +
    'educational sections, mentioning pricing only when the website clearly ' +
    'supports it, and not claiming results, guarantees, or features that are ' +
    'not clearly supported. ' + PK_MENTION_RULES_DIRECTIVE + '\n\n' +
    'SECTION COMPLETION: Do not leave later sections empty if earlier ' +
    'product/service information gives you enough to write careful, supported ' +
    'inferences. If the website provides enough product/service information to ' +
    'infer problems solved, benefits, best-fit customers, how it works, or ' +
    'product mention rules, write careful supported inferences instead of ' +
    'marking the section as missing. For example: if the platform unifies ' +
    'marketing, sales, and service data, Problems Solved can address ' +
    'disconnected tools, data silos, and fragmented customer operations; if AI ' +
    'agents automate ticket resolution, Benefits / Outcomes can mention reduced ' +
    'manual support workload and faster response times; if product pages ' +
    'describe target users or company sizes, use that for Best-Fit Customers; ' +
    'Product Mention Rules can be derived from the product knowledge itself ' +
    'even without a dedicated page. Only mark a section as not clearly found ' +
    'when there is genuinely no supporting information. Do not be overly ' +
    'timid.\n\n' +
    'Do not fabricate products, features, pricing, guarantees, results, ' +
    'awards, customer types, or claims. Never invent exact prices, plan names, ' +
    'metrics, customer results, unsupported features, or unsupported customer ' +
    'segments. For Pricing / Plans, if pricing text is present summarize the ' +
    'pricing structure carefully; if pricing is not readable, say it was not ' +
    'clearly found rather than inventing numbers. Use website evidence first ' +
    'and optional user context second. If something is directly supported, ' +
    'write it confidently. If something is inferred, make that clear. If ' +
    'something is genuinely missing, say it is missing.\n\n' +
    'COMPLETENESS IS REQUIRED: You must output ALL 11 required section ' +
    'headings, in the exact order, every time. Do not stop early. Do not spend ' +
    'so much detail on early sections that later sections are skipped. Budget ' +
    'your length so every section gets written. Keep within these depth ' +
    'limits:\n' +
    '- Product / Service Overview: 2 to 3 short paragraphs\n' +
    '- Core Products / Services: at most 8 products/services; each ### ' +
    'subsection 2 to 4 sentences\n' +
    '- Core Features: at most 12 bullets\n' +
    '- Use Cases: at most 8 bullets\n' +
    '- Problems Solved: at most 8 bullets\n' +
    '- Benefits / Outcomes: at most 8 bullets\n' +
    '- Best-Fit Customers: 4 to 7 bullets or short paragraphs\n' +
    '- Not a Good Fit For: 3 to 5 bullets, based on careful inference\n' +
    '- How It Works: 4 to 7 bullets or short steps\n' +
    '- Pricing / Plans: 2 to 5 bullets or short paragraphs\n' +
    '- Product Mention Rules: 5 to 8 practical bullets\n\n' +
    'Never mark Problems Solved, Benefits / Outcomes, Best-Fit Customers, Not ' +
    'a Good Fit For, How It Works, or Product Mention Rules as missing just ' +
    'because the website has no literal section for them — these must be ' +
    'generated from the product/service information when enough context ' +
    'exists.\n\n' +
    'PRICING / PLANS: If pricing-related pages or pricing text appear in the ' +
    'corpus, you must write a Pricing / Plans section: summarize the pricing ' +
    'structure carefully, name plans only if clearly present, give exact ' +
    'prices only if clearly present, and write "Exact pricing should be ' +
    'confirmed on the pricing page" when prices vary or are not fully ' +
    'readable. Do not mark Pricing / Plans as not clearly found if a pricing ' +
    'page was fetched and contains usable pricing or plan information.\n\n' +
    'WEBSITE CONTENT:\n' + corpus + pricingPromptAddon + '\n\n' +
    'USER EXTRA CONTEXT:\n' + (ctx || '(none provided)');

    console.info('[ProductKnowledge] firstPassStarted');
    let rawOut;
    try {
      rawOut = await operation.run(() => window.appLLMAdapter({ prompt, mode: 'knowledge', requestOrigin: operation.origin }));
    } catch (e) {
      console.warn('[ProductKnowledge] failureStage=ai-call');
      operation.assert();
      const failure = new Error('ai-failed');
      failure.code = e && e.code || 'ai_provider_error';
      if (e && e.statusCode) failure.statusCode = e.statusCode;
      throw failure;
    }
    const rawLen = rawOut ? String(rawOut).length : 0;

    // First-pass parse (fallback dump allowed only here).
    const first = pkParseSections(rawOut, true);
    if (!first) {
      console.warn('[ProductKnowledge] failureStage=ai-empty; aiRawChars=' + rawLen);
      throw new Error('ai-empty');
    }
    console.info('[ProductKnowledge] firstPassCompleted; aiRawChars=' + rawLen);
    const bodies = first.bodies;
    const firstPassDetected = first.detected.slice();
    const firstPassMissing = first.missing.slice();

    // --- Missing-section completion pass --------------------------------
    // If any required section is missing after the first response, ask the
    // model to write ONLY the missing sections, using the same corpus, the
    // existing draft, and the same rules. Never insert "Not clearly found"
    // before this second attempt has run.
    let secondPassStarted = false;
    let secondPassDetected = [];
    if (first.missing.length) {
      secondPassStarted = true;
      console.info('[ProductKnowledge] secondPassStarted; missing=' + JSON.stringify(first.missing));
      tell('Completing the remaining sections…');
      const missingHeadings = first.missing.map((k) => PK_HEADING_BY_KEY[k]);
      const second_prompt =
      'You previously generated a Product Knowledge draft for an AI writing ' +
      'software from the website text below. The draft is MISSING these ' +
      'required sections:\n' + missingHeadings.join('\n') + '\n\n' +
      'Using the website corpus and the existing draft, write ONLY the ' +
      'missing sections in the same plain structured text format. Do not ' +
      'repeat sections that already exist. Do NOT return JSON or HTML. Do NOT ' +
      'use code fences. Use the EXACT missing section headings shown above, ' +
      'each on its own line.\n\n' +
      'Write from the brand’s own point of view using "we," "our," and ' +
      '"us." ' + (brand ? 'The brand is "' + brand + '". ' : '') +
      'Use ### subsections, and "* Label: explanation" or "- " bullet lines ' +
      'where useful, matching the original formatting and the same depth ' +
      'limits.\n\n' +
      'If a section can be inferred from the product/service context (for ' +
      'example Problems Solved, Benefits / Outcomes, Best-Fit Customers, Not ' +
      'a Good Fit For, How It Works, or Product Mention Rules), write a ' +
      'careful supported answer instead of marking it missing. Product ' +
      'Mention Rules can always be derived from the product knowledge itself. ' +
      PK_MENTION_RULES_DIRECTIVE + ' ' +
      'For Pricing / Plans, summarize readable pricing carefully and write ' +
      '"Exact pricing should be confirmed on the pricing page" when prices ' +
      'vary or are not fully readable. Only say information is genuinely ' +
      'missing when there is truly not enough evidence. Do not fabricate ' +
      'exact prices, plan names, metrics, results, or unsupported features or ' +
      'customer segments.\n\n' +
      'WEBSITE CONTENT:\n' + corpus + '\n\n' +
      'EXISTING DRAFT:\n' + String(rawOut).slice(0, 8000);
      let raw2 = null;
      try {
        raw2 = await operation.run(() => window.appLLMAdapter({ prompt: second_prompt, mode: 'knowledge', requestOrigin: operation.origin }));
      } catch (e) {
        console.warn('[ProductKnowledge] second pass aiCallError');
      }
      if (raw2) {
        const second = pkParseSections(raw2, false);
        if (second) {
          secondPassDetected = second.detected.slice();
          // Merge in only the sections that were missing and now have content.
          for (const k of first.missing) {
            if (pkHtmlText((second.bodies[k] || []).join('\n')).length > 0) {
              bodies[k] = second.bodies[k];
            }
          }
        }
      }
      console.info('[ProductKnowledge] secondPassCompleted; detected=' + JSON.stringify(secondPassDetected));
    } else {
      console.info('[ProductKnowledge] secondPassSkipped');
    }

    // --- Final targeted completion pass --------------------------------
    // Recompute what is STILL missing after the second pass merges. The second
    // pass is often handed too many sections at once and stops early, leaving a
    // tail (commonly Pricing / Plans and Product Mention Rules). If anything is
    // still missing, run ONE more short, strict pass that asks for ONLY those
    // remaining sections — with pricing and mention rules prioritized first so
    // they can't be dropped again. "Not clearly found" is never applied before
    // this pass has run.
    const secondPassMissingAfterMerge = pkMissingSections(bodies);
    let finalTargetedPassStarted = false;
    let finalTargetedPassRequested = [];
    let finalTargetedPassDetected = [];
    if (secondPassMissingAfterMerge.length) {
      // Prioritize pricing + mention_rules at the front of the request.
      const FINAL_PRIORITY = ['pricing', 'mention_rules'];
      const ordered = secondPassMissingAfterMerge.slice().sort((a, b) => {
        const ra = FINAL_PRIORITY.indexOf(a),rb = FINAL_PRIORITY.indexOf(b);
        return (ra === -1 ? 99 : ra) - (rb === -1 ? 99 : rb);
      });
      finalTargetedPassStarted = true;
      finalTargetedPassRequested = ordered.slice();
      console.info('[ProductKnowledge] finalTargetedPassStarted; requested=' + JSON.stringify(ordered));
      tell('Finishing the last sections…');
      const headings = ordered.map((k) => PK_HEADING_BY_KEY[k]);
      const third_prompt =
      'The Product Knowledge draft is still missing only these sections:\n' +
      headings.join('\n') + '\n\n' +
      'Write only these sections. Use the exact headings shown above, each on ' +
      'its own line, in this order. Do not repeat existing sections. Keep each ' +
      'section concise but useful. Do not return JSON. Do not return HTML. Do ' +
      'not use code fences.\n\n' +
      'Write from the brand’s own point of view using "we," "our," and "us." ' + (
      brand ? 'The brand is "' + brand + '". ' : '') +
      'Use "* Label: explanation" or "- " bullet lines where useful.\n\n' +
      'For Product Mention Rules, derive practical rules from the product ' +
      'knowledge itself: when to mention the product (clear pains, workflows, ' +
      'or use cases it solves), when to avoid forcing mentions in purely ' +
      'educational sections, mentioning pricing only for pricing, comparison, ' +
      'or buying content, and never claiming unsupported features, guarantees, ' +
      'metrics, or customer results. ' + PK_MENTION_RULES_DIRECTIVE + '\n' +
      'For Pricing / Plans, summarize readable pricing carefully and write ' +
      '"Exact pricing should be confirmed on the pricing page" when prices vary ' +
      'or are not fully readable. Do not invent exact prices, plan names, or ' +
      'discounts.\n\n' +
      'WEBSITE CONTENT:\n' + corpus + '\n\n' +
      'EXISTING DRAFT:\n' + String(rawOut).slice(0, 8000);
      let raw3 = null;
      try {
        raw3 = await operation.run(() => window.appLLMAdapter({ prompt: third_prompt, mode: 'knowledge', requestOrigin: operation.origin }));
      } catch (e) {
        console.warn('[ProductKnowledge] final targeted pass aiCallError');
      }
      if (raw3) {
        const third = pkParseSections(raw3, false);
        if (third) {
          finalTargetedPassDetected = third.detected.slice();
          // Merge in only the requested sections that now have content.
          for (const k of ordered) {
            if (pkHtmlText((third.bodies[k] || []).join('\n')).length > 0) {
              bodies[k] = third.bodies[k];
            }
          }
        }
      }
      console.info('[ProductKnowledge] finalTargetedPassCompleted; detected=' + JSON.stringify(finalTargetedPassDetected));
    } else {
      console.info('[ProductKnowledge] finalTargetedPassSkipped');
    }

    // --- Section quality validation + targeted rewrite ----------------
    // Heading detection isn't enough: a section can be present yet cut off
    // mid-word, too thin, a vague pricing punt, or generic mention rules.
    // Flag present-but-weak sections and, if any, rewrite ONLY those.
    const weakSections = pkWeakSections(bodies, pricingInfo);
    const pricingSectionWeak = weakSections.indexOf('pricing') !== -1;
    const benefitsSectionWeak = weakSections.indexOf('benefits_outcomes') !== -1;
    let qualityRewriteStarted = false;
    let qualityRewriteRequested = [];
    let qualityRewriteDetected = [];
    if (weakSections.length) {
      // pricing + mention_rules first so they're never dropped.
      const QR_PRIORITY = ['pricing', 'mention_rules'];
      const ordered = weakSections.slice().sort((a, b) => {
        const ra = QR_PRIORITY.indexOf(a),rb = QR_PRIORITY.indexOf(b);
        return (ra === -1 ? 99 : ra) - (rb === -1 ? 99 : rb);
      });
      qualityRewriteStarted = true;
      qualityRewriteRequested = ordered.slice();
      console.info('[ProductKnowledge] qualityRewriteStarted; weak=' + JSON.stringify(ordered));
      tell('Improving section quality…');
      const headings = ordered.map((k) => PK_HEADING_BY_KEY[k]);
      // Plain-text snapshot of the current draft for context.
      const draftText = PK_SECTIONS.map(([k, h]) =>
      h + '\n' + (pkHtmlText((bodies[k] || []).join('\n')) || '(empty)')).join('\n\n');
      const pricingRewriteRule = pricingSectionWeak && pricingSignalsIncluded ?
      '\n\nThe Pricing / Plans section is incomplete. Pricing signals suggest ' +
      'these plan names: ' + (pricingInfo.planNames.join(', ') || '(see PRICING SIGNALS)') + '. ' +
      'Rewrite Pricing / Plans only. Include every plan that is clearly present ' +
      'in pricing signals. Include exact prices only when clearly present. If a ' +
      'plan name is present but exact pricing is unclear, mention the plan and ' +
      'say exact pricing should be confirmed. Do not invent features, prices, ' +
      'limits, or discounts.\n' +
      'Prefer complete coverage over extreme detail: write one short intro ' +
      'sentence, then one short paragraph or bullet group per plan, mention key ' +
      'price/seat/limit details only when clearly present, and end with "Exact ' +
      'pricing should be confirmed on the pricing page" if pricing may vary. Do ' +
      'not give large detail for the first two plans and skip the rest.' : '';
      const mentionRewriteRule = ordered.indexOf('mention_rules') !== -1 ?
      '\n\n' + PK_MENTION_RULES_DIRECTIVE : '';
      const quality_prompt =
      'The Product Knowledge draft has these weak or incomplete sections:\n' +
      headings.join('\n') + '\n\n' +
      'Rewrite only these sections. Use the exact headings shown above, each ' +
      'on its own line. Do not repeat other sections. Use the website corpus, ' +
      'pricing signals, and existing draft. Keep the output concise, specific, ' +
      'and supported. Do not use JSON, HTML, or code fences.\n\n' +
      'Write from the brand’s own point of view using "we," "our," and "us." ' + (
      brand ? 'The brand is "' + brand + '". ' : '') +
      'Use "* Label: explanation" or "- " bullet lines where useful. Finish ' +
      'every sentence and every bullet — never stop mid-word or mid-list. Do ' +
      'not claim unsupported features, guarantees, metrics, or customer ' +
      'results.' + pricingRewriteRule + mentionRewriteRule + '\n\n' +
      'WEBSITE CONTENT:\n' + corpus + '\n\n' +
      'EXISTING DRAFT:\n' + draftText.slice(0, 8000);
      let raw4 = null;
      try {
        raw4 = await operation.run(() => window.appLLMAdapter({ prompt: quality_prompt, mode: 'knowledge', requestOrigin: operation.origin }));
      } catch (e) {
        console.warn('[ProductKnowledge] quality rewrite aiCallError');
      }
      if (raw4) {
        const fourth = pkParseSections(raw4, false);
        if (fourth) {
          qualityRewriteDetected = fourth.detected.slice();
          // Accept a rewrite only when it now reads as useful, or is at least
          // more substantial than the weak version it replaces.
          for (const k of ordered) {
            const rewritten = (fourth.bodies[k] || []).join('\n');
            if (pkHtmlText(rewritten).length === 0) continue;
            const betterText = pkWordCount(pkHtmlText(rewritten)) >
            pkWordCount(pkHtmlText((bodies[k] || []).join('\n')));
            if (isSectionUseful(k, rewritten, pricingInfo) || betterText) {
              bodies[k] = fourth.bodies[k];
            }
          }
        }
      }
      console.info('[ProductKnowledge] qualityRewriteCompleted; detected=' + JSON.stringify(qualityRewriteDetected));
    } else {
      console.info('[ProductKnowledge] qualityRewriteSkipped');
    }

    // --- Deterministic safety fills (only when a section is STILL empty) -
    // Product Mention Rules must ALWAYS be filled — never "Not clearly found".
    let mentionRulesFallbackUsed = false;
    if (pkHtmlText((bodies.mention_rules || []).join('\n')).length === 0) {
      bodies.mention_rules = [pkDefaultMentionRulesHtml()];
      mentionRulesFallbackUsed = true;
    }
    // Pricing / Plans: if a pricing/plans page was actually fetched but the
    // model still wrote nothing, point to the pricing page rather than marking
    // it missing — without inventing any prices or plan names.
    const pricingPageFetched =
    extracted.some((e) => e.bucket === 'pricingPages' || e.bucket === 'planPages') ||
    fetchedUrls.some((u) => /\/(pricing|plans|prices|cost|packages|tiers|editions)/i.test(u));
    let pricingFallbackUsed = false;
    if (pkHtmlText((bodies.pricing || []).join('\n')).length === 0 && pricingPageFetched) {
      bodies.pricing = ['<p>' + pkEscape(PK_PRICING_UNCLEAR) + '</p>'];
      pricingFallbackUsed = true;
    }

    // Product Mention Rules is ALWAYS a numbered list, whatever shape it arrived
    // in (bullets, paragraphs, or already-numbered lines).
    if (pkHtmlText((bodies.mention_rules || []).join('\n')).length > 0) {
      bodies.mention_rules = [pkToOrderedRules((bodies.mention_rules || []).join('\n'))];
    }

    // Assemble: any section STILL empty after all passes + safety fills gets
    // "Not clearly found" (the only place that placeholder is now applied).
    console.info('[ProductKnowledge] finalAssemblyStarted');
    const html = pkAssembleHtml(bodies);
    const finalMissing = pkMissingSections(bodies);
    const finalWeakSections = pkWeakSections(bodies, pricingInfo);
    // Pricing plan coverage in the final output (names + counts only).
    const finalPricingText = pkHtmlText((bodies.pricing || []).join('\n'));
    const pricingPlansMentionedInOutput = pkPlansMentionedInOutput(finalPricingText, pricingInfo.planNames);
    const pricingPlanOutputCount = pricingPlansMentionedInOutput.length;
    const pricingCompletenessWeak = pkPricingCompletenessWeak((bodies.pricing || []).join('\n'), pricingInfo);
    console.info('[ProductKnowledge] finalAssemblyCompleted; finalRenderedHtmlChars=' + html.length);

    console.info('[ProductKnowledge] sections ' + JSON.stringify({
      firstPassDetectedHeadings: firstPassDetected,
      firstPassMissingSections: firstPassMissing,
      secondPassStarted: secondPassStarted,
      secondPassDetectedHeadings: secondPassDetected,
      secondPassMissingAfterMerge: secondPassMissingAfterMerge,
      finalTargetedPassStarted: finalTargetedPassStarted,
      finalTargetedPassRequestedSections: finalTargetedPassRequested,
      finalTargetedPassDetectedHeadings: finalTargetedPassDetected,
      pricingPageFetched: pricingPageFetched,
      pricingFallbackUsed: pricingFallbackUsed,
      mentionRulesFallbackUsed: mentionRulesFallbackUsed,
      pricingSignalsIncluded: pricingSignalsIncluded,
      pricingSignalChars: pricingSignalChars,
      pricingPlanCandidates: pricingInfo.planNames,
      pricingPlanCandidateCount: pricingInfo.planCount,
      pricingPlansMentionedInOutput: pricingPlansMentionedInOutput,
      pricingPlanOutputCount: pricingPlanOutputCount,
      pricingCompletenessWeak: pricingCompletenessWeak,
      pricingSectionWeak: pricingSectionWeak,
      benefitsSectionWeak: benefitsSectionWeak,
      weakSections: weakSections,
      qualityRewriteStarted: qualityRewriteStarted,
      qualityRewriteRequestedSections: qualityRewriteRequested,
      qualityRewriteDetectedHeadings: qualityRewriteDetected,
      finalMissingSections: finalMissing,
      finalWeakSections: finalWeakSections,
      finalRenderedHtmlChars: html.length
    }));

    operation.assert();
    return html;
  }

  /* ------------------------------------------------------------------ */
  /* Reusable rich text editor — shares Brand Profile's bp- and ed- visual
     language for full consistency. Uncontrolled: the parent reads/writes
     content imperatively through `editorRef`. */
  function PkToolBtn({ 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-pressed={!!on}
        disabled={!access.canMutate()}
        onMouseDown={(e) => {e.preventDefault();if (access.canMutate()) onCmd(cmd, arg);}}>
        {icon && <i data-lucide={icon}></i>}
        {label && <span>{label}</span>}
      </button>);
  }

  function PkRichTextEditor({ editorRef, onInput, onGenerate, 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(() => {if (window.lucide) window.lucide.createIcons();});

    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) => <PkToolBtn onCmd={onCmd} {...p} />;

    return (
      <div className="bp-editor" style={{ margin: "0px" }}>
        <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();}}>
                <PkIconUndo />
              </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();}}>
                <PkIconRedo />
              </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="bold" title="Bold" on={active.bold} />
              <Btn cmd="italic" icon="italic" title="Italic" on={active.italic} />
            </div>
            <span className="ed-divider"></span>
            <div className="ed-tgroup">
              <Btn cmd="ul" icon="list" title="Bulleted list" on={active.ul} />
              <Btn cmd="ol" icon="list-ordered" 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">
              <PkIconReset />
              <span>Restore</span>
            </button>
            <button type="button" className="bp-gen-btn bp-gen-btn--tool" disabled={!access.canAi()} onClick={access.guard(onGenerate, true)}>
              <PkIconSparkles />
              <span>Generate from website</span>
            </button>
          </div>
        </div>

        <div className="bp-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="Product details"></div>
        </div>
      </div>);
  }

  /* ------------------------------------------------------------------ */
  /* Generate from website — modal + flow. Builds the draft, asks for
     confirmation before overwriting custom content, hands the result back via
     onApply (which does NOT auto-save). */
  function PkGenerateModal({ open, onClose, onApply, isCustom, brandName }) {
    const generationScope = useRef(null);
    const access = window.ClicklyxKnowledgeAccess.useAccess(() => {
      const scope = generationScope.current;
      const state = window.ClicklyxWorkspaceAccess.getState();
      generationScope.current = null;
      setLoading(false);setSuccess(false);setConfirm(false);setProgress('');
      setError(open && scope && scope.workspaceId === state.workspaceId && scope.epoch === state.epoch
        && state.status === 'access_unavailable' && state.errorCode === 'workspace_access_unavailable'
        ? PK_ERR_ACCESS : null);
    });
    const [url, setUrl] = useState('');
    const [context, setContext] = useState('');
    const [urlErr, setUrlErr] = useState(null);
    const [error, setError] = useState(null);
    const [loading, setLoading] = useState(false);
    const [progress, setProgress] = useState('');
    const [confirm, setConfirm] = useState(false);
    const [success, setSuccess] = useState(false);
    const urlRef = useRef(null);

    useEffect(() => {
      generationScope.current = null;
      if (!open) return;
      setUrl('');setContext('');setUrlErr(null);setError(null);setLoading(false);setProgress('');setConfirm(false);setSuccess(false);
      const t = setTimeout(() => {if (urlRef.current) urlRef.current.focus();}, 60);
      return () => clearTimeout(t);
    }, [open]);

    useEffect(() => {
      if (!open) return;
      const onKey = (e) => {if (e.key === 'Escape' && !loading && !success) onClose();};
      document.addEventListener('keydown', onKey);
      return () => document.removeEventListener('keydown', onKey);
    }, [open, loading, success, onClose]);

    useEffect(() => {if (window.lucide) window.lucide.createIcons();}, [open, confirm, loading, success]);

    const runGeneration = useCallback(async () => {
      const operation = access.capture(true);
      if (!operation) return;
      const state = window.ClicklyxWorkspaceAccess.getState();
      const scope = { workspaceId: state.workspaceId, epoch: state.epoch };
      generationScope.current = scope;
      setLoading(true);setError(null);setConfirm(false);setSuccess(false);setProgress('Reading homepage…');
      try {
        const html = await generateProductKnowledgeFromWebsite({
          url,
          extraContext: context,
          brandName,
          operation,
          onProgress: (message) => { if (operation.current()) setProgress(message); }
        });
        if (!operation.current()) return;
        if (!html) throw new Error('bad-output');
        // Brief success state before revealing the draft, so a content swap in
        // an already-filled editor is never missed. Draft is applied after.
        setLoading(false);
        setSuccess(true);
        access.schedule(() => {
          if (!operation.current()) return;
          onApply(html);
          onClose();
        }, 1050);
      } catch (e) {
        if (!operation.current()) return;
        // Honest failure diagnostic — real error object, no keys/tokens/user data.
        console.error('[ProductKnowledge] generation failed', {
          message: e && e.message,
          name: e && e.name,
          stack: e && e.stack
        });
        setLoading(false);
        setSuccess(false);
        setProgress('');
        setError(pkErrorMessage(e));
      } finally {
        if (generationScope.current === scope) generationScope.current = null;
      }
    }, [url, context, brandName, onApply, onClose]);

    const onGenerateClick = () => {
      if (!access.canAi()) return;
      if (!pkIsValidUrl(url)) {
        setUrlErr(url.trim() ? 'Please enter a valid website URL.' : 'Please enter your website URL.');
        if (urlRef.current) urlRef.current.focus();
        return;
      }
      setUrlErr(null);
      if (isCustom()) {setConfirm(true);return;}
      runGeneration();
    };

    if (!open) return null;

    return (
      <div className="bp-modal-scrim" onMouseDown={() => {if (!loading && !success) onClose();}}>
        <div
          className="bp-modal"
          role="dialog"
          aria-modal="true"
          aria-labelledby="pk-gen-title"
          onMouseDown={(e) => e.stopPropagation()}>
          <button type="button" className="bp-modal__x" onClick={onClose} aria-label="Close" disabled={loading || success}>
            <PkIconClose />
          </button>

          <div className="bp-modal__hd">
            <span className="bp-modal__icon"><PkIconSparkles /></span>
            <h2 id="pk-gen-title" className="bp-modal__title">Generate Product Knowledge from Website</h2>
            <p className="bp-modal__sub">
              Enter your website URL and we'll create a first draft of your product
              knowledge. You can edit everything before saving.
            </p>
          </div>

          <div className="bp-modal__body">
            {success ?
            <div className="bp-modal__success">
                <span className="bp-modal__success-ic"><PkIconCheckCircle /></span>
                <div className="bp-modal__success-title">Product Knowledge generated</div>
                <div className="bp-modal__success-sub">Your new draft is ready. Review it before saving.</div>
              </div> :
            loading ?
            <div className="bp-modal__loading">
                <span className="bp-spinner"></span>
                <span>{progress || 'Analyzing website…'}</span>
              </div> :
            confirm ?
            <div className="bp-modal__confirm">
                <span className="bp-modal__confirm-ic"><PkIconAlert /></span>
                <p>This will replace your current Product details draft. You can still edit the generated version before saving.</p>
              </div> :
            <React.Fragment>
                <div className="bp-modal__field">
                  <label className="bp-modal__label" htmlFor="pk-gen-url">
                    Website URL <span className="bp-modal__req">*</span>
                  </label>
                  <input readOnly={!access.canAi()}
                  id="pk-gen-url"
                  ref={urlRef}
                  className={`bp-input ${urlErr ? 'bp-input--err' : ''}`}
                  type="url"
                  value={url}
                  onChange={access.guard((e) => {setUrl(e.target.value);if (urlErr) setUrlErr(null);}, true)}
                  placeholder="https://example.com"
                  autoComplete="off" />
                  {urlErr && <div className="bp-modal__fielderr">{urlErr}</div>}
                </div>

                <div className="bp-modal__field">
                  <label className="bp-modal__label" htmlFor="pk-gen-ctx">
                    Extra context <span className="bp-modal__opt">· optional</span>
                  </label>
                  <textarea readOnly={!access.canAi()}
                  id="pk-gen-ctx"
                  className="bp-textarea"
                  value={context}
                  onChange={access.guard((e) => setContext(e.target.value), true)}
                  placeholder="Add anything the website may not explain clearly, such as your main product focus, services, pricing, or best-fit customers." />
                </div>

                {error &&
              <div className="bp-modal__error" role="alert">
                    <PkIconAlert />
                    <span>{error}</span>
                  </div>}
              </React.Fragment>}
          </div>

          <div className="bp-modal__ft">
            {success ?
            <button type="button" className="rl-btn rl-btn--secondary bp-btn" disabled>
                Cancel
              </button> :
            confirm ?
            <React.Fragment>
                <button type="button" className="rl-btn rl-btn--secondary bp-btn" onClick={() => setConfirm(false)} disabled={loading}>
                  Cancel
                </button>
                <button type="button" className="rl-btn rl-btn--primary bp-btn" onClick={runGeneration} disabled={!access.canAi() || loading}>
                  Replace and generate
                </button>
              </React.Fragment> :
            <React.Fragment>
                <button type="button" className="rl-btn rl-btn--secondary bp-btn" onClick={onClose} disabled={loading}>
                  Cancel
                </button>
                <button type="button" className="rl-btn rl-btn--primary bp-btn" onClick={onGenerateClick} disabled={!access.canAi() || loading}>
                  {loading ?
                <React.Fragment><span className="bp-spinner bp-spinner--light"></span><span>Generating…</span></React.Fragment> :
                <React.Fragment><PkIconSparkles /><span>Generate Product Knowledge</span></React.Fragment>}
                </button>
              </React.Fragment>}
          </div>
        </div>
      </div>);
  }

  /* ------------------------------------------------------------------ */
  /* Restore starter template — confirmation modal. Replaces the Product
     details content with the starter template + writing prompts. Never
     auto-saves. */
  function PkRestoreModal({ open, onClose, onConfirm }) {
    const access = window.ClicklyxKnowledgeAccess.useAccess();
    useEffect(() => {
      if (!open) return;
      const onKey = (e) => {if (e.key === 'Escape') onClose();};
      document.addEventListener('keydown', onKey);
      return () => document.removeEventListener('keydown', onKey);
    }, [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="pk-restore-title"
          onMouseDown={(e) => e.stopPropagation()}>
          <button type="button" className="bp-modal__x" onClick={onClose} aria-label="Close">
            <PkIconClose />
          </button>

          <div className="bp-modal__hd">
            <span className="bp-modal__icon"><PkIconReset /></span>
            <h2 id="pk-restore-title" className="bp-modal__title">Restore starter template?</h2>
            <p className="bp-modal__sub">
              This will replace the current Product Knowledge details with the
              original starter template and writing prompts. Your changes will not
              be saved until you click Save Product Knowledge.
            </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)}>
              <PkIconReset />
              <span>Restore template</span>
            </button>
          </div>
        </div>
      </div>);
  }

  /* ------------------------------------------------------------------ */
  /* Product Knowledge page */
  function ProductKnowledge() {
    const access = window.ClicklyxKnowledgeAccess.useAccess(() => { if (commitTimerRef.current) access.clearTimer(commitTimerRef.current); setStatus('idle'); });
    const emptyBaseline = useRef({ details: PK_DEFAULT_DETAILS, updatedAt: null });
    const savedRef = useRef(emptyBaseline.current);
    const editorRef = useRef(null);
    const controllerRef = useRef(null);
    const draftRevisionRef = useRef(0);

    const [dirty, setDirty] = useState(false);
    const [status, setStatus] = useState('idle'); // 'idle' | 'saving' | 'saved' | 'error'
    const [saveError, setSaveError] = useState('');
    const [loadState, setLoadState] = useState('loading'); // 'loading' | 'ready' | 'error'
    const [cloudBrandName, setCloudBrandName] = useState('');
    const [genOpen, setGenOpen] = useState(false);
    const [restoreOpen, setRestoreOpen] = useState(false);
    const [canUndo, setCanUndo] = useState(false);
    const [canRedo, setCanRedo] = useState(false);
    /* Editor undo/redo history - our own stack (not browser-native) so the
       disabled states stay reliable. Generated/saved/discarded content becomes
       a fresh baseline; only manual edits enter the stack. Capped to 50. */
    const undoStackRef = useRef([]);
    const redoStackRef = useRef([]);
    const lastHtmlRef = useRef('');
    const commitTimerRef = useRef(null);
    const HISTORY_MAX = 50;

    /* Push HTML into the uncontrolled editor + reveal the top of the doc. */
    const writeEditor = useCallback((html) => {
      const el = editorRef.current;
      if (el) {
        el.innerHTML = html;
        const scroll = el.closest('.bp-editor__scroll');
        if (scroll) scroll.scrollTop = 0;
        el.scrollTop = 0;
      }
      if (window.lucide) window.lucide.createIcons();
    }, []);

    /* Make `html` the new undo baseline and clear all history. */
    const clearEditorHistory = useCallback((html) => {
      undoStackRef.current = [];
      redoStackRef.current = [];
      lastHtmlRef.current = html != null ? html : editorRef.current ? editorRef.current.innerHTML : '';
      if (commitTimerRef.current) {access.clearTimer(commitTimerRef.current);commitTimerRef.current = null;}
      setCanUndo(false);
      setCanRedo(false);
    }, []);

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

    const applyCloudBaseline = useCallback((record, brandProfile) => {
      const next = record ? {
        details: record.details && record.details.trim() ? record.details : PK_DEFAULT_DETAILS,
        updatedAt: record.updatedAt || null
      } : emptyBaseline.current;
      savedRef.current = next;
      setCloudBrandName(brandProfile && brandProfile.brandName ? String(brandProfile.brandName).trim() : '');
      writeEditor(next.details);
      clearEditorHistory(next.details);
      draftRevisionRef.current += 1;
      setDirty(false);
      setStatus('idle');
      setSaveError('');
      setLoadState('ready');
      requestAnimationFrame(() => {
        const el = editorRef.current;
        const scroll = el && el.closest('.bp-editor__scroll');
        if (scroll) scroll.scrollTop = 0;
      });
    }, [writeEditor, clearEditorHistory]);

    const loadCloudKnowledge = useCallback(async () => {
      setLoadState('loading');
      const controller = ensureController();
      const result = controller ? await controller.load() : null;
      if (result && result.stale) return;
      if (!result || !result.ok) {
        setLoadState('error');
        return;
      }
      applyCloudBaseline(result.record, result.knowledge && result.knowledge.brandProfile);
    }, [ensureController, applyCloudBaseline]);
    const openGenerate = useCallback(async () => {
      const operation = access.capture(true);
      if (!operation) return;
      const cloud = window.RankLyxCloudKnowledge;
      if (cloud && typeof cloud.getKnowledgeSnapshot === 'function') {
        const result = await cloud.getKnowledgeSnapshot();
        if (!operation.current()) return;
        if (result && result.stale) return;
        if (result && result.ok && result.knowledge) {
          const brandProfile = result.knowledge.brandProfile;
          setCloudBrandName(brandProfile && brandProfile.brandName ? String(brandProfile.brandName).trim() : '');
        }
      }
      setGenOpen(true);
    }, []);

    useEffect(() => {
      if (loadState === 'ready') writeEditor(savedRef.current.details);
    }, [loadState, writeEditor]);

    useEffect(() => {
      const onWorkspaceSwitching = () => {
        access.cancel();
        setGenOpen(false); setRestoreOpen(false);
        if (commitTimerRef.current) access.clearTimer(commitTimerRef.current);
        if (controllerRef.current) controllerRef.current.invalidate();
        savedRef.current = emptyBaseline.current;
        setCloudBrandName('');
        writeEditor('');
        clearEditorHistory('');
        draftRevisionRef.current += 1;
        setDirty(false);
        setStatus('idle');
        setSaveError('');
        setLoadState('loading');
      };
      window.addEventListener('ranklyx:workspace-switching', onWorkspaceSwitching);
      loadCloudKnowledge();
      return () => {
        window.removeEventListener('ranklyx:workspace-switching', onWorkspaceSwitching);
        if (controllerRef.current) controllerRef.current.dispose();
      };
    }, [loadCloudKnowledge, writeEditor, clearEditorHistory]);

    const markDirty = useCallback(() => {
      if (!access.canMutate()) return;
      draftRevisionRef.current += 1;
      setDirty(true);
      setSaveError('');
      setStatus((s) => s === 'saved' || s === 'error' ? 'idle' : s);
    }, []);
    /* Commit the current editor HTML as one undo step (debounced grouping of a
       burst of typing). No-op when nothing changed since the last baseline. */
    const commitEdit = useCallback(() => {
      if (!access.canMutate()) return;
      if (commitTimerRef.current) {access.clearTimer(commitTimerRef.current);commitTimerRef.current = null;}
      const cur = editorRef.current ? editorRef.current.innerHTML : '';
      if (cur === lastHtmlRef.current) return;
      undoStackRef.current.push(lastHtmlRef.current);
      if (undoStackRef.current.length > HISTORY_MAX) undoStackRef.current.shift();
      redoStackRef.current = [];
      lastHtmlRef.current = cur;
      setCanUndo(true);
      setCanRedo(false);
    }, []);

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

    const undoEditor = useCallback(() => {
      if (!access.canMutate()) return;
      commitEdit(); // flush any pending typing into the stack first
      if (!undoStackRef.current.length) return;
      const cur = editorRef.current ? editorRef.current.innerHTML : '';
      const prev = undoStackRef.current.pop();
      redoStackRef.current.push(cur);
      if (redoStackRef.current.length > HISTORY_MAX) redoStackRef.current.shift();
      if (editorRef.current) editorRef.current.innerHTML = prev;
      lastHtmlRef.current = prev;
      if (window.lucide) window.lucide.createIcons();
      setCanUndo(undoStackRef.current.length > 0);
      setCanRedo(true);
      draftRevisionRef.current += 1;
      setDirty(true);
      setSaveError('');
    }, [commitEdit]);

    const redoEditor = useCallback(() => {
      if (!access.canMutate()) return;
      if (!redoStackRef.current.length) return;
      const cur = editorRef.current ? editorRef.current.innerHTML : '';
      const next = redoStackRef.current.pop();
      undoStackRef.current.push(cur);
      if (undoStackRef.current.length > HISTORY_MAX) undoStackRef.current.shift();
      if (editorRef.current) editorRef.current.innerHTML = next;
      lastHtmlRef.current = next;
      if (window.lucide) window.lucide.createIcons();
      setCanRedo(redoStackRef.current.length > 0);
      setCanUndo(true);
      draftRevisionRef.current += 1;
      setDirty(true);
      setSaveError('');
    }, []);

    const onSave = useCallback(async () => {
      const operation = access.capture(false);
      if (!operation) return;
      const controller = controllerRef.current;
      if (!controller || loadState !== 'ready') return;
      const revision = draftRevisionRef.current;
      const payload = {
        details: editorRef.current ? editorRef.current.innerHTML : savedRef.current.details
      };
      setStatus('saving');
      setSaveError('');
      const result = await controller.save(payload);
      if (!operation.current()) return;
      if (result && result.stale) return;
      if (!result || !result.ok) {
        const conflict = result && result.error && result.error.code === 'knowledge_conflict';
        setSaveError(conflict
          ? 'This Product Knowledge was updated elsewhere. Reload the latest version before saving again.'
          : "Couldn't save. Please try again.");
        setStatus('error');
        return;
      }
      const record = result.record;
      const next = {
        details: record.details && record.details.trim() ? record.details : PK_DEFAULT_DETAILS,
        updatedAt: record.updatedAt || null
      };
      savedRef.current = next;
      if (draftRevisionRef.current === revision) {
        writeEditor(next.details);
        clearEditorHistory(next.details);
        setDirty(false);
        setStatus('saved');
      } else {
        setDirty(true);
        setStatus('idle');
      }
    }, [loadState, writeEditor, clearEditorHistory]);

    /* Reset unsaved edits back to the last cloud-loaded or cloud-saved version. */
    const onReset = useCallback(() => {
      writeEditor(savedRef.current.details);
      draftRevisionRef.current += 1;
      setDirty(false);
      setStatus('idle');
      setSaveError('');
      clearEditorHistory(savedRef.current.details);
    }, [writeEditor, clearEditorHistory]);

    /* True when the editor holds content the user would not want silently
       overwritten — neither the default template nor the last saved draft. */
    const isCustomContent = useCallback(() => {
      const norm = (s) => (s || '').replace(/>\s+</g, '><').replace(/\s+/g, ' ').trim();
      const cur = editorRef.current ? norm(editorRef.current.innerHTML) : '';
      if (!cur) return false;
      return cur !== norm(PK_DEFAULT_DETAILS) && cur !== norm(savedRef.current.details);
    }, []);

    /* Drop a generated draft into the editor. Stays UNSAVED + fully editable.
       The generated draft becomes the new undo baseline (Undo/Redo disabled). */
    const applyGenerated = useCallback((html) => {
      if (!access.canAi()) return;
      writeEditor(html);
      draftRevisionRef.current += 1;
      setDirty(true);
      setStatus('idle');
      setSaveError('');
      clearEditorHistory(html);
    }, [writeEditor, clearEditorHistory]);

    /* Restore the starter template + writing prompts into the Product details
       editor. Like a generated draft this stays UNSAVED and fully editable, and
       keeps the user on this page. "Discard unsaved changes" still returns to the
       last saved version; "Save Product Knowledge" persists the restored
       template. */
    const applyRestore = useCallback(() => {
      if (!access.canMutate()) return;
      writeEditor(PK_DEFAULT_DETAILS);
      draftRevisionRef.current += 1;
      setDirty(true);
      setStatus('idle');
      setSaveError('');
      clearEditorHistory(PK_DEFAULT_DETAILS);
      setRestoreOpen(false);
    }, [writeEditor, clearEditorHistory]);

    useEffect(() => {if (window.lucide) window.lucide.createIcons();});

    if (loadState !== 'ready') {
      return (
        <div className={"rl-page bp-page" + (loadState === 'error' ? '' : ' c5-knowledge-loading')} data-screen-label={loadState === 'error' ? 'Product Knowledge unavailable' : 'Loading Product Knowledge'}>
          <div className="rl-ph" style={{ maxWidth: 560 }}>
            <span className="rl-ph__icon"><i data-lucide={loadState === 'error' ? 'alert-triangle' : 'loader-circle'}></i></span>
            <h2 className="rl-ph__title">{loadState === 'error' ? "We couldn't load Product Knowledge" : 'Loading Product Knowledge'}</h2>
            <p className="rl-ph__desc">{loadState === 'error' ? 'Your cloud knowledge 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={loadCloudKnowledge}>Try again</button>}
          </div>
        </div>);
    }

    return (
      <div className="rl-page bp-page" data-screen-label="Product Knowledge">
        <div className="bp-wrap">
          <header className="bp-head">
            <div className="bp-eyebrow">
              <i data-lucide="book-open"></i>
              <span>Knowledge</span>
            </div>
            <h1 className="bp-title">Product Knowledge</h1>
            <p className="bp-lede">
              Add details about your products, services, features, use cases, and
              offers so the AI can mention them accurately in your content.
            </p>
          </header>

          {/* Card — Product details */}
          <section className="bp-card">
            <div className="bp-card__hd" style={{ padding: "20px 22px 0px" }}>
              <div className="bp-card__heading">Product details</div>
              <div className="bp-card__help">
                Describe what you sell, how it works, who it helps, and when the AI
                should mention it in your content.
              </div>
            </div>
            <div className="bp-card__body bp-card__body--editor" style={{ margin: "0px" }}>
              <PkRichTextEditor
                editorRef={editorRef}
                onInput={onEditorInput}
                onGenerate={openGenerate}
                onRestore={access.guard(() => setRestoreOpen(true))}
                canUndo={canUndo}
                canRedo={canRedo}
                onUndo={undoEditor}
                onRedo={redoEditor} />
            </div>
          </section>

          <div className="bp-ai-note" style={{ height: "16px", gap: "6px", margin: "14px 2px 0px" }}>
            <PkIconAlert />
            <span>AI can make mistakes. Review important details before saving.</span>
          </div>

          {/* Actions */}
          <div className="bp-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">
                  <PkIconCheckCircle />
                  <span>Product knowledge saved</span>
                </span>}
              {status === 'error' &&
              <span className="bp-status bp-status--err">
                  <PkIconAlert />
                  <span>{saveError || "Couldn't save. Please try again."}</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">
              <button
                type="button"
                className="rl-btn rl-btn--secondary bp-btn"
                onClick={onReset}
                disabled={!dirty || status === 'saving'}>
                <PkIconReset />
                <span>Discard unsaved changes</span>
              </button>
              <button
                type="button"
                className="rl-btn rl-btn--primary bp-btn"
                onClick={onSave}
                disabled={!access.canMutate() || status === 'saving'}>
                {status === 'saving' ?
                <React.Fragment><span className="bp-spinner bp-spinner--light"></span><span>Saving…</span></React.Fragment> :
                <React.Fragment><PkIconCheck /><span>Save Product Knowledge</span></React.Fragment>}
              </button>
            </div>
          </div>
        </div>

        <PkGenerateModal
          open={genOpen}
          onClose={() => setGenOpen(false)}
          onApply={applyGenerated}
          brandName={cloudBrandName}
          isCustom={isCustomContent} />

        <PkRestoreModal
          open={restoreOpen}
          onClose={() => setRestoreOpen(false)}
          onConfirm={applyRestore} />
      </div>);
  }

  window.ProductKnowledge = ProductKnowledge;
})();
