/* Rank Lyx — AI Writer / Outline step
   Editable outline workspace: H2/H3 headings, talking points, reorder + edit + delete,
   compact brief summary. Exposes window.OutlineScreen and window.buildOutline. */

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

/* Lucide refresh after renders that add new <i data-lucide> */
function olLucide(deps) {
  useEffect(() => {
    if (window.lucide) window.lucide.createIcons();
  }, deps);
}

function olPlainTextFromHtml(value) {
  if (value == null) return '';
  return String(value).
  replace(/<script\b[\s\S]*?(?:<\/script>|$)/gi, '').
  replace(/<style\b[\s\S]*?(?:<\/style>|$)/gi, '').
  replace(/<br\s*\/?>/gi, '\n').
  replace(/<\/p\s*>/gi, '\n\n').
  replace(/<\/h[1-6]\s*>/gi, '\n\n').
  replace(/<li[^>]*>/gi, '- ').
  replace(/<\/li\s*>/gi, '\n').
  replace(/<[^>]+>/g, '').
  replace(/&nbsp;/g, ' ').
  replace(/&amp;/g, '&').
  replace(/&lt;/g, '<').
  replace(/&gt;/g, '>').
  replace(/&quot;/g, '"').
  replace(/&#39;/g, "'").
  replace(/\n{3,}/g, '\n\n').
  trim();
}

function olSafeIntroPreviewText(value) {
  let text = olPlainTextFromHtml(value);
  if (!text) return '';
  const sourceMarkers = [
    /\)\s*\+\s*['"]\\b\\s\*/, /\bfor\s*\(\s*var\s+\w+\s*=/,
    /\bfunction\s+\w+\s*\(/, /\bvar\s+[A-Z0-9_]+\s*=/,
    /\bAI_STYLE_BANNED_/, /\breturn\s+\{\s*matched\s*:/,
    /\bnew\s+RegExp\s*\(/, /\bsanitize[A-Za-z]+\s*\(/
  ];
  let cut = -1;
  sourceMarkers.forEach((re) => {
    const m = re.exec(text);
    if (m && (cut === -1 || m.index < cut)) cut = m.index;
  });
  if (cut >= 0) text = text.slice(0, cut);
  return text.replace(/\n{3,}/g, '\n\n').trim();
}

class IntroTestPanelBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { error: null };
  }
  static getDerivedStateFromError(error) {
    return { error: error };
  }
  componentDidCatch(error) {
    window.ClicklyxBrowserErrors?.capture(error);
    try { console.error('Intro-only preview render failed', error); } catch (e) {}
  }
  render() {
    if (this.state.error) {
      return (
        <div className="rl-intro-test" style={{ marginTop: "14px", marginLeft: "auto", maxWidth: "720px", textAlign: "left", background: "var(--rl-surface)", border: "1px solid var(--rl-border)", borderRadius: "8px", padding: "16px" }}>
          <strong style={{ fontSize: "13px", color: "var(--rl-fg)" }}>Intro-only preview</strong>
          <p style={{ margin: "10px 0 0", fontSize: "13px", lineHeight: "20px", color: "var(--rl-danger)" }}>
            Intro preview failed to render. The draft editor was not changed.
          </p>
        </div>
      );
    }
    return this.props.children;
  }
}

/* ---------- ids ----------
   STABLE, durable section IDs. These get serialized into the article record and
   are the key research notes + every downstream agent use to find a section, so
   they must NOT reset to a fresh "ol1, ol2…" sequence on each page load (the old
   bug that let notes lose their section). We delegate to ArticleStore.genSectionId
   when present (collision-resistant `sec_…`), with a durable local fallback.
   Once minted, an ID rides with its node through edits, reorders, level changes,
   save, and reload — only a brand-new node ever gets a brand-new ID. */
let _olUid = 0;
const olid = () =>
  window.ArticleStore && window.ArticleStore.genSectionId ?
  window.ArticleStore.genSectionId() :
  `sec_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 7)}${(++_olUid).toString(36)}`;

/* ---------- Brief → Outline Agent → editable UI shape ----------
   The Outline AGENT logic lives in outline-agent.js (pure, framework-free).
   The two helpers below are the only glue between that service and this UI:
     • briefFromForm  — maps the brief FORM fields to the agent's brief input
     • adaptOutlineForUI — maps the agent's outline DATA to the editable UI nodes
   Keeping them tiny makes the agent easy to copy into another app. */
function outlineTextFromHtml(html) {
  const raw = String(html || '');
  if (!raw) return '';
  if (window.bvSampleText) return String(window.bvSampleText(raw) || '').trim();
  try {
    const div = document.createElement('div');
    div.innerHTML = raw;
    return (div.textContent || '').replace(/\s+/g, ' ').trim();
  } catch (e) {
    return raw.replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim();
  }
}

function normalizeBrandVoiceStoreForOutline() {
  try {
    if (window.BrandVoiceStorage && typeof window.BrandVoiceStorage.readStore === 'function') {
      return window.BrandVoiceStorage.readStore();
    }
  } catch (e) {}
  try {
    const raw = localStorage.getItem('brand_voice_knowledge');
    const data = raw ? JSON.parse(raw) : {};
    if (window.BrandVoiceStorage && typeof window.BrandVoiceStorage.normalizeStore === 'function') {
      return window.BrandVoiceStorage.normalizeStore(data);
    }
    if (data && Array.isArray(data.profiles)) return data;
    if (data && (data.editorHtml || data.sample || data.voiceProfileSummary)) {
      return {
        version: 2,
        activeProfileId: String(data.id || 'workspace-brand-voice'),
        profiles: [{
          id: String(data.id || 'workspace-brand-voice'),
          name: String(data.name || data.title || data.label || 'Workspace brand voice').trim(),
          editorHtml: data.editorHtml || data.sample || '',
          sample: data.sample || data.editorHtml || '',
          voiceProfileSummary: data.voiceProfileSummary || '',
          analyzedAt: data.analyzedAt || null,
          updatedAt: data.updatedAt || data.lastUpdated || null
        }]
      };
    }
  } catch (e) {}
  return { version: 2, activeProfileId: null, profiles: [] };
}

function resolveBrandVoiceForOutline(form) {
  const selectedId = String(form.selectedBrandVoiceId || form.brandVoiceId || 'default').trim() || 'default';
  if (selectedId === 'default') {
    return {
      id: 'default',
      name: 'Default',
      kind: 'default',
      resolution: 'default',
      voiceProfileSummary: 'Use a conversational and authoritative voice.',
      sampleText: ''
    };
  }
  const store = normalizeBrandVoiceStoreForOutline();
  const profile = (store.profiles || []).find((voice) => String(voice && voice.id || '') === selectedId);
  if (!profile) {
    return {
      id: 'default',
      name: 'Default',
      kind: 'default',
      resolution: 'missing_selected_profile_used_default',
      requestedId: selectedId,
      voiceProfileSummary: 'Use a conversational and authoritative voice.',
      sampleText: ''
    };
  }
  const rawHtml = profile.editorHtml || profile.sample || '';
  const strip = window.bvStripTemplateHelpers || ((value) => value);
  const strippedHtml = strip(rawHtml);
  return {
    id: String(profile.id),
    name: String(profile.name || form.selectedBrandVoiceName || 'Brand voice').trim(),
    kind: 'custom',
    resolution: 'selected_profile',
    voiceProfileSummary: String(profile.voiceProfileSummary || '').trim(),
    sampleText: outlineTextFromHtml(strippedHtml),
    analyzedAt: profile.analyzedAt || null,
    updatedAt: profile.updatedAt || profile.lastUpdated || null
  };
}

function resolveIcpForOutline(form) {
  const selectedId = String(form.selectedIcpId || form.targetAudienceId || '').trim();
  if (!selectedId) {
    return { id: '', name: '', resolution: 'none_selected', text: '' };
  }
  try {
    const raw = localStorage.getItem('rl.audienceIcpKnowledge');
    const data = raw ? JSON.parse(raw) : {};
    const list = data && Array.isArray(data.icps) ? data.icps : [];
    const match = list.find((icp) => String(icp && icp.id || '') === selectedId);
    if (!match) {
      return { id: selectedId, name: String(form.selectedIcpName || '').trim(), resolution: 'missing_selected_icp_omitted', text: '' };
    }
    const strip = window.audStripTemplateHelpers || window.icpStripTemplateHelpers || ((value) => value);
    const html = strip(match.details || '');
    return {
      id: String(match.id),
      name: String(match.name || form.selectedIcpName || '').trim(),
      resolution: 'selected_icp',
      text: outlineTextFromHtml(html),
      details: match.details || ''
    };
  } catch (e) {
    return { id: selectedId, name: String(form.selectedIcpName || '').trim(), resolution: 'selected_icp_read_failed', text: '' };
  }
}

function outlineVoiceFromKnowledgeContext(knowledge) {
  const voice = knowledge && knowledge.brandVoice;
  if (!voice) return null;
  return {
    id: String(voice.id || '').trim(),
    name: String(voice.name || '').trim(),
    kind: String(voice.kind || '').trim(),
    resolution: String(voice.resolution || '').trim(),
    voiceProfileSummary: typeof voice.voiceProfileSummary === 'string' ? voice.voiceProfileSummary : '',
    sampleText: typeof voice.sampleExcerpt === 'string' ? voice.sampleExcerpt : '',
    analyzedAt: voice.analyzedAt || null,
    instructionVersion: voice.instructionVersion || null
  };
}

function outlineIcpFromKnowledgeContext(knowledge) {
  const list = knowledge && knowledge.icpKnowledge && Array.isArray(knowledge.icpKnowledge.icps)
    ? knowledge.icpKnowledge.icps
    : [];
  if (!list.length) return { id: '', name: '', resolution: 'none_selected', text: '' };
  return {
    id: String(list[0].id || '').trim(),
    name: String(list[0].name || '').trim(),
    resolution: 'selected_icp',
    text: typeof list[0].text === 'string' ? list[0].text : ''
  };
}

function normalizeBriefForOutline(form, options) {
  const f = form || {};
  const opts = options || {};
  const knowledgeContext = opts.knowledgeContext && typeof opts.knowledgeContext === 'object'
    ? opts.knowledgeContext
    : null;
  const brandVoiceId = f.brandVoiceId || f.selectedBrandVoiceId || 'default';
  const selectedIcpId = f.selectedIcpId || f.targetAudienceId || '';
  const resolvedBrandVoice = knowledgeContext
    ? outlineVoiceFromKnowledgeContext(knowledgeContext)
    : resolveBrandVoiceForOutline({ ...f, brandVoiceId, selectedBrandVoiceId: f.selectedBrandVoiceId || brandVoiceId });
  const resolvedIcp = knowledgeContext
    ? outlineIcpFromKnowledgeContext(knowledgeContext)
    : resolveIcpForOutline({ ...f, selectedIcpId, targetAudienceId: f.targetAudienceId || selectedIcpId });
  const authoritativeBrandVoiceId = knowledgeContext && resolvedBrandVoice ? resolvedBrandVoice.id : (f.selectedBrandVoiceId || brandVoiceId);
  const authoritativeIcpId = knowledgeContext ? (resolvedIcp && resolvedIcp.id || '') : selectedIcpId;
  const selectedIcpName = knowledgeContext
    ? (resolvedIcp && resolvedIcp.name || '')
    : (f.selectedIcpName || (resolvedIcp && resolvedIcp.name) || '');
  return {
    title: f.topic,
    primaryKeyword: f.keyword,
    postType: f.postType,
    contentType: f.postType,
    additionalInformation: f.notes,
    notes: f.notes,
    selectedBrandVoiceId: authoritativeBrandVoiceId,
    selectedBrandVoiceName: knowledgeContext && resolvedBrandVoice ? resolvedBrandVoice.name : (f.selectedBrandVoiceName || (resolvedBrandVoice && resolvedBrandVoice.name) || ''),
    selectedIcpId: authoritativeIcpId,
    selectedIcpName: selectedIcpName,
    resolvedBrandVoice: resolvedBrandVoice,
    resolvedIcp: resolvedIcp,
    brandVoiceResolution: resolvedBrandVoice && resolvedBrandVoice.resolution,
    icpResolution: resolvedIcp && resolvedIcp.resolution,
    selectedIcpResolution: resolvedIcp && resolvedIcp.resolution,
    knowledgeContext: knowledgeContext
  };
}

function briefFromForm(form, options) {
  const f = form || {};
  const normalized = normalizeBriefForOutline(f, options);
  const resolvedIcp = normalized.resolvedIcp || {};
  const resolvedBrandVoice = normalized.resolvedBrandVoice || {};
  return {
    title: normalized.title,
    primaryKeyword: normalized.primaryKeyword,
    secondaryKeywords: f.secondaryKeywords || '',
    contentType: normalized.contentType,
    postType: normalized.postType,
    goal: f.goal || '',
    audience: resolvedIcp.resolution === 'selected_icp' ? (resolvedIcp.name || '') : (normalized.knowledgeContext ? '' : (f.audience || '')),
    tone: resolvedBrandVoice.kind === 'default' ? 'Conversational and authoritative' : '',
    brandVoiceId: normalized.selectedBrandVoiceId,
    selectedBrandVoiceId: normalized.selectedBrandVoiceId,
    selectedBrandVoiceName: normalized.selectedBrandVoiceName,
    targetAudienceId: normalized.knowledgeContext ? normalized.selectedIcpId : (f.targetAudienceId || normalized.selectedIcpId),
    selectedIcpId: normalized.selectedIcpId,
    selectedIcpName: normalized.selectedIcpName,
    additionalInformation: normalized.additionalInformation,
    notes: normalized.notes,
    resolvedBrandVoice: resolvedBrandVoice,
    resolvedIcp: resolvedIcp,
    brandVoiceResolution: normalized.brandVoiceResolution,
    icpResolution: normalized.icpResolution,
    selectedIcpResolution: normalized.selectedIcpResolution || normalized.icpResolution,
    knowledgeContext: normalized.knowledgeContext
  };
}
/* ---------- Provider-neutral LLM adapter (Prompt-4) ----------
   The actual model call belongs to the host. In Lovable, connect this adapter
   to the built-in AI action: it receives { prompt, outlinePlan,
   expectedOutputSchema } and should return the model's JSON response — either a
   raw JSON string or a parsed object. User-facing outline generation fails
   clearly when no live adapter is available; local fallback is explicit
   dev/test behavior only.

   DO NOT add API keys here. Browser code must call server-side adapters only. */
async function outlineLLMAdapter({ prompt, outlinePlan, expectedOutputSchema, articleGeneration, requestOrigin }) {
  // Local/dev live path: reuse the same app-level adapter as the Writing Agent.
  // It posts to the server-side /api/openai-complete route and never exposes
  // model names or API keys in browser code.
  if (typeof window !== 'undefined' && typeof window.appLLMAdapter === 'function') {
    return await window.appLLMAdapter({
      prompt,
      outlinePlan,
      expectedOutputSchema,
      mode: 'outline',
      articleGeneration,
      requestOrigin
    });
  }

  // Local/dev live path: use the same server-side endpoint as dev-ai-adapter.js
  // when the global adapter has not been initialized.
  if (typeof window !== 'undefined' && window.RankLyxAuth && typeof window.RankLyxAuth.authenticatedFetch === 'function') {
    const transport = window.ClicklyxWebsiteContext
      ? (url, options) => window.ClicklyxWebsiteContext.request(url, options, { origin: requestOrigin })
      : window.RankLyxAuth.authenticatedFetch;
    const res = await transport('/api/openai-complete', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        prompt,
        expectedOutputSchema,
        mode: 'outline',
        articleGeneration
      })
    });
    const body = await res.json().catch(() => ({}));
    if (!res.ok) {
      const msg = body && body.error && body.error.message
        ? body.error.message
        : 'The local outline model endpoint failed.';
      const error = new Error(msg);
      if (articleGeneration && body && body.error) error.code = body.error.code;
      throw error;
    }
    return body.html || body.text || body.content || '';
  }

  if (articleGeneration) throw new Error('Authenticated Article generation is not available.');

  // LIVE PATH: this app exposes window.claude.complete — the SAME adapter used
  // by Brand Voice analysis, Test this voice, Brand Profile, Product Knowledge,
  // and ICP generation. Use it when present so Create outline runs live; the
  // full prompt (including [AI CONTEXT]) is sent as-is and the model returns the
  // outline JSON the existing parser/validator expects.
  if (typeof window !== 'undefined' && window.claude && typeof window.claude.complete === 'function') {
    return await window.claude.complete(prompt);
  }
  // TODO: if window.claude is unavailable, connect a live LLM adapter here
  // (e.g. Lovable built-in AI action):
  //   const raw = await lovableAI.run({ prompt, schema: expectedOutputSchema });
  //   return raw; // string or object
  // Returning null makes user-facing generation fail clearly unless a caller
  // explicitly opts into local fallback for tests.
  return null;
}

