/* Rank Lyx — Knowledge / Brand Voice — AI voice analysis

   Companion module to brand-voice.jsx. It analyses the user's writing SAMPLE
   (it never rewrites it) and turns it into an editable, structured Voice
   Profile that lives in its own card — outside the "How We Write" editor.

   Loaded BEFORE brand-voice.jsx. Everything the page needs is published on
   window:
     window.bvSampleText(htmlOrText)         -> plain text of a sample
     window.bvHash(str)                       -> short stable hash
     window.bvBuildVoicePrompt(sampleText)    -> the analysis prompt
     window.bvParseVoiceProfile(rawText)      -> { profile, parsedSections, missingSections }
     window.bvProfileValid(parsedSections)    -> bool
     window.bvAnalyzeVoice({ sampleText, onProgress }) -> raw model text (async)
     window.getPreparedBrandVoiceContext()    -> future AI-Writer context (not yet wired)
     window.BvVoiceProfileCard                -> React card with editable fields
     window.BvReanalyzeModal                  -> React confirmation modal
     window.BV_SECTIONS / BV_MSG / BV_ERR     -> shared constants

   The AI is asked for PLAIN structured text only (no JSON / HTML / code fences)
   under fixed headings; bvParseVoiceProfile splits that into editable fields. */

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

  /* The eight Voice Profile sections, in display order. `kind` only drives
     editing affordances (textarea sizing / helper hint), never AI behaviour. */
  const BV_SECTIONS = [
    { key: 'voiceSummary', heading: 'Voice Summary', label: 'Voice Summary', kind: 'summary',
      hint: '1–3 sentences describing the voice.' },
    { key: 'tonePersonality', heading: 'Tone & Personality', label: 'Tone & Personality', kind: 'bullets',
      hint: 'One trait per line.' },
    { key: 'sentenceParagraphStyle', heading: 'Sentence & Paragraph Style', label: 'Sentence & Paragraph Style', kind: 'bullets',
      hint: 'Rhythm, sentence and paragraph length.' },
    { key: 'readerRelationship', heading: 'Reader Relationship', label: 'Reader Relationship', kind: 'bullets',
      hint: 'How it speaks to the reader; pronouns like you / we / I / they.' },
    { key: 'vocabularyWordChoice', heading: 'Vocabulary & Word Choice', label: 'Vocabulary & Word Choice', kind: 'bullets',
      hint: 'Word choice, simplicity vs. complexity.' },
    { key: 'explanationStyle', heading: 'Explanation Style', label: 'Explanation Style', kind: 'bullets',
      hint: 'How ideas get explained.' },
    { key: 'formattingStyle', heading: 'Formatting Style', label: 'Formatting Style', kind: 'bullets',
      hint: 'Formatting habits: lists, headings, emphasis.' },
    { key: 'aiWritingRules', heading: 'AI Writing Rules', label: 'AI Writing Rules', kind: 'rules',
      hint: 'Numbered rules the AI should follow when writing in this voice.' }
  ];

  const BV_MIN_CHARS = 300;

  const BV_MSG = {
    empty: 'No voice profile yet. Add a writing sample above, then analyze it to create your AI voice profile.',
    tooShort: 'Add a longer writing sample before analyzing voice. Aim for at least a few paragraphs so the AI can understand your style.',
    sampleChanged: 'Your writing sample changed since this voice profile was analyzed. Re-analyze when you’re ready.',
    progress: ['Reading writing sample…', 'Identifying voice patterns…', 'Creating voice profile…']
  };

  const BV_ERR = {
    ai: 'We couldn’t analyze the writing sample. Please try again or add a longer sample.',
    parse: 'We analyzed the sample, but couldn’t format the voice profile. Please try again.'
  };

  /* ---------------------------------------------------------------- */
  /* Plain-text helpers */

  /* Visible plain text of a writing sample. Accepts HTML or text; converts
     block boundaries to newlines so character counts and prompts read like the
     user's actual prose. */
  function bvSampleText(htmlOrText) {
    const s = String(htmlOrText == null ? '' : htmlOrText);
    if (s.indexOf('<') === -1) return s.replace(/\u00a0/g, ' ').replace(/[ \t]+/g, ' ').replace(/\n{3,}/g, '\n\n').trim();
    const withBreaks = s
      .replace(/<\/(p|div|li|h[1-6]|blockquote|tr)>/gi, '\n')
      .replace(/<br\s*\/?>/gi, '\n');
    let text = '';
    try {
      const tmp = document.createElement('div');
      tmp.innerHTML = withBreaks;
      text = tmp.textContent || '';
    } catch (e) {
      text = withBreaks.replace(/<[^>]+>/g, '');
    }
    return text.replace(/\u00a0/g, ' ').replace(/[ \t]+/g, ' ').replace(/\n{3,}/g, '\n\n').trim();
  }

  /* Small stable hash (djb2) — used only to notice when the sample changed
     since the last analysis. Never stores or logs the text itself. */
  function bvHash(str) {
    const s = String(str == null ? '' : str);
    let h = 5381;
    for (let i = 0; i < s.length; i++) {
      h = ((h << 5) + h) + s.charCodeAt(i);
      h = h & 0xffffffff;
    }
    return (h >>> 0).toString(36);
  }

  /* ---------------------------------------------------------------- */
  /* Prompt — analyse style, never rewrite or invent. */
  function bvBuildVoicePrompt(sampleText) {
    return [
      'You are a writing-voice analyst. Analyze the WRITING SAMPLE below and describe HOW this person writes.',
      'Analyze the writing style only. Do NOT rewrite, improve, summarize, or continue the sample.',
      'Do NOT invent a brand strategy. Do NOT add product information. Do NOT write marketing copy.',
      'Base every observation strictly on evidence in the sample.',
      '',
      'Identify: how the writer sounds; sentence rhythm; paragraph style; vocabulary and word choice;',
      'directness; use of pronouns (you, we, I, they); level of simplicity or complexity; emotional tone;',
      'explanation style; formatting habits; and rules the AI should follow when writing in this voice.',
      '',
      'Return PLAIN STRUCTURED TEXT ONLY. Do NOT use JSON. Do NOT use HTML. Do NOT use code fences. Do NOT use markdown bold or headers (#).',
      'Use these exact section headings, each on its own line, in this order:',
      '',
      'Voice Summary',
      '(1–3 sentences explaining the voice)',
      '',
      'Tone & Personality',
      '(bulleted lines, each starting with "- ")',
      '',
      'Sentence & Paragraph Style',
      '(bulleted lines)',
      '',
      'Reader Relationship',
      '(bulleted lines about how the writing speaks to the reader and which pronouns it uses)',
      '',
      'Vocabulary & Word Choice',
      '(bulleted lines)',
      '',
      'Explanation Style',
      '(bulleted lines)',
      '',
      'Formatting Style',
      '(bulleted lines)',
      '',
      'AI Writing Rules',
      'A numbered list of 5 to 10 concrete, useful rules. Example style:',
      '1. Use short, direct sentences when explaining important ideas.',
      '2. Speak to the reader with "you" when giving advice or direction.',
      '3. Avoid corporate phrasing and make the writing sound human.',
      '',
      'WRITING SAMPLE (between triple quotes):',
      '"""',
      sampleText,
      '"""'
    ].join('\n');
  }

  /* ---------------------------------------------------------------- */
  /* Parser — split the model's plain text into editable fields. */

  function bvNormHeading(line) {
    return String(line || '')
      .replace(/^[\s>#*•\-\d.)]+/, '') // strip leading bullets / numbers / markdown
      .replace(/[*_`#]/g, '')
      .replace(/&/g, ' and ')
      .replace(/:/g, ' ')
      .toLowerCase()
      .replace(/[^a-z0-9 ]/g, ' ')
      .replace(/\s+/g, ' ')
      .trim();
  }

  /* Tidy a section body: drop leading/trailing blank lines, collapse runs of
     blank lines, trim trailing spaces. Leaves bullet markers / numbers intact
     so the editor preserves list formatting. */
  function bvCleanBody(lines) {
    const out = (lines || []).map((l) => l.replace(/\s+$/g, ''));
    while (out.length && !out[0].trim()) out.shift();
    while (out.length && !out[out.length - 1].trim()) out.pop();
    return out.join('\n').replace(/\n{3,}/g, '\n\n');
  }

  function bvParseVoiceProfile(raw) {
    const text = String(raw == null ? '' : raw)
      .replace(/```[a-z]*\n?/gi, '')
      .replace(/```/g, '')
      .replace(/\r/g, '');

    const normToKey = {};
    BV_SECTIONS.forEach((s) => {normToKey[bvNormHeading(s.heading)] = s.key;});

    const buckets = {};
    let current = null;
    text.split('\n').forEach((line) => {
      const norm = bvNormHeading(line);
      // A heading line is a line whose normalized form exactly equals a section
      // heading AND which carries no other body content.
      if (norm && normToKey[norm] && line.trim().replace(/[*_`#:]/g, '').length <= s_len(normToKey[norm])) {
        current = normToKey[norm];
        if (!buckets[current]) buckets[current] = [];
        return;
      }
      if (current) buckets[current].push(line);
    });

    const profile = {};
    const parsedSections = [];
    const missingSections = [];
    BV_SECTIONS.forEach((s) => {
      const body = bvCleanBody(buckets[s.key]);
      profile[s.key] = body;
      if (body && body.trim()) parsedSections.push(s.key); else missingSections.push(s.key);
    });
    return { profile, parsedSections, missingSections };
  }

  /* Length of a section's plain heading text — used to reject lines that merely
     start with a heading word but carry a full sentence after it. */
  function s_len(key) {
    const sec = BV_SECTIONS.find((x) => x.key === key);
    return sec ? sec.heading.length + 6 : 40;
  }

  /* A profile is usable if the core sections came through. */
  function bvProfileValid(parsedSections) {
    const set = new Set(parsedSections || []);
    return set.has('voiceSummary') && set.has('aiWritingRules') && set.size >= 5;
  }

  /* Combine a structured profile object into ONE formatted summary string
     ("Heading:\n<body>"), in section order. This is what now lives in the single
     editable field, and what legacy multi-field data is migrated into. */
  function bvBuildSummary(profile) {
    if (!profile || typeof profile !== 'object') return '';
    const parts = [];
    BV_SECTIONS.forEach((s) => {
      const body = String(profile[s.key] == null ? '' : profile[s.key]).trim();
      if (!body) return;
      parts.push(s.heading + ':\n' + body);
    });
    return parts.join('\n\n').trim();
  }

  /* Resolve a stored record to a single summary string:
       1. use voiceProfileSummary if present;
       2. else migrate a legacy voiceProfile object into one summary;
       3. else null.
     Never loses existing saved analysis. */
  function bvCoerceVoiceSummary(data) {
    if (!data || typeof data !== 'object') return null;
    if (typeof data.voiceProfileSummary === 'string' && data.voiceProfileSummary.trim()) {
      return data.voiceProfileSummary;
    }
    if (data.voiceProfile && typeof data.voiceProfile === 'object') {
      const s = bvBuildSummary(data.voiceProfile);
      return s || null;
    }
    return null;
  }

  /* ---------------------------------------------------------------- */
  function bvDelay(ms) {return new Promise((r) => setTimeout(r, ms));}

  /* Run the analysis. Reports progress through onProgress at each real step.
     Returns the raw model text; the caller parses + validates it. Diagnostics
     are intentionally metadata-only — never the sample or the response. */
  async function bvAnalyzeVoice({ sampleText, onProgress, operation = window.ClicklyxKnowledgeAccess.begin(true) }) {
    operation.assert();
    const report = (m) => {operation.assert(); if (typeof onProgress === 'function') onProgress(m);};
    report(BV_MSG.progress[0]); // Reading writing sample…
    await operation.run(() => bvDelay(420));

    const prompt = bvBuildVoicePrompt(sampleText);
    report(BV_MSG.progress[1]); // Identifying voice patterns…
    console.log('[BrandVoice] aiCallStarted');

    if (typeof window.appLLMAdapter !== 'function') throw new Error('ai-unavailable');
    const raw = await operation.run(() => window.appLLMAdapter({ prompt, mode: 'knowledge', requestOrigin: operation.origin }));
    console.log('[BrandVoice] aiCallCompleted');

    report(BV_MSG.progress[2]); // Creating voice profile…
    await operation.run(() => bvDelay(320));

    const clean = String(raw == null ? '' : raw).replace(/```[a-z]*\n?/gi, '').replace(/```/g, '').trim();
    if (!clean) throw new Error('empty');
    return clean;
  }

  /* ---------------------------------------------------------------- */
  /* Future AI-Writer context. EXISTS and is ready; not yet wired to the AI
     Writer (no shared Knowledge context builder yet). Returns the stripped
     sample text, the editable Voice Profile fields, and the AI Writing Rules. */
  function getPreparedBrandVoiceContext() {
    let data = {};
    try {data = JSON.parse(localStorage.getItem('brand_voice_knowledge') || '{}') || {};} catch (e) {}
    if (window.BrandVoiceStorage && typeof window.BrandVoiceStorage.getActiveProfile === 'function') {
      const active = window.BrandVoiceStorage.getActiveProfile(data);
      if (active) data = active;
    }
    const html = data.editorHtml || data.sample || '';
    const strip = (typeof window.bvStripTemplateHelpers === 'function') ? window.bvStripTemplateHelpers : (x) => x;
    const sampleText = bvSampleText(strip(html));
    /* Always hand the AI Writer ONE clean summary — migrate legacy fields first. */
    const voiceProfileSummary = bvCoerceVoiceSummary(data) || '';
    return { sampleText, voiceProfileSummary };
  }

  /* ---------------------------------------------------------------- */
  /* Voice Profile card body — ONE editable summary field. Empty state /
     progress / single textarea, plus the Analyze · Re-analyze action row. All
     higher-level behaviour (running analysis, confirming re-analysis, marking
     unsaved) lives in BrandVoice. */
  function BvVoiceProfileCard(props) {
    const access = window.ClicklyxKnowledgeAccess.useAccess();
    const {
      summary, analyzing, progress, error, validation,
      sampleChanged, onAnalyzeClick, onSummaryChange
    } = props;
    const hasProfile = !!(summary && summary.trim());
    const btnLabel = analyzing
      ? 'Analyzing voice…'
      : hasProfile ? 'Re-analyze voice' : 'Analyze voice';

    /* Fixed-height field with internal scroll. We deliberately do NOT auto-grow
       the height on each keystroke: toggling height to 'auto' and back collapses
       the textarea for a frame, shrinks the page, and clamps the page scroll to
       the top — which is the "jumps back to the first paragraph" bug. A stable
       height lets the browser keep the caret and scroll position naturally. */

    return (
      <section className="bp-card bv-vp-card">
        <div className="bp-card__hd">
          <div className="bp-card__heading">AI Voice Profile</div>
          <div className="bp-card__help">
            Review and edit the AI’s understanding of your writing voice.
          </div>
        </div>

        <div className="bp-card__body">
          {analyzing ? (
            <div className="bv-progress" role="status" aria-live="polite">
              <span className="bp-spinner"></span>
              <span className="bv-progress__msg">{progress || BV_MSG.progress[0]}</span>
            </div>
          ) : hasProfile ? (
            <div className="bv-profile">
              {sampleChanged &&
                <div className="bv-note" role="status">
                  <svg width="15" height="15" 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>
                  <span>{BV_MSG.sampleChanged}</span>
                </div>}

              <div className="bv-field bv-field--summary-one">
                <label className="bv-field__label" htmlFor="bv-summary">Voice Profile Summary</label>
                <textarea readOnly={!access.canMutate()}
                  id="bv-summary"
                  className="rl-textarea bv-summary__ta"
                  value={summary || ''}
                  spellCheck={true}
                  onChange={access.guard((e) => onSummaryChange(e.target.value))}></textarea>
                <div className="bv-field__hint">
                  Edit anything the AI got wrong. This summary will help future AI
                  writing match your voice more closely.
                </div>
              </div>
            </div>
          ) : (
            <div className="bv-empty">
              <span className="bv-empty__icon">
                <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><path d="M12 3a6 6 0 0 0-6 6c0 1.6.6 2.7 1.5 3.8.6.7 1.2 1.5 1.3 2.7h6.4c.1-1.2.7-2 1.3-2.7C17.4 11.7 18 10.6 18 9a6 6 0 0 0-6-6Z"></path><path d="M9 18h6"></path><path d="M10 21h4"></path></svg>
              </span>
              <p className="bv-empty__text">{BV_MSG.empty}</p>
            </div>
          )}

          {error &&
            <div className="bv-feedback bv-feedback--err" role="alert">
              <svg width="15" height="15" 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>
              <span>{error === 'parse' ? BV_ERR.parse : BV_ERR.ai}</span>
            </div>}

          {validation &&
            <div className="bv-feedback bv-feedback--warn" role="alert">
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m21.73 18-8-14a2 2 0 0 0-3.46 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z"></path><path d="M12 9v4"></path><path d="M12 17h.01"></path></svg>
              <span>{validation}</span>
            </div>}

          <div className="bv-analyze-row">
            <button
              type="button"
              className="rl-btn rl-btn--primary bp-btn bv-analyze-btn"
              onClick={access.guard(onAnalyzeClick, true)}
              disabled={!access.canAi() || analyzing}>
              {analyzing
                ? <React.Fragment><span className="bp-spinner bp-spinner--light"></span><span>{btnLabel}</span></React.Fragment>
                : <React.Fragment>
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M9.5 2.5 11 6l3.5 1.5L11 9l-1.5 3.5L8 9 4.5 7.5 8 6Z"></path><path d="M18 14l.9 2.1L21 17l-2.1.9L18 20l-.9-2.1L15 17l2.1-.9Z"></path></svg>
                    <span>{btnLabel}</span>
                  </React.Fragment>}
            </button>
            {hasProfile && !analyzing &&
              <span className="bv-analyze-row__hint">Editing the summary marks the page as unsaved.</span>}
          </div>
        </div>
      </section>);
  }

  /* Re-analyze confirmation modal — only shown when a profile already exists. */
  function BvReanalyzeModal({ open, onClose, onConfirm }) {
    const access = window.ClicklyxKnowledgeAccess.useAccess();
    React.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="bv-reanalyze-title"
          onMouseDown={(e) => e.stopPropagation()}>
          <button type="button" className="bp-modal__x" onClick={onClose} aria-label="Close">
            <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>
          </button>

          <div className="bp-modal__hd">
            <span className="bp-modal__icon">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M9.5 2.5 11 6l3.5 1.5L11 9l-1.5 3.5L8 9 4.5 7.5 8 6Z"></path><path d="M18 14l.9 2.1L21 17l-2.1.9L18 20l-.9-2.1L15 17l2.1-.9Z"></path></svg>
            </span>
            <h2 id="bv-reanalyze-title" className="bp-modal__title">Re-analyze voice?</h2>
            <p className="bp-modal__sub">
              This will replace the current AI Voice Profile with a new analysis
              based on your latest writing sample. Your writing sample will not be
              changed.
            </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.canAi()} onClick={access.guard(onConfirm, true)}>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M9.5 2.5 11 6l3.5 1.5L11 9l-1.5 3.5L8 9 4.5 7.5 8 6Z"></path><path d="M18 14l.9 2.1L21 17l-2.1.9L18 20l-.9-2.1L15 17l2.1-.9Z"></path></svg>
              <span>Re-analyze voice</span>
            </button>
          </div>
        </div>
      </div>);
  }

  /* ---------------------------------------------------------------- */
  /* Test this voice — generate a short sample in the captured voice so the user
     can sanity-check the analysis BEFORE relying on it. This is a Brand-Voice-
     only test: it uses ONLY the writing sample + the voice profile summary +
     the topic/instructions. It never touches Brand Profile, Product Knowledge,
     ICP Knowledge, prior tests, uploads, or website content. */

  const BV_TEST_MSG = {
    needSample: 'Add a writing sample before testing the voice.',
    needSummary: 'Analyze your writing sample first so the AI has a voice profile to follow.',
    needTopic: 'Add a test topic first.',
    failed: 'We couldn’t generate the sample. Please try again.',
    short: 'The sample was too short. Please try again.'
  };

  function bvBuildTestPrompt({ sampleText, voiceProfileSummary, topic, instructions }) {
    const lines = [
      'You are writing a short sample in a specific brand voice. Output ONLY the sample text — nothing else.',
      'Write in the style described in VOICE PROFILE and demonstrated in WRITING SAMPLE, matching it as closely as possible.',
      'Do not analyze the voice. Do not explain what you are doing. Do not say this is a test and do not mention the voice profile.',
      'Use the writing sample only as a style reference — do NOT copy or reuse its sentences.',
      'Avoid generic AI phrasing and overly polished corporate writing. Keep it natural and human.',
      '',
      'Length: 100–180 words, UNLESS the optional instructions ask for a different length or format.',
      '',
      'TOPIC:',
      topic
    ];
    if (instructions && instructions.trim()) {
      lines.push('', 'OPTIONAL INSTRUCTIONS:', instructions.trim());
    }
    lines.push('', 'VOICE PROFILE:', voiceProfileSummary);
    lines.push('', 'WRITING SAMPLE (style reference only — do not copy its sentences):', '"""', sampleText, '"""');
    lines.push('', 'Now write the sample:');
    return lines.join('\n');
  }

  async function bvGenerateTestSample({ sampleText, voiceProfileSummary, topic, instructions, operation = window.ClicklyxKnowledgeAccess.begin(true) }) {
    operation.assert();
    const prompt = bvBuildTestPrompt({ sampleText, voiceProfileSummary, topic, instructions });
    console.log('[BrandVoiceTest] aiCallStarted');
    if (typeof window.appLLMAdapter !== 'function') throw new Error('ai-unavailable');
    const raw = await operation.run(() => window.appLLMAdapter({ prompt, mode: 'knowledge', requestOrigin: operation.origin }));
    console.log('[BrandVoiceTest] aiCallCompleted');
    return String(raw == null ? '' : raw).replace(/```[a-z]*\n?/gi, '').replace(/```/g, '').trim();
  }

  /* Self-contained test card. All of its state (topic, instructions, output,
     loading, errors, copied) lives here so it NEVER marks Brand Voice unsaved
     and does not persist. Reads the live editor sample via getSampleHtml() and
     the current (incl. unsaved) summary via the voiceProfileSummary prop. */
  function BvTestVoiceCard({ getSampleHtml, voiceProfileSummary }) {
    const access = window.ClicklyxKnowledgeAccess.useAccess(() => { setLoading(false); });
    const [topic, setTopic] = useState('');
    const [instructions, setInstructions] = useState('');
    const [output, setOutput] = useState('');
    const [loading, setLoading] = useState(false);
    const [validation, setValidation] = useState(null); // 'sample' | 'summary' | 'topic'
    const [error, setError] = useState(null);            // 'failed' | 'short'
    const [copied, setCopied] = useState(false);

    const run = useCallback(async () => {
      const operation = access.capture(true);
      if (!operation) return;
      const html = getSampleHtml ? getSampleHtml() : '';
      const text = window.bvSampleText(window.bvStripTemplateHelpers(html));
      const hasSummary = !!(voiceProfileSummary && voiceProfileSummary.trim());
      console.log('[BrandVoiceTest] testStarted');
      console.log('[BrandVoiceTest] sampleChars', text.length);
      console.log('[BrandVoiceTest] hasVoiceProfileSummary', hasSummary);
      console.log('[BrandVoiceTest] topicChars', topic.trim().length);
      console.log('[BrandVoiceTest] optionalInstructionsChars', instructions.trim().length);

      setError(null);
      if (text.length < BV_MIN_CHARS) {setValidation('sample');return;}
      if (!hasSummary) {setValidation('summary');return;}
      if (!topic.trim()) {setValidation('topic');return;}
      setValidation(null);
      setLoading(true);
      try {
        const out = await bvGenerateTestSample({
          sampleText: text,
          operation,
          voiceProfileSummary,
          topic: topic.trim(),
          instructions: instructions.trim()
        });
        if (!operation.current()) return;
        console.log('[BrandVoiceTest] outputChars', (out || '').length);
        if (!out) {setError('failed');return;}
        if (out.split(/\s+/).filter(Boolean).length < 20) {setError('short');return;}
        setOutput(out);
      } catch (e) {
        if (!operation.current()) return;
        setError('failed');
        console.log('[BrandVoiceTest] testFailed');
      } finally {
        if (operation.current()) setLoading(false);
      }
    }, [getSampleHtml, voiceProfileSummary, topic, instructions]);

    const copy = useCallback(async () => {
      if (!output) return;
      /* Best-effort copy. The async clipboard API is the real path in normal
         browsers; execCommand is a gesture-bound fallback. Sandboxed preview
         iframes can block both, so the "Copied" confirmation is shown after the
         attempt rather than gated on a success flag that those contexts never
         report. */
      try {
        if (navigator.clipboard && navigator.clipboard.writeText) {
          await navigator.clipboard.writeText(output);
        } else {
          const t = document.createElement('textarea');
          t.value = output; t.style.position = 'fixed'; t.style.top = '0'; t.style.opacity = '0';
          document.body.appendChild(t); t.focus(); t.select();
          document.execCommand('copy');
          document.body.removeChild(t);
        }
      } catch (e) {
        try {
          const t = document.createElement('textarea');
          t.value = output; t.style.position = 'fixed'; t.style.top = '0'; t.style.opacity = '0';
          document.body.appendChild(t); t.focus(); t.select();
          document.execCommand('copy');
          document.body.removeChild(t);
        } catch (e2) {}
      }
      setCopied(true);
      setTimeout(() => setCopied(false), 1600);
    }, [output]);

    return (
      <section className="bp-card bv-test-card">
        <div className="bp-card__hd">
          <div className="bp-card__heading">Test this voice</div>
          <div className="bp-card__help">
            Generate a short sample to see whether the AI is matching your writing style.
          </div>
        </div>

        <div className="bp-card__body">
          <div className="bv-field">
            <label className="bv-field__label" htmlFor="bv-test-topic">Test topic</label>
            <input readOnly={!access.canAi()}
              id="bv-test-topic"
              className="rl-input"
              type="text"
              value={topic}
              onChange={access.guard((e) => setTopic(e.target.value), true)}
              placeholder="Example: Explain why SaaS companies should invest in SEO before they need it." />
          </div>

          <div className="bv-field bv-test__instr">
            <label className="bv-field__label" htmlFor="bv-test-instr">Optional instructions</label>
            <textarea readOnly={!access.canAi()}
              id="bv-test-instr"
              className="rl-textarea bv-test__instr-ta"
              value={instructions}
              onChange={access.guard((e) => setInstructions(e.target.value), true)}
              placeholder="Example: Make it sound more direct, keep it under 150 words, or write it as an intro."></textarea>
          </div>

          {validation &&
            <div className="bv-feedback bv-feedback--warn" role="alert">
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m21.73 18-8-14a2 2 0 0 0-3.46 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z"></path><path d="M12 9v4"></path><path d="M12 17h.01"></path></svg>
              <span>{validation === 'sample' ? BV_TEST_MSG.needSample : validation === 'summary' ? BV_TEST_MSG.needSummary : BV_TEST_MSG.needTopic}</span>
            </div>}

          {error &&
            <div className="bv-feedback bv-feedback--err" role="alert">
              <svg width="15" height="15" 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>
              <span>{error === 'short' ? BV_TEST_MSG.short : BV_TEST_MSG.failed}</span>
            </div>}

          {output &&
            <div className="bv-field bv-test__out">
              <label className="bv-field__label" htmlFor="bv-test-output">Generated sample</label>
              <textarea
                id="bv-test-output"
                className="rl-textarea bv-test__output"
                value={output}
                readOnly></textarea>
              <div className="bv-test__outrow">
                <button type="button" className="rl-btn rl-btn--secondary bp-btn" onClick={run} disabled={!access.canAi() || loading}>
                  <svg width="15" height="15" 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>
                  <span>Regenerate</span>
                </button>
                <button type="button" className="rl-btn rl-btn--secondary bp-btn" onClick={copy}>
                  {copied
                    ? <React.Fragment><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6 9 17l-5-5"></path></svg><span>Copied</span></React.Fragment>
                    : <React.Fragment><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect width="14" height="14" x="8" y="8" rx="2" ry="2"></rect><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"></path></svg><span>Copy</span></React.Fragment>}
                </button>
              </div>
            </div>}

          <div className="bv-analyze-row">
            <button
              type="button"
              className="rl-btn rl-btn--primary bp-btn bv-test-btn"
              onClick={run}
              disabled={!access.canAi() || loading}>
              {loading
                ? <React.Fragment><span className="bp-spinner bp-spinner--light"></span><span>Generating sample…</span></React.Fragment>
                : <React.Fragment>
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M9.5 2.5 11 6l3.5 1.5L11 9l-1.5 3.5L8 9 4.5 7.5 8 6Z"></path><path d="M18 14l.9 2.1L21 17l-2.1.9L18 20l-.9-2.1L15 17l2.1-.9Z"></path></svg>
                    <span>Generate sample</span>
                  </React.Fragment>}
            </button>
          </div>
        </div>
      </section>);
  }

  /* Publish */
  Object.assign(window, {
    BV_SECTIONS, BV_MIN_CHARS, BV_MSG, BV_ERR, BV_TEST_MSG,
    bvSampleText, bvHash, bvBuildVoicePrompt,
    bvParseVoiceProfile, bvProfileValid, bvAnalyzeVoice,
    bvBuildSummary, bvCoerceVoiceSummary,
    bvBuildTestPrompt, bvGenerateTestSample,
    getPreparedBrandVoiceContext,
    BvVoiceProfileCard, BvReanalyzeModal, BvTestVoiceCard
  });
})();
