/* Rank Lyx — Knowledge / Brand Profile

   The first Knowledge page. Lets a user set up their brand as an editable
   "brand document" rather than a stiff multi-field form:
     • Card 1 — Brand name (single-line)
     • Card 2 — Brand details (rich text editor, stores HTML)

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

const { useState, useEffect, useRef, useCallback } = React;

/* Starter Brand Profile template — the 8 section headings plus a short writing
   prompt under each. This is both the editable default shown when no profile is
   saved yet AND the content restored on demand via the toolbar's "Restore"
   button. Each prompt paragraph is tagged data-template-helper so the strip
   helper below can keep unchanged guidance out of the AI knowledge context. */
const BP_TEMPLATE_SECTIONS = [
  ['Business Type', 'Write what kind of business this is. Example: B2B SaaS company, SEO agency, ecommerce brand, marketplace, service business, or consulting firm.'],
  ['Industry', 'Write the industry, niche, or market the company operates in.'],
  ['Company Description', 'Explain what the company does, who it helps, and the main outcome it helps customers achieve.'],
  ['Products / Services Description', 'Describe the main products or services the company offers. Mention what each one does and who it is for.'],
  ['Positioning', 'Explain how the brand should be understood in the market. Mention what makes it different from alternatives.'],
  ['Target Customers', 'Describe the main customer types, buyer roles, company types, industries, or use cases the brand serves.'],
  ['Main Benefits', 'List the main outcomes customers get from using the product or service.'],
  ['Key Differentiators', 'Explain what makes the brand different or better than competitors, alternatives, or doing the work manually.']
];

const BP_DEFAULT_DETAILS = BP_TEMPLATE_SECTIONS
  .map(([heading, prompt]) => '<h2>' + heading + '</h2>\n<p data-template-helper="1">' + prompt + '</p>')
  .join('\n');

/* Normalized lookup of the starter prompts, used to detect guidance the user
   left untouched. */