async function researchLLMCall(args) {
  args = args || {};
  const systemPrompt = args.systemPrompt ? String(args.systemPrompt) : '';
  const userPrompt = args.userPrompt ? String(args.userPrompt) : '';
  const prompt = systemPrompt
    ? ['SYSTEM:', systemPrompt, '', 'USER:', userPrompt].join('\n')
    : userPrompt;
  const expectedOutputSchema = {
    notes: [],
    coverageStatus: 'within_target',
    reason: null
  };

  const requestCompletion = async (mode) => {
    if (typeof window !== 'undefined' && typeof window.appLLMAdapter === 'function') {
      return await window.appLLMAdapter({
        prompt,
        expectedOutputSchema,
        mode,
        articleGeneration: args.articleGeneration,
        requestOrigin: args.requestOrigin
      });
    }

    if (typeof window !== 'undefined' && window.RankLyxAuth && typeof window.RankLyxAuth.authenticatedFetch === 'function') {
      const transport = window.ClicklyxWebsiteContext
        ? (url, options) => window.ClicklyxWebsiteContext.request(url, options, { origin: args.requestOrigin })
        : window.RankLyxAuth.authenticatedFetch;
      const res = await transport('/api/openai-complete', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          prompt,
          expectedOutputSchema,
          mode,
          articleGeneration: args.articleGeneration
        })
      });
      const body = await res.json().catch(() => ({}));
      if (!res.ok) {
        const msg = body && body.error && body.error.message
          ? body.error.message
          : 'The local research model endpoint failed.';
        throw new Error(msg);
      }
      return body.html || body.text || body.content || '';
    }

    throw new Error('Research model adapter is not available.');
  };

  return await requestCompletion('research');
}

async function tavilySearchProvider(req) {
  req = req || {};
  const authRuntime = typeof window !== 'undefined' && window.RankLyxAuth;
  if (!authRuntime || typeof authRuntime.authenticatedFetch !== 'function') {
    throw new Error('Live research search requires authenticated browser fetch support.');
  }
  const transport = window.ClicklyxWebsiteContext
    ? (url, options) => window.ClicklyxWebsiteContext.request(url, options, { origin: req.requestOrigin })
    : authRuntime.authenticatedFetch;
  const res = await transport('/api/tavily-search', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      queries: req.queries || [],
      plannedQueries: req.plannedQueries || [],
      maxResultsPerQuery: req.maxResultsPerQuery || 4,
      searchPurpose: req.searchPurpose || 'external_research_source_candidates',
      articleContext: req.articleContext || null,
      metadata: req.metadata || null,
      articleGeneration: req.articleGeneration || null
    })
  });
  const body = await res.json().catch(() => ({}));
  if (!res.ok) {
    const msg = body && body.error && body.error.message
      ? body.error.message
      : 'Live research search failed.';
    throw new Error(msg);
  }
  return body;
}

/* Map ONE agent/LLM section object → an editable UI node. Handles BOTH shapes:
     • LLM result  — { heading, headingLevel, intro, intentRole, talkingPoints, children }
     • local agent — { heading, level, intro, intentRole, talkingPoints, children, writerNote, … }
   Nested children (H4 under H3, etc.) are flattened into the flat children
   list the editor expects, each carrying its own heading level. Preserves the
   Prompt-3 hierarchy fields so the Research + Writing agents and the live role
   labels keep the agent's structural read of every section. */
const _olPts = (arr) => (arr || []).filter((t) => typeof t === 'string').map((text) => ({ id: olid(), text }));
function _olFlattenChildren(kids, acc) {
  (kids || []).forEach((c) => {
    if (!c || typeof c !== 'object') return;
    let level = c.level || c.headingLevel || 3;
    if (level < 3) level = 3;
    if (level > 6) level = 6;
    acc.push({
      id: olid(),
      text: c.heading || c.text || '',
      level,
      points: _olPts(c.talkingPoints),
      writerNote: c.writerNote || null,
      intentRole: c.intentRole || null,
      intentRoleLabel: c.intentRoleLabel || null,
      sectionImportance: c.sectionImportance || null,
      writingInstructions: c.writingInstructions || null
    });
    if (Array.isArray(c.children) && c.children.length) _olFlattenChildren(c.children, acc);
  });
  return acc;
}
function adaptSectionsForUI(sections) {
  if (!Array.isArray(sections)) return [];
  return sections.
  filter((s) => s && typeof s === 'object').
  map((s) => ({
    id: olid(),
    text: s.heading || s.text || '',
    points: _olPts(s.talkingPoints),
    writerNote: s.writerNote || null,
    intentRole: s.intentRole || null,
    intentRoleLabel: s.intentRoleLabel || null,
    sectionImportance: s.sectionImportance || null,
    writingInstructions: s.writingInstructions || null,
    children: _olFlattenChildren(s.children, []),
    intro: !!s.intro
  }));
}

/* Backward-compatible: agent outline DATA (local generateOutline) → UI nodes. */
function adaptOutlineForUI(result) {
  return adaptSectionsForUI(result && result.sections);
}

/* generateOutlineWithLLM ENVELOPE → UI nodes. User-facing callers refuse failed
   or local-fallback envelopes before rendering. */
function adaptOutlineResultForUI(envelope) {
  if (envelope && (envelope.status === 'failed' || envelope.source === 'local-fallback')) return [];
  const r = envelope && envelope.outlineResult ? envelope.outlineResult : envelope;
  if (!r) return [];
  return adaptSectionsForUI(r.outlineSections || r.sections);
}

/* Backward-compatible SYNC entry used only for legacy/dev local generation:
   brief form → editable outline using the LOCAL agent (no LLM). */
const SECTION_AI_ACTIONS = [
{ id: 'expand', label: 'Expand this section' },
{ id: 'shorten', label: 'Shorten this section' },
{ id: 'improve_talking_points', label: 'Improve talking points' },
{ id: 'make_more_practical', label: 'Make more practical' },
{ id: 'make_more_beginner_friendly', label: 'Make beginner-friendly' },
{ id: 'custom_instruction', label: 'Custom instruction' }];

const SECTION_AI_LOADING_LABELS = {
  expand: 'Expanding section...',
  shorten: 'Shortening section...',
  improve_talking_points: 'Improving talking points...',
  make_more_practical: 'Making section more practical...',
  make_more_beginner_friendly: 'Making section more beginner-friendly...',
  custom_instruction: 'Applying custom instruction...'
};

const SECTION_AI_SUCCESS_LABELS = {
  expand: 'Section expanded.',
  shorten: 'Section shortened.',
  improve_talking_points: 'Talking points improved.',
  make_more_practical: 'Section made more practical.',
  make_more_beginner_friendly: 'Section made more beginner-friendly.',
  custom_instruction: 'Section updated.'
};

function outlineUiPointsToText(points) {
  return (points || []).map((p) => p && p.text ? String(p.text).trim() : '').filter(Boolean);
}

function outlineUiChildrenToNested(children) {
  const roots = [];
  const stack = [{ level: 2, children: roots }];
  (children || []).forEach((child) => {
    if (!child) return;
    let level = Number(child.level || 3) || 3;
    if (level < 3) level = 3;
    if (level > 6) level = 6;
    const node = {
      id: child.id,
      heading: child.text || '',
      headingLevel: level,
      intro: false,
      intentRole: child.intentRole || null,
      talkingPoints: outlineUiPointsToText(child.points),
      children: []
    };
    while (stack.length > 1 && stack[stack.length - 1].level >= level) stack.pop();
    const parent = stack[stack.length - 1];
    parent.children.push(node);
    stack.push({ level, children: node.children });
  });
  return roots;
}

function outlineUiSectionToAgent(section) {
  return {
    id: section.id,
    heading: section.intro ? 'Introduction' : section.text || '',
    headingLevel: 2,
    intro: !!section.intro,
    intentRole: section.intro ? 'introduction' : section.intentRole || null,
    talkingPoints: outlineUiPointsToText(section.points),
    children: outlineUiChildrenToNested(section.children)
  };
}

function outlineUiToAgentOutline(outline, form) {
  return {
    articleTitle: form && form.topic || '',
    outlineSections: (outline || []).map(outlineUiSectionToAgent)
  };
}

function outlineAgentSectionToUi(section, previousSection) {
  const flatChildren = [];
  const flatten = (items) => {
    (items || []).forEach((child) => {
      if (!child || typeof child !== 'object') return;
      let level = Number(child.headingLevel || child.level || 3) || 3;
      if (level < 3) level = 3;
      if (level > 6) level = 6;
      flatChildren.push({
        id: child.id || olid(),
        text: child.heading || child.text || '',
        level,
        points: _olPts(child.talkingPoints),
        writerNote: child.writerNote || null,
        intentRole: child.intentRole || null,
        intentRoleLabel: child.intentRoleLabel || null,
        sectionImportance: child.sectionImportance || null,
        writingInstructions: child.writingInstructions || null
      });
      if (Array.isArray(child.children) && child.children.length) flatten(child.children);
    });
  };
  flatten(section && section.children);
  return {
    id: previousSection && previousSection.id || section && section.id || olid(),
    text: section && (section.heading || section.text) || '',
    points: _olPts(section && section.talkingPoints),
    writerNote: section && section.writerNote || previousSection && previousSection.writerNote || null,
    intentRole: section && section.intentRole || previousSection && previousSection.intentRole || null,
    intentRoleLabel: section && section.intentRoleLabel || previousSection && previousSection.intentRoleLabel || null,
    sectionImportance: section && section.sectionImportance || previousSection && previousSection.sectionImportance || null,
    writingInstructions: section && section.writingInstructions || previousSection && previousSection.writingInstructions || null,
    children: flatChildren,
    intro: false
  };
}

function buildOutline(form) {
  try {
    const result = window.OutlineAgent.generateOutline(briefFromForm(form));
    return adaptOutlineForUI(result);
  } catch (e) {
    return [];
  }
}

/* ---------- Create-Outline flow (Prompt-4) ----------
   The async path the "Create outline" button uses. Drives the new Outline Agent
   workflow and reports human-readable progress so the UI can show a clear
   loading state:
     plan → write (LLM) → validate → (repair) → prepare editable outline.

   Provider-neutral: it passes outlineLLMAdapter to generateOutlineWithLLM. When
   the adapter is unavailable or validation fails, user-facing generation returns
   a clear failure instead of rendering local fallback output.
   Returns the full result envelope { outlinePlan, outlineResult, validation,
   initialValidation, repairAttempts, repairHistory, source, status }. */
async function runCreateOutline(form, onProgress, options) {
  const opts = options || {};
  const report = (s) => { if (typeof onProgress === 'function') onProgress(s); };
  const pause = (ms) => new Promise((r) => setTimeout(r, ms));
  const brief = briefFromForm(form, { knowledgeContext: opts.knowledgeContext || null });

  report('Planning outline\u2026');
  await pause(450);

  report('Writing outline with AI\u2026');
  // Run the real workflow; keep the "writing" message visible a beat so the
  // staged messages read naturally even when validation resolves quickly.
  const [result] = await Promise.all([
  window.OutlineAgent.generateOutlineWithLLM(brief, {
    llmAdapter: opts.llmAdapter || outlineLLMAdapter,
    maxRepairAttempts: opts.maxRepairAttempts == null ? 1 : opts.maxRepairAttempts
  }),
  pause(650)]);

  report('Validating outline\u2026');
  await pause(450);

  if (result && result.repairAttempts > 0) {
    report('Repairing outline\u2026');
    await pause(550);
  }

  if (!result || result.status === 'failed' || result.source === 'local-fallback') {
    const err = new Error(
      result && result.errorMessage
        ? result.errorMessage
        : 'The outline could not be generated.'
    );
    err.code = result && result.errorCode || 'outline_generation_failed';
    err.result = result || null;
    throw err;
  }

  report('Preparing editable outline\u2026');
  await pause(400);
  return result;
}

/* ---------- Auto-growing textarea for talking points ---------- */
function AutoText({ value, onChange, placeholder, className, readOnly = false }) {
  const ref = useRef(null);
  useLayoutEffect(() => {
    const el = ref.current;
    if (!el) return;
    el.style.height = 'auto';
    el.style.height = el.scrollHeight + 'px';
  }, [value]);
  return (
    <textarea
      ref={ref}
      rows={1}
      className={className}
      value={value}
      readOnly={readOnly}
      aria-readonly={readOnly}
      placeholder={placeholder}
      onChange={(e) => {if (!readOnly) onChange(e.target.value);}} />);

}

/* ---------- Between-block inserter — "Add heading" on hover ---------- */
function Inserter({ showH3, onAddH2, onAddH3, disabled = false }) {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);

  useEffect(() => {
    if (disabled) setOpen(false);
  }, [disabled]);

  useEffect(() => {
    if (!open) return;
    const onDoc = (e) => {if (ref.current && !ref.current.contains(e.target)) setOpen(false);};
    const onKey = (e) => {if (e.key === 'Escape') setOpen(false);};
    document.addEventListener('mousedown', onDoc);
    document.addEventListener('keydown', onKey);
    return () => {document.removeEventListener('mousedown', onDoc);document.removeEventListener('keydown', onKey);};
  }, [open]);

  olLucide([open]);

  return (
    <div className={`rl-ins ${open ? 'rl-ins--open' : ''}`} ref={ref}>
      <button
        type="button"
        className="rl-ins__btn"
        disabled={disabled}
        onClick={() => {if (disabled) return;if (showH3) setOpen((o) => !o);else onAddH2();}} style={{ height: "25px" }}>

        <i data-lucide="plus"></i>
        <span>Add heading</span>
      </button>

      {open && showH3 &&
      <div className="rl-ins__menu" role="menu">
        <button type="button" className="rl-ins__opt" role="menuitem" disabled={disabled} onClick={() => {if (disabled) return;onAddH2();setOpen(false);}}>
          <span className="rl-tag rl-tag--h2">H2</span>
          <span>New section here</span>
        </button>
        <button type="button" className="rl-ins__opt" role="menuitem" disabled={disabled} onClick={() => {if (disabled) return;onAddH3();setOpen(false);}}>
          <span className="rl-tag rl-tag--h3">H3</span>
          <span>Subsection under the section above</span>
        </button>
      </div>}
    </div>);

}

