/* Rank Lyx — Knowledge / Brand Voice

   The fourth Knowledge page. Teaches the AI how the brand naturally writes by
   capturing one real writing sample — nothing else. Deliberately focused for
   V1: a single rich text editor ("How We Write"). No voice notes, words to
   avoid, formatting rules, examples, tone dropdowns, analysis, scoring, or AI
   generation — those may come later.

   Persistence uses the Workspace-scoped Knowledge API. Custom profiles are
   shared Workspace resources, while selection on this page is UI-only.


   Visual language is shared with Brand Profile / Product Knowledge — it reuses
   the existing .bp-* and .ed-* classes so the page looks identical to the other
   Knowledge pages. */

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

  /* Starter "How We Write" prompt — a single writing prompt (NOT multiple
     sections). Shown when nothing is saved yet and restored on demand via the
     toolbar's "Restore" button. Every block is tagged data-template-helper so
     bvStripTemplateHelpers can keep unchanged guidance out of any future AI
     knowledge context. */
  const BV_HELPER_PARAS = [
    'Write or paste a sample of your brand’s writing here.',
    'Talk naturally. Explain something the way you would explain it to a real person.',
    'You can write about:'
  ];
  const BV_HELPER_BULLETS = [
    'something your company believes',
    'a common problem your customers face',
    'how you explain your product or service',
    'a topic you care about',
    'an opinion you want your content to reflect'
  ];
  const BV_HELPER_CLOSER =
    'Do not worry about making it perfect. The AI needs your natural rhythm, word choice, and point of view.';

  const BV_DEFAULT_SAMPLE =
    BV_HELPER_PARAS.map((t) => '<p data-template-helper="1">' + t + '</p>').join('\n') +
    '\n<ul data-template-helper="1">\n' +
    BV_HELPER_BULLETS.map((t) => '<li data-template-helper="1">' + t + '</li>').join('\n') +
    '\n</ul>\n<p data-template-helper="1">' + BV_HELPER_CLOSER + '</p>';

  /* Normalized lookup of every starter prompt (paragraphs + closer + bullets),
     used to detect guidance the user left untouched. */
  const BV_HELPER_NORM_SET = new Set(
    BV_HELPER_PARAS
      .concat([BV_HELPER_CLOSER])
      .concat(BV_HELPER_BULLETS)
      .map((t) => t.replace(/\s+/g, ' ').trim().toLowerCase())
  );

  /* Remove starter helper text the user never edited, so the default writing
     prompt can never leak into the knowledge context sent to AI agents in the
     future. Only elements whose visible text EXACTLY matches a starter prompt
     are dropped — any user-written content, including an edited prompt, is
     preserved. A bullet list left fully default is emptied and then removed.

     For now this only needs to EXIST and be ready; it is not yet connected to
     the AI Writer. When a shared Knowledge context builder consumes Brand Voice,
     it should call window.bvStripTemplateHelpers(html) first. */
  function bvStripTemplateHelpers(html) {
    const s = String(html == null ? '' : html);
    if (s.indexOf('<') === -1) return s;
    try {
      const tmp = document.createElement('div');
      tmp.innerHTML = s;
      const norm = (el) => (el.textContent || '').replace(/\s+/g, ' ').trim().toLowerCase();
      tmp.querySelectorAll('li').forEach((li) => {
        const t = norm(li);
        if (t && BV_HELPER_NORM_SET.has(t)) li.remove();
      });
      tmp.querySelectorAll('ol, ul').forEach((list) => {
        if (!list.querySelector('li')) list.remove();
      });
      tmp.querySelectorAll('p').forEach((p) => {
        const t = norm(p);
        if (t && BV_HELPER_NORM_SET.has(t)) p.remove();
      });
      return tmp.innerHTML;
    } catch (e) {
      return s;
    }
  }
  window.bvStripTemplateHelpers = bvStripTemplateHelpers;

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

  /* Inline SVG icons for anything that mounts/unmounts or swaps across renders
     (same set/visual language as Brand Profile). Inline SVG rather than letting
     lucide rewrite a <i data-lucide> into <svg> — that can throw removeChild
     when React later reconciles the node. */
  function BvIconCheck() {
    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 BvIconCheckCircle() {
    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 BvIconAlert() {
    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 BvIconReset() {
    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 BvIconClose() {
    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 BvIconUndo() {
    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 BvIconRedo() {
    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>);
  }

  /* ------------------------------------------------------------------ */
  /* Reusable rich text editor — same contentEditable + execCommand pattern and
     .ed-* visual language as Brand Profile / Product Knowledge. Uncontrolled:
     the parent reads/writes content imperatively through `editorRef`.
     Toolbar: Paragraph, H2, H3, Bold, Italic, Bullets, Numbered list, plus
     Undo/Redo and Restore. No "Generate from website". */
  function BvToolBtn({ 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 BvRichTextEditor({ editorRef, onInput, onRestore, canUndo, canRedo, onUndo, onRedo }) {
    const access = window.ClicklyxKnowledgeAccess.useAccess();
    const [active, setActive] = useState({ block: 'p', bold: false, italic: false, ul: false, ol: false });

    /* Keep toolbar buttons' icons painted after every render. */
    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) {}
        setActive({
          block,
          bold: safeState('bold'),
          italic: safeState('italic'),
          ul: safeState('insertUnorderedList'),
          ol: safeState('insertOrderedList')
        });
      };
      document.addEventListener('selectionchange', update);
      return () => document.removeEventListener('selectionchange', update);
    }, [editorRef]);

    const exec = (cmd, arg) => {try {document.execCommand(cmd, false, arg);} catch (e) {}};

    const onCmd = (cmd, arg) => {
      if (!access.canMutate()) return;
      if (editorRef.current) editorRef.current.focus();
      switch (cmd) {
        case 'format': exec('formatBlock', arg.toUpperCase()); break;
        case 'bold': exec('bold'); break;
        case 'italic': exec('italic'); break;
        case 'ul': exec('insertUnorderedList'); break;
        case 'ol': exec('insertOrderedList'); break;
        default: break;
      }
      if (onInput) onInput();
    };

    const Btn = (p) => <BvToolBtn onCmd={onCmd} {...p} />;

    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();}}>
                <BvIconUndo />
              </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();}}>
                <BvIconRedo />
              </button>
            </div>
            <span className="ed-divider"></span>
            <div className="ed-tgroup">
              <Btn cmd="format" arg="p" label="¶" title="Paragraph" on={active.block === 'p'} />
              <Btn cmd="format" arg="h2" label="H2" title="Heading 2" on={active.block === 'h2'} />
              <Btn cmd="format" arg="h3" label="H3" title="Heading 3" on={active.block === 'h3'} />
            </div>
            <span className="ed-divider"></span>
            <div className="ed-tgroup">
              <Btn cmd="bold" icon="bold" title="Bold" on={active.bold} />
              <Btn cmd="italic" icon="italic" title="Italic" on={active.italic} />
            </div>
            <span className="ed-divider"></span>
            <div className="ed-tgroup">
              <Btn cmd="ul" icon="list" title="Bulleted list" on={active.ul} />
              <Btn cmd="ol" icon="list-ordered" title="Numbered list" on={active.ol} />
            </div>
          </div>
          <div className="bp-toolbar__actions">
            <button type="button" className="bp-gen-btn bp-gen-btn--tool" disabled={!access.canMutate()} onClick={access.guard(onRestore)} title="Restore the starter writing prompt">
              <BvIconReset />
              <span>Restore</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="How we write"></div>
        </div>
      </div>);
  }

  /* ------------------------------------------------------------------ */
  /* Restore starter template — confirmation modal.
     Replaces ONLY the Brand Voice editor content with the starter writing
     prompt. Never auto-saves, marks the page unsaved, and keeps the user here. */
  function BvRestoreModal({ 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="bv-restore-title"
          onMouseDown={(e) => e.stopPropagation()}>
          <button type="button" className="bp-modal__x" onClick={onClose} aria-label="Close">
            <BvIconClose />
          </button>

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

  function BvDeleteModal({ open, onClose, onConfirm, voiceName, busy }) {
    const access = window.ClicklyxKnowledgeAccess.useAccess();
    useEffect(() => {
      if (!open) return;
      const onKey = (e) => {if (e.key === 'Escape' && !busy) onClose();};
      document.addEventListener('keydown', onKey);
      return () => document.removeEventListener('keydown', onKey);
    }, [open, busy, onClose]);

    if (!open) return null;

    return (
      <div className="bp-modal-scrim" onMouseDown={busy ? undefined : onClose}>
        <div
          className="bp-modal bp-modal--confirm"
          role="dialog"
          aria-modal="true"
          aria-labelledby="bv-delete-title"
          onMouseDown={(e) => e.stopPropagation()}>
          <button type="button" className="bp-modal__x" onClick={onClose} aria-label="Close" disabled={busy}>
            <BvIconClose />
          </button>

          <div className="bp-modal__hd">
            <span className="bp-modal__icon aud-icon-danger"><BvIconAlert /></span>
            <h2 id="bv-delete-title" className="bp-modal__title">Delete this voice?</h2>
            <p className="bp-modal__sub">
              {voiceName ? <>“{voiceName}” will be removed from your saved Brand Voice profiles.</> : <>This Brand Voice profile will be removed.</>}
            </p>
          </div>

          <div className="bp-modal__ft">
            <button type="button" className="rl-btn rl-btn--secondary bp-btn" onClick={onClose} disabled={busy}>
              Keep voice
            </button>
            <button type="button" className="rl-btn rl-btn--primary bp-btn aud-danger-btn" disabled={!access.canMutate() || busy} onClick={access.guard(onConfirm)}>
              {busy ? 'Deleting...' : 'Delete voice'}
            </button>
          </div>
        </div>
      </div>);
  }

  /* ------------------------------------------------------------------ */
  /* Brand Voice page */
  function BrandVoice({ briefReturnContext, onReturnToBrief }) {
    const access = window.ClicklyxKnowledgeAccess.useAccess(() => { if (commitTimerRef.current) access.clearTimer(commitTimerRef.current); analysisRequestRef.current += 1; setAnalyzing(false); setStatus('idle'); setDeleteBusy(false); });
    const VoiceCard = window.BvVoiceProfileCard;
    const ReanalyzeModal = window.BvReanalyzeModal;
    const TestCard = window.BvTestVoiceCard;

    /* Last saved snapshot — the source of truth for Discard. Holds BOTH the
       writing sample and the Voice Profile summary + analysis metadata. */
    const emptyBaselineRef = useRef({
      id: null,
      name: '',
      editorHtml: BV_DEFAULT_SAMPLE,
      sample: BV_DEFAULT_SAMPLE,
      voiceProfileSummary: null,
      analyzedAt: null,
      sourceSampleHash: null,
      sourceSampleLength: null,
      metadata: {},
      createdAt: null,
      updatedAt: null
    });
    const savedRef = useRef(emptyBaselineRef.current);
    const editorRef = useRef(null);
    const controllerRef = useRef(null);
    const pageOrigin = access.getOrigin();
    const loadOriginRef = useRef(pageOrigin);
    const draftRevisionRef = useRef(0);
    const workspaceRevisionRef = useRef(0);
    const analysisRequestRef = useRef(0);
    const mountedRef = useRef(true);
    const briefReturnContextRef = useRef(briefReturnContext || null);
    const pendingEditorWriteRef = useRef(false);
    const pendingEditorHtmlRef = useRef(null);

    const [dirty, setDirty] = useState(false);
    const [status, setStatus] = useState('idle'); // 'idle' | 'saving' | 'saved' | 'error'
    const [loadState, setLoadState] = useState('loading'); // 'loading' | 'ready' | 'error'
    const [saveError, setSaveError] = useState('');
    const [reloadRequired, setReloadRequired] = useState(false);
    const [deleteBusy, setDeleteBusy] = useState(false);
    const [profiles, setProfiles] = useState([]);
    const [selectedProfileId, setSelectedProfileId] = useState(null);
    const [voiceName, setVoiceName] = useState('');
    const [nameError, setNameError] = useState('');
    const [deleteOpen, setDeleteOpen] = useState(false);
    const [restoreOpen, setRestoreOpen] = useState(false);
    const [canUndo, setCanUndo] = useState(false);
    const [canRedo, setCanRedo] = useState(false);

    /* AI Voice Profile state. The profile is now ONE editable summary string;
       analysis metadata lets us detect when the sample has drifted from what
       was analyzed. */
    const [voiceProfileSummary, setVoiceProfileSummary] = useState(null);
    const [analyzing, setAnalyzing] = useState(false);
    const [analyzeProgress, setAnalyzeProgress] = useState('');
    const [analyzeError, setAnalyzeError] = useState(null); // null | 'ai' | 'parse'
    const [validationMsg, setValidationMsg] = useState(null);
    const [sampleChanged, setSampleChanged] = useState(false);
    const [reanalyzeOpen, setReanalyzeOpen] = useState(false);
    const [analyzedHash, setAnalyzedHash] = useState(null);
    const [analyzedLen, setAnalyzedLen] = useState(null);
    const [analyzedAt, setAnalyzedAt] = useState(null);

    /* Refs mirrored from state so the editor's input handler can read the
       latest summary/hash without being re-created on every change. */
    const summaryRef = useRef(null);
    const analyzedHashRef = useRef(null);
    useEffect(() => {summaryRef.current = voiceProfileSummary;}, [voiceProfileSummary]);
    useEffect(() => {analyzedHashRef.current = analyzedHash;}, [analyzedHash]);

    /* Editor undo/redo history — our own stack (not browser-native) so disabled
       states stay reliable. Saved/discarded/restored 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. */
    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();
    }, []);

    /* Compute whether the current sample differs from what was last analyzed. */
    const computeChanged = useCallback((html, hash) => {
      if (!hash) return false;
      const cur = window.bvHash(window.bvSampleText(window.bvStripTemplateHelpers(html)));
      return cur !== hash;
    }, []);

    /* Normalize every cloud field needed for the editor and saved baseline. */
    const snapshotFromProfile = useCallback((profile) => {
      const p = profile || {};
      const editorHtml = (p.editorHtml || p.sample || '').trim() ? (p.editorHtml || p.sample) : BV_DEFAULT_SAMPLE;
      return {
        id: p.id || null,
        name: p.name || '',
        editorHtml,
        sample: p.sample || editorHtml,
        voiceProfileSummary: p.voiceProfileSummary && String(p.voiceProfileSummary).trim() ? p.voiceProfileSummary : null,
        analyzedAt: p.analyzedAt || null,
        sourceSampleHash: p.sourceSampleHash || null,
        sourceSampleLength: p.sourceSampleLength != null ? p.sourceSampleLength : null,
        metadata: p.metadata && typeof p.metadata === 'object' ? p.metadata : {},
        createdAt: p.createdAt || null,
        updatedAt: p.updatedAt || null
      };
    }, []);

    const loadProfileIntoEditor = useCallback((profile) => {
      const next = snapshotFromProfile(profile);
      savedRef.current = next;
      setSelectedProfileId(next.id);
      setVoiceName(next.name);
      setNameError('');
      writeEditor(next.editorHtml);
      lastHtmlRef.current = next.editorHtml;
      undoStackRef.current = [];
      redoStackRef.current = [];
      setCanUndo(false);
      setCanRedo(false);
      setVoiceProfileSummary(next.voiceProfileSummary);
      setAnalyzedHash(next.sourceSampleHash);
      setAnalyzedLen(next.sourceSampleLength);
      setAnalyzedAt(next.analyzedAt);
      setSampleChanged(next.voiceProfileSummary ? computeChanged(next.editorHtml, next.sourceSampleHash) : false);
      draftRevisionRef.current += 1;
      setDirty(false);
      setStatus('idle');
      setSaveError('');
      setReloadRequired(false);
      requestAnimationFrame(() => {
        const el = editorRef.current;
        const scroll = el && el.closest('.bp-editor__scroll');
        if (scroll) scroll.scrollTop = 0;
      });
    }, [snapshotFromProfile, writeEditor, computeChanged]);

    const startNewVoice = useCallback(() => {
      if (!access.canMutate()) return;
      if (controllerRef.current) controllerRef.current.select(null);
      loadProfileIntoEditor(emptyBaselineRef.current);
    }, [loadProfileIntoEditor]);

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

    const loadCloudCollection = useCallback(async (options) => {
      const preserveDraft = !!(options && options.preserveDraft);
      const startNew = !!(options && options.startNew);
      const retainedHtml = preserveDraft ? (editorRef.current ? editorRef.current.innerHTML : lastHtmlRef.current) : null;
      setLoadState('loading');
      const controller = ensureController();
      const result = controller ? await controller.load() : null;
      if (!mountedRef.current || result && result.stale) return result;
      if (!result || !result.ok) {
        if (preserveDraft) {
          pendingEditorHtmlRef.current = retainedHtml;
          pendingEditorWriteRef.current = true;
          setLoadState('ready');
          setStatus('error');
          setSaveError("Couldn't reload the latest Brand Voices. Your draft is still here.");
          setReloadRequired(true);
        } else {
          setLoadState('error');
        }
        return result;
      }
      const nextProfiles = result.profiles || [];
      setProfiles(nextProfiles);
      pendingEditorHtmlRef.current = null;
      pendingEditorWriteRef.current = true;
      if (startNew && access.canMutate()) {
        startNewVoice();
      } else {
        const selectedId = result.selectedProfileId || null;
        const selected = nextProfiles.find((profile) => profile.id === selectedId) || nextProfiles[0] || null;
        if (selected) {
          controller.select(selected.id);
          loadProfileIntoEditor(selected);
        } else {
          loadProfileIntoEditor(emptyBaselineRef.current);
        }
      }
      setLoadState('ready');
      return result;
    }, [ensureController, loadProfileIntoEditor, startNewVoice]);

    useEffect(() => {briefReturnContextRef.current = briefReturnContext || null;}, [briefReturnContext]);

    useEffect(() => {
      mountedRef.current = true;
      const onWorkspaceSwitching = () => {
        access.cancel();
        if (commitTimerRef.current) access.clearTimer(commitTimerRef.current);
        workspaceRevisionRef.current += 1;
        analysisRequestRef.current += 1;
        if (controllerRef.current) controllerRef.current.invalidate();
        pendingEditorWriteRef.current = false;
        pendingEditorHtmlRef.current = null;
        savedRef.current = emptyBaselineRef.current;
        setProfiles([]);
        setSelectedProfileId(null);
        setVoiceName('');
        writeEditor('');
        lastHtmlRef.current = '';
        undoStackRef.current = [];
        redoStackRef.current = [];
        setCanUndo(false);
        setCanRedo(false);
        setVoiceProfileSummary(null);
        setAnalyzedHash(null);
        setAnalyzedLen(null);
        setAnalyzedAt(null);
        setAnalyzing(false);
        setDirty(false);
        setStatus('idle');
        setSaveError('');
        setReloadRequired(false);
        setDeleteOpen(false);
        setDeleteBusy(false);
        setLoadState('loading');
      };
      window.addEventListener('ranklyx:workspace-switching', onWorkspaceSwitching);
      loadCloudCollection({ startNew: !!(briefReturnContextRef.current && briefReturnContextRef.current.source === 'brief') });
      return () => {
        mountedRef.current = false;
        analysisRequestRef.current += 1;
        window.removeEventListener('ranklyx:workspace-switching', onWorkspaceSwitching);
        if (controllerRef.current) controllerRef.current.dispose();
      };
    }, [loadCloudCollection, writeEditor]);

    useEffect(() => {
      const changed = loadOriginRef.current !== pageOrigin;
      loadOriginRef.current = pageOrigin;
      // Cached Website pages survive navigation. Replace an unfinished read
      // only when the page receives a new valid origin; retain hydrated drafts.
      if (changed && loadState !== 'ready' && pageOrigin && window.ClicklyxWebsiteContext?.isCurrent(pageOrigin)
          && controllerRef.current && !controllerRef.current.isHydrated()) loadCloudCollection();
    }, [pageOrigin, loadState, loadCloudCollection]);

    useEffect(() => {
      if (loadState !== 'ready' || !pendingEditorWriteRef.current) return;
      pendingEditorWriteRef.current = false;
      writeEditor(pendingEditorHtmlRef.current === null ? savedRef.current.editorHtml : pendingEditorHtmlRef.current);
      pendingEditorHtmlRef.current = null;
    }, [loadState, writeEditor]);

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

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

    /* 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);
    }, []);

    /* 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);
      /* Notice when the sample drifts from what the Voice Profile was built on. */
      if (summaryRef.current && analyzedHashRef.current) {
        const html = editorRef.current ? editorRef.current.innerHTML : '';
        const changed = computeChanged(html, analyzedHashRef.current);
        setSampleChanged((prev) => {
          if (prev !== changed) console.log('[BrandVoice] sampleChangedSinceAnalysis', changed);
          return changed;
        });
      }
    }, [markDirty, commitEdit, computeChanged]);

    /* Run AI voice analysis on the CURRENT editor content (not just the saved
       sample). Strips unchanged starter helpers first, validates length, then
       parses the model output into editable fields. Never auto-saves. */
    const runAnalysis = useCallback(async () => {
      const operation = access.capture(true);
      if (!operation) return;
      const html = editorRef.current ? editorRef.current.innerHTML : '';
      const strippedHtml = window.bvStripTemplateHelpers(html);
      const text = window.bvSampleText(strippedHtml);
      const helperStripped = strippedHtml !== html;
      console.log('[BrandVoice] analysisStarted');
      console.log('[BrandVoice] sampleChars', text.length);
      console.log('[BrandVoice] helperTextStripped', helperStripped);

      setAnalyzeError(null);
      if (text.length < window.BV_MIN_CHARS) {
        setValidationMsg(window.BV_MSG.tooShort);
        console.log('[BrandVoice] analysisFailed', { reason: 'too-short', sampleChars: text.length });
        return;
      }
      setValidationMsg(null);
      const requestId = analysisRequestRef.current + 1;
      analysisRequestRef.current = requestId;
      const workspaceRevision = workspaceRevisionRef.current;
      const requestIsCurrent = () => operation.current() && mountedRef.current &&
        analysisRequestRef.current === requestId && workspaceRevisionRef.current === workspaceRevision;
      setAnalyzing(true);
      setAnalyzeProgress(window.BV_MSG.progress[0]);
      try {
        const raw = await window.bvAnalyzeVoice({
          sampleText: text,
          operation,
          onProgress: (message) => {if (requestIsCurrent()) setAnalyzeProgress(message);}
        });
        if (!requestIsCurrent()) return;
        const parsed = window.bvParseVoiceProfile(raw);
        console.log('[BrandVoice] parsedSections', parsed.parsedSections);
        console.log('[BrandVoice] missingSections', parsed.missingSections);
        if (!window.bvProfileValid(parsed.parsedSections)) {
          setAnalyzeError('parse');
          console.log('[BrandVoice] analysisFailed', { reason: 'parse', missingSections: parsed.missingSections });
          return;
        }
        /* Collapse the parsed sections into ONE clean summary string. */
        const summary = window.bvBuildSummary(parsed.profile);
        const h = window.bvHash(text);
        setVoiceProfileSummary(summary);
        setAnalyzedHash(h);
        setAnalyzedLen(text.length);
        setAnalyzedAt(Date.now());
        setSampleChanged(false);
        markDirty();
        console.log('[BrandVoice] analysisApplied');
      } catch (e) {
        if (!requestIsCurrent()) return;
        setAnalyzeError('ai');
        console.log('[BrandVoice] analysisFailed', { reason: 'ai-call' });
      } finally {
        if (requestIsCurrent()) setAnalyzing(false);
      }
    }, [markDirty]);

    /* Analyze button: first time runs directly; once a profile exists it asks
       for confirmation before replacing it. */
    const onAnalyzeClick = useCallback(() => {
      if (!access.canAi()) return;
      if (analyzing) return;
      if (voiceProfileSummary && voiceProfileSummary.trim()) setReanalyzeOpen(true);
      else runAnalysis();
    }, [analyzing, voiceProfileSummary, runAnalysis]);

    const confirmReanalyze = useCallback(() => {
      if (!access.canAi()) return;
      setReanalyzeOpen(false);
      runAnalysis();
    }, [runAnalysis]);

    /* Edit the Voice Profile summary — marks unsaved, never auto-saves. */
    const onSummaryChange = useCallback((val) => {
      if (!access.canMutate()) return;
      setVoiceProfileSummary(val);
      markDirty();
    }, [markDirty]);

    const onVoiceNameChange = useCallback((e) => {
      if (!access.canMutate()) return;
      const value = e.target.value.slice(0, 60);
      setVoiceName(value);
      if (value.trim()) setNameError('');
      markDirty();
    }, [markDirty]);

    const selectProfile = useCallback((id) => {
      if (!id || id === selectedProfileId) return;
      if (dirty && !window.confirm('Discard unsaved changes and switch Brand Voice profiles?')) return;
      const controller = controllerRef.current;
      const profile = controller ? controller.select(id) : null;
      if (profile) loadProfileIntoEditor(profile);
    }, [selectedProfileId, dirty, loadProfileIntoEditor]);

    const onNewVoice = useCallback(() => {
      if (!access.canMutate()) return;
      if (dirty && !window.confirm('Discard unsaved changes and start a new Brand Voice profile?')) return;
      startNewVoice();
    }, [dirty, startNewVoice]);

    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);
      markDirty();
    }, [commitEdit, markDirty]);

    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);
      markDirty();
    }, [markDirty]);

    /* Save — persist the writing sample AND the Voice Profile summary. No
       auto-save. */
    const saveBrandVoice = useCallback(async (afterSave) => {
      const operation = access.capture(false);
      if (!operation) return;
      const controller = controllerRef.current;
      if (!controller || loadState !== 'ready') return false;
      const cleanName = String(voiceName || '').replace(/\s+/g, ' ').trim().slice(0, 60);
      if (!cleanName) {
        setNameError('Add a voice name before saving.');
        setStatus('error');
        setSaveError('Add a voice name before saving.');
        return false;
      }
      const html = editorRef.current ? editorRef.current.innerHTML : savedRef.current.editorHtml;
      const text = window.bvSampleText(window.bvStripTemplateHelpers(html));
      const summarySnap = (voiceProfileSummary && voiceProfileSummary.trim()) ? voiceProfileSummary : null;
      const payload = {
        name: cleanName,
        editorHtml: html,
        sample: html,
        voiceProfileSummary: summarySnap,
        analyzedAt: summarySnap ? (analyzedAt || Date.now()) : null,
        sourceSampleHash: summarySnap ? (analyzedHash || window.bvHash(text)) : null,
        sourceSampleLength: summarySnap ? (analyzedLen != null ? analyzedLen : text.length) : null,
        metadata: savedRef.current.metadata || {}
      };
      const revision = draftRevisionRef.current;
      const profileId = selectedProfileId;
      setStatus('saving');
      setSaveError('');
      setReloadRequired(false);
      const result = profileId ? await controller.update(profileId, payload) : await controller.create(payload);
      if (!operation.current()) return;
      if (!mountedRef.current || result && result.stale) return false;
      if (!result || !result.ok || !result.profile) {
        const code = result && result.error && result.error.code;
        const conflict = code === 'knowledge_conflict';
        const missing = code === 'knowledge_not_found';
        setStatus('error');
        setSaveError(conflict
          ? 'This Brand Voice changed in the cloud. Reload the latest version before saving again.'
          : missing
            ? 'This Brand Voice was deleted elsewhere. Reload the latest profiles.'
            : "Couldn't save. Your draft is still here, so you can try again.");
        setReloadRequired(conflict || missing);
        return false;
      }
      const savedProfile = result.profile;
      savedRef.current = snapshotFromProfile(savedProfile);
      setProfiles(result.profiles || controller.restoreCollection());
      controller.select(savedProfile.id);
      setSelectedProfileId(savedProfile.id);
      setNameError('');
      setSaveError('');
      setReloadRequired(false);
      if (draftRevisionRef.current === revision) {
        loadProfileIntoEditor(savedProfile);
        setStatus('saved');
      } else {
        setDirty(true);
        setStatus('idle');
      }
      if (draftRevisionRef.current === revision && typeof afterSave === 'function') {
        afterSave({ type: 'brand-voice', id: savedProfile.id });
      }
      return true;
    }, [loadState, selectedProfileId, voiceName, voiceProfileSummary, analyzedAt, analyzedHash, analyzedLen, snapshotFromProfile, loadProfileIntoEditor]);
    const onSave = useCallback(() => {
      saveBrandVoice();
    }, [saveBrandVoice]);
    const saveAndReturnToBrief = useCallback(() => {
      saveBrandVoice((payload) => {
        if (onReturnToBrief) onReturnToBrief(payload);
      });
    }, [saveBrandVoice, onReturnToBrief]);
    const returnToBrief = useCallback(() => {
      if (onReturnToBrief) onReturnToBrief({ type: 'brand-voice', id: selectedProfileId || '' });
    }, [selectedProfileId, onReturnToBrief]);

    const deleteSelectedVoice = useCallback(async () => {
      const operation = access.capture(false);
      if (!operation) return;
      const controller = controllerRef.current;
      if (!selectedProfileId || !controller || loadState !== 'ready') {
        setDeleteOpen(false);
        return;
      }
      setDeleteBusy(true);
      setSaveError('');
      setReloadRequired(false);
      const result = await controller.delete(selectedProfileId);
      if (!operation.current()) return;
      if (!mountedRef.current || result && result.stale) return;
      if (!result || !result.ok) {
        const code = result && result.error && result.error.code;
        const conflict = code === 'knowledge_conflict';
        const missing = code === 'knowledge_not_found';
        setStatus('error');
        setSaveError(conflict
          ? 'This Brand Voice changed in the cloud and was not deleted. Reload the latest profiles.'
          : missing
            ? 'This Brand Voice was already deleted elsewhere. Reload the latest profiles.'
            : "Couldn't delete this Brand Voice. Please try again.");
        setReloadRequired(conflict || missing);
        setDeleteBusy(false);
        setDeleteOpen(false);
        return;
      }
      const nextProfiles = result.profiles || controller.restoreCollection();
      setProfiles(nextProfiles);
      const next = result.selectedProfileId ? controller.restore(result.selectedProfileId) : null;
      if (next) loadProfileIntoEditor(next);
      else startNewVoice();
      setDeleteBusy(false);
      setDeleteOpen(false);
      setStatus('idle');
      setSaveError('');
      setReloadRequired(false);
    }, [selectedProfileId, loadState, loadProfileIntoEditor, startNewVoice]);

    /* Discard unsaved changes — restore the last saved writing sample AND Voice
       Profile summary (and analysis metadata), then recompute the sample-changed
       notice. */
    const onDiscard = useCallback(() => {
      const controller = controllerRef.current;
      const baseline = selectedProfileId && controller ? controller.restore(selectedProfileId) : null;
      if (baseline) loadProfileIntoEditor(baseline);
      else loadProfileIntoEditor(emptyBaselineRef.current);
      setAnalyzeError(null);
      setValidationMsg(null);
    }, [selectedProfileId, loadProfileIntoEditor, startNewVoice]);

    const reloadLatest = useCallback(() => {
      if (dirty && !window.confirm('Discard unsaved changes and reload the latest Brand Voices?')) return;
      setReloadRequired(false);
      loadCloudCollection({ preserveDraft: true });
    }, [dirty, loadCloudCollection]);

    /* Restore the starter writing prompt into the editor. Stays UNSAVED and
       fully editable; the user must click Save Brand Voice to persist. Works
       even when the editor is currently empty. Does NOT delete the Voice
       Profile summary — only the writing sample is replaced. */
    const applyRestore = useCallback(() => {
      if (!access.canMutate()) return;
      writeEditor(BV_DEFAULT_SAMPLE);
      markDirty();
      clearEditorHistory(BV_DEFAULT_SAMPLE);
      setRestoreOpen(false);
      if (summaryRef.current && analyzedHashRef.current) {
        setSampleChanged(computeChanged(BV_DEFAULT_SAMPLE, analyzedHashRef.current));
      }
    }, [writeEditor, clearEditorHistory, computeChanged, markDirty]);

    /* Live getter for the current editor HTML — lets the Test card use the
       current (incl. unsaved) writing sample without re-rendering on keystrokes. */
    const getSampleHtml = useCallback(() => (editorRef.current ? editorRef.current.innerHTML : ''), []);
    const cameFromBrief = !!(briefReturnContext && briefReturnContext.source === 'brief' && onReturnToBrief);

    bvLucide([loadState, status, analyzing, !!voiceProfileSummary, sampleChanged]);

    if (loadState !== 'ready') {
      return (
        <div className={"rl-page bp-page" + (loadState === 'error' ? '' : ' c5-knowledge-loading')} data-screen-label={loadState === 'error' ? 'Brand Voice unavailable' : 'Loading Brand Voice'}>
          <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 Voice" : 'Loading Brand Voice'}</h2>
            <p className="rl-ph__desc">{loadState === 'error' ? 'Your cloud profiles are still safe. Try loading them again.' : 'Loading the latest Workspace profiles...'}</p>
            {loadState === 'error' &&
              <button type="button" className="rl-btn rl-btn--secondary" onClick={() => loadCloudCollection()}>Try again</button>}
          </div>
        </div>);
    }

    return (
      <div className="rl-page bp-page" data-screen-label="Brand Voice">
        <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">Brand Voice</h1>
            <p className="bp-lede">
              Teach the AI how your brand sounds by adding a real writing sample.
            </p>
          </header>

          <section className="bp-card bv-profile-card">
            <div className="bp-card__hd">
              <div className="bp-card__heading">Saved voices</div>
              <div className="bp-card__help">
                Create and manage named Brand Voice profiles for different channels or writing styles.
              </div>
            </div>
            <div className="bp-card__body bv-profile-card__body">
              <label className="bv-field">
                <span className="bv-field__label">Brand Voice</span>
                <select
                  className="bp-input bv-select"
                  value={selectedProfileId || ''}
                  onChange={(e) => selectProfile(e.target.value)}
                  disabled={!profiles.length || status === 'saving' || deleteBusy || reloadRequired}>
                  {!profiles.length && <option value="">No saved voices yet</option>}
                  {profiles.map((profile) =>
                  <option key={profile.id} value={profile.id}>{profile.name}</option>
                  )}
                </select>
              </label>
              <button type="button" className="rl-btn rl-btn--secondary bp-btn" onClick={onNewVoice} disabled={!access.canMutate() || status === 'saving' || deleteBusy || reloadRequired}>
                New voice
              </button>
              <button
                type="button"
                className="rl-btn rl-btn--secondary bp-btn"
                onClick={access.guard(() => setDeleteOpen(true))}
                disabled={!access.canMutate() || !selectedProfileId || status === 'saving' || deleteBusy || reloadRequired}>
                Delete voice
              </button>
            </div>
          </section>

          <section className="bp-card bv-name-card">
            <div className="bp-card__body bv-name-card__body">
              <label className="bv-field">
                <span className="bv-field__label">Voice name</span>
                <input readOnly={!access.canMutate()}
                  className={'bp-input' + (nameError ? ' bp-input--error' : '')}
                  value={voiceName}
                  onChange={onVoiceNameChange}
                  maxLength={60}
                  placeholder="Example: Founder voice" />
              </label>
              {nameError && <p className="bv-field__error">{nameError}</p>}
            </div>
          </section>

          {/* Card — How We Write (single editor) */}
          <section className="bp-card">
            <div className="bp-card__hd">
              <div className="bp-card__heading">How We Write</div>
              <div className="bp-card__help">
                Add a real writing sample that sounds like your brand. You can
                write from scratch or paste content from your blog, newsletter,
                website, or social posts.
              </div>
              <div className="bp-card__help bp-card__help--sub">
                Write naturally. Do not try to sound perfect. The goal is to show
                the AI your rhythm, word choice, sentence style, and point of view.
              </div>
            </div>
            <div className="bp-card__body bp-card__body--editor">
              <BvRichTextEditor
                editorRef={editorRef}
                onInput={onEditorInput}
                onRestore={access.guard(() => setRestoreOpen(true))}
                canUndo={canUndo}
                canRedo={canRedo}
                onUndo={undoEditor}
                onRedo={redoEditor} />
            </div>
          </section>

          {/* Card — AI Voice Profile (separate card, outside the editor) */}
          {VoiceCard &&
            <VoiceCard
              summary={voiceProfileSummary}
              analyzing={analyzing}
              progress={analyzeProgress}
              error={analyzeError}
              validation={validationMsg}
              sampleChanged={sampleChanged}
              onAnalyzeClick={onAnalyzeClick}
              onSummaryChange={onSummaryChange} />}

          {/* Card — Test this voice (Brand-Voice-only; never marks page unsaved) */}
          {TestCard &&
            <TestCard
              getSampleHtml={getSampleHtml}
              voiceProfileSummary={voiceProfileSummary} />}

          <div className="bp-ai-note">
            <BvIconAlert />
            <span>AI can make mistakes. Review your writing sample 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">
                  <BvIconCheckCircle />
                  <span>Brand voice saved</span>
                </span>}
              {status === 'error' &&
                <span className="bp-status bp-status--err">
                  <BvIconAlert />
                  <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">
              {reloadRequired &&
              <button
                type="button"
                className="rl-btn rl-btn--secondary bp-btn"
                onClick={reloadLatest}
                disabled={status === 'saving' || deleteBusy}>
                <span>Reload latest</span>
              </button>}
              {cameFromBrief && !dirty && status !== 'saving' &&
              <button
                type="button"
                className="rl-btn rl-btn--secondary bp-btn"
                onClick={returnToBrief}>
                <span>Return to brief</span>
              </button>}
              <button
                type="button"
                className="rl-btn rl-btn--secondary bp-btn"
                onClick={onDiscard}
                disabled={!dirty || status === 'saving' || deleteBusy || reloadRequired}>
                <BvIconReset />
                <span>Discard unsaved changes</span>
              </button>
              <button
                type="button"
                className="rl-btn rl-btn--primary bp-btn"
                onClick={cameFromBrief ? saveAndReturnToBrief : onSave}
                disabled={!access.canMutate() || status === 'saving' || deleteBusy || reloadRequired}>
                {status === 'saving'
                  ? <React.Fragment><span className="bp-spinner bp-spinner--light"></span><span>Saving…</span></React.Fragment>
                  : <React.Fragment><BvIconCheck /><span>{cameFromBrief ? 'Save and return to brief' : 'Save Brand Voice'}</span></React.Fragment>}
              </button>
            </div>
          </div>
        </div>

        <BvRestoreModal
          open={restoreOpen}
          onClose={() => setRestoreOpen(false)}
          onConfirm={applyRestore} />

        <BvDeleteModal
          open={deleteOpen}
          onClose={() => {if (!deleteBusy) setDeleteOpen(false);}}
          onConfirm={deleteSelectedVoice}
          busy={deleteBusy}
          voiceName={voiceName} />

        {ReanalyzeModal &&
          <ReanalyzeModal
            open={reanalyzeOpen}
            onClose={() => setReanalyzeOpen(false)}
            onConfirm={confirmReanalyze} />}
      </div>);
  }

  window.BrandVoice = BrandVoice;
})();