const BP_HELPER_NORM_SET = new Set(
  BP_TEMPLATE_SECTIONS.map(([, prompt]) => prompt.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 (Outline,
   Research, Writing, Editor). Only paragraphs whose visible text EXACTLY
   matches a starter prompt are dropped — any user-written content, including an
   edited prompt, is preserved. Exposed on window so the knowledge consumers
   (e.g. ICP generation) can call it when preparing Brand Profile context. */
function bpStripTemplateHelpers(html) {
  const s = String(html == null ? '' : html);
  if (s.indexOf('<') === -1) return s;
  try {
    const tmp = document.createElement('div');
    tmp.innerHTML = s;
    tmp.querySelectorAll('p').forEach((p) => {
      const t = (p.textContent || '').replace(/\s+/g, ' ').trim().toLowerCase();
      if (t && BP_HELPER_NORM_SET.has(t)) p.remove();
    });
    return tmp.innerHTML;
  } catch (e) {
    return s;
  }
}
window.bpStripTemplateHelpers = bpStripTemplateHelpers;

function bpLucide(deps) {
  useEffect(() => {if (window.lucide) window.lucide.createIcons();}, deps);
}

/* Inline SVG icons for anything that mounts/unmounts or swaps across renders.
   Letting lucide rewrite a <i data-lucide> into <svg> and then having React
   reconcile/remove that same node throws removeChild and unmounts the app. */
function BpIconCheck() {
  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 BpIconCheckCircle() {
  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 BpIconAlert() {
  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 BpIconReset() {
  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 BpIconSparkles() {
  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 BpIconClose() {
  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 BpIconUndo() {
  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 BpIconRedo() {
  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.

   How it actually works here:
     • Page content comes from the authenticated Clicklyx Reader route, which
       securely fetches static website content and returns readable text.
       JavaScript-only content may be unavailable; there is no render fallback.
     • The homepage + a small set of priority internal pages are extracted,
       combined into a corpus, and sent through the authenticated app adapter
       under strict no-fabrication rules.
     • "Not clearly found" is only ever produced by the model AFTER it has been
       handed real page text — never as an instant stand-in. */
const BP_NOT_FOUND = 'Not clearly found on the website. Please add this manually.';
const BP_PRIORITY = [
  'about', 'product', 'products', 'features', 'service', 'services',
  'solution', 'solutions', 'use-case', 'use-cases', 'usecases', 'customer',
  'customers', 'case-stud', 'case-studies', 'pricing', 'plans', 'demo',
  'contact', 'platform', 'industr', 'company', 'what-we-do', 'how-it-works'];
/* Failure messages, separated by pipeline stage so the user sees what actually
   went wrong instead of a blanket "couldn't read the website". */
const BP_ERR_READ = 'We couldn’t read enough content from this website. You can try another URL, add extra context, or fill the Brand Profile manually.';
const BP_ERR_AI = 'We could read the website, but couldn’t generate a Brand Profile from it. Please try again or add extra context.';
const BP_ERR_OUTPUT = 'We generated a draft, but couldn’t format it safely for the editor. Please try again.';
const BP_ERR_ACCESS = 'Brand Profile generation stopped because Workspace access is temporarily unavailable. Your existing content has not changed. Try again once access is restored.';
/* Map a thrown error code → the right stage message. Unknown/reading codes
   (no-content, invalid-url, empty, network) fall back to the reading message. */
function bpErrorMessage(err) {
  const code = err && err.message ? err.message : '';
  if (code === 'ai-failed' || code === 'ai-empty') return BP_ERR_AI;
  if (code === 'bad-output') return BP_ERR_OUTPUT;
  return BP_ERR_READ;
}

function bpNormalizeUrl(raw) {
  const s = (raw || '').trim();
  return /^https?:\/\//i.test(s) ? s : 'https://' + s;
}
function bpIsValidUrl(raw) {
  if (!raw || !raw.trim()) return false;
  try {
    const u = new URL(bpNormalizeUrl(raw));
    return !!u.hostname && u.hostname.indexOf('.') > 0;
  } catch (e) {return false;}
}
function bpHostFromUrl(raw) {
  try {return new URL(bpNormalizeUrl(raw)).hostname.replace(/^www\./i, '');} catch (e) {return (raw || '').trim();}
}
function bpBrandFromUrl(raw) {
  const host = bpHostFromUrl(raw);
  const base = (host.split('.')[0] || host).replace(/[-_]+/g, ' ').trim();
  if (!base) return null;
  return base.replace(/\b\w/g, (c) => c.toUpperCase());
}
function bpEscape(s) {
  return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

/* Fetch one page through the shared, bounded Clicklyx Reader transport.
   Returns the text, or null on any failure (caller decides what's fatal). */
async function bpFetchReadable(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;
  }
}

/* Pull same-origin candidate links out of the reader's markdown, scored by
   how well their path/anchor text matches the priority list. */
function bpDiscoverInternalPages(markdown, homeFullUrl, max) {
  let baseHost = '';
  try { baseHost = new URL(homeFullUrl).hostname.replace(/^www\./i, ''); } catch (e) { return []; }
  const re = /\[([^\]]*)\]\((https?:\/\/[^)\s]+)\)/g;
  const seen = new Set();
  const scored = [];
  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;                                  // skip homepage itself
    if (/\.(png|jpe?g|gif|svg|webp|pdf|zip|css|js|ico|woff2?)$/i.test(path)) continue;
    const clean = u.origin + path;
    if (seen.has(clean)) continue;
    const hay = (path + ' ' + anchor).toLowerCase();
    let score = 0;
    for (const kw of BP_PRIORITY) if (hay.indexOf(kw) !== -1) score += 1;
    if (score === 0) continue;
    seen.add(clean);
    scored.push({ url: clean, score });
  }
  scored.sort((a, b) => b.score - a.score);
  return scored.slice(0, max || 8).map((x) => x.url);
}

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

/* Exact 8 sections, in order: [json key, display heading]. */
const BP_SECTIONS = [
  ['business_type', 'Business Type'],
  ['industry', 'Industry'],
  ['company_description', 'Company Description'],
  ['products_services_description', 'Products / Services Description'],
  ['positioning', 'Positioning'],
  ['target_customers', 'Target Customers'],
  ['main_benefits', 'Main Benefits'],
  ['key_differentiators', 'Key Differentiators']];

/* ---- Tolerant key matching ----------------------------------------------
   The model sometimes returns the right content under differently-cased or
   re-worded keys ("Business Type", "businessType", "Products and Services").
   We normalize keys to a comparable slug and match each of our 8 canonical
   sections against a list of accepted aliases (also normalized). */
function bpNormalizeKey(value) {
  return String(value == null ? '' : value)
    .toLowerCase()
    .replace(/&/g, ' and ')
    .replace(/[^a-z0-9]+/g, ' ')   // slashes, underscores, camelCase gaps, punctuation → space
    .replace(/([a-z])([0-9])/g, '$1 $2')
    .trim()
    .replace(/\s+/g, '_');
}
/* Canonical key → accepted aliases (compared after bpNormalizeKey). */
const BP_SECTION_ALIASES = {
  business_type: ['business_type', 'businesstype', 'business type', 'type_of_business', 'company_type'],
  industry: ['industry', 'industries', 'sector', 'vertical'],
  company_description: ['company_description', 'companydescription', 'company description',
    'about', 'about_us', 'overview', 'company_overview', 'description'],
  products_services_description: ['products_services_description', 'productsservicesdescription',
    'products / services description', 'products and services description', 'products & services description',
    'product / service description', 'product_service_description', 'products_services',
    'products_and_services', 'products', 'services', 'product', 'service',
    'products_and_services_description', 'offerings', 'solutions'],
  positioning: ['positioning', 'brand_positioning', 'market_positioning', 'position'],
  target_customers: ['target_customers', 'targetcustomers', 'target customers', 'target_customer',
    'target_audience', 'audience', 'icp', 'ideal_customer_profile', 'customers', 'target_market'],
  main_benefits: ['main_benefits', 'mainbenefits', 'main benefits', 'benefits',
    'customer_benefits', 'key_benefits', 'value'],
  key_differentiators: ['key_differentiators', 'keydifferentiators', 'key differentiators',
    'differentiators', 'key_differences', 'differences', 'unique_selling_points', 'usps',
    'unique_selling_proposition', 'competitive_advantages', 'what_makes_us_different']
};
/* Build a normalized-alias → canonicalKey lookup once. */
const BP_ALIAS_LOOKUP = (() => {
  const map = {};
  Object.keys(BP_SECTION_ALIASES).forEach((canon) => {
    BP_SECTION_ALIASES[canon].forEach((alias) => { map[bpNormalizeKey(alias)] = canon; });
    map[bpNormalizeKey(canon)] = canon;
  });
  return map;
})();

/* ---- Structured plain-text → safe editor HTML ---------------------------
   The model returns PLAIN STRUCTURED TEXT (not JSON): the 8 section headings on
   their own lines, "### Name" product subsections, and "- / * / •" bullet
   lines. We parse that forgivingly and build escaped editor HTML ourselves, so
   imperfect formatting can't break generation and the model never supplies
   markup. Allowed output tags: <h2> <h3> <p> <ul> <li> <strong>. */
const BP_NOT_FOUND_P = '<p>' + bpEscape(BP_NOT_FOUND) + '</p>';

/* Visible text of an HTML string — used to measure usefulness. */
function bpHtmlText(html) {
  return String(html || '').replace(/<[^>]*>/g, ' ').replace(/&[a-z]+;/gi, ' ')
    .replace(/\s+/g, ' ').trim();
}
/* One "Label: explanation" bullet → <li><strong>Label:</strong> explanation</li>.
   No colon → a plain <li>. Everything escaped. */
function bpBulletLi(text) {
  const t = String(text || '').trim();
  if (!t) return '';
  const m = t.match(/^([^:]{1,60}):\s+(.*\S)$/);
  if (m) return '<li><strong>' + bpEscape(m[1].trim()) + ':</strong> ' + bpEscape(m[2].trim()) + '</li>';
  return '<li>' + bpEscape(t) + '</li>';
}
/* Detect a MAIN section heading line → canonical key, else null.
   Strips leading hashes, surrounding bold markers, and a trailing colon, then
   matches the normalized text against the section aliases. Guarded to short
   lines so a sentence that merely contains "industry" is never a heading. */
function bpMatchHeading(line) {
  let s = String(line || '').trim();
  if (!s) return null;
  s = s.replace(/^#{1,6}\s*/, '');                 // markdown heading hashes
  s = s.replace(/^\*\*(.+?)\*\*$/, '$1').replace(/^__(.+?)__$/, '$1'); // bold wrap
  s = s.replace(/[:：]\s*$/, '').trim();            // trailing colon
  if (!s || s.length > 60 || s.split(/\s+/).length > 6) return null;
  return BP_ALIAS_LOOKUP[bpNormalizeKey(s)] || null;
}

/* Forgiving structured-text parser. Returns { html, detected, missing,
   fallbackUsed } or null when the response is genuinely empty/unusable. */
function bpStructuredTextToHtml(raw) {
  let text = String(raw == null ? '' : raw);
  // Drop any stray markdown code fences without trusting their contents.
  text = text.replace(/```[a-z]*\n?/gi, '').replace(/```/g, '');
  if (bpHtmlText(text).length < 40) return null;     // genuinely empty / too short

  const lines = text.split(/\r?\n/);
  const bodies = {};                                  // canon key → [block html, …]
  let cur = null;                                     // current canon key
  let para = [];                                      // buffered paragraph lines
  let bullets = [];                                   // buffered bullet items

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

  for (const rawLine of lines) {
    const line = rawLine.trim();
    if (!line) { flush(); continue; }

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

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

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

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

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

  // Fallback: nothing matched at all → dump the whole escaped response as
  // paragraphs under Company Description, the rest get the placeholder.
  let fallbackUsed = detected.length < 4;
  if (detected.length === 0) {
    const paras = text.split(/\n{2,}/).map((p) => p.replace(/\s+/g, ' ').trim()).filter(Boolean)
      .map((p) => '<p>' + bpEscape(p) + '</p>').join('\n');
    bodies.company_description = [paras || ('<p>' + bpEscape(text.trim()) + '</p>')];
    detected.push('company_description');
    const i = missing.indexOf('company_description');
    if (i !== -1) missing.splice(i, 1);
  }

  const html = BP_SECTIONS.map(([key, heading]) => {
    const body = (bodies[key] || []).join('\n').trim();
    return '<h2>' + heading + '</h2>\n' + (bpHtmlText(body).length > 0 ? body : BP_NOT_FOUND_P);
  }).join('\n');

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

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

  // 1–3 — fetch + read the homepage.
  tell('Reading homepage…');
  const home = await bpFetchReadable(full, operation);
  operation.assert();
  const homeLen = home ? home.replace(/\s+/g, ' ').trim().length : 0;
  if (homeLen < 350) {
    console.warn('[BrandProfile] read failed; stage=read-home; readableChars=' + homeLen);
    throw new Error('no-content');           // blocked / empty / unreadable
  }

  // 4 — discover priority internal pages from homepage links.
  tell('Looking for product and company pages…');
  const pages = bpDiscoverInternalPages(home, full, 6);

  // 5–6 — read up to 6 pages sequentially so their access checks cannot supersede each other.
  const extracted = [];
  if (pages.length) {
    tell('Extracting brand details…');
    for (const page of pages) {
      const txt = await bpFetchReadable(page, operation);
      operation.assert();
      if (txt) extracted.push({ url: page, txt });
    }
  }

  // 7 — build the corpus from the real page text (bounded).
  let corpus = 'HOMEPAGE:\n' + bpTrim(home, 4500);
  for (const e of extracted) {
    let path = e.url;
    try { path = new URL(e.url).pathname; } catch (x) {}
    corpus += '\n\n----\nPAGE (' + path + '):\n' + bpTrim(e.txt, 1800);
  }
  corpus = bpTrim(corpus, 12000);

  // Reading-stage guard (A): only fires when the REAL website text is too thin,
  // BEFORE the AI call — never for AI or formatting problems downstream.
  const corpusTextLen = corpus.replace(/\s+/g, ' ').trim().length;
  console.info('[BrandProfile] stage=read-ok pagesFetched=' + (1 + extracted.length) +
    ' corpusChars=' + corpus.length + ' corpusTextChars=' + corpusTextLen);
  if (corpusTextLen < 400) {
    console.warn('[BrandProfile] read failed; stage=read-corpus; corpusTextChars=' + corpusTextLen);
    throw new Error('no-content');
  }

  // 8 — hand the real text + user context to the model under strict rules.
  tell('Preparing your Brand Profile draft…');
  const ctx = (extraContext || '').trim();
  const brand = (brandName || '').trim();
  const prompt =
    'You are generating a Brand Profile for an AI writing software. This Brand ' +
    'Profile is an internal knowledge document that future AI agents (an Outline ' +
    'Agent, Research Agent, Writing Agent, and Editor) will use to create ' +
    'briefs, outlines, research notes, and articles.\n\n' +
    'Analyze the provided website text and optional user context. Write a ' +
    'useful, detailed Brand Profile from the brand’s own point of view using ' +
    'first-person plural language such as "we," "our," and "us." Do not use ' +
    'third person. ' +
    (brand
      ? ('The brand is "' + brand + '"; use this name naturally in important ' +
         'sections, such as "At ' + brand + ', we…". Do not repeat it in every ' +
         'sentence, but make the profile clearly specific to this exact ' +
         'company.\n\n')
      : ('Use the brand name naturally in important sections, such as "At ' +
         '[Brand Name], we…".\n\n')) +
    'Do NOT return JSON. Do NOT return HTML. Do NOT include markdown code ' +
    'fences. Return PLAIN STRUCTURED TEXT only.\n\n' +
    'Use exactly these 8 main section headings, each on its own line, in this ' +
    'order:\n' +
    'Business Type\nIndustry\nCompany Description\nProducts / Services ' +
    'Description\nPositioning\nTarget Customers\nMain Benefits\nKey ' +
    'Differentiators\n\n' +
    'Write each section as plain paragraphs under its heading. For Products / ' +
    'Services Description, if the company has multiple core products, services, ' +
    'hubs, modules, or solutions, use product subsections in this exact format:\n' +
    '### Product Name\n' +
    'Description of the product (what it does, who it helps, why it matters).\n\n' +
    'For Main Benefits and Key Differentiators, use bullet lists when there are ' +
    'multiple points, one per line, in the form:\n' +
    '* Label: explanation\n\n' +
    'Do not write a shallow summary. When the website contains enough ' +
    'information, provide useful detail. Do not fabricate products, features, ' +
    'pricing, results, awards, customer types, or differentiators. 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. Avoid generic writing ' +
    'and very long sentences. Keep the output easy for the user to review and ' +
    'edit.\n\n' +
    'WEBSITE CONTENT:\n' + corpus + '\n\n' +
    'USER EXTRA CONTEXT:\n' + (ctx || '(none provided)');

  // --- Single AI call (no JSON, no repair passes) ------------------------
  console.info('[BrandProfile] aiCallStarted');
  let raw;
  try {
    raw = await operation.run(() => window.appLLMAdapter({ prompt, mode: 'knowledge', requestOrigin: operation.origin }));
  } catch (e) {
    console.warn('[BrandProfile] aiCallError; stage=ai-call');
    operation.assert();
    const failure = new Error('ai-failed'); // website read OK, AI call failed
    failure.code = e && e.code || 'ai_provider_error';
    if (e && e.statusCode) failure.statusCode = e.statusCode;
    throw failure;
  }
  const rawLen = raw ? String(raw).length : 0;
  console.info('[BrandProfile] aiCallCompleted; aiRawChars=' + rawLen);

  // --- Forgiving structured-text → escaped editor HTML -------------------
  const parsed = bpStructuredTextToHtml(raw);
  if (!parsed) {                              // response genuinely empty / unusable
    console.warn('[BrandProfile] AI failed; stage=ai-empty; aiRawChars=' + rawLen);
    throw new Error('ai-empty');
  }

  console.info('[BrandProfile] detectedHeadings=' + JSON.stringify(parsed.detected) +
    ' missingHeadings=' + JSON.stringify(parsed.missing) +
    ' renderedHtmlChars=' + parsed.html.length +
    ' fallbackUsed=' + parsed.fallbackUsed);

  return parsed.html;
}

/* ------------------------------------------------------------------ */
/* Reusable rich text editor — contentEditable + a focused toolbar.
   Mirrors the Article Editor's approach (execCommand) and shares the
   .ed-* visual language so the interface stays consistent. Uncontrolled:
   the parent reads/writes content imperatively through `editorRef`. */
function BpToolBtn({ 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 RichTextEditor({ editorRef, onInput, onGenerate, onRestore, onSave, saveStatus, canUndo, canRedo, onUndo, onRedo }) {
  const access = window.ClicklyxKnowledgeAccess.useAccess();
  const [active, setActive] = useState({ block: 'p', bold: false, italic: false, ul: false, ol: false });

  /* The fixed toolbar icons only need painting when the editor mounts. */
  useEffect(() => {if (window.lucide) window.lucide.createIcons();}, []);

  /* Track active formatting for the caret/selection. */
  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) {}
      const next = {
        block,
        bold: safeState('bold'),
        italic: safeState('italic'),
        ul: safeState('insertUnorderedList'),
        ol: safeState('insertOrderedList')
      };
      setActive(previous => previous.block === next.block && previous.bold === next.bold &&
        previous.italic === next.italic && previous.ul === next.ul && previous.ol === next.ol
        ? previous : next);
    };
    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 saving = saveStatus === 'saving';

  return (
    <div className="bp-editor">
      <div className="ed-toolbar bp-toolbar" role="toolbar" aria-label="Formatting">
        <div className="bp-toolbar__format">
          <div className="ed-tgroup">
            <button
              type="button"
              className="ed-tool"
              title="Undo"
              aria-label="Undo"
              disabled={!access.canMutate() || !canUndo}
              onMouseDown={(e) => {e.preventDefault();if (access.canMutate() && canUndo && onUndo) onUndo();}}>
              <BpIconUndo />
            </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();}}>
              <BpIconRedo />
            </button>
          </div>
          <span className="ed-divider"></span>
          <div className="ed-tgroup">
            <BpToolBtn onCmd={onCmd} cmd="format" arg="p" label="¶" title="Paragraph" on={active.block === 'p'} />
            <BpToolBtn onCmd={onCmd} cmd="format" arg="h2" label="H2" title="Heading 2" on={active.block === 'h2'} />
            <BpToolBtn onCmd={onCmd} cmd="format" arg="h3" label="H3" title="Heading 3" on={active.block === 'h3'} />
          </div>
          <span className="ed-divider"></span>
          <div className="ed-tgroup">
            <BpToolBtn onCmd={onCmd} cmd="bold" icon="bold" title="Bold" on={active.bold} />
            <BpToolBtn onCmd={onCmd} cmd="italic" icon="italic" title="Italic" on={active.italic} />
          </div>
          <span className="ed-divider"></span>
          <div className="ed-tgroup">
            <BpToolBtn onCmd={onCmd} cmd="ul" icon="list" title="Bulleted list" on={active.ul} />
            <BpToolBtn onCmd={onCmd} 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">
            <BpIconReset />
            <span>Restore</span>
          </button>
          <button type="button" className="bp-gen-btn bp-gen-btn--tool" disabled={!access.canAi()} onClick={access.guard(onGenerate, true)}>
            <BpIconSparkles />
            <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="Brand details"></div>
      </div>
    </div>);

}

/* ------------------------------------------------------------------ */
/* Generate from website — modal + flow.
   Builds the draft, asks for confirmation before overwriting custom content,
   and hands the result back via onApply (which does NOT auto-save). */
function GenerateModal({ 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'
      ? BP_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);

  /* Reset everything each time the modal opens; focus the URL field. */
  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]);

  /* Escape closes (unless mid-generation or showing success). */
  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 generateBrandProfileFromWebsite({
        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 (never auto-saves).
      setLoading(false);
      setSuccess(true);
      access.schedule(() => {
        if (!operation.current()) return;
        onApply(html);          // writes into editor + flags unsaved
        onClose();              // close after the draft is inserted
      }, 1050);
    } catch (e) {
      if (!operation.current()) return;
      setLoading(false);
      setSuccess(false);
      setProgress('');
      setError(bpErrorMessage(e));
    } finally {
      if (generationScope.current === scope) generationScope.current = null;
    }
  }, [url, context, brandName, onApply, onClose]);

  const onGenerateClick = () => {
    if (!access.canAi()) return;
    if (!bpIsValidUrl(url)) {
      setUrlErr(url.trim() ? 'Please enter a valid website URL.' : 'Please enter your website URL.');
      if (urlRef.current) urlRef.current.focus();
      return;
    }
    setUrlErr(null);
    /* Only confirm when the editor holds custom content (not the default
       template and not the last saved version). */
    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="bp-gen-title"
        onMouseDown={(e) => e.stopPropagation()}>
        <button type="button" className="bp-modal__x" onClick={onClose} aria-label="Close" disabled={loading || success}>
          <BpIconClose />
        </button>

        <div className="bp-modal__hd">
          <span className="bp-modal__icon"><BpIconSparkles /></span>
          <h2 id="bp-gen-title" className="bp-modal__title">Generate Brand Profile from Website</h2>
          <p className="bp-modal__sub">
            Enter your website URL and we'll create a first draft of your brand
            profile. 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"><BpIconCheckCircle /></span>
              <div className="bp-modal__success-title">Brand Profile 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"><BpIconAlert /></span>
              <p>This will replace your current Brand 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="bp-gen-url">
                  Website URL <span className="bp-modal__req">*</span>
                </label>
                <input readOnly={!access.canAi()}
                  id="bp-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="bp-gen-ctx">
                  Extra context <span className="bp-modal__opt">· optional</span>
                </label>
                <textarea readOnly={!access.canAi()}
                  id="bp-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 best-fit customers, positioning, or product focus." />
              </div>

              {error &&
                <div className="bp-modal__error" role="alert">
                  <BpIconAlert />
                  <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><BpIconSparkles /><span>Generate Brand Profile</span></React.Fragment>}
              </button>
            </React.Fragment>}
        </div>
      </div>
    </div>);

}

/* ------------------------------------------------------------------ */
/* Restore starter template — confirmation modal.
   Replaces the Brand details content with the starter template + writing
   prompts. Never auto-saves and never touches the Brand name. */
function RestoreModal({ 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="bp-restore-title"
        onMouseDown={(e) => e.stopPropagation()}>
        <button type="button" className="bp-modal__x" onClick={onClose} aria-label="Close">
          <BpIconClose />
        </button>

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

}

/* ------------------------------------------------------------------ */
/* Brand Profile page */
function BrandProfile() {
  const access = window.ClicklyxKnowledgeAccess.useAccess(() => { if (commitTimerRef.current) access.clearTimer(commitTimerRef.current); setStatus('idle'); });
  const emptyBaseline = useRef({ brandName: '', details: BP_DEFAULT_DETAILS, updatedAt: null });
  const savedRef = useRef(emptyBaseline.current);
  const editorRef = useRef(null);
  const controllerRef = useRef(null);
  const brandNameRef = useRef('');
  const draftRevisionRef = useRef(0);

  const [brandName, setBrandName] = useState('');
  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 [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 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 + refresh any lucide icons inside. */
  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('brandProfile', { getOrigin: access.getOrigin });
    return controllerRef.current;
  }, []);

  const applyCloudBaseline = useCallback((record) => {
    const next = record ? {
      brandName: record.brandName || '',
      details: record.details && record.details.trim() ? record.details : BP_DEFAULT_DETAILS,
      updatedAt: record.updatedAt || null
    } : emptyBaseline.current;
    savedRef.current = next;
    brandNameRef.current = next.brandName;
    setBrandName(next.brandName);
    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 loadCloudProfile = 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);
  }, [ensureController, applyCloudBaseline]);

  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;
      brandNameRef.current = '';
      setBrandName('');
      writeEditor('');
      clearEditorHistory('');
      draftRevisionRef.current += 1;
      setDirty(false);
      setStatus('idle');
      setSaveError('');
      setLoadState('loading');
    };
    window.addEventListener('ranklyx:workspace-switching', onWorkspaceSwitching);
    loadCloudProfile();
    return () => {
      window.removeEventListener('ranklyx:workspace-switching', onWorkspaceSwitching);
      if (controllerRef.current) controllerRef.current.dispose();
    };
  }, [loadCloudProfile, writeEditor, clearEditorHistory]);

  const markDirty = useCallback(() => {
    if (!access.canMutate()) return;
    draftRevisionRef.current += 1;
    setDirty(true);
    setSaveError('');
    setStatus((s) => (s === 'saved' || s === 'error') ? 'idle' : s);
  }, []);
  /* Commit current editor HTML as one undo step (debounced grouping). */
  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 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 onName = (v) => {
    if (!access.canMutate()) return;
    brandNameRef.current = v;
    setBrandName(v);
    markDirty();
  };

  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 = {
      brandName: brandNameRef.current.trim(),
      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 Brand Profile 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 = {
      brandName: record.brandName || '',
      details: record.details && record.details.trim() ? record.details : BP_DEFAULT_DETAILS,
      updatedAt: record.updatedAt || null
    };
    savedRef.current = next;
    if (draftRevisionRef.current === revision) {
      brandNameRef.current = next.brandName;
      setBrandName(next.brandName);
      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(() => {
    const snap = savedRef.current;
    brandNameRef.current = snap.brandName;
    setBrandName(snap.brandName);
    writeEditor(snap.details);
    draftRevisionRef.current += 1;
    setDirty(false);
    setStatus('idle');
    setSaveError('');
    clearEditorHistory(snap.details);
  }, [writeEditor, clearEditorHistory]);

  /* True when the editor holds content the user would not want silently
     overwritten — i.e. neither the default template nor the last saved draft.
     Whitespace/inter-tag differences from contentEditable are normalized out. */
  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(BP_DEFAULT_DETAILS) && cur !== norm(savedRef.current.details);
  }, []);

  /* Drop a generated draft into the editor. Stays UNSAVED + fully editable;
     the user must click Save Brand Profile to persist. */
  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 Brand details
     editor. Like a generated draft this stays UNSAVED and fully editable, leaves
     the Brand name untouched, and keeps the user on this page. "Discard unsaved
     changes" still returns to the last saved version; "Save Brand Profile"
     persists the restored template. */
  const applyRestore = useCallback(() => {
    if (!access.canMutate()) return;
    writeEditor(BP_DEFAULT_DETAILS);
    draftRevisionRef.current += 1;
    setDirty(true);
    setStatus('idle');
    setSaveError('');
    clearEditorHistory(BP_DEFAULT_DETAILS);
    setRestoreOpen(false);
  }, [writeEditor, clearEditorHistory]);

  bpLucide([loadState, status]);

  if (loadState !== 'ready') {
    return (
      <div className={"rl-page bp-page" + (loadState === 'error' ? '' : ' c5-knowledge-loading')} data-screen-label={loadState === 'error' ? 'Brand Profile unavailable' : 'Loading Brand Profile'}>
        <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 Brand Profile" : 'Loading Brand Profile'}</h2>
          <p className="rl-ph__desc">{loadState === 'error' ? 'Your cloud profile 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={loadCloudProfile}>Try again</button>}
        </div>
      </div>);
  }

  return (
    <div className="rl-page bp-page" data-screen-label="Brand Profile">
      <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">Set up Brand Profile</h1>
          <p className="bp-lede">
            Add your brand details so the AI can understand your company and create
            content that feels relevant to your business.
          </p>
        </header>

        {/* Card 1 — Brand name */}
        <section className="bp-card">
          <div className="bp-card__hd">
            <div className="bp-card__heading">Brand name</div>
            <div className="bp-card__help">What is your brand called?</div>
          </div>
          <div className="bp-card__body">
            <input readOnly={!access.canMutate()}
              className="bp-input"
              type="text"
              value={brandName}
              onChange={(e) => onName(e.target.value)}
              placeholder="e.g. Surfer SEO"
              autoComplete="off"
              aria-label="Brand name" />
          </div>
        </section>

        {/* Card 2 — Brand details */}
        <section className="bp-card">
          <div className="bp-card__hd">
            <div className="bp-card__heading">Brand details</div>
            <div className="bp-card__help">
              Tell the AI what your company does, who you help, how you are
              positioned, and what makes your brand different.
            </div>
          </div>
          <div className="bp-card__body bp-card__body--editor">
            <RichTextEditor
              editorRef={editorRef}
              onInput={onEditorInput}
              onGenerate={access.guard(() => setGenOpen(true), true)}
              onRestore={access.guard(() => setRestoreOpen(true))}
              onSave={onSave}
              saveStatus={status}
              canUndo={canUndo}
              canRedo={canRedo}
              onUndo={undoEditor}
              onRedo={redoEditor} />
          </div>
        </section>

        <div className="bp-ai-note">
          <BpIconAlert />
          <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">
                <BpIconCheckCircle />
                <span>Brand profile saved</span>
              </span>}
            {status === 'error' &&
              <span className="bp-status bp-status--err">
                <BpIconAlert />
                <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'}>
              <BpIconReset />
              <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><BpIconCheck /><span>Save Brand Profile</span></React.Fragment>}
            </button>
          </div>
        </div>
      </div>

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

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

}

window.BrandProfile = BrandProfile;