/* ---------- Clickable heading-level badge with a level dropdown ---------- */
function LevelBadge({ level, isTop, prevLevel, nextLevel, onChange, disabled = false }) {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);

  /* Only show logical neighbours: current level ±1, clamped to the valid
     range. Top section cards offer H2/H3; subsections never reach above H3.
       H2 → 2,3 · H3 → 3,4 · H4 → 3,4,5 · H5 → 4,5,6 · H6 → 5,6 */
  const visible = isTop ?
  [2, 3] :
  (() => {
    const lo = Math.max(3, level - 1);
    const hi = Math.min(6, level + 1);
    const a = [];
    for (let i = lo; i <= hi; i++) a.push(i);
    return a;
  })();

  /* A level is allowed if it keeps the hierarchy intact:
     - top-level section cards stay at H2 (others would orphan the card)
     - a child can't be H2 (that's a section card, not a subsection)
     - can't dive deeper than one level past the heading above it
     - can't orphan the heading below it */
  const allowed = (L) => {
    if (isTop) return L === 2 || L === 3;
    if (L < 3) return false;
    if (L > prevLevel + 1) return false;
    if (nextLevel != null && nextLevel > L + 1) return false;
    return true;
  };

  useEffect(() => {
    if (disabled) setOpen(false);
  }, [disabled]);

  useEffect(() => {
    if (!open) return;
    const onDoc = (e) => {if (ref.current && !ref.current.contains(e.target)) setOpen(false);};
    const onKey = (e) => {if (e.key === 'Escape') setOpen(false);};
    document.addEventListener('mousedown', onDoc);
    document.addEventListener('keydown', onKey);
    return () => {document.removeEventListener('mousedown', onDoc);document.removeEventListener('keydown', onKey);};
  }, [open]);

  olLucide([open, level]);

  return (
    <div className="rl-badge-wrap" ref={ref}>
      <button
        type="button"
        className={`rl-tag rl-tag--h${level} rl-tag--btn`}
        aria-haspopup="menu"
        aria-expanded={open}
        disabled={disabled}
        title="Change heading level"
        onClick={() => {if (!disabled) setOpen((o) => !o);}}>

        H{level}
      </button>

      {open &&
      <div className="rl-lvl-menu" role="menu">
        {visible.map((L) => {
          const isCurrent = L === level;
          const isOn = isCurrent || allowed(L);
          return (
            <button
              key={L}
              type="button"
              role="menuitemradio"
              aria-checked={isCurrent}
              disabled={disabled || !isOn}
              className={`rl-lvl-opt ${isCurrent ? 'rl-lvl-opt--on' : ''}`}
              onClick={() => {if (disabled) return;if (!isCurrent && allowed(L)) onChange(L);setOpen(false);}}>

              <span className={`rl-tag rl-tag--h${L}`}>H{L}</span>
            </button>);

        })}
      </div>}
    </div>);

}

function SectionAIMenu({ sectionId, running, onAction, disabled = false }) {
  const [open, setOpen] = useState(false);
  const [customOpen, setCustomOpen] = useState(false);
  const [customInstruction, setCustomInstruction] = useState('');
  const ref = useRef(null);
  const customText = customInstruction.trim();

  useEffect(() => {
    if (disabled) setOpen(false);
  }, [disabled]);

  useEffect(() => {
    if (!open) return;
    const onDoc = (e) => {if (ref.current && !ref.current.contains(e.target)) setOpen(false);};
    const onKey = (e) => {if (e.key === 'Escape') setOpen(false);};
    document.addEventListener('mousedown', onDoc);
    document.addEventListener('keydown', onKey);
    return () => {document.removeEventListener('mousedown', onDoc);document.removeEventListener('keydown', onKey);};
  }, [open]);

  useEffect(() => {
    if (open) return;
    setCustomOpen(false);
    setCustomInstruction('');
  }, [open]);

  olLucide([open, running, customOpen]);

  return (
    <div className={`rl-sec-ai ${open ? 'rl-sec-ai--open' : ''}`} ref={ref}>
      <button
        type="button"
        className="rl-tool rl-tool--ai"
        aria-label="AI section actions"
        aria-haspopup="menu"
        aria-expanded={open}
        disabled={running || disabled}
        title="AI section actions"
        onClick={() => {if (!disabled) setOpen((o) => !o);}}>
        <i data-lucide={running ? 'loader-2' : 'sparkles'}></i>
      </button>
      {open &&
      <div className="rl-sec-ai__menu" role="menu">
        {SECTION_AI_ACTIONS.map((item) =>
        <React.Fragment key={item.id}>
        <button
          type="button"
          className={`rl-sec-ai__item ${item.id === 'custom_instruction' && customOpen ? 'rl-sec-ai__item--open' : ''}`}
          role="menuitem"
          disabled={running || disabled}
          onClick={() => {
            if (disabled) return;
            if (item.id === 'custom_instruction') {
              setCustomOpen(true);
              return;
            }
            setOpen(false);
            onAction(sectionId, item.id);
          }}>
          {item.label}
        </button>
        {item.id === 'custom_instruction' && customOpen &&
        <div className="rl-sec-ai-custom">
          <textarea
            className="rl-sec-ai-custom__input"
            value={customInstruction}
            maxLength={400}
            disabled={running || disabled}
            placeholder="Tell the AI how to improve this section..."
            onChange={(e) => {if (!disabled) setCustomInstruction(e.target.value);}} />
          <div className="rl-sec-ai-custom__meta">{customInstruction.length} / 400</div>
          <div className="rl-sec-ai-custom__actions">
            <button
              type="button"
              className="rl-sec-ai-custom__cancel"
              disabled={running || disabled}
              onClick={() => {setCustomOpen(false);setCustomInstruction('');}}>
              Cancel
            </button>
            <button
              type="button"
              className="rl-sec-ai-custom__apply"
              disabled={running || disabled || !customText}
              onClick={() => {
                if (disabled || !customText) return;
                setOpen(false);
                onAction(sectionId, 'custom_instruction', { customInstruction: customText });
              }}>
              Apply
            </button>
          </div>
        </div>}
        </React.Fragment>
        )}
      </div>}
    </div>);

}

/* ---------- Live outline-structure summary (right rail) ---------- */
function OutlineSummary({ outline, onJump }) {
  const [expandedIds, setExpandedIds] = useState(() => new Set());
  const intro = (outline || []).find((s) => s && s.intro);
  const sections = (outline || []).filter((s) => s && !s.intro);
  const expandableIds = sections.
    filter((s) => Array.isArray(s.children) && s.children.length > 0).
    map((s) => String(s.id));
  const expandableIdSet = new Set(expandableIds);
  const allExpandableOpen = expandableIds.length > 0 && expandableIds.every((id) => expandedIds.has(id));
  const anyExpandableOpen = expandableIds.some((id) => expandedIds.has(id));
  const sectionCount = sections.length;

  useEffect(() => {
    setExpandedIds((prev) => {
      let changed = false;
      const next = new Set();
      prev.forEach((id) => {
        if (expandableIdSet.has(id)) {
          next.add(id);
        } else {
          changed = true;
        }
      });
      return changed ? next : prev;
    });
  }, [outline]);

  const toggleSection = (sectionId) => {
    const id = String(sectionId);
    setExpandedIds((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);else next.add(id);
      return next;
    });
  };

  const expandAll = () => setExpandedIds(() => new Set(expandableIds));
  const collapseAll = () => setExpandedIds(() => new Set());

  const labelFor = (text, fallback) => (String(text || '').trim() || fallback || 'Untitled');
  const levelFor = (child) => {
    const level = Number(child && child.level) || 3;
    return Math.min(6, Math.max(3, level));
  };

  return (
    <aside className="rl-ol-side" aria-label="Outline summary">
      <div className="rl-summary__hd">
        <span className="rl-summary__heading">Outline summary</span>
        <div className="rl-osum__seg" aria-label="Expand or collapse outline summary sections">
          <button
            type="button"
            className={`rl-osum__seg-btn ${allExpandableOpen ? 'rl-osum__seg-btn--active' : ''}`}
            aria-label="Expand outline summary subsections"
            aria-pressed={allExpandableOpen}
            onClick={expandAll}
            disabled={expandableIds.length === 0}>
            Expand
          </button>
          <button
            type="button"
            className={`rl-osum__seg-btn ${expandableIds.length > 0 && !anyExpandableOpen ? 'rl-osum__seg-btn--active' : ''}`}
            aria-label="Collapse outline summary subsections"
            aria-pressed={expandableIds.length > 0 && !anyExpandableOpen}
            onClick={collapseAll}
            disabled={expandableIds.length === 0}>
            Collapse
          </button>
        </div>
      </div>
      <nav className="rl-summary rl-ol-summary" aria-label="Outline table of contents">
        {sectionCount === 0 && !intro ?
        <div className="rl-osum__empty">No outline added yet.</div> :
        <ol className="rl-osum__list">
          {intro &&
          <li className="rl-osum__row rl-osum__row--intro" key={intro.id}>
            <button
              type="button"
              className="rl-osum__jump"
              aria-label="Jump to Introduction"
              onClick={() => onJump && onJump(intro.id)}>
              <span className="rl-osum__tag">Intro</span>
              <span className="rl-osum__text">Introduction</span>
            </button>
          </li>}
          {sections.map((section) => {
            const children = Array.isArray(section.children) ? section.children : [];
            const hasChildren = children.length > 0;
            const isOpen = expandedIds.has(String(section.id));
            const headingLabel = labelFor(section.text, 'Untitled section');
            return (
              <li className="rl-osum__group" key={section.id}>
                <div className="rl-osum__row rl-osum__row--h2">
                  <button
                    type="button"
                    className="rl-osum__jump rl-osum__jump--h2"
                    aria-label={`Jump to ${headingLabel}`}
                    onClick={() => onJump && onJump(section.id)}>
                    <span className="rl-osum__tag">H2</span>
                    <span className="rl-osum__text">
                      {String(section.text || '').trim() || <span className="rl-osum__untitled">Untitled</span>}
                    </span>
                  </button>
                  {hasChildren &&
                  <button
                    type="button"
                    className={`rl-osum__chev ${isOpen ? 'rl-osum__chev--open' : ''}`}
                    aria-label={`${isOpen ? 'Collapse' : 'Expand'} subsections for ${headingLabel}`}
                    aria-expanded={isOpen}
                    onClick={() => toggleSection(section.id)}>
                    <span aria-hidden="true">›</span>
                  </button>}
                </div>
                {hasChildren && isOpen &&
                <ol className="rl-osum__children">
                  {children.map((child) => {
                    const level = levelFor(child);
                    const childLabel = labelFor(child.text, `Untitled H${level}`);
                    return (
                      <li className={`rl-osum__row rl-osum__row--child rl-osum__row--l${level}`} key={child.id}>
                        <button
                          type="button"
                          className="rl-osum__jump"
                          aria-label={`Jump to ${childLabel}`}
                          onClick={() => onJump && onJump(child.id)}>
                          <span className="rl-osum__tag">H{level}</span>
                          <span className="rl-osum__text">
                            {String(child.text || '').trim() || <span className="rl-osum__untitled">Untitled</span>}
                          </span>
                        </button>
                      </li>);
                  })}
                </ol>}
              </li>);
          })}
        </ol>}
      </nav>
    </aside>);

}

/* ---------- Research note types (v1 data contract — the only allowed types) ---------- */
const RL_NOTE_TYPES = [
'product_fact', 'statistic', 'benchmark', 'industry_report', 'trend'];
const RL_NOTE_TYPE_LABELS = {
  product_fact: 'Product fact',
  statistic: 'Statistic',
  benchmark: 'Benchmark',
  industry_report: 'Industry report',
  trend: 'Trend'
};
function rlNoteTypeLabel(type) {
  return RL_NOTE_TYPE_LABELS[type] || type || 'Research note';
}

/* Pull a 4-digit year out of an ISO/loose date string, for the legacy pubYear alias. */
function rlYearOf(dateStr) {
  const m = (dateStr == null ? '' : String(dateStr)).match(/\b(19|20)\d{2}\b/);
  return m ? m[0] : null;
}

/* Build a v1 research note from the edit-form draft + section meta.
   - create (no `existing`): origin "manual", editedByUser true, createdAt now, updatedAt null
   - edit (`existing` present): preserve origin + hidden fields, set editedByUser true + updatedAt now
   Keeps both modern (sourcePublisher/sourceDate) and legacy (sourceName/pubYear) aliases.
   Runs window.ResearchAgent.normalizeResearchNote when available (never blocks the user). */
function rlBuildNote(meta, draft, existing) {
  const RA = window.ResearchAgent;
  const now = new Date().toISOString();
  const base = existing || {};
  const isExample = false;
  const publisher = (draft.sourcePublisher || '').trim() || null;
  const url = (draft.sourceUrl || '').trim() || null;
  const isTimeSensitive = !!draft.isTimeSensitive;
  const sourceDate = (draft.sourceDate || '').trim() || null;

  let note = {
    id: base.id || ('note_' + meta.id),
    articleId: base.articleId || (RA && RA.currentArticleId ? RA.currentArticleId() : null),
    sectionId: meta.sectionId,
    headingId: meta.id,
    headingTitle: meta.title,
    headingLevel: meta.level,

    noteType: draft.noteType,
    note: (draft.note || '').trim(),
    whyItMatters: (draft.whyItMatters || '').trim(),

    sourcePublisher: publisher,
    sourceUrl: url,
    sourceTitle: base.sourceTitle != null ? base.sourceTitle : null,

    isTimeSensitive: isTimeSensitive,
    sourceDate: sourceDate,

    exampleKind: isExample ? (base.exampleKind || null) : null,
    sourceRelationship: base.sourceRelationship || 'unknown',
    competitorRisk: base.competitorRisk || 'none',

    origin: base.origin || 'manual',
    editedByUser: true,
    createdAt: base.createdAt || now,
    updatedAt: existing ? now : null,
    deletedAt: null,

    /* legacy aliases the older note renderer / workflow may still read */
    sourceName: publisher,
    pubYear: rlYearOf(sourceDate),
    sourceType: /case_study|approved_internal|non_competing/.test(base.sourceRelationship || '') ? 'Brand Knowledge' : 'External web source'
  };

  if (RA && RA.normalizeResearchNote) {
    try { note = RA.normalizeResearchNote(note); } catch (e) {/* never block the user */}
    /* keep the display-critical aliases normalize doesn't set */
    if (note.sourceName == null) note.sourceName = note.sourcePublisher || null;
    if (note.pubYear == null) note.pubYear = rlYearOf(note.sourceDate);
  }
  return note;
}

/* Coerce an incoming AI/workflow note into the v1 shape for display + merge. */
function rlNormalizeIncoming(raw) {
  const RA = window.ResearchAgent;
  let n = Object.assign({ origin: 'ai' }, raw);
  if (RA && RA.normalizeResearchNote) {
    try { n = RA.normalizeResearchNote(n); } catch (e) {}
  }
  if (n.sourcePublisher == null && n.sourceName != null) n.sourcePublisher = n.sourceName;
  if (n.sourceName == null && n.sourcePublisher != null) n.sourceName = n.sourcePublisher;
  if (n.sourceDate == null && n.pubYear != null) n.sourceDate = String(n.pubYear);
  if (n.pubYear == null) n.pubYear = rlYearOf(n.sourceDate);
  /* older workflow notes carry `reason` instead of whyItMatters — surface it */
  if (!n.whyItMatters && raw && raw.reason) n.whyItMatters = raw.reason;
  if (n.origin !== 'manual') n.origin = 'ai';
  return n;
}

function rlResearchNotesMapFromList(list) {
  const map = {};
  (Array.isArray(list) ? list : []).forEach((raw) => {
    if (!raw || raw.deletedAt) return;
    const note = rlNormalizeIncoming(raw);
    if (!note || !note.headingId || note.deletedAt) return;
    map[String(note.headingId)] = note;
  });
  return map;
}

function rlIsProtected(note) {
  return !!note && (note.origin === 'manual' || (note.origin === 'ai' && note.editedByUser));
}

function rlOutlineHeadingIds(outline) {
  const ids = new Set();
  (outline || []).forEach((section) => {
    if (section && section.id) ids.add(String(section.id));
    (section && section.children || []).forEach((child) => {
      if (child && child.id) ids.add(String(child.id));
    });
  });
  return ids;
}

function rlActiveResearchNoteIds(notes, outline) {
  const headingIds = rlOutlineHeadingIds(outline);
  return Object.keys(notes || {}).filter((id) => {
    const note = notes[id];
    return note && !note.deletedAt && headingIds.has(String(id));
  });
}

window.__rlOutlineResearchNoteVisibility = {
  activeIds: rlActiveResearchNoteIds,
  mapIncoming: rlResearchNotesMapFromList,
  visibleIdsFromList: (list, outline) => rlActiveResearchNoteIds(rlResearchNotesMapFromList(list), outline)
};


/* ---------- Collapsible research-note block (per heading) ----------
   Displays an AI-generated or manual research note in the required format, or
   an inline manual editor when the heading has no note yet. Defined at module
   level so its local draft state survives parent re-renders (keeps input focus). */
function ResearchNoteBlock({ note, onSave, onRemove, onClose, readOnly = false }) {
  const initDraft = (n) => ({
    noteType: n ? (n.noteType || 'statistic') : 'statistic',
    note: n ? (n.note || '') : '',
    whyItMatters: n ? (n.whyItMatters || '') : '',
    sourcePublisher: n ? (n.sourcePublisher || n.sourceName || '') : '',
    sourceUrl: n ? (n.sourceUrl || '') : '',
    isTimeSensitive: n ? !!n.isTimeSensitive : false,
    sourceDate: n ? (n.sourceDate || n.pubYear || '') : ''
  });
  const [editing, setEditing] = useState(!note);
  const [draft, setDraft] = useState(() => initDraft(note));

  /* If an AI note lands (or changes) while this block is open, show it. */
  const noteSig = note ?
    `${note.note}|${note.noteType}|${note.whyItMatters || ''}|${note.sourcePublisher || note.sourceName || ''}|${note.sourceUrl || ''}|${note.isTimeSensitive ? 1 : 0}|${note.sourceDate || note.pubYear || ''}` :
    '';
  useEffect(() => {
    if (note) {
      setDraft(initDraft(note));
      setEditing(false);
    }
    // eslint-disable-next-line
  }, [noteSig]);

  olLucide([editing, noteSig]);

  /* ---- Display mode (existing note) ---- */
  if (!editing && note) {
    const publisher = note.sourcePublisher || note.sourceName || null;
    const dateText = note.sourceDate || note.pubYear || null;
    const showDate = !!note.isTimeSensitive && !!dateText;
    return (
      <div className="rl-note">
        <div className="rl-note__hd">
          <span className="rl-note__title">Research note</span>
          <span className="rl-note__type">{rlNoteTypeLabel(note.noteType)}</span>
          {!readOnly && <div className="rl-note__tools">
            <button type="button" className="rl-note__tool" title="Edit note" onClick={() => setEditing(true)}>
              <i data-lucide="pencil"></i>
            </button>
            <button type="button" className="rl-note__tool rl-note__tool--danger" title="Remove note" onClick={onRemove}>
              <i data-lucide="trash-2"></i>
            </button>
          </div>}
        </div>
        <p className="rl-note__body">{note.note}</p>
        {note.whyItMatters &&
        <p className="rl-note__why" style={{ margin: '6px 0 0', fontSize: '12px', lineHeight: '17px', color: 'var(--rl-fg-3)' }}>
          <span style={{ fontWeight: 600 }}>Why this matters: </span>{note.whyItMatters}
        </p>}
        {publisher &&
        <p className="rl-note__body" style={{ margin: '7px 0 0' }}>
          <span className="rl-note__src">Source:{' '}
            {note.sourceUrl ?
            <a href={note.sourceUrl} target="_blank" rel="noopener noreferrer">{publisher}</a> :
            <span className="rl-note__brand">{publisher}</span>}
            {showDate ? <span className="rl-note__year"> ({dateText})</span> : null}
          </span>
        </p>}
      </div>);

  }

  /* ---- Edit / manual mode ---- */
  if (readOnly) return null;
  const canSave = draft.note.trim().length > 0;
  return (
    <div className="rl-note rl-note--edit">
      <div className="rl-note__hd">
        <span className="rl-note__title">Research note</span>
        <span className="rl-note__type rl-note__type--muted">{note ? 'Editing' : 'Manual'}</span>
      </div>
      <div className="rl-note__form">
        <label className="rl-note__label">Note type</label>
        <select className="rl-note__select" value={draft.noteType} onChange={(e) => setDraft((d) => ({ ...d, noteType: e.target.value }))}>
          {RL_NOTE_TYPES.map((t) => <option key={t} value={t}>{rlNoteTypeLabel(t)}</option>)}
        </select>
        <label className="rl-note__label">Note</label>
        <textarea
          className="rl-note__textarea"
          rows={2}
          value={draft.note}
          placeholder="The exact note the writer should consider — e.g. a stat, benchmark, or product fact."
          onChange={(e) => setDraft((d) => ({ ...d, note: e.target.value }))} />
        <label className="rl-note__label">Why this matters</label>
        <textarea
          className="rl-note__textarea"
          rows={2}
          value={draft.whyItMatters}
          placeholder="How the writer should use this note — e.g. open the section by quantifying the problem."
          onChange={(e) => setDraft((d) => ({ ...d, whyItMatters: e.target.value }))} />
        <label className="rl-note__label">Source publisher <span className="rl-note__opt">· optional</span></label>
        <input
          className="rl-note__input"
          value={draft.sourcePublisher}
          placeholder="e.g. Content Marketing Institute"
          onChange={(e) => setDraft((d) => ({ ...d, sourcePublisher: e.target.value }))} />
        <label className="rl-note__label">Source URL <span className="rl-note__opt">· optional</span></label>
        <input
          className="rl-note__input"
          value={draft.sourceUrl}
          placeholder="https://…"
          onChange={(e) => setDraft((d) => ({ ...d, sourceUrl: e.target.value }))} />
        <label className="rl-note__check" style={{ display: 'flex', alignItems: 'center', gap: '7px', margin: '10px 0 0', fontSize: '12px', color: 'var(--rl-fg-2)', cursor: 'pointer' }}>
          <input
            type="checkbox"
            checked={draft.isTimeSensitive}
            onChange={(e) => setDraft((d) => ({ ...d, isTimeSensitive: e.target.checked }))} />
          Time-sensitive (show a source date)
        </label>
        {draft.isTimeSensitive &&
        <React.Fragment>
          <label className="rl-note__label">Source date</label>
          <input
            className="rl-note__input"
            value={draft.sourceDate}
            placeholder="e.g. 2025 or 2025-03"
            onChange={(e) => setDraft((d) => ({ ...d, sourceDate: e.target.value }))} />
        </React.Fragment>}
        <div className="rl-note__actions">
          <button type="button" className="rl-note__save" disabled={!canSave} onClick={() => canSave && onSave(draft)}>Save note</button>
          <button type="button" className="rl-note__cancel" onClick={() => note ? setEditing(false) : onClose()}>Cancel</button>
        </div>
      </div>
    </div>);

}

/* ---------- Live section-role tag ----------
   Hidden in the normal user-facing editor. Add ?showOutlineRoles=1 locally to
   inspect the Outline Agent's live role read without mutating outline data.
   Previously this labeled a heading with the Outline Agent's Prompt-3 read:
   (intentRole) plus an importance dot. Computed LIVE from the current heading
   text + detected search intent, so it stays accurate as the user edits or
   adds headings. Pure read — never mutates the outline. */
const RL_IMPORTANCE_LABEL = {
  critical: 'Critical section',
  important: 'Important section',
  supporting: 'Supporting section',
  optional: 'Optional section'
};
const SHOW_OUTLINE_ROLE_TAGS = typeof window !== 'undefined' &&
  window.location &&
  /(?:[?&])showOutlineRoles=1(?:&|$)/.test(window.location.search || '');

function RoleTag({ heading, intent, isChild }) {
  if (!window.OutlineAgent || !window.OutlineAgent.classifySection) return null;
  const text = (heading || '').trim();
  if (!text) return null;
  let info;
  try {
    info = window.OutlineAgent.classifySection(text, intent, isChild);
  } catch (e) {
    return null;
  }
  if (!info) return null;
  const imp = info.importance || 'important';
  const title = (RL_IMPORTANCE_LABEL[imp] || 'Section') +
    (info.writingInstructions ? ' — ' + info.writingInstructions : '');
  return (
    <span className="rl-role" title={title}>
      <span className={`rl-role__dot rl-role__dot--${imp}`}></span>
      <span className="rl-role__label">{info.roleLabel}</span>
    </span>);

}


/* ---------- Outline screen ---------- */
function OutlineScreen({ outline, setOutline, form, meta, onBack, onGenerateDraft, workflowIdentity, workflowKnowledgeSnapshot, workflowResearch, outlineSaveState, outlineSaveError, canCompleteOutline, onRetryOutlineSave, onCloudResearchSaved, workspaceAccess }) {
  const headingCount = outline.filter((s) => !s.intro).length;
  const isCloudWorkflow = !!(workflowIdentity && workflowIdentity.kind === 'cloud');
  const accessRef = useRef(workspaceAccess);
  accessRef.current = workspaceAccess;
  const canMutateOutline = !!(workspaceAccess && workspaceAccess.canMutateWorkspaceContent === true);
  const canUseOutlineAi = !!(canMutateOutline && workspaceAccess && workspaceAccess.canUseAi === true);
  const canMutateNow = () => !!(accessRef.current && accessRef.current.canMutateWorkspaceContent === true);
  const canUseAiNow = () => !!(canMutateNow() && accessRef.current && accessRef.current.canUseAi === true);
  const workflowKnowledgeState = React.useMemo(() => {
    if (!isCloudWorkflow) return { context: null, error: null };
    if (!workflowKnowledgeSnapshot) {
      return { context: null, error: new Error('This Article needs saved Knowledge before generation can continue.') };
    }
    try {
      if (typeof window.buildAIContext !== 'function') throw new Error('Saved Article Knowledge is unavailable right now.');
      return {
        context: window.buildAIContext({ taskType: 'outline', knowledgeSnapshot: workflowKnowledgeSnapshot }),
        error: null
      };
    } catch (error) {
      return { context: null, error };
    }
  }, [isCloudWorkflow, workflowKnowledgeSnapshot]);
  const cloudOutlineBusy = isCloudWorkflow && outlineSaveState === 'saving';
  const cloudOutlineUnsaved = isCloudWorkflow && outlineSaveState === 'error';
  const [cloudResearchSaveState, setCloudResearchSaveState] = useState(Array.isArray(workflowResearch) && workflowResearch.length ? 'saved' : 'idle');
  const [cloudResearchSaveError, setCloudResearchSaveError] = useState('');
  const cloudResearchControllerRef = useRef(null);
  const cloudResearchSaveRequestRef = useRef(0);
  const cloudUnsavedResearchRef = useRef(null);
  const outlineResearchResetReadyRef = useRef(false);
  const cloudResearchBusy = isCloudWorkflow && cloudResearchSaveState === 'saving';
  const cloudResearchUnsaved = isCloudWorkflow && cloudResearchSaveState === 'error';
  const cloudBoundaryMessage = cloudOutlineUnsaved ?
    'Save the outline before continuing.' :
    cloudResearchUnsaved ?
      'Save research before continuing to the draft.' :
      '';

  /* Read-only strategy analysis from the Outline Agent. We call generateOutline
     (not analyzeBrief) so heading role tags can use the same detected search
     intent. Pure read — does not touch the editable sections below. */
  const strategy = React.useMemo(() => {
    try {
      if (!canUseOutlineAi) return null;
      if (isCloudWorkflow && !workflowKnowledgeState.context) return null;
      return window.OutlineAgent ? window.OutlineAgent.generateOutline(briefFromForm(form, { knowledgeContext: workflowKnowledgeState.context })) : null;
    } catch (e) {
      return null;
    }
  }, [form, isCloudWorkflow, workflowKnowledgeState.context, canUseOutlineAi]);

  /* Pre-research + research step.
     'idle' → 'understanding' (button loading) → 'done' (result message).
     Phase 1: build + persist the internal Article Research Context.
     Phase 2: decide which sections need evidence and attach structured
     research notes to them (saved to the DB, connected to section/heading IDs).
     The user only ever sees the button state and the result message — neither
     the context object nor the notes are rendered as a page/panel. */
  const [researchState, setResearchState] = useState('idle');
  const [researchCount, setResearchCount] = useState(null);
  const [researchStage, setResearchStage] = useState(null);
  const [researchError, setResearchError] = useState('');
  const [introTestState, setIntroTestState] = useState('idle');
  const [introTestResult, setIntroTestResult] = useState(null);
  const [introTestWarning, setIntroTestWarning] = useState('');
  const [introTestError, setIntroTestError] = useState('');
  const [introTestRuntimeDiagnostics, setIntroTestRuntimeDiagnostics] = useState(null);
  const [sectionActionRunningId, setSectionActionRunningId] = useState(null);
  const [sectionActionRunningAction, setSectionActionRunningAction] = useState(null);
  const [sectionActionToast, setSectionActionToast] = useState(null);
  /* Confirmation modal shown only when the user clicks Write article with no
     research notes attached. Notes present → write immediately, no modal. */
  const [showWriteConfirm, setShowWriteConfirm] = useState(false);

  const getCloudResearchController = () => {
    const WF = window.RankLyxArticleWorkflow;
    if (!cloudResearchControllerRef.current && WF && typeof WF.createCloudResearchController === 'function') {
      cloudResearchControllerRef.current = WF.createCloudResearchController();
    }
    return cloudResearchControllerRef.current;
  };

  /* ---- Per-heading research notes ----
     `notes`: map headingId → note object (AI-generated or manual).
     `openNotes`: set of headingIds whose research-note area is expanded.
     Saved notes open by default on load; AI notes auto-expand their own headings on completion. */
  const [notes, setNotes] = useState({});
  const [openNotes, setOpenNotes] = useState(() => new Set());

  useEffect(() => {
    if (!isCloudWorkflow) return;
    const map = rlResearchNotesMapFromList(workflowResearch);
    setNotes(map);
    const ids = rlActiveResearchNoteIds(map, outline);
    setOpenNotes(new Set(ids));
    setResearchCount(ids.length || null);
    if (ids.length && researchState === 'idle') setResearchState('done');
    if (ids.length && cloudResearchSaveState === 'idle') setCloudResearchSaveState('saved');
    if (!ids.length && cloudResearchSaveState === 'saved') setCloudResearchSaveState('idle');
    // eslint-disable-next-line
  }, [isCloudWorkflow, workflowResearch]);

  useEffect(() => {
    if (!sectionActionToast || sectionActionToast.kind !== 'error') return;
    const t = setTimeout(() => setSectionActionToast(null), 5200);
    return () => clearTimeout(t);
  }, [sectionActionToast]);

  /* Foundation: rehydrate saved research notes for this article, keyed by the
     STABLE heading/section IDs they were stored against. This proves the linkage
     survives a reload — notes reattach to the same outline nodes. */
  useEffect(() => {
    if (isCloudWorkflow) return;
    try {
      const RA = window.ResearchAgent;
      if (!RA || !RA.loadArticleResearchNotes) return;
      const saved = RA.loadArticleResearchNotes({
        userId: RA.AUTH && RA.AUTH.userId,
        workspaceId: RA.AUTH && RA.AUTH.workspaceId,
        articleId: RA.currentArticleId && RA.currentArticleId()
      }) || [];
      if (!saved.length) return;
      const map = {};
      saved.forEach((n) => { if (n && n.headingId && !n.deletedAt) map[n.headingId] = rlNormalizeIncoming(n); });
      if (Object.keys(map).length) {
        setNotes((prev) => Object.keys(prev).length ? prev : map);
        setOpenNotes(new Set(rlActiveResearchNoteIds(map, outline)));
      }
    } catch (e) {}
    // eslint-disable-next-line
  }, []);

  /* Whether any research note is currently attached to this outline — drives the
     non-blocking "no research notes" hint under the Write article button. */
  const hasResearchNotes = Object.keys(notes || {}).some((k) => notes[k] && !notes[k].deletedAt);

  const toggleNote = (hid) => setOpenNotes((prev) => {
    const n = new Set(prev);
    if (n.has(hid)) n.delete(hid);else n.add(hid);
    return n;
  });
  const persistNotes = (map) => {
    if (!canMutateNow() || isCloudWorkflow) return;
    if (window.ResearchNotes) window.ResearchNotes.saveResearchNotes(Object.values(map), null);
  };
  const saveNote = (meta, draft) => {
    if (!canMutateNow() || isCloudWorkflow) return;
    const existing = notes[meta.id] || null;
    const noteObj = rlBuildNote(meta, draft, existing);
    const nextNotes = { ...notes, [meta.id]: noteObj };
    setNotes(nextNotes);
    persistNotes(nextNotes);
    /* Collapse a freshly-created manual note; keep an edited note open showing
       its updated display. */
    if (!existing) {
      setOpenNotes((prev) => {
        const n = new Set(prev);
        n.delete(meta.id);
        return n;
      });
    }
  };
  const removeNote = (hid) => {
    if (!canMutateNow() || isCloudWorkflow) return;
    const nextNotes = { ...notes };
    delete nextNotes[hid];
    setNotes(nextNotes);
    persistNotes(nextNotes);
    setOpenNotes((prev) => {
      const n = new Set(prev);
      n.delete(hid);
      return n;
    });
    /* Mirror the deletion to the v1 research-notes store when available. */
    const RA = window.ResearchAgent;
    if (RA && RA.softDeleteArticleResearchNote) {
      try {
        RA.softDeleteArticleResearchNote({
          userId: RA.AUTH && RA.AUTH.userId,
          workspaceId: RA.AUTH && RA.AUTH.workspaceId,
          articleId: RA.currentArticleId && RA.currentArticleId(),
          headingId: hid
        });
      } catch (e) {/* keep local deletion regardless */}
    }
  };

  const onWriteClick = () => {
    if (!canUseAiNow()) return;
    if (cloudOutlineBusy || cloudOutlineUnsaved || cloudResearchBusy || cloudResearchUnsaved) {
      setSectionActionToast({ kind: 'error', label: cloudBoundaryMessage });
      return;
    }
    if (headingCount < 1) return;
    /* No research notes → confirm first. Notes present → write immediately. */
    if (!hasResearchNotes) {
      try { console.log('write-without-research-confirm-open'); } catch (e) {}
      setShowWriteConfirm(true);
      return;
    }
    onGenerateDraft();
  };
  const onBackClick = () => {
    if (onBack) onBack();
  };
  const cancelWrite = () => {
    try { console.log('write-without-research-cancel'); } catch (e) {}
    setShowWriteConfirm(false);
  };
  const confirmWriteAnyway = () => {
    if (!canUseAiNow()) return;
    try { console.log('write-without-research-confirmed'); } catch (e) {}
    setShowWriteConfirm(false);
    onGenerateDraft();
  };

  const getIntroTestRuntimeDiagnostics = () => {
    const WA = typeof window !== 'undefined' ? window.WritingAgent : null;
    const hasAppLLMAdapter = typeof window !== 'undefined' && typeof window.appLLMAdapter === 'function';
    const appAdapter = hasAppLLMAdapter ? window.appLLMAdapter : null;
    let appAdapterAccepted = false;
    let writingAgentLiveAdapterAvailable = false;
    let adapterSource = null;
    try {
      appAdapterAccepted = !!(WA && typeof WA.hasLiveAdapter === 'function' && appAdapter && WA.hasLiveAdapter({ llmAdapter: appAdapter }));
    } catch (e) {
      appAdapterAccepted = false;
    }
    try {
      writingAgentLiveAdapterAvailable = !!(WA && typeof WA.hasLiveAdapter === 'function' && WA.hasLiveAdapter({}));
    } catch (e) {
      writingAgentLiveAdapterAvailable = false;
    }
    try {
      if (appAdapterAccepted) adapterSource = WA && typeof WA.liveAdapterSource === 'function' ? WA.liveAdapterSource({ llmAdapter: appAdapter }) : 'options.llmAdapter';
      else if (writingAgentLiveAdapterAvailable) adapterSource = WA && typeof WA.liveAdapterSource === 'function' ? WA.liveAdapterSource({}) : 'WritingAgent internal live adapter';
    } catch (e) {
      adapterSource = appAdapterAccepted ? 'options.llmAdapter' : writingAgentLiveAdapterAvailable ? 'WritingAgent internal live adapter' : null;
    }
    return {
      appLLMAdapterExists: hasAppLLMAdapter,
      appLLMAdapterAccepted: appAdapterAccepted,
      sameAdapterAsFullArticleAvailable: appAdapterAccepted || writingAgentLiveAdapterAvailable,
      writingAgentInternalAdapterAvailable: writingAgentLiveAdapterAvailable,
      adapterSource: adapterSource
    };
  };

  const onTestIntroOnly = async () => {
    if (!canUseAiNow()) return;
    if (isCloudWorkflow) {
      setIntroTestState('failed');
      setIntroTestError('Intro-only testing is not available for this cloud article yet.');
      setSectionActionToast({ kind: 'error', label: cloudBoundaryMessage });
      return;
    }
    if (introTestState === 'running') return;
    setIntroTestState('running');
    setIntroTestResult(null);
    setIntroTestError('');
    setIntroTestWarning('');

    const WA = window.WritingAgent;
    const AS = window.ArticleStore;
    const runtime = getIntroTestRuntimeDiagnostics();
    setIntroTestRuntimeDiagnostics(runtime);

    try {
      if (!WA || typeof WA.generateArticleIntroduction !== 'function') {
        throw new Error('Writing Agent intro-only function is not available. Please reload and try again.');
      }
      if (!AS || typeof AS.getActiveArticleId !== 'function') {
        throw new Error('Article storage is not available. Please reload and try again.');
      }
      const aid = AS.getActiveArticleId();
      if (!canUseAiNow()) return;
      try { if (AS.setBrief) AS.setBrief(aid, form); } catch (e) {}
      try { if (AS.setOutline) AS.setOutline(aid, outline); } catch (e) {}

      if (!runtime.sameAdapterAsFullArticleAvailable) {
        setIntroTestState('failed');
        setIntroTestError('Live LLM adapter not available. Intro-only test cannot judge writing quality in local fallback mode.');
        setIntroTestResult({
          success: false,
          articleId: aid,
          title: '',
          html: '',
          intro: '',
          sections: [],
          diagnostics: null,
          errors: ['Live LLM adapter not available. Intro-only test cannot judge writing quality in local fallback mode.'],
          source: 'no-live-adapter',
          sectionSources: [],
          hasLiveAdapter: false,
          adapterSource: null,
          repairAttempts: 0
        });
        return;
      }

      const options = {
        requireLiveAdapter: true,
        allowLocalFallback: false,
        allowLocalRepair: false
      };
      if (runtime.appLLMAdapterAccepted && typeof window.appLLMAdapter === 'function') options.llmAdapter = window.appLLMAdapter;
      const result = await WA.generateArticleIntroduction(aid, options);
      if (!canUseAiNow()) return;
      const strict = result && result.strictLiveDiagnostics || null;
      const liveUsed = !!(strict && (strict.liveGenerationAttempted || strict.liveRepairAttempted)) ||
        !!(result && (result.sectionSources || []).some(function (s) { return /^llm/.test(String(s && s.source || '')); }));
      setIntroTestResult(result);
      if (!liveUsed) {
        setIntroTestState('failed');
        setIntroTestError('Live LLM adapter did not produce usable intro output. Intro-only test cannot judge writing quality in local fallback mode.');
      } else {
        setIntroTestState(result && result.success ? 'done' : 'failed');
      }
      if (liveUsed && !(result && result.success)) {
        const msg = result && result.errors && result.errors.length ? result.errors[0] : 'Intro generation failed.';
        setIntroTestError(msg);
      }
    } catch (e) {
      if (!canUseAiNow()) return;
      setIntroTestState('failed');
      setIntroTestError((e && e.message) || 'Intro generation failed.');
    }
  };

  const retryCloudResearchSave = () => {
    if (!isCloudWorkflow || !workflowIdentity || !workflowIdentity.articleId || !cloudUnsavedResearchRef.current) return;
    const controller = getCloudResearchController();
    if (!controller) return;
    const canComplete = controller.hasPendingCompletion(workflowIdentity.articleId, cloudUnsavedResearchRef.current.research);
    if (!canMutateNow() && !canComplete) return;
    const requestId = cloudResearchSaveRequestRef.current + 1;
    cloudResearchSaveRequestRef.current = requestId;
    setCloudResearchSaveState('saving');
    setCloudResearchSaveError('');
    controller.retryResearchSave(workflowIdentity.articleId, cloudUnsavedResearchRef.current.research, form, {
      expectedRevision: workflowIdentity.revision,
      cloudClient: window.RankLyxCloudArticles,
      accessClient: window.ClicklyxWorkspaceAccess
    }).then((result) => {
      if ((!canMutateNow() && !canComplete) || cloudResearchSaveRequestRef.current !== requestId) return;
      if (result && result.stale) {
        cloudUnsavedResearchRef.current = null;
        setNotes({});
        setResearchCount(null);
        setCloudResearchSaveState('idle');
        setResearchStage(null);
        setResearchState('failed');
        setResearchError(result.publicMessage || 'Workspace changed before this research finished saving. Retry in the current Workspace.');
        return;
      }
      if (result && result.ok) {
        setCloudResearchSaveState('saved');
        setCloudResearchSaveError('');
        setResearchState('done');
        setResearchCount((cloudUnsavedResearchRef.current.research || []).length);
        if (onCloudResearchSaved) onCloudResearchSaved(cloudUnsavedResearchRef.current.research || [], result.article);
        cloudUnsavedResearchRef.current = null;
        return;
      }
      setCloudResearchSaveState('error');
      setCloudResearchSaveError(result && result.publicMessage || 'Research could not be saved. Retry before continuing.');
    });
  };
  const onResearch = () => {
    if (!canUseAiNow()) return;
    if (researchState === 'understanding' || cloudResearchBusy) return;
    if (cloudOutlineBusy || cloudOutlineUnsaved || cloudResearchUnsaved) {
      setSectionActionToast({ kind: 'error', label: cloudBoundaryMessage });
      return;
    }
    setResearchState('understanding');
    setResearchCount(null);
    setResearchError('');
    setResearchStage({ key: 'start', label: 'Starting research...', detail: null });
    const notesApi = window.ResearchNotes;
    if (!notesApi || !notesApi.runResearchWorkflow) {
      setResearchStage(null);
      setResearchError('Research could not be generated. Please try again. If this keeps happening, contact support.');
      setResearchState('failed');
      return;
    }
    if (isCloudWorkflow) {
      const controller = getCloudResearchController();
      const articleId = workflowIdentity && workflowIdentity.articleId;
      if (!controller || !articleId) {
        setResearchStage(null);
        setResearchError('Article storage is unavailable right now.');
        setResearchState('failed');
        return;
      }
      setCloudResearchSaveState('saving');
      setCloudResearchSaveError('');
      controller.runResearch(articleId, {
        cloudClient: window.RankLyxCloudArticles,
        accessClient: window.ClicklyxWorkspaceAccess,
        defaultForm: form,
        runResearchWorkflow: notesApi.runResearchWorkflow,
        callLLM: researchLLMCall,
        useExternalResearch: true,
        searchProvider: tavilySearchProvider,
        useMockResearch: false,
        onStatus: (s) => {if (canUseAiNow()) setResearchStage(s);},
        onResearchGenerated: (generated) => {
          const research = Array.isArray(generated.research) ? generated.research : [];
          const map = rlResearchNotesMapFromList(research);
          const ids = rlActiveResearchNoteIds(map, outline);
          setNotes(map);
          setOpenNotes((prev) => {
            const next = new Set(prev);
            ids.forEach((hid) => next.add(hid));
            return next;
          });
          setResearchCount(research.length);
          cloudUnsavedResearchRef.current = { research: research, form: generated.form || form };
        }
      }).then((result) => {
        if (result && result.stale) {
          cloudUnsavedResearchRef.current = null;
          setNotes({});
          setResearchCount(null);
          setResearchStage(null);
          setResearchError(result.publicMessage || 'Workspace changed before this research finished saving. Retry in the current Workspace.');
          setResearchState('failed');
          setCloudResearchSaveState('idle');
          return;
        }
        if (result && result.ok) {
          const research = Array.isArray(result.research) ? result.research : [];
          setResearchStage(null);
          setResearchState('done');
          setResearchCount(research.length);
          setCloudResearchSaveState('saved');
          setCloudResearchSaveError('');
          cloudUnsavedResearchRef.current = null;
          if (onCloudResearchSaved) onCloudResearchSaved(research, result.article);
          return;
        }
        if (result && result.stage === 'research_save' && Array.isArray(result.research)) {
          setResearchStage(null);
          setResearchState('done');
          setResearchCount(result.research.length);
          setCloudResearchSaveState('error');
          setCloudResearchSaveError(result.publicMessage || 'Research could not be saved. Retry before continuing.');
          cloudUnsavedResearchRef.current = { research: result.research, form: result.form || form };
          return;
        }
        setResearchStage(null);
        setResearchError(result && result.publicMessage || 'Research could not be generated. Please try again. If this keeps happening, contact support.');
        setResearchState('failed');
        setCloudResearchSaveState('idle');
      }).catch(() => {
        if (!canUseAiNow()) return;
        setResearchStage(null);
        setResearchError('Research could not be generated. Please try again. If this keeps happening, contact support.');
        setResearchState('failed');
        setCloudResearchSaveState('idle');
      });
      return;
    }

    /* Real multi-step workflow: understand context → select targets → search →
       validate sources → check brand knowledge → match → save. Progress messages
       are driven by actual step completion (with real counts), not a fake timer.
       Success is shown only after the whole workflow — including saving — finishes. */
    notesApi.runResearchWorkflow({
      context: null,
      form,
      outline,
      callLLM: researchLLMCall,
      useExternalResearch: true,
      searchProvider: tavilySearchProvider,
      useMockResearch: false,
      canContinue: canUseAiNow,
      onProgress: (s) => {if (canUseAiNow()) setResearchStage(s);}
    }).
    then((res) => {
      if (!canUseAiNow()) return;
      const summary = res && res.summary ? res.summary : {};
      if (summary.status === 'skipped' || summary.status === 'failed') {
        setResearchStage(null);
        setResearchError('Research couldn’t be generated. Please try again. If this keeps happening, contact support.');
        setResearchState('failed');
        setResearchCount(0);
        return;
      }
      const aiNotes = res && res.notes ? res.notes : [];
      setResearchCount(aiNotes.length);
      /* Merge AI notes into state, normalizing to the v1 contract and NEVER
         overwriting protected notes (manual, or AI notes the user has edited).
         Compute the merge synchronously (against current `notes`) so we know
         which headings are new BEFORE scheduling state updates — a state-updater
         body does not run in time to populate these lists. */
      const addedHeadingIds = [];
      const addedV1Notes = [];
      const nextNotes = { ...notes };
      aiNotes.forEach((raw) => {
        const hid = raw.headingId;
        if (!hid) return;
        if (rlIsProtected(nextNotes[hid])) return; // skip protected sections
        const v1 = rlNormalizeIncoming(raw);
        nextNotes[hid] = v1;
        addedHeadingIds.push(hid);
        addedV1Notes.push(v1);
      });
      setNotes(nextNotes);
      persistNotes(nextNotes);
      /* Persist the accepted AI notes to the v1 store too, respecting protection. */
      const RA = window.ResearchAgent;
      if (RA && RA.upsertArticleResearchNotes && addedV1Notes.length) {
        try {
          RA.upsertArticleResearchNotes({
            userId: RA.AUTH && RA.AUTH.userId,
            workspaceId: RA.AUTH && RA.AUTH.workspaceId,
            articleId: RA.currentArticleId && RA.currentArticleId(),
            notes: addedV1Notes,
            mode: 'fill_missing_only'
          });
        } catch (e) {}
      }
      if (addedHeadingIds.length) {
        /* Open only the sections that received NEW research notes; others stay closed. */
        setOpenNotes((prev) => {
          const n = new Set(prev);
          addedHeadingIds.forEach((hid) => n.add(hid));
          return n;
        });
      }
      setResearchStage(null);
      setResearchState('done');
      /* Foundation: mark the article as having reached the research state.
         advanceStatus never regresses the lifecycle. Notes themselves are
         already persisted (ResearchAgent store) against stable section IDs. */
      try {
        if (window.ArticleStore) window.ArticleStore.advanceStatus(window.ArticleStore.getActiveArticleId(), 'research');
      } catch (e) {}
    }).
    catch(() => {
      if (!canUseAiNow()) return;
      setResearchStage(null);
      setResearchError('Research couldn’t be generated. Please try again. If this keeps happening, contact support.');
      setResearchState('failed');
    });
  };
  /* Any edit to the outline invalidates the result — re-run to refresh. */
  useEffect(() => {
    if (!outlineResearchResetReadyRef.current) {
      outlineResearchResetReadyRef.current = true;
      return;
    }
    setResearchState((s) => s === 'done' ? 'idle' : s);
    setResearchError('');
    // eslint-disable-next-line
  }, [outline]);

  /* ---- mutation helpers (immutable) ---- */
  const upd = (fn) => {
    if (!canMutateNow()) return;
    setOutline((prev) => canMutateNow() ? fn(prev) : prev);
  };

  const setSecText = (sid, text) => upd((o) => o.map((s) => s.id === sid ? { ...s, text } : s));
  const setSubText = (sid, cid, text) =>
  upd((o) => o.map((s) => s.id === sid ?
  { ...s, children: s.children.map((c) => c.id === cid ? { ...c, text } : c) } : s));

  const mapPts = (o, t, fn) => o.map((s) => {
    if (s.id !== t.sid) return s;
    if (!t.cid) return { ...s, points: fn(s.points) };
    return { ...s, children: s.children.map((c) => c.id === t.cid ? { ...c, points: fn(c.points) } : c) };
  });
  const setPoint = (t, pid, text) => upd((o) => mapPts(o, t, (pts) => pts.map((p) => p.id === pid ? { ...p, text } : p)));
  const addPoint = (t) => upd((o) => mapPts(o, t, (pts) => [...pts, { id: olid(), text: '' }]));
  const delPoint = (t, pid) => upd((o) => mapPts(o, t, (pts) => pts.filter((p) => p.id !== pid)));

  const addSection = () => upd((o) => [...o, { id: olid(), text: 'New section', points: [{ id: olid(), text: '' }], children: [] }]);
  /* Insert a new H2 section at an arbitrary position in the outline. */
  const insertSectionAt = (gi) => upd((o) => {
    const n = { id: olid(), text: 'New section', points: [{ id: olid(), text: '' }], children: [] };
    return [...o.slice(0, gi), n, ...o.slice(gi)];
  });
  const delSection = (sid) => upd((o) => o.filter((s) => s.id !== sid));
  const addSub = (sid) => upd((o) => o.map((s) => s.id === sid ?
  { ...s, children: [...s.children, { id: olid(), text: 'New subsection', points: [{ id: olid(), text: '' }], level: 3 }] } : s));
  const delSub = (sid, cid) => upd((o) => o.map((s) => s.id === sid ?
  { ...s, children: s.children.filter((c) => c.id !== cid) } : s));

  /* Change a subsection's heading level (H3–H6). */
  const jumpToOutlineHeading = (headingId) => {
    if (!headingId || typeof document === 'undefined') return;
    const target = Array.from(document.querySelectorAll('[data-outline-node-id]')).
      find((el) => el && el.getAttribute('data-outline-node-id') === String(headingId));
    if (!target || typeof target.scrollIntoView !== 'function') return;
    target.scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'nearest' });
  };

  const runSectionAIAction = async (sid, action, actionOptions) => {
    if (!canUseAiNow() || sectionActionRunningId) return;
    const requestOrigin = window.ClicklyxWebsiteContext && window.ClicklyxWebsiteContext.capture();
    const OA = window.OutlineAgent;
    if (isCloudWorkflow && !workflowKnowledgeState.context) {
      const message = workflowKnowledgeState.error && workflowKnowledgeState.error.message || 'This Article needs saved Knowledge before generation can continue.';
      setSectionActionToast({ kind: 'error', label: message });
      return;
    }
    if (!OA || typeof OA.runSectionOutlineAction !== 'function') {
      setSectionActionToast({ kind: 'error', label: 'This section couldn\u2019t be updated. Please try again.' });
      return;
    }
    const currentSection = (outline || []).find((s) => s && s.id === sid);
    if (!currentSection || currentSection.intro) {
      setSectionActionToast({ kind: 'error', label: 'This section couldn\u2019t be updated. Please try again.' });
      return;
    }
    const fullAgentOutline = outlineUiToAgentOutline(outline, form);
    const targetSection = outlineUiSectionToAgent(currentSection);
    setSectionActionRunningId(sid);
    setSectionActionRunningAction(action);
    setSectionActionToast(null);
    try {
      let sectionAdapter = outlineLLMAdapter;
      if (isCloudWorkflow) {
        const WF = window.RankLyxArticleWorkflow;
        if (!WF || typeof WF.createArticleGenerationAuthority !== 'function' || typeof WF.createArticleGenerationAdapter !== 'function') {
          throw new Error('Authenticated Article generation is unavailable.');
        }
        const authority = WF.createArticleGenerationAuthority(
          workflowIdentity && workflowIdentity.articleId,
          'outline',
          workflowKnowledgeState.context,
          window.RankLyxCloudArticles
        );
        authority.purpose = 'section_edit';
        sectionAdapter = WF.createArticleGenerationAdapter(outlineLLMAdapter, authority);
      }
      const result = await OA.runSectionOutlineAction({
        briefData: normalizeBriefForOutline(form, { knowledgeContext: workflowKnowledgeState.context }),
        outline: fullAgentOutline,
        targetSectionId: sid,
        targetSection,
        action,
        customInstruction: actionOptions && actionOptions.customInstruction
      }, {
        llmAdapter: sectionAdapter
      });
      if (requestOrigin && !window.ClicklyxWebsiteContext.isCurrent(requestOrigin)) return;
      if (!canUseAiNow()) return;
      if (!result || result.status !== 'passed' || !result.replacementSection) {
        if (result && ['article_generation_rate_limited', 'article_provider_rate_limited',
          'article_provider_quota_unavailable'].includes(result.errorCode)) {
          setSectionActionToast({ kind: 'error', label: result.errorMessage });
          return;
        }
        throw new Error(result && result.errorMessage || 'This section could not be updated.');
      }
      const replacement = outlineAgentSectionToUi(result.replacementSection, currentSection);
      setOutline((prev) => canUseAiNow() ? prev.map((s) => s.id === sid ? replacement : s) : prev);
      setSectionActionToast({
        kind: 'success',
        sectionId: sid,
        action,
        label: SECTION_AI_SUCCESS_LABELS[action] || 'Section updated.',
        undo: {
          sectionId: sid,
          previousSection: currentSection
        }
      });
      try {
        console.log('[OutlineSectionAction] uiApplied', {
          action,
          targetSectionId: sid,
          source: result.source,
          status: result.status
        });
      } catch (e) {}
    } catch (e) {
      if (!canUseAiNow()) return;
      setSectionActionToast({ kind: 'error', label: 'This section couldn\u2019t be updated. Please try again.' });
      try {
        console.warn('[OutlineSectionAction] uiFailed', {
          action,
          targetSectionId: sid,
          message: e && e.message ? e.message : String(e)
        });
      } catch (err) {}
    } finally {
      setSectionActionRunningId(null);
      setSectionActionRunningAction(null);
    }
  };

  const undoSectionAIAction = () => {
    if (!canMutateNow()) return;
    const undo = sectionActionToast && sectionActionToast.undo;
    if (!undo || !undo.previousSection) return;
    setOutline((prev) => canMutateNow() ? prev.map((s) => s.id === undo.sectionId ? undo.previousSection : s) : prev);
    setSectionActionToast(null);
  };

  const dismissSectionAIMessage = () => {
    setSectionActionToast(null);
  };

  const setChildLevel = (sid, cid, level) =>
  upd((o) => o.map((s) => s.id === sid ?
  { ...s, children: s.children.map((c) => c.id === cid ? { ...c, level } : c) } : s));

  /* Clamp a children list so levels never skip a step (each ≤ prev + 1,
     min 3). Protects the hierarchy after reorders. */
  const normalizeChildren = (children) => {
    let prev = 2;
    return children.map((c) => {
      let lvl = Math.min(c.level || 3, prev + 1);
      if (lvl < 3) lvl = 3;
      prev = lvl;
      return lvl === c.level ? c : { ...c, level: lvl };
    });
  };

  const moveIn = (arr, idx, dir) => {
    const j = idx + dir;
    if (j < 0 || j >= arr.length) return arr;
    const a = [...arr];
    const tmp = a[idx];a[idx] = a[j];a[j] = tmp;
    return a;
  };
  const moveSection = (idx, dir) => upd((o) => moveIn(o, idx, dir));
  const moveSub = (sid, idx, dir) => upd((o) => o.map((s) => s.id === sid ? { ...s, children: normalizeChildren(moveIn(s.children, idx, dir)) } : s));

  /* Converting a top-level H2 → H3: an H3 can't live at the top level, so we
     wrap it in a brand-new empty H2 that becomes its parent section. The
     original heading text + talking points move onto the converted H3 (its
     former subsections ride along as siblings). The new H2 title is focused. */
  const focusH2Ref = useRef(null);
  const convertH2toH3 = (sid) => {
    const newId = olid();
    focusH2Ref.current = newId;
    upd((o) => o.map((s) => {
      if (s.id !== sid) return s;
      const converted = { id: olid(), text: s.text, points: s.points, level: 3 };
      return {
        id: newId,
        text: '',
        points: [{ id: olid(), text: '' }],
        children: normalizeChildren([converted, ...s.children])
      };
    }));
  };

  useEffect(() => {
    const id = focusH2Ref.current;
    if (!id) return;
    const el = document.querySelector(`[data-h2-input="${id}"]`);
    if (el) el.focus();
    focusH2Ref.current = null;
  }, [outline]);

  /* ---- Drag-and-drop reordering for whole H2 sections ----
     The handle drags the entire section card (its H3–H6 subsections,
     talking points and nested content move with it). Arrows still work. */
  const [dragIndex, setDragIndex] = useState(null);
  const [dropSlot, setDropSlot] = useState(null);

  useEffect(() => {
    if (canMutateOutline) return;
    cloudResearchSaveRequestRef.current += 1;
    setDragIndex(null);
    setDropSlot(null);
    setShowWriteConfirm(false);
    setSectionActionRunningId(null);
    setSectionActionRunningAction(null);
    setSectionActionToast(null);
    setResearchStage(null);
    setResearchState((current) => current === 'understanding' ? 'idle' : current);
    setIntroTestState((current) => current === 'running' ? 'idle' : current);
  }, [canMutateOutline]);

  const moveSectionTo = (from, slot) => upd((o) => {
    const arr = [...o];
    const [item] = arr.splice(from, 1);
    let t = from < slot ? slot - 1 : slot;
    const minIdx = arr[0] && arr[0].intro ? 1 : 0; // never above the intro block
    if (t < minIdx) t = minIdx;
    if (t > arr.length) t = arr.length;
    arr.splice(t, 0, item);
    return arr;
  });

  const onSecDragStart = (e, si) => {
    if (!canMutateNow()) { e.preventDefault(); return; }
    setDragIndex(si);
    e.dataTransfer.effectAllowed = 'move';
    try {e.dataTransfer.setData('text/plain', String(si));} catch (err) {}
    const card = e.currentTarget.closest('.rl-sec');
    if (card) e.dataTransfer.setDragImage(card, 24, 20);
  };
  const onSecDragOver = (e, si) => {
    if (!canMutateNow() || dragIndex == null) return;
    e.preventDefault();
    e.dataTransfer.dropEffect = 'move';
    const rect = e.currentTarget.getBoundingClientRect();
    const before = e.clientY - rect.top < rect.height / 2;
    let slot = before ? si : si + 1;
    const minSlot = outline[0] && outline[0].intro ? 1 : 0;
    if (slot < minSlot) slot = minSlot;
    setDropSlot(slot);
  };
  const onSecDrop = (e) => {
    if (!canMutateNow() || dragIndex == null) return;
    e.preventDefault();
    e.stopPropagation();
    if (dropSlot != null) moveSectionTo(dragIndex, dropSlot);
    setDragIndex(null);
    setDropSlot(null);
  };
  const onSecDragEnd = () => {setDragIndex(null);setDropSlot(null);};

  olLucide([outline]);
  olLucide([researchState]);
  olLucide([openNotes, notes]);
  olLucide([strategy]);
  olLucide([sectionActionRunningId, sectionActionRunningAction, sectionActionToast]);
  olLucide([isCloudWorkflow, outlineSaveState, outlineSaveError, cloudResearchSaveState, cloudResearchSaveError]);

  /* shared talking-points renderer.
     `meta` (optional) = { id, sectionId, level, title } enables the per-heading
     research-note action + collapsible block. Omitted for the intro block. */
  const renderPoints = (target, points, meta) =>
  <React.Fragment>
      <ul className="rl-points">
        {points.map((p) =>
      <li className="rl-point" key={p.id}>
            <span className="rl-point__dot"></span>
            <AutoText
          className="rl-ptext"
          value={p.text}
          readOnly={!canMutateOutline}
          placeholder="Talking point \u2014 what the AI should cover here\u2026"
          onChange={(v) => setPoint(target, p.id, v)} />

            <button
          type="button"
          className="rl-point__del"
          disabled={!canMutateOutline}
          aria-label="Remove talking point"
          onClick={() => delPoint(target, p.id)}>

              <i data-lucide="x"></i>
            </button>
          </li>
      )}
      </ul>
      {meta && openNotes.has(meta.id) && (!isCloudWorkflow || (notes[meta.id] && !notes[meta.id].deletedAt)) &&
      <ResearchNoteBlock
        note={notes[meta.id] || null}
        readOnly={isCloudWorkflow || !canMutateOutline}
        onSave={(draft) => saveNote(meta, draft)}
        onRemove={() => removeNote(meta.id)}
        onClose={() => toggleNote(meta.id)} />}
      <div className="rl-pt-actions">
        <button type="button" className="rl-add rl-add--point" disabled={!canMutateOutline} onClick={() => addPoint(target)} style={{ gap: "2px" }}>
          <i data-lucide="plus"></i>
          <span style={{ fontSize: "11px" }}>Add talking point</span>
        </button>
        {meta && ((!isCloudWorkflow && canMutateOutline) || (notes[meta.id] && !notes[meta.id].deletedAt)) &&
        <button
          type="button"
          className={`rl-add rl-add--note ${openNotes.has(meta.id) ? 'rl-add--note-on' : ''}`}
          aria-expanded={openNotes.has(meta.id)}
          onClick={() => toggleNote(meta.id)} style={{ gap: "3px" }}>
          <i data-lucide="flask-conical"></i>
          <span style={{ fontSize: "11px" }}>Research note</span>
          {notes[meta.id] && <span className="rl-add__dot" aria-hidden="true"></span>}
        </button>}
      </div>
    </React.Fragment>;

  const introDiagnostics = introTestResult && introTestResult.diagnostics ? introTestResult.diagnostics : null;
  const introStrictDiagnostics = introTestResult && introTestResult.strictLiveDiagnostics ? introTestResult.strictLiveDiagnostics : null;
  const introFixedIssues = introDiagnostics && introDiagnostics.validationIssuesFixed || [];
  const introRemainingIssues = introDiagnostics && introDiagnostics.validationIssuesStillFailing || [];
  const introPostMechanicalReview = introTestResult && introTestResult.postMechanicalRevisionEditorDiagnostics || introDiagnostics && introDiagnostics.postMechanicalRevisionEditorReview || null;
  const introUsedLiveAdapter = !!(introStrictDiagnostics && (introStrictDiagnostics.liveGenerationAttempted || introStrictDiagnostics.liveRepairAttempted)) ||
    !!(introTestResult && (introTestResult.sectionSources || []).some(function (s) { return /^llm/.test(String(s && s.source || '')); }));
  const introValidationStatus = introDiagnostics && introDiagnostics.validationStatus || (introTestResult && introTestResult.success ? 'pass' : 'not run');
  const introPreviewText = olSafeIntroPreviewText(introTestResult && (introTestResult.intro || introTestResult.html || ''));
  const currentIntroRuntimeDiagnostics = getIntroTestRuntimeDiagnostics();
  const introAdapterDiagnostics = introTestRuntimeDiagnostics || currentIntroRuntimeDiagnostics;
  const introDiagnosticReport = introTestResult ? {
    appLLMAdapterExists: !!(introAdapterDiagnostics && introAdapterDiagnostics.appLLMAdapterExists),
    sameAdapterAsFullArticleAvailable: !!(introAdapterDiagnostics && introAdapterDiagnostics.sameAdapterAsFullArticleAvailable),
    adapterSource: (introTestResult && introTestResult.adapterSource) || (introAdapterDiagnostics && introAdapterDiagnostics.adapterSource) || null,
    adapterDetected: introStrictDiagnostics ? !!introStrictDiagnostics.adapterDetected : !!(introAdapterDiagnostics && introAdapterDiagnostics.sameAdapterAsFullArticleAvailable),
    liveGenerationAttempted: introStrictDiagnostics ? !!introStrictDiagnostics.liveGenerationAttempted : false,
    liveGenerationSucceeded: introStrictDiagnostics ? !!introStrictDiagnostics.liveGenerationSucceeded : false,
    liveRepairAttempted: introStrictDiagnostics ? !!introStrictDiagnostics.liveRepairAttempted : false,
    liveRepairSucceeded: introStrictDiagnostics ? !!introStrictDiagnostics.liveRepairSucceeded : false,
    writerMechanicalRevisionAttempted: introStrictDiagnostics ? !!(introStrictDiagnostics.writerMechanicalRevisionAttempted || introStrictDiagnostics.liveRepairAttempted) : false,
    writerMechanicalRevisionSucceeded: introStrictDiagnostics ? !!(introStrictDiagnostics.writerMechanicalRevisionSucceeded || introStrictDiagnostics.liveRepairSucceeded) : false,
    writerMechanicalRevisionLabel: introStrictDiagnostics && introStrictDiagnostics.writerMechanicalRevisionLabel || 'Writer mechanical revision',
    writerMechanicalRevisionAdapterMode: introStrictDiagnostics && introStrictDiagnostics.writerMechanicalRevisionMode || 'repair',
    introChangedDuringWriterMechanicalRevision: !!(introDiagnostics && introDiagnostics.writerMechanicalRevision && introDiagnostics.writerMechanicalRevision.introChangedDuringWriterMechanicalRevision),
    mechanicallyValidRevisedIntro: introDiagnostics && introDiagnostics.writerMechanicalRevision && introDiagnostics.writerMechanicalRevision.mechanicallyValidRevisedIntro || '',
    postMechanicalRevisionEditorReviewAttempted: introStrictDiagnostics ? !!introStrictDiagnostics.postMechanicalRevisionEditorReviewAttempted : !!(introPostMechanicalReview && introPostMechanicalReview.reviewAttempted),
    postMechanicalRevisionEditorReviewResult: introStrictDiagnostics && introStrictDiagnostics.postMechanicalRevisionEditorReviewResult || introPostMechanicalReview && introPostMechanicalReview.editorReview && introPostMechanicalReview.editorReview.status || null,
    writerEditorialCleanupAfterMechanicalRevisionAttempted: introStrictDiagnostics ? !!introStrictDiagnostics.writerEditorialCleanupAfterMechanicalRevisionAttempted : !!(introPostMechanicalReview && introPostMechanicalReview.writerCleanupAttempted),
    writerEditorialCleanupAfterMechanicalRevisionSucceeded: introStrictDiagnostics ? !!introStrictDiagnostics.writerEditorialCleanupAfterMechanicalRevisionSucceeded : !!(introPostMechanicalReview && introPostMechanicalReview.cleanupUsed),
    cleanupFallbackToMechanicallyValidIntro: !!(introPostMechanicalReview && introPostMechanicalReview.fallbackToMechanicallyValidIntro),
    cleanupFallbackReason: introPostMechanicalReview && introPostMechanicalReview.fallbackReason || '',
    localFallbackUsed: introStrictDiagnostics ? !!introStrictDiagnostics.localFallbackUsed : false,
    localRepairUsed: introStrictDiagnostics ? !!introStrictDiagnostics.localRepairUsed : false,
    initialLiveWordCount: introStrictDiagnostics ? introStrictDiagnostics.initialLiveWordCount : null,
    wordCount: introDiagnostics && introDiagnostics.wordCount != null ? introDiagnostics.wordCount : null,
    finalWordCount: introStrictDiagnostics ? introStrictDiagnostics.finalWordCount : (introDiagnostics && introDiagnostics.wordCount != null ? introDiagnostics.wordCount : null),
    keywordCount: introDiagnostics && introDiagnostics.primaryKeywordCount != null ? introDiagnostics.primaryKeywordCount : null,
    validationStatus: introValidationStatus,
    repairAttempts: introTestResult.repairAttempts || 0,
    initialLiveValidationIssues: introStrictDiagnostics && introStrictDiagnostics.initialLiveValidationIssues || [],
    fixedIssues: introFixedIssues,
    remainingIssues: introRemainingIssues,
    finalValidationIssues: introStrictDiagnostics && introStrictDiagnostics.finalValidationIssues || introRemainingIssues,
    passed: !!introTestResult.success,
    liveAdapterUsed: introUsedLiveAdapter,
    source: introTestResult.source || null,
    finalSource: introStrictDiagnostics && introStrictDiagnostics.finalSource || introTestResult.source || null,
    sectionSources: introTestResult.sectionSources || []
  } : null;
  const introDiagnosticJson = introDiagnosticReport ? JSON.stringify(introDiagnosticReport, null, 2) : '';
  const showIntroTestButton = typeof window !== 'undefined' && (
    window.location.hostname === 'localhost' ||
    window.location.hostname === '127.0.0.1' ||
    window.location.hostname === '::1'
  );

  return (
    <React.Fragment>
    {sectionActionToast && sectionActionToast.kind === 'error' &&
    <div className={'rl-toast rl-sec-ai-toast' + (sectionActionToast.kind === 'error' ? ' rl-toast--error' : '')} role={sectionActionToast.kind === 'error' ? 'alert' : 'status'}>
      <i data-lucide={sectionActionToast.kind === 'error' ? 'alert-circle' : 'check'}></i>
      <span>{sectionActionToast.label}</span>
    </div>}
    <div className="rl-outline-layout" data-screen-label="Outline">
      <div className="rl-ol-main"
        onDragOver={(e) => {if (dragIndex != null) e.preventDefault();}}
        onDrop={onSecDrop}>
        {/* Dev/test note — surfaces the Outline Agent workflow status for
            developers without alarming normal users. Hidden when the LLM flow
            passed cleanly. (In Lovable this can move to a dedicated dev panel.) */}
        {isCloudWorkflow && outlineSaveState === 'saving' &&
        <div className="rl-ol-devnote" role="status" style={{ display: 'flex', alignItems: 'center', gap: '8px', margin: '0 0 14px', padding: '8px 12px', borderRadius: '8px', fontSize: '12px', lineHeight: '16px', color: 'var(--rl-fg-3)', background: 'var(--rl-surface-2, rgba(10,13,15,0.04))', border: '1px solid var(--rl-border)' }}>
          <span className="rl-osum__spinner rl-osum__spinner--dark"></span>
          <span>Saving outline...</span>
        </div>}
        {isCloudWorkflow && outlineSaveState === 'error' &&
        <div className="rl-ol-devnote" role="alert" style={{ display: 'flex', alignItems: 'center', gap: '10px', margin: '0 0 14px', padding: '8px 12px', borderRadius: '8px', fontSize: '12px', lineHeight: '16px', color: 'var(--rl-danger)', background: 'rgba(220,38,38,0.08)', border: '1px solid rgba(220,38,38,0.22)', flexWrap: 'wrap' }}>
          <i data-lucide="alert-triangle" style={{ width: 14, height: 14, flex: '0 0 auto' }}></i>
          <span>{outlineSaveError || 'The outline could not be saved. Retry before continuing.'}</span>
          <button type="button" className="rl-sec-ai-status__btn" disabled={!canMutateOutline && !canCompleteOutline} onClick={() => {if ((canMutateNow() || canCompleteOutline) && onRetryOutlineSave) onRetryOutlineSave();}}>Retry save</button>
        </div>}
        {isCloudWorkflow && outlineSaveState === 'saved' &&
        <div className="rl-ol-devnote" role="status" style={{ display: 'flex', alignItems: 'center', gap: '8px', margin: '0 0 14px', padding: '8px 12px', borderRadius: '8px', fontSize: '12px', lineHeight: '16px', color: 'var(--rl-success)', background: 'rgba(22,163,74,0.08)', border: '1px solid rgba(22,163,74,0.22)' }}>
          <i data-lucide="check-circle-2" style={{ width: 14, height: 14, flex: '0 0 auto' }}></i>
          <span>Outline saved to Workspace.</span>
        </div>}
        {meta && (meta.source === 'local-fallback' || meta.status === 'repaired' || meta.status === 'failed-validation') &&
        <div
          className="rl-ol-devnote"
          role="note"
          style={{
            display: 'flex', alignItems: 'center', gap: '8px',
            margin: '0 0 14px', padding: '8px 12px', borderRadius: '8px',
            fontSize: '12px', lineHeight: '16px',
            color: meta.status === 'failed-validation' ? 'var(--rl-fg-2)' : 'var(--rl-fg-3)',
            background: meta.status === 'failed-validation' ? 'rgba(180,120,20,0.08)' : 'var(--rl-surface-2, rgba(120,85,255,0.06))',
            border: '1px solid ' + (meta.status === 'failed-validation' ? 'rgba(180,120,20,0.28)' : 'var(--rl-border, rgba(120,85,255,0.18))')
          }}>
          <i data-lucide={meta.status === 'failed-validation' ? 'alert-triangle' : 'info'} style={{ width: 14, height: 14, flex: '0 0 auto' }}></i>
          <span>
            {meta.source === 'local-fallback' ?
            'Dev: using local fallback because no LLM adapter is connected yet.' :
            meta.status === 'repaired' ?
            'Dev: outline repaired after validation.' :
            'Dev: the outline was created, but some validation issues remain. You can still edit it.'}
          </span>
        </div>}


        {/* Sections — each followed by a hover "Add heading" inserter */}
        {outline.map((s, si) => {
            const dragging = dragIndex === si;
            const noOp = dropSlot === dragIndex || dropSlot === dragIndex + 1;
            const dropAbove = dragIndex != null && dropSlot === si && !noOp;
            const dropBelow = dragIndex != null && si === outline.length - 1 && dropSlot === outline.length && !noOp;
            const isSectionActionRunning = sectionActionRunningId === s.id;
            const sectionActionLoadingLabel = isSectionActionRunning ? SECTION_AI_LOADING_LABELS[sectionActionRunningAction] || 'Updating section...' : '';
            const sectionActionSuccess = sectionActionToast && sectionActionToast.kind === 'success' && sectionActionToast.sectionId === s.id ? sectionActionToast : null;
            return (
              <React.Fragment key={s.id}>
        <div
                  className={`rl-sec ${s.intro ? 'rl-sec--intro' : ''} ${dragging ? 'rl-sec--dragging' : ''} ${dropAbove ? 'rl-sec--drop-above' : ''} ${dropBelow ? 'rl-sec--drop-below' : ''}`}
                  style={{ borderWidth: "2px 2px 2px 1px" }}
                  onDragOver={(e) => onSecDragOver(e, si)}
                  onDrop={onSecDrop}>
            <div className="rl-hrow" data-outline-node-id={s.id}>
              {!s.intro &&
                    <button
                      type="button"
                      className="rl-drag"
                      aria-label="Drag to reorder section"
                      title="Drag to reorder"
                      draggable={canMutateOutline}
                      disabled={!canMutateOutline}
                      onDragStart={(e) => onSecDragStart(e, si)}
                      onDragEnd={onSecDragEnd}>
                <i data-lucide="grip-vertical"></i>
              </button>}
              {s.intro ?
                    <span className="rl-tag rl-tag--intro">Intro</span> :
                    <LevelBadge level={2} isTop={true} disabled={!canMutateOutline} onChange={(L) => {if (L === 3) convertH2toH3(s.id);}} />}
              <input
                      className={`rl-hinput ${s.intro ? 'rl-hinput--intro' : 'rl-hinput--h2'}`}
                      data-h2-input={s.id}
                      value={s.text}
                      readOnly={!canMutateOutline}
                      aria-readonly={!canMutateOutline}
                      placeholder={s.intro ? 'Opening block' : 'Section heading'}
                      onChange={(e) => setSecText(s.id, e.target.value)} />

              {!s.intro && SHOW_OUTLINE_ROLE_TAGS &&
                    <RoleTag heading={s.text} intent={strategy && strategy.searchIntent} isChild={false} />}
              {!s.intro && isSectionActionRunning &&
              <div className="rl-sec-ai-status rl-sec-ai-status--loading" role="status">
                <span className="rl-osum__spinner rl-osum__spinner--dark"></span>
                <span>{sectionActionLoadingLabel}</span>
              </div>}
              {!s.intro && sectionActionSuccess &&
              <div className="rl-sec-ai-status rl-sec-ai-status--success" role="status">
                <i data-lucide="check"></i>
                <span>{sectionActionSuccess.label}</span>
                <button type="button" className="rl-sec-ai-status__btn" disabled={!canMutateOutline} onClick={undoSectionAIAction}>Undo</button>
                <button type="button" className="rl-sec-ai-status__btn" onClick={dismissSectionAIMessage}>OK</button>
              </div>}
              {!s.intro &&
                    <div className="rl-tools">
                <SectionAIMenu
                  sectionId={s.id}
                  running={sectionActionRunningId === s.id}
                  disabled={!canUseOutlineAi}
                  onAction={runSectionAIAction} />
                <button type="button" className="rl-tool" disabled={!canMutateOutline || si === 0 || outline[si - 1]?.intro} aria-label="Move section up" onClick={() => moveSection(si, -1)}>
                  <i data-lucide="chevron-up"></i>
                </button>
                <button type="button" className="rl-tool" disabled={!canMutateOutline || si === outline.length - 1} aria-label="Move section down" onClick={() => moveSection(si, 1)}>
                  <i data-lucide="chevron-down"></i>
                </button>
                <button type="button" className="rl-tool rl-tool--danger" disabled={!canMutateOutline} aria-label="Delete section" onClick={() => delSection(s.id)}>
                  <i data-lucide="trash-2"></i>
                </button>
              </div>}
            </div>

            {s.intro &&
                  <div className="rl-intro-hint">
              <i data-lucide="eye-off"></i>
              <span>Not shown as a heading in the article — these notes guide the opening paragraphs.</span>
            </div>}

            {renderPoints({ sid: s.id }, s.points, s.intro ?
              { id: s.id || 'intro', sectionId: s.id || 'intro', level: 'intro', title: 'Introduction' } :
              { id: s.id, sectionId: s.id, level: 2, title: s.text })}

            {!s.intro && s.children.map((c, ci) =>
                  <div className={`rl-sub rl-sub--l${c.level}`} key={c.id}>
                <div className="rl-hrow" data-outline-node-id={c.id}>
                  <LevelBadge
                        level={c.level}
                        disabled={!canMutateOutline}
                        prevLevel={ci === 0 ? 2 : s.children[ci - 1].level}
                        nextLevel={ci < s.children.length - 1 ? s.children[ci + 1].level : null}
                        onChange={(L) => setChildLevel(s.id, c.id, L)} />
                  <input
                        className={`rl-hinput rl-hinput--h${c.level}`}
                        value={c.text}
                        readOnly={!canMutateOutline}
                        aria-readonly={!canMutateOutline}
                        placeholder="Subsection heading"
                        onChange={(e) => setSubText(s.id, c.id, e.target.value)} />

                  {SHOW_OUTLINE_ROLE_TAGS &&
                  <RoleTag heading={c.text} intent={strategy && strategy.searchIntent} isChild={true} />}
                  <div className="rl-tools">
                    <button type="button" className="rl-tool" disabled={!canMutateOutline || ci === 0} aria-label="Move subsection up" onClick={() => moveSub(s.id, ci, -1)}>
                      <i data-lucide="chevron-up"></i>
                    </button>
                    <button type="button" className="rl-tool" disabled={!canMutateOutline || ci === s.children.length - 1} aria-label="Move subsection down" onClick={() => moveSub(s.id, ci, 1)}>
                      <i data-lucide="chevron-down"></i>
                    </button>
                    <button type="button" className="rl-tool rl-tool--danger" disabled={!canMutateOutline} aria-label="Delete subsection" onClick={() => delSub(s.id, c.id)}>
                      <i data-lucide="trash-2"></i>
                    </button>
                  </div>
                </div>
                {renderPoints({ sid: s.id, cid: c.id }, c.points, { id: c.id, sectionId: s.id, level: c.level, title: c.text })}
              </div>
                  )}

            {!s.intro &&
                  <button type="button" className="rl-add rl-add--h3" disabled={!canMutateOutline} onClick={() => addSub(s.id)} style={{ gap: "2px" }}>
              <i data-lucide="plus"></i>
              <span style={{ fontSize: "11px" }}>Add H3 subsection</span>
            </button>}
          </div>
          <Inserter
                  showH3={!s.intro}
                  disabled={!canMutateOutline}
                  onAddH2={() => insertSectionAt(si + 1)}
                  onAddH3={() => addSub(s.id)} />
        </React.Fragment>);

          })}

        <button type="button" className="rl-add-sec" disabled={!canMutateOutline} onClick={addSection}>
          <i data-lucide="plus"></i>
          <span>Add section (H2)</span>
        </button>
      </div>

      <OutlineSummary outline={outline} onJump={jumpToOutlineHeading} />

      {/* Research + Write action row — inside the outline grid, right-aligned
        to match the Outline summary column. One horizontal group on desktop;
        wraps to stacked only when the viewport is too narrow. */}
      <div className="rl-research-cta">
      <div className="rl-research-cta__col">
        <div className="rl-outline-actions">
          <button
              type="button"
              className="rl-btn rl-btn--secondary"
              style={{ borderRadius: "10px", padding: "12px 22px", borderColor: "var(--rl-border)", color: "var(--rl-fg)", minHeight: "44px" }}
              onClick={onBackClick}
              disabled={canMutateOutline && (researchState === 'understanding' || introTestState === 'running' || cloudOutlineBusy || cloudResearchBusy)}>
            <span>Back</span>
          </button>
        <div className="rl-cta-row" style={{ display: "flex", gap: "12px", justifyContent: "flex-end", flexWrap: "wrap", alignItems: "center" }}>
          {/* Research article — secondary: white bg, dark border, dark text */}
          <span className="rl-research-beta-wrap">
          <button
              type="button"
              className="rl-btn rl-btn--secondary"
              aria-describedby="rl-research-beta-tooltip"
              style={{ borderRadius: "10px", padding: "12px 22px", borderColor: "var(--rl-primary)", color: "var(--rl-fg)", minHeight: "44px" }}
              onClick={onResearch}
              disabled={!canUseOutlineAi || researchState === 'understanding' || cloudOutlineBusy || cloudOutlineUnsaved || cloudResearchBusy || cloudResearchUnsaved}>
            {researchState === 'understanding' ?
              <React.Fragment><span className="rl-osum__spinner rl-osum__spinner--dark"></span><span>Researching…</span></React.Fragment> :
              <React.Fragment><span>Research article</span><span className="rl-research-beta-badge">Beta</span></React.Fragment>}
          </button>
          <span id="rl-research-beta-tooltip" className="rl-research-beta-tooltip" role="tooltip">
            Research is in beta. It can add source-backed notes to your outline, but results may be incomplete. Please review notes before using them.
          </span>
          </span>
          {/* Write article — primary: black bg, white text */}
          {showIntroTestButton &&
          <button
              type="button"
              className="rl-btn rl-btn--secondary"
              style={{ borderRadius: "10px", padding: "12px 18px", borderColor: "var(--rl-border)", color: "var(--rl-fg)", minHeight: "44px" }}
              onClick={onTestIntroOnly}
              disabled={!canUseOutlineAi || isCloudWorkflow || introTestState === 'running' || headingCount < 1 || cloudOutlineBusy || cloudOutlineUnsaved}>
            {introTestState === 'running' ?
              <React.Fragment><span className="rl-osum__spinner rl-osum__spinner--dark"></span><span>Testing intro...</span></React.Fragment> :
              <span>Test Intro Only</span>}
          </button>}
          <button
              type="button"
              className="rl-btn rl-btn--primary"
              style={{ borderRadius: "10px", padding: "12px 22px", minHeight: "44px" }}
              onClick={onWriteClick}
              disabled={!canUseOutlineAi || headingCount < 1 || cloudOutlineBusy || cloudOutlineUnsaved || cloudResearchBusy || cloudResearchUnsaved}>
            <span>Write article</span>
          </button>
        </div>
        </div>
        {isCloudWorkflow && (cloudOutlineUnsaved || cloudResearchUnsaved) &&
        <p className="rl-research-status rl-research-status--muted" role={(cloudOutlineUnsaved || cloudResearchUnsaved) ? 'alert' : 'status'} style={{ justifyContent: 'flex-end', color: (cloudOutlineUnsaved || cloudResearchUnsaved) ? 'var(--rl-danger)' : 'var(--rl-fg-3)' }}>
          <i data-lucide={(cloudOutlineUnsaved || cloudResearchUnsaved) ? 'alert-triangle' : 'info'}></i>
          <span>{cloudBoundaryMessage}</span>
        </p>}
        {isCloudWorkflow && cloudResearchBusy && researchState !== 'understanding' &&
        <p className="rl-research-status rl-research-status--muted" role="status" style={{ justifyContent: 'flex-end' }}>
          <span className="rl-osum__spinner rl-osum__spinner--dark"></span>
          <span>Saving research...</span>
        </p>}
        {isCloudWorkflow && cloudResearchUnsaved &&
        <p className="rl-research-status" role="alert" style={{ justifyContent: 'flex-end', color: 'var(--rl-danger)' }}>
          <i data-lucide="alert-triangle"></i>
          <span>{cloudResearchSaveError || 'Research was generated but is not saved.'}</span>
          <button type="button" className="rl-btn rl-btn--secondary" disabled={!canMutateOutline && !(workflowIdentity && cloudUnsavedResearchRef.current && getCloudResearchController() && getCloudResearchController().hasPendingCompletion(workflowIdentity.articleId, cloudUnsavedResearchRef.current.research))} onClick={retryCloudResearchSave} style={{ borderRadius: 10, padding: '8px 12px' }}>
            <i data-lucide="refresh-cw"></i>
            <span>Retry research save</span>
          </button>
        </p>}
        {researchState === 'understanding' && researchStage &&
        <div className="rl-research-progress" role="status" aria-live="polite" style={{ justifyContent: "flex-end", marginTop: "12px" }}>
          <span className="rl-osum__spinner rl-osum__spinner--dark"></span>
          <div className="rl-research-progress__txt" style={{ textAlign: "left" }}>
            <span className="rl-research-progress__step">{researchStage.label}</span>
            {researchStage.detail && <span className="rl-research-progress__detail">{researchStage.detail}</span>}
          </div>
        </div>}
        {researchState === 'done' && researchCount > 0 &&
        <React.Fragment>
          <p className="rl-research-status" role="status" style={{ justifyContent: "flex-end" }}>
            <i data-lucide="check-circle-2"></i>
            <span>Research notes added to the outline.</span>
          </p>
          <p className="rl-osum__research-help" style={{ textAlign: "right" }}>
            {researchCount} research note{researchCount === 1 ? '' : 's'} found.
          </p>
        </React.Fragment>}
        {researchState === 'done' && !(researchCount > 0) &&
        <p className="rl-research-status rl-research-status--muted" role="status" style={{ justifyContent: "flex-end" }}>
          <i data-lucide="info"></i>
          <span>No strong research notes found for this outline yet.</span>
        </p>}
        {researchState === 'failed' && researchError &&
        <p className="rl-research-status rl-research-status--muted" role="alert" style={{ justifyContent: "flex-end", color: "var(--rl-danger)" }}>
          <i data-lucide="alert-triangle"></i>
          <span>{researchError}</span>
        </p>}
        {showIntroTestButton && introTestState !== 'idle' &&
        <IntroTestPanelBoundary key="intro-test-panel">
          <div className="rl-intro-test" style={{ marginTop: "14px", marginLeft: "auto", maxWidth: "720px", textAlign: "left", background: "var(--rl-surface)", border: "1px solid var(--rl-border)", borderRadius: "8px", padding: "16px" }}>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: "12px", marginBottom: "10px" }}>
              <strong style={{ fontSize: "13px", color: "var(--rl-fg)" }}>Intro-only preview</strong>
              <span style={{ fontSize: "12px", fontWeight: 700, color: introTestState === 'done' ? "var(--rl-success)" : introTestState === 'failed' ? "var(--rl-danger)" : "var(--rl-fg-3)" }}>
                {introTestState === 'running' ? 'RUNNING' : introTestResult && introTestResult.success ? 'PASS' : 'FAIL'}
              </span>
            </div>
            {introTestWarning &&
            <p style={{ margin: "0 0 10px", fontSize: "13px", lineHeight: "20px", color: "var(--rl-warning, #9a5b00)" }}>
              {introTestWarning}
            </p>}
            {introTestState === 'running' &&
            <p style={{ margin: "0 0 10px", fontSize: "13px", lineHeight: "20px", color: "var(--rl-fg-2)" }}>
              Generating introduction only...
            </p>}
            {introTestError &&
            <p style={{ margin: "0 0 10px", fontSize: "13px", lineHeight: "20px", color: "var(--rl-danger)" }}>
              {String(introTestError)}
            </p>}
            {introTestResult && introUsedLiveAdapter &&
            <React.Fragment>
              <pre style={{ margin: "0 0 14px", whiteSpace: "pre-wrap", fontFamily: "inherit", fontSize: "14px", lineHeight: "22px", color: "var(--rl-fg-2)" }}>
                {introPreviewText || 'No introduction text returned.'}
              </pre>
            </React.Fragment>}
            {introTestResult &&
            <React.Fragment>
              <pre style={{ margin: 0, whiteSpace: "pre-wrap", overflowX: "auto", fontSize: "12px", lineHeight: "18px", color: "var(--rl-fg-2)", background: "var(--rl-surface-2, rgba(10,13,15,0.04))", borderRadius: "6px", padding: "10px" }}>
                {introDiagnosticJson}
              </pre>
            </React.Fragment>}
          </div>
        </IntroTestPanelBoundary>}
      </div>
    </div>
    </div>

    {/* Confirmation modal — only when writing without research notes. */}
    {showWriteConfirm &&
    <div className="rl-modal-overlay" role="dialog" aria-modal="true" aria-labelledby="rl-wc-title"
         onMouseDown={(e) => { if (e.target === e.currentTarget) cancelWrite(); }}
         style={{ position: "fixed", inset: 0, background: "rgba(10,13,15,0.42)", display: "flex", alignItems: "center", justifyContent: "center", zIndex: 1000, padding: "20px" }}>
      <div className="rl-modal" style={{ background: "var(--rl-surface)", borderRadius: "16px", maxWidth: "420px", width: "100%", padding: "26px 26px 22px", boxShadow: "0 24px 60px rgba(10,13,15,0.22)" }}>
        <h3 id="rl-wc-title" style={{ margin: "0 0 10px", fontSize: "18px", fontWeight: 700, letterSpacing: "-0.02em", color: "var(--rl-fg)" }}>Write without research?</h3>
        <p style={{ margin: "0 0 22px", fontSize: "14px", lineHeight: "21px", color: "var(--rl-fg-2)" }}>
          No research notes have been added yet. The draft will be written from the brief, outline, and knowledge context only.
        </p>
        <div style={{ display: "flex", gap: "10px", justifyContent: "flex-end", flexWrap: "wrap" }}>
          <button type="button" className="rl-btn rl-btn--secondary" style={{ borderRadius: "10px", padding: "10px 18px", borderColor: "var(--rl-primary)", color: "var(--rl-fg)" }} onClick={cancelWrite}>
            <span>Cancel</span>
          </button>
          <button type="button" className="rl-btn rl-btn--primary" disabled={!canUseOutlineAi} style={{ borderRadius: "10px", padding: "10px 18px" }} onClick={confirmWriteAnyway}>
            <span>Write anyway</span>
          </button>
        </div>
      </div>
    </div>}
    </React.Fragment>);

}

window.OutlineScreen = OutlineScreen;
window.buildOutline = buildOutline;
window.normalizeBriefForOutline = normalizeBriefForOutline;
window.__rlSafeIntroPreviewText = olSafeIntroPreviewText;
/* Prompt-4: async Create-Outline flow + provider-neutral adapter + result→UI mapper */
window.runCreateOutline = runCreateOutline;
window.outlineLLMAdapter = outlineLLMAdapter;
window.researchLLMCall = researchLLMCall;
window.tavilySearchProvider = tavilySearchProvider;
window.adaptOutlineResultForUI = adaptOutlineResultForUI;
