/* Rank Lyx — AI Research Agent / Step 2: "Find research support for the outline"
   ------------------------------------------------------------------------------
   Runs AFTER the Article Research Context exists. Decides which outline sections
   genuinely need EVIDENCE / PROOF support and attaches structured research notes
   to them. It is NOT an outline agent and NOT a writing agent:

     • It never rewrites the outline or its talking points.
     • It never adds writing instructions (define / explain / summarize / compare /
       add a table / add an example). The outline already covers WHAT to write.
     • It only adds extra evidence, proof, or brand-specific support.

   ── What it is allowed to add ─────────────────────────────────────────────────
   External web research (must be < 2 years old, with source URL + name + year):
     Statistics · Data points · Studies · Industry benchmarks · Survey findings ·
     Research reports.
   Brand Knowledge (max 3 notes per article):
     Product feature · Case study · Pricing point · Use case · Customer segment ·
     Pain point · Internal opinion · Comparison point · Brand-owned benchmark.
   Comparison post type only: competitor pricing / competitor features (external);
   the user's OWN product always comes from Brand Knowledge, never competitor
   testimonials / case studies / customer stories / experiments.

   ── Not allowed ──────────────────────────────────────────────────────────────
   Public experiences, experiments, Reddit/forum/community opinions, public
   reviews, expert quotes, definitions, generic explanations, writing advice,
   section summaries, table suggestions, generic examples, and any OTHER company's
   case studies / testimonials / customer stories. Unsupported numbers, or stats
   from pages that don't clearly name/link their source, are never used.

   ── Web search note ──────────────────────────────────────────────────────────
   User-facing v1 research uses a live searchProvider after the Research Planner
   LLM returns validated planned queries. Tavily is the current local-dev backend
   retrieval provider. It returns source candidates; it does not write notes and
   it does not bypass validation. The older local candidate library remains only
   for explicit mock/dev flows.
*/

(function () {
  const AUTH = (window.ResearchAgent && window.ResearchAgent.AUTH) ||
    { userId: 'user_jamie_doyle', workspaceId: 'ws_ranklyx_demo' };
  const CURRENT_YEAR = 2026;
  const RECENCY_MAX_AGE = 2; // years

  /* ----------------------------------------------------------------------------
     VERIFIED EXTERNAL LIBRARY — real sources, all published 2024–2026.
     Each entry carries the fields every external note must include: noteType,
     the stat text, sourceName, sourceUrl, pubYear. `tags` drive section matching.
     (In production this array is replaced by live, verified web-search results.)
  ---------------------------------------------------------------------------- */
  const EXTERNAL_LIBRARY = [
    {
      id: 'ext_activation',
      noteType: 'Data point',
      stat: 'The average activation rate for SaaS and AI products was 37.5% in 2025 (median 37%) — meaning roughly two-thirds of new users never reach the product\u2019s core value.',
      sourceName: 'Shno — SaaS Onboarding Statistics',
      sourceUrl: 'https://www.shno.co/marketing-statistics/saas-onboarding-statistics',
      pubYear: '2025',
      tags: ['activation', 'onboarding', 'value', 'adoption', 'signup', 'sign up', 'first', 'users', 'engage']
    },
    {
      id: 'ext_ttv_arr',
      noteType: 'Study',
      stat: 'A 2024 Amplitude study found that cutting time-to-value by 20% lifted ARR growth by 18% for mid-market SaaS companies.',
      sourceName: 'Amplitude (2024 study)',
      sourceUrl: 'https://www.shno.co/marketing-statistics/saas-onboarding-statistics',
      pubYear: '2024',
      tags: ['time to value', 'ttv', 'results', 'measur', 'roi', 'revenue', 'arr', 'growth', 'metric', 'track']
    },
    {
      id: 'ext_openview_benchmark',
      noteType: 'Benchmark',
      stat: 'Top-quartile SaaS companies have 2.3\u00d7 higher activation rates than the median, per OpenView\u2019s 2024 SaaS Benchmarks.',
      sourceName: 'OpenView 2024 SaaS Benchmarks',
      sourceUrl: 'https://www.shno.co/marketing-statistics/saas-onboarding-statistics',
      pubYear: '2024',
      tags: ['benchmark', 'activation', 'best practice', 'results', 'measur', 'metric', 'standard']
    },
    {
      id: 'ext_custify_onboarding',
      noteType: 'Survey finding',
      stat: '90% of customers believe companies could improve their onboarding, and 97% of companies consider a good onboarding process necessary for product growth (Custify, 2025).',
      sourceName: 'Custify',
      sourceUrl: 'https://www.custify.com/blog/saas-customer-onboarding-and-retention-statistics/',
      pubYear: '2025',
      tags: ['onboarding', 'mistake', 'common', 'improve', 'customer', 'experience', 'fundamental', 'retention']
    },
    {
      id: 'ext_userorbit_personalized',
      noteType: 'Survey finding',
      stat: '82% of SaaS users expect onboarding tailored to their role, goals and use case, and 67% say interactive guided tours help them grasp a product\u2019s value faster (Userorbit 2025 Onboarding Report, 500 users).',
      sourceName: 'Userorbit 2025 Onboarding Report',
      sourceUrl: 'https://userorbit.com/blog/2025-onboarding-report-what-makes-500-saas-users-stay',
      pubYear: '2025',
      tags: ['personaliz', 'onboarding', 'step', 'guided', 'tour', 'practice', 'setup', 'set up', 'getting started', 'workflow']
    },
    {
      id: 'ext_churn_window',
      noteType: 'Statistic',
      stat: '43% of SMB SaaS customer losses occur within the first 90 days after purchase, making the early onboarding window the highest-leverage retention investment (Focus Digital, 2025).',
      sourceName: 'Focus Digital',
      sourceUrl: 'https://www.shno.co/marketing-statistics/saas-onboarding-statistics',
      pubYear: '2025',
      tags: ['churn', 'retention', 'mistake', 'results', 'first', 'window', 'onboarding', 'lose']
    },
    {
      id: 'ext_cm_documented_roi',
      noteType: 'Statistic',
      stat: 'Companies with a documented content strategy report 33% higher ROI than those without one (SQ Magazine, 2025).',
      sourceName: 'SQ Magazine',
      sourceUrl: 'https://sqmagazine.co.uk/content-marketing-statistics/',
      pubYear: '2025',
      tags: ['content', 'strategy', 'roi', 'documented', 'results', 'marketing', 'plan', 'process']
    },
    {
      id: 'ext_cm_ai_outlines',
      noteType: 'Survey finding',
      stat: '67% of small businesses now use AI tools for content and SEO, and 39% use AI specifically to create outlines (Semrush, cited 2026).',
      sourceName: 'Semrush (via Adam Connell)',
      sourceUrl: 'https://adamconnell.me/content-marketing-statistics/',
      pubYear: '2026',
      tags: ['ai', 'content', 'seo', 'outline', 'writing', 'tool', 'automate', 'workflow']
    },
    {
      id: 'ext_cm_rank_intent',
      noteType: 'Survey finding',
      stat: 'The top two frustrations for content marketers in 2025 are getting content to rank (77.6%) and meeting user/search intent (70.6%) (Siege Media + Wynter, 2025).',
      sourceName: 'Siege Media + Wynter',
      sourceUrl: 'https://www.siegemedia.com/strategy/content-marketing-statistics',
      pubYear: '2025',
      tags: ['rank', 'search intent', 'intent', 'seo', 'content', 'keyword', 'serp', 'traffic']
    },
    {
      id: 'ext_cm_roi_dollar',
      noteType: 'Data point',
      stat: 'Content marketing returned an average of $7.65 for every $1 spent in 2025 (SQ Magazine, via Taboola).',
      sourceName: 'Taboola / SQ Magazine',
      sourceUrl: 'https://www.taboola.com/marketing-hub/content-marketing-statistics/',
      pubYear: '2025',
      tags: ['roi', 'content', 'spend', 'budget', 'results', 'marketing', 'value', 'cost']
    }
  ];

  /* ----------------------------------------------------------------------------
     RAW SEARCH NOISE — the kind of low-quality results a web search also surfaces.
     These are intentionally NOT usable and MUST be rejected by validation:
     forum/Reddit posts, expert quotes, public reviews, an out-of-date study, and
     an unsupported number with no named source. Including them lets the validate
     stage do real source-quality work (and visibly reject them) rather than just
     animate. In production these are simply whatever the web search returns.
  ---------------------------------------------------------------------------- */
  const DISALLOWED_CANDIDATES = [
    { id: 'noise_reddit', noteType: 'Data point', stat: 'A Reddit thread claims most SaaS users churn in the first week.', sourceName: 'r/SaaS thread', sourceUrl: 'https://www.reddit.com/r/SaaS/', pubYear: '2025', sourceKind: 'forum', tags: ['onboarding', 'churn', 'users', 'content', 'seo', 'marketing', 'retention', 'step', 'results', 'activation'] },
    { id: 'noise_quote', noteType: 'Statistic', stat: '"Onboarding is everything," says a popular LinkedIn influencer.', sourceName: 'LinkedIn post', sourceUrl: 'https://www.linkedin.com/', pubYear: '2025', sourceKind: 'quote', tags: ['onboarding', 'content', 'marketing', 'seo', 'strategy', 'results', 'customer', 'fundamental'] },
    { id: 'noise_review', noteType: 'Data point', stat: 'A G2 review says the tool boosted activation by 200%.', sourceName: 'G2 review', sourceUrl: 'https://www.g2.com/', pubYear: '2025', sourceKind: 'review', tags: ['activation', 'tool', 'product', 'feature', 'onboarding', 'results', 'workflow'] },
    { id: 'noise_old', noteType: 'Study', stat: 'A 2019 study reported a 60% onboarding completion rate.', sourceName: 'Legacy Onboarding Report', sourceUrl: 'https://example.com/2019-report', pubYear: '2019', sourceKind: 'study', tags: ['onboarding', 'completion', 'step', 'results', 'setup', 'set up', 'content', 'getting started'] },
    { id: 'noise_unsupported', noteType: 'Statistic', stat: '87% of marketers say research-backed content performs better.', sourceName: null, sourceUrl: null, unsupported: true, pubYear: '2025', sourceKind: 'statistic', tags: ['content', 'research', 'marketing', 'seo', 'strategy', 'rank', 'results', 'roi'] }
  ];

  /* Source kinds that are never allowed, regardless of recency/attribution. */
  const DISALLOWED_KINDS = new Set(['forum', 'reddit', 'review', 'community', 'quote', 'experiment', 'testimonial', 'competitor_case_study', 'customer_story']);

  /* Real per-source validation gate (spec step 4). Returns { ok, reason }. */
  function validateExternalSource(c) {
    if (!c.sourceUrl) return { ok: false, reason: 'no usable source URL' };
    if (!c.sourceName) return { ok: false, reason: 'missing source name' };
    if (c.unsupported) return { ok: false, reason: 'repeats an unsupported claim with no original source' };
    if (DISALLOWED_KINDS.has(c.sourceKind)) return { ok: false, reason: `disallowed source type (${c.sourceKind})` };
    if (!recencyOk(c.pubYear)) return { ok: false, reason: 'older than 2 years' };
    return { ok: true };
  }

  /* ----------------------------------------------------------------------------
     Helpers
  ---------------------------------------------------------------------------- */
  const clean = (s) => (s || '').trim();

  function recencyOk(pubYear) {
    const y = parseInt(String(pubYear).slice(0, 4), 10);
    if (isNaN(y)) return false;
    return (CURRENT_YEAR - y) <= RECENCY_MAX_AGE;
  }
  /* An external entry is only usable if it is recent AND clearly attributed. */
  function externalUsable(e) {
    return !!(e.stat && e.sourceUrl && e.sourceName && e.pubYear && recencyOk(e.pubYear));
  }

  function tokenize(text) {
    const stop = new Set(['the', 'and', 'for', 'with', 'your', 'that', 'this', 'from', 'into',
      'what', 'how', 'are', 'you', 'our', 'their', 'will', 'use', 'using', 'a', 'an', 'of', 'to',
      'in', 'on', 'is', 'it', 'as', 'at', 'or', 'be', 'by']);
    return (text || '').toLowerCase().replace(/[^a-z0-9\s]/g, ' ').split(/\s+/)
      .filter((w) => w.length > 3 && !stop.has(w));
  }

  function score(text, tags) {
    const t = (text || '').toLowerCase();
    let s = 0;
    tags.forEach((k) => { if (t.includes(k)) s++; });
    return s;
  }

  /* All text the section is "about" — heading + points + child headings/points. */
  function sectionText(sec) {
    let parts = [sec.text];
    (sec.points || []).forEach((p) => parts.push(p.text));
    (sec.children || []).forEach((c) => {
      parts.push(c.text);
      (c.points || []).forEach((p) => parts.push(p.text));
    });
    return parts.filter(Boolean).join(' ');
  }

  /* Pick the best-matching H3+ child for placement, else place on the H2. */
  function placeOn(sec, tags) {
    let best = null;
    (sec.children || []).forEach((c) => {
      const sc = score(sectionText(c), tags);
      if (sc > 0 && (!best || sc > best.score)) best = { child: c, score: sc };
    });
    if (best) return { headingId: best.child.id, headingTitle: best.child.text || 'Untitled', headingLevel: best.child.level || 3 };
    return { headingId: sec.id, headingTitle: sec.text || 'Untitled', headingLevel: 2 };
  }

  /* ----------------------------------------------------------------------------
     Brand Knowledge candidates — built ONLY from the user's own workspace data.
     Mapped to the allowed brand note types (no testimonials, no customer stories
     — those aren't allowed brand note types).
  ---------------------------------------------------------------------------- */
  function brandCandidates(brand, isComparison) {
    const out = [];
    (brand.features || []).forEach((f) =>
      out.push({ noteType: 'Brand feature', note: `Reference the relevant product capability — "${f}" — as proof where it genuinely helps the reader.`, tags: tokenize(f).concat(['feature', 'product', 'tool', 'capability', 'workflow']) }));
    (brand.useCases || []).forEach((u) =>
      out.push({ noteType: 'Brand use case', note: `Ground the point in a real use case from our customers: ${u}.`, tags: tokenize(u).concat(['use case', 'audience', 'team', 'workflow', 'getting started']) }));
    (brand.pricing || []).forEach((p) =>
      out.push({ noteType: 'Brand pricing', note: `Cite our own pricing for specificity: ${p.plan} — ${p.price} (${p.detail}).`, tags: tokenize(p.plan + ' ' + p.detail).concat(['pricing', 'price', 'cost', 'plan', 'budget', 'compare', 'comparison']) }));
    (brand.caseStudies || []).forEach((c) =>
      out.push({ noteType: 'Brand case study', note: `Use our own case-study proof: ${c.title} (${c.metric}).`, tags: tokenize(c.title).concat(['results', 'measur', 'roi', 'case', 'proof', 'growth']) }));
    (brand.targetCustomers || []).slice(0, 1).forEach((t) =>
      out.push({ noteType: 'Brand customer segment', note: `Anchor to our core customer segment: ${(brand.targetCustomers || []).join(', ')}.`, tags: ['audience', 'customer', 'segment', 'reader', 'who'].concat(tokenize(t)) }));
    if (brand.positioningNotes)
      out.push({ noteType: isComparison ? 'Brand comparison point' : 'Brand internal opinion', note: `Bring in our positioning as ${isComparison ? 'a comparison point' : 'an informed point of view'}: ${brand.positioningNotes}`, tags: ['compar', 'comparison', 'versus', 'vs', 'alternativ', 'positioning', 'conclusion', 'recommend', 'choose', 'next steps'] });
    return out;
  }

  /* ----------------------------------------------------------------------------
     CORE — build research notes for the outline.
  ---------------------------------------------------------------------------- */
  function buildResearchNotes({ context, form, outline }) {
    form = form || {};
    const brand = (window.ResearchAgent && window.ResearchAgent.loadBrandKnowledge)
      ? window.ResearchAgent.loadBrandKnowledge() : {};
    const isComparison = clean(form.postType).toLowerCase().includes('comparison');

    const usableExternal = EXTERNAL_LIBRARY.filter(externalUsable);
    const brandCands = brandCandidates(brand, isComparison);

    const sections = (outline || []).filter((s) => !s.intro);
    const N = sections.length;
    if (N === 0) return [];

    /* Target ~1/3 of sections — never every section, never forced. */
    const targetCount = N >= 3 ? Math.round(N / 3) : (N >= 1 ? 1 : 0);

    /* Build the best external + best brand match for every section. */
    const cands = sections.map((sec) => {
      const text = sectionText(sec);
      let bestExt = null;
      usableExternal.forEach((e) => {
        const sc = score(text, e.tags);
        if (sc > 0 && (!bestExt || sc > bestExt.score)) bestExt = { entry: e, score: sc };
      });
      let bestBrand = null;
      brandCands.forEach((b) => {
        const sc = score(text, b.tags);
        if (sc > 0 && (!bestBrand || sc > bestBrand.score)) bestBrand = { cand: b, score: sc };
      });
      const topScore = Math.max(bestExt ? bestExt.score : 0, bestBrand ? bestBrand.score : 0);
      return { sec, text, bestExt, bestBrand, topScore };
    })
      /* Only sections where a note would genuinely fit (score > 0). */
      .filter((c) => c.topScore > 0)
      .sort((a, b) => b.topScore - a.topScore);

    const chosen = cands.slice(0, targetCount);

    /* Pick the best-matching H3 child for placement, else place on the H2. */
    function placeOn(sec, tags) {
      let best = null;
      (sec.children || []).forEach((c) => {
        const sc = score(sectionText(c), tags);
        if (sc > 0 && (!best || sc > best.score)) best = { child: c, score: sc };
      });
      if (best) return { headingId: best.child.id, headingTitle: best.child.text || 'Untitled', headingLevel: best.child.level || 3 };
      return { headingId: sec.id, headingTitle: sec.text || 'Untitled', headingLevel: 2 };
    }

    const notes = [];
    let brandCount = 0;
    let noteUid = 0;

    chosen.forEach(({ sec, bestExt, bestBrand }) => {
      const extScore = bestExt ? bestExt.score : 0;
      const brandScore = bestBrand ? bestBrand.score : 0;

      /* Prefer the stronger match; respect the max-3 brand-note cap. */
      let useBrand = false;
      if (bestBrand && (brandScore >= extScore) && brandCount < 3) useBrand = true;
      else if (!bestExt && bestBrand && brandCount < 3) useBrand = true;

      if (!useBrand && !bestExt && bestBrand && brandCount < 3) useBrand = true;
      if (!useBrand && !bestExt && !bestBrand) return;

      const base = {
        id: 'note_' + (++noteUid),
        sectionId: sec.id
      };

      if (useBrand) {
        const b = bestBrand.cand;
        const place = placeOn(sec, b.tags);
        notes.push({
          ...base,
          noteType: b.noteType,
          note: b.note,
          headingId: place.headingId,
          headingTitle: place.headingTitle,
          headingLevel: place.headingLevel,
          sourceType: 'Brand Knowledge',
          sourceUrl: null,
          sourceName: 'Workspace Brand Knowledge',
          pubYear: null,
          reason: `"${place.headingTitle}" is a good fit for brand-specific proof; this adds specificity from your own knowledge without rewriting the outline.`
        });
        brandCount++;
      } else if (bestExt) {
        const e = bestExt.entry;
        const place = placeOn(sec, e.tags);
        notes.push({
          ...base,
          noteType: e.noteType,
          note: e.stat,
          headingId: place.headingId,
          headingTitle: place.headingTitle,
          headingLevel: place.headingLevel,
          sourceType: 'External web source',
          sourceUrl: e.sourceUrl,
          sourceName: e.sourceName,
          pubYear: e.pubYear,
          reason: `A recent ${e.noteType.toLowerCase()} makes "${place.headingTitle}" more credible and specific without changing what the section covers.`
        });
      }
    });

    return notes;
  }

  /* ----------------------------------------------------------------------------
     PERSISTENCE — save / load, scoped per user + article, connected to sections.
     Swap the bodies for Supabase upsert/select in the real app.
  ---------------------------------------------------------------------------- */
  function notesKey(userId, articleId) {
    return `rl.researchNotes.${userId}.${articleId}`;
  }

  function saveResearchNotes(notes, ctx) {
    const userId = (ctx && ctx.userId) || AUTH.userId;
    const articleId = (ctx && ctx.articleId) ||
      (window.ResearchAgent && window.ResearchAgent.currentArticleId());
    const record = {
      schemaVersion: 1,
      userId, articleId, workspaceId: AUTH.workspaceId,
      generatedAt: new Date().toISOString(),
      count: notes.length,
      notes
    };
    try { localStorage.setItem(notesKey(userId, articleId), JSON.stringify(record)); } catch (e) {}
    try {
      console.info('[Research Agent] Saved', notes.length, 'research notes for', userId, '/', articleId);
      console.debug('[Research Agent] research notes:', record);
    } catch (e) {}
    return record;
  }

  function loadResearchNotes(userId, articleId) {
    try {
      const raw = localStorage.getItem(notesKey(
        userId || AUTH.userId,
        articleId || (window.ResearchAgent && window.ResearchAgent.currentArticleId())
      ));
      return raw ? JSON.parse(raw) : null;
    } catch (e) { return null; }
  }

  /* ============================================================================
     MOCK RESEARCH ADAPTER — local testing stand-in for the future Research LLM.
     ----------------------------------------------------------------------------
     This is the ONLY place that "produces" research without a real LLM, and it
     runs strictly for the prototype (useMockResearch). It returns an LLM-STYLE
     response — { notes, coverageStatus, reason } — whose notes follow the v1 data
     contract. Every mock object carries `__mock: true` so it is never mistaken
     for real research. It does NOT bypass validation: the pipeline validates the
     mock output exactly as it would a real LLM's.

     NOTE: the foundation still makes no per-section research decisions. The mock,
     like the real Research LLM later, is the layer ALLOWED to choose notes; it
     reads the neutral eligibleSections from the payload and decides for itself.
  ============================================================================ */
  const MOCK_SOURCE_BANK = [
    { match: ['activation', 'onboarding', 'signup', 'sign up', 'users', 'value', 'adopt', 'first'], noteType: 'statistic',
      note: 'SaaS activation rates averaged just 37.5% in 2025.',
      whyItMatters: 'Open the section by quantifying how many new users never reach core value.',
      sourcePublisher: 'Shno', sourceUrl: 'https://www.shno.co/marketing-statistics/saas-onboarding-statistics', sourceTitle: 'SaaS Onboarding Statistics 2025',
      isTimeSensitive: true, sourceDate: '2025', sourceRelationship: 'trusted_external' },
    { match: ['time to value', 'ttv', 'results', 'roi', 'revenue', 'arr', 'growth', 'measur', 'metric'], noteType: 'industry_report',
      note: 'Cutting time-to-value by 20% lifted ARR growth by 18% for mid-market SaaS.',
      whyItMatters: 'Use this where the section links faster activation to revenue outcomes.',
      sourcePublisher: 'Amplitude', sourceUrl: 'https://amplitude.com/', sourceTitle: '2024 Product Benchmarks',
      isTimeSensitive: true, sourceDate: '2024', sourceRelationship: 'trusted_external' },
    { match: ['churn', 'retention', 'window', 'lose', 'mistake', 'drop'], noteType: 'statistic',
      note: '43% of SMB SaaS losses happen within the first 90 days.',
      whyItMatters: 'Anchor the retention argument to the high-leverage early-onboarding window.',
      sourcePublisher: 'Focus Digital', sourceUrl: 'https://www.shno.co/marketing-statistics/saas-onboarding-statistics', sourceTitle: 'SaaS Retention Statistics',
      isTimeSensitive: true, sourceDate: '2025', sourceRelationship: 'trusted_external' },
    { match: ['personaliz', 'tailor', 'role', 'guided', 'tour', 'step', 'setup', 'set up', 'practice'], noteType: 'statistic',
      note: '82% of SaaS users expect onboarding tailored to their role.',
      whyItMatters: 'Back the personalization recommendation with concrete user-expectation data.',
      sourcePublisher: 'Userorbit', sourceUrl: 'https://userorbit.com/blog/2025-onboarding-report-what-makes-500-saas-users-stay', sourceTitle: '2025 Onboarding Report',
      isTimeSensitive: true, sourceDate: '2025', sourceRelationship: 'trusted_external' },
    { match: ['content', 'strategy', 'plan', 'documented', 'process'], noteType: 'statistic',
      note: 'Teams with a documented content strategy report 33% higher ROI.',
      whyItMatters: 'Justify the planning step with a measurable payoff figure.',
      sourcePublisher: 'SQ Magazine', sourceUrl: 'https://sqmagazine.co.uk/content-marketing-statistics/', sourceTitle: 'Content Marketing Statistics 2025',
      isTimeSensitive: true, sourceDate: '2025', sourceRelationship: 'trusted_external' },
    { match: ['ai', 'automate', 'tool', 'outline', 'writing', 'generate'], noteType: 'trend',
      note: '39% of small businesses now use AI to create content outlines.',
      whyItMatters: 'Use as a trend signal that AI-assisted outlining is becoming standard.',
      sourcePublisher: 'Semrush', sourceUrl: 'https://adamconnell.me/content-marketing-statistics/', sourceTitle: 'Content Marketing Statistics',
      isTimeSensitive: true, sourceDate: '2026', sourceRelationship: 'trusted_external' },
    { match: ['rank', 'search intent', 'intent', 'seo', 'keyword', 'traffic', 'serp'], noteType: 'statistic',
      note: '77.6% of marketers say getting content to rank is their top frustration.',
      whyItMatters: 'Frame the core SEO problem the article sets out to solve.',
      sourcePublisher: 'Siege Media', sourceUrl: 'https://www.siegemedia.com/strategy/content-marketing-statistics', sourceTitle: 'Content Marketing Statistics',
      isTimeSensitive: true, sourceDate: '2025', sourceRelationship: 'trusted_external' },
    /* brand facts — approved internal, so no external source/date is required */
    { match: ['pricing', 'price', 'cost', 'plan', 'budget', 'compare', 'tier'], noteType: 'product_fact',
      note: 'Rank Lyx Pro is $79/mo with unlimited articles and brand knowledge.',
      whyItMatters: 'Cite our own pricing for specificity wherever plans or cost come up.',
      sourcePublisher: null, sourceUrl: null, sourceTitle: null,
      isTimeSensitive: false, sourceDate: null, sourceRelationship: 'approved_internal' },
    { match: ['feature', 'capability', 'workflow', 'product', 'brief', 'how'], noteType: 'product_fact',
      note: 'Rank Lyx matches search intent on every brief it generates.',
      whyItMatters: 'Reference this capability where briefs or search intent are discussed.',
      sourcePublisher: null, sourceUrl: null, sourceTitle: null,
      isTimeSensitive: false, sourceDate: null, sourceRelationship: 'approved_internal' }
  ];

  function mockSectionText(sec) {
    return [sec.headingTitle].concat(sec.talkingPoints || []).filter(Boolean).join(' ').toLowerCase();
  }
  function mockBankScore(text, item) {
    let s = 0;
    item.match.forEach((k) => { if (text.indexOf(k) !== -1) s++; });
    return s;
  }
  function mockNoteFromItem(ctx, sec, item) {
    return {
      articleId: ctx.articleId,
      sectionId: sec.sectionId,
      headingId: sec.headingId,
      headingTitle: sec.headingTitle,
      headingLevel: sec.headingLevel,
      noteType: item.noteType,
      note: item.note,
      whyItMatters: item.whyItMatters,
      sourcePublisher: item.sourcePublisher,
      sourceUrl: item.sourceUrl,
      sourceTitle: item.sourceTitle,
      isTimeSensitive: item.isTimeSensitive,
      sourceDate: item.sourceDate,
      exampleKind: null,
      sourceRelationship: item.sourceRelationship,
      competitorRisk: 'none',
      origin: 'ai',
      editedByUser: false,
      __mock: true
    };
  }

  /* The mock adapter: reads eligibleSections from the payload, picks one note per
     section (no source reused), respects the coverage maximum, and reports an
     honest coverageStatus. Never invents sources or fills below the minimum with
     weak notes — it flags below_target with a real reason instead. */
  function mockResearchAdapter(ctx, payload) {
    const eligible = (payload && payload.outline && payload.outline.eligibleSections) ||
      (ctx && ctx.outlineContext && ctx.outlineContext.eligibleSections) || [];
    const n = eligible.length;
    const budget = window.ResearchAgent && window.ResearchAgent.coverageBudget
      ? window.ResearchAgent.coverageBudget(n)
      : { minNotes: n ? Math.max(1, Math.floor(n / 3)) : 0, maxNotes: n ? Math.max(1, Math.ceil(n / 3)) : 0 };
    const minNotes = budget.minNotes;
    const maxNotes = budget.maxNotes;

    /* rank sections by how strong their best available match is */
    const ranked = eligible.map((sec) => {
      const text = mockSectionText(sec);
      let bestS = 0;
      MOCK_SOURCE_BANK.forEach((it) => { const s = mockBankScore(text, it); if (s > bestS) bestS = s; });
      return { sec, text, bestS };
    }).filter((o) => o.bestS > 0).sort((a, b) => b.bestS - a.bestS);

    const usedBank = new Set();
    const notes = [];
    for (let i = 0; i < ranked.length; i++) {
      if (notes.length >= maxNotes) break;
      const o = ranked[i];
      let best = null;
      MOCK_SOURCE_BANK.forEach((it, idx) => {
        if (usedBank.has(idx)) return;
        const s = mockBankScore(o.text, it);
        if (s > 0 && (!best || s > best.s)) best = { idx: idx, it: it, s: s };
      });
      if (best) { usedBank.add(best.idx); notes.push(mockNoteFromItem(ctx, o.sec, best.it)); }
    }

    let coverageStatus, reason = null;
    if (notes.length < minNotes) {
      coverageStatus = 'below_target';
      reason = 'Remaining eligible sections lacked a strong, recent, well-sourced match; adding more would require weak or unsourced research.';
    } else {
      coverageStatus = 'within_target';
    }
    return { notes: notes, coverageStatus: coverageStatus, reason: reason, __mock: true };
  }

  /* ---- explicit mock helpers for tests/dev (never auto-run) ---- */
  function createMockValidResearchResponse(ctx) {
    const payload = window.ResearchAgent.buildResearchLLMPayload(ctx);
    return mockResearchAdapter(ctx, payload);
  }
  function createMockBelowTargetResearchResponse(ctx) {
    const eligible = (ctx.outlineContext && ctx.outlineContext.eligibleSections) || [];
    const sec = eligible[0];
    const notes = sec ? [mockNoteFromItem(ctx, sec, MOCK_SOURCE_BANK[0])] : [];
    return {
      notes: notes,
      coverageStatus: 'below_target',
      reason: 'Additional eligible sections would require weak, outdated, or unsourced research, so only the strongest note was kept.',
      __mock: true
    };
  }
  function createMockInvalidResearchResponse(ctx) {
    const eligible = (ctx.outlineContext && ctx.outlineContext.eligibleSections) || [];
    const a = eligible[0];
    const notes = [];
    if (a) {
      /* two notes for the same heading (duplicate), an invalid note type, a generic
         whyItMatters, a high competitor risk, an overlong note, and a Reddit
         statistic — a deliberate spread of violations for the validator to catch. */
      notes.push({
        articleId: ctx.articleId, sectionId: a.sectionId, headingId: a.headingId,
        headingTitle: a.headingTitle, headingLevel: a.headingLevel,
        noteType: 'Quote', note: 'A short note.', whyItMatters: 'This makes the article better.',
        sourcePublisher: null, sourceUrl: null, sourceTitle: null,
        isTimeSensitive: false, sourceDate: null, exampleKind: null,
        sourceRelationship: 'unknown', competitorRisk: 'high', origin: 'ai', editedByUser: false, __mock: true
      });
      notes.push({
        articleId: ctx.articleId, sectionId: a.sectionId, headingId: a.headingId,
        headingTitle: a.headingTitle, headingLevel: a.headingLevel,
        noteType: 'statistic',
        note: 'This is an extremely long research note that runs well past the sixty word ceiling by repeating itself again and again and again and again and again and again and again and again and again and again to be sure it trips the length rule.',
        whyItMatters: 'This helps improve credibility.',
        sourcePublisher: 'r/SaaS', sourceUrl: 'https://www.reddit.com/r/SaaS/', sourceTitle: 'Thread',
        isTimeSensitive: true, sourceDate: null, exampleKind: null,
        sourceRelationship: 'community_reddit', competitorRisk: 'none', origin: 'ai', editedByUser: false, __mock: true
      });
    }
    return { notes: notes, coverageStatus: 'within_target', reason: null, __mock: true };
  }

  /* ============================================================================
     VALIDATED RESEARCH WORKFLOW — the single path from the "Research article"
     button to validated, saved notes.

       context → payload → research adapter → validate → repair-once → save →
       return newly-added notes for the Outline UI + a clean summary.

     Saving, fill_missing_only, protected-note skipping, and the one repair attempt
     all live in research-validation.jsx; this function orchestrates them. It never
     saves raw output before validation and never fabricates research silently.
  ============================================================================ */
  function dwell(ms) { return new Promise((r) => setTimeout(r, ms || 420)); }

  function cloneJson(value, fallback) {
    try { return JSON.parse(JSON.stringify(value)); } catch (e) { return fallback; }
  }

  function activeResearchNotes(notes) {
    return (Array.isArray(notes) ? notes : []).filter((n) => n && !n.deletedAt).map((n) => cloneJson(n, n));
  }

  function mergeResearchNotesInMemory(existingNotes, incomingNotes) {
    const merged = activeResearchNotes(existingNotes);
    const activeByHeading = {};
    merged.forEach((n, i) => { if (n && n.headingId) activeByHeading[n.headingId] = i; });
    let savedCount = 0;
    let skippedCount = 0;
    (incomingNotes || []).forEach((incoming) => {
      const note = cloneJson(incoming, incoming);
      const headingId = note && note.headingId;
      if (!headingId) return;
      if (activeByHeading[headingId] === undefined) {
        merged.push(note);
        activeByHeading[headingId] = merged.length - 1;
        savedCount++;
      } else {
        skippedCount++;
      }
    });
    return { notes: merged, savedCount: savedCount, skippedCount: skippedCount };
  }

  async function repairResearchResponseInMemory({ ctx, originalResponse, validationResult, repairLLM, existingNotes, agent }) {
    let response = originalResponse || { notes: [] };
    let finalValidation = validationResult || (agent && agent.validateResearchResponse ? agent.validateResearchResponse(response, ctx) : { valid: false, validNotes: [], invalidNotes: [], errors: [], warnings: [], coverage: {} });
    if (!finalValidation.valid && typeof repairLLM === 'function') {
      try {
        const repairPayload = agent && agent.buildRepairPayload ? agent.buildRepairPayload(ctx, response, finalValidation) : { originalResponse: response, validationErrors: finalValidation.errors || [] };
        const repaired = await repairLLM(repairPayload);
        response = repaired || { notes: [] };
        finalValidation = agent.validateResearchResponse(response, ctx);
      } catch (e) {
        /* keep valid notes from the original validation, matching the legacy fallback */
      }
    }
    const merged = mergeResearchNotesInMemory(existingNotes, finalValidation.validNotes || []);
    const rejectedCount = ((finalValidation.invalidNotes || []).length) + (merged.skippedCount || 0);
    let status;
    if (merged.savedCount > 0 && (finalValidation.errors || []).length === 0 && rejectedCount === 0) status = 'saved';
    else if (merged.savedCount > 0) status = 'partial';
    else status = 'failed';
    return {
      status: status,
      savedCount: merged.savedCount,
      rejectedCount: rejectedCount,
      errors: finalValidation.errors || [],
      warnings: finalValidation.warnings || [],
      coverageStatus: response && response.coverageStatus || finalValidation.coverage && finalValidation.coverage.status || null,
      reason: response && response.reason || null,
      notes: merged.notes,
      validationResult: finalValidation
    };
  }

  async function runResearchWorkflow(opts) {
    opts = opts || {};
    const form = opts.form || {};
    const outline = opts.outline || [];
    const onProgress = opts.onProgress;
    let researchLLM = opts.researchLLM;
    const callLLM = opts.callLLM;
    let planningLLM = opts.planningLLM;
    const repairLLM = opts.repairLLM;
    const searchProvider = opts.searchProvider;
    const fetchProvider = opts.fetchProvider;
    const useExternalResearch = !!opts.useExternalResearch;
    /* Legacy/dev default: explicit test callers may omit a live Research LLM and
       use mock research. User-facing callers pass useMockResearch:false plus a
       provider-neutral callLLM, from which we build the real adapter below. */
    let useMockResearch = opts.useMockResearch;
    if (useMockResearch === undefined) useMockResearch = !researchLLM && !callLLM;
    const useMemoryResearchStorage = opts.persistResearchLocally === false || opts.disableLocalResearchStorage === true;
    const existingResearchNotes = activeResearchNotes(opts.existingResearchNotes);
    const canContinue = typeof opts.canContinue === 'function' ? opts.canContinue : function () { return true; };

    const agent = window.ResearchAgent;

    /* If a provider-neutral callLLM was supplied but no researchLLM, build the
       real Research LLM adapter from it. The adapter only builds prompts, calls
       callLLM, and parses — validation + saving stay in this workflow. */
    if (!researchLLM && typeof callLLM === 'function' && agent && agent.createResearchLLMAdapter) {
      researchLLM = agent.createResearchLLMAdapter({ callLLM: callLLM, ctx: opts.context || null });
    }
    if (!planningLLM && typeof callLLM === 'function' && agent && agent.createResearchPlanningAdapter) {
      planningLLM = agent.createResearchPlanningAdapter({ callLLM: callLLM, ctx: opts.context || null });
    }
    const say = async (key, label) => { if (onProgress) onProgress({ key: key, label: label, detail: null }); await dwell(); };

    /* 1 — Build (or reuse) the neutral Article Research Context. */
    await say('context', 'Understanding article context');
    let ctx = opts.context || null;
    if (!ctx && agent && agent.buildArticleResearchContext) {
      ctx = agent.buildArticleResearchContext({ form: form, outline: outline, articleId: opts.articleId, protectedNotes: existingResearchNotes, knowledgeContext: opts.knowledgeContext || null });
      if (!useMemoryResearchStorage && canContinue() && agent.saveArticleResearchContext) agent.saveArticleResearchContext(ctx);
    }
    const auth = (agent && agent.AUTH) || AUTH;
    const articleId = (ctx && ctx.articleId) || (agent && agent.currentArticleId && agent.currentArticleId());
    const userId = (ctx && ctx.userId) || auth.userId;
    const workspaceId = (ctx && ctx.workspaceId) || auth.workspaceId;
    /* external-retrieval warnings collected before save, folded into the summary */
    const externalWarnings = [];

    const skipped = (status, reason) => ({
      notes: [], count: 0, context: ctx, payload: null, validationResult: null, storageResult: null,
      summary: { status: status, savedCount: 0, rejectedCount: 0, errors: [], warnings: externalWarnings.slice(), coverageStatus: null, reason: reason || null }
    });

    if (!canContinue()) return skipped('cancelled', 'Research stopped because this Workspace is read-only.');

    if (!ctx || !agent || !agent.buildResearchLLMPayload || !agent.validateResearchResponse) {
      return skipped('skipped', 'Research engine is not available.');
    }

    /* 2 — Build the neutral LLM payload (no per-section recommendations).
       It already carries INTERNAL source candidates. */
    await say('payload', 'Preparing research payload');
    const payload = agent.buildResearchLLMPayload(ctx);

    /* 2b — External source retrieval (optional, provider-neutral). Finds external
       sources, converts them to candidates, merges with internal candidates, and
       overwrites payload.sourceCandidates. The LLM may ONLY cite these. In the
       user-facing flow, planning/search failures return a clear failed result
       instead of silently falling back to mock/demo or internal-only research.
       Skipped under mock research unless explicitly requested. */
    if (useExternalResearch && (!useMockResearch || opts.allowExternalDuringMock) && agent.createExternalResearchSourceAdapter) {
      if (typeof planningLLM !== 'function') {
        return skipped('failed', 'Research planning is not connected.');
      }
      await say('plan', 'Planning research');
      if (!canContinue()) return skipped('cancelled', 'Research stopped because this Workspace is read-only.');
      let planResult = null;
      try {
        planResult = await planningLLM(payload);
        if (!canContinue()) return skipped('cancelled', 'Research stopped because this Workspace is read-only.');
      } catch (e) {
        return skipped('failed', 'Research planning failed.');
      }
      const planValidation = planResult && planResult.validation;
      if (!planValidation || !planValidation.valid || !planValidation.plannedQueries || !planValidation.plannedQueries.length) {
        return skipped('failed', 'Research planning did not produce valid search queries.');
      }
      payload.researchPlan = {
        plannedQueries: planValidation.plannedQueries,
        rejectedQueries: planValidation.rejectedQueries || [],
        budgets: planValidation.budgets || null
      };
      await say('sources', 'Finding source candidates');
      if (!canContinue()) return skipped('cancelled', 'Research stopped because this Workspace is read-only.');
      try {
        const srcAdapter = agent.createExternalResearchSourceAdapter({
          searchProvider: searchProvider, fetchProvider: fetchProvider
        });
        const srcResult = await srcAdapter({
          ctx: ctx, payload: payload,
          meta: { articleId: articleId, workspaceId: workspaceId }
        });
        if (!canContinue()) return skipped('cancelled', 'Research stopped because this Workspace is read-only.');
        if (srcResult && Array.isArray(srcResult.sourceCandidates)) {
          payload.sourceCandidates = srcResult.sourceCandidates;
        }
        (srcResult && srcResult.warnings || []).forEach((w) => externalWarnings.push(w));
        const stats = srcResult && srcResult.stats ? srcResult.stats : {};
        if (!stats.externalRawCount) {
          return skipped('failed', 'No valid research sources were found.');
        }
        await say('source_quality', 'Checking source quality');
      } catch (e) {
        return skipped('failed', 'Research source search failed.');
      }
    } else if (useExternalResearch && !searchProvider) {
      externalWarnings.push({ issue: 'no_search_provider', detail: 'External research requested but no searchProvider is connected; using internal sources only.' });
    }

    /* snapshot existing active headings so we can tell which notes are NEW */
    const beforeNotes = useMemoryResearchStorage
      ? existingResearchNotes
      : (agent.loadArticleResearchNotes
        ? agent.loadArticleResearchNotes({ userId: userId, workspaceId: workspaceId, articleId: articleId })
        : []);
    const beforeHeadings = new Set(beforeNotes.map((nt) => nt.headingId));

    /* 3 — Research adapter: real LLM → mock (testing) → skip (no fabrication). */
    await say('research', 'Running research');
    if (!canContinue()) return skipped('cancelled', 'Research stopped because this Workspace is read-only.');
    let response = null;
    try {
      if (typeof researchLLM === 'function') {
        response = await researchLLM(payload);
        if (!canContinue()) return skipped('cancelled', 'Research stopped because this Workspace is read-only.');
      } else if (useMockResearch) {
        response = mockResearchAdapter(ctx, payload);
      } else {
        return skipped('skipped', 'No research engine is connected yet.');
      }
    } catch (e) {
      try { console.warn('[Research Agent] research adapter failed:', e); } catch (e2) {}
      return skipped('failed', 'Research could not be completed. Try again or add notes manually.');
    }
    response = response || { notes: [], coverageStatus: null, reason: null };

    /* 4 — Validate the response BEFORE anything is saved. */
    await say('quality', 'Checking research quality');
    const validationResult = agent.validateResearchResponse(response, ctx);

    /* 5 + 6 — One repair attempt (only if invalid AND a repairLLM exists), then
       save valid notes (fill_missing_only). repairResearchResponseOnce owns the
       single-attempt repair, the re-validation, and the protected-safe save. */
    if (!validationResult.valid && typeof repairLLM === 'function') {
      await say('repair', 'Repairing research notes');
    }
    await say('save', 'Saving research notes');
    if (!canContinue()) return skipped('cancelled', 'Research stopped because this Workspace is read-only.');
    const memorySummary = useMemoryResearchStorage ? await repairResearchResponseInMemory({
      ctx: ctx,
      originalResponse: response,
      validationResult: validationResult,
      repairLLM: typeof repairLLM === 'function' ? repairLLM : null,
      existingNotes: existingResearchNotes,
      agent: agent
    }) : null;
    const summary = memorySummary || await agent.repairResearchResponseOnce({
      ctx: ctx,
      originalResponse: response,
      validationResult: validationResult,
      repairLLM: typeof repairLLM === 'function' ? repairLLM : null
    });

    /* 7 — Collect the notes that are NEW this run (for the Outline UI to open). */
    const afterNotes = useMemoryResearchStorage
      ? (summary.notes || [])
      : (agent.loadArticleResearchNotes
        ? agent.loadArticleResearchNotes({ userId: userId, workspaceId: workspaceId, articleId: articleId })
        : []);
    const newNotes = afterNotes.filter((nt) => nt && nt.origin === 'ai' && !beforeHeadings.has(nt.headingId));

    await say('done', 'Research notes added');

    /* fold external-retrieval warnings into the developer-facing summary */
    if (externalWarnings.length && summary && Array.isArray(summary.warnings)) {
      summary.warnings = summary.warnings.concat(externalWarnings);
    }

    return {
      /* `notes` = validated + saved + newly-added — the only notes the Outline
         UI receives. Raw/invalid output never reaches here. */
      notes: newNotes,
      research: afterNotes,
      allNotes: afterNotes,
      count: newNotes.length,
      context: ctx,
      payload: payload,
      validationResult: validationResult,
      storageResult: { savedCount: summary.savedCount, rejectedCount: summary.rejectedCount, articleId: articleId },
      summary: summary
    };
  }

  /* Backward-compatible no-progress entry point (delegates to the one workflow). */
  function generateAndSaveResearchNotes({ context, form, outline }) {
    return runResearchWorkflow({ context: context, form: form, outline: outline, onProgress: null });
  }

  window.ResearchNotes = {
    /* legacy source data + per-source gate kept for backward compatibility */
    EXTERNAL_LIBRARY,
    DISALLOWED_CANDIDATES,
    validateExternalSource,
    buildResearchNotes,
    saveResearchNotes,
    loadResearchNotes,
    /* the one validated workflow path */
    runResearchWorkflow,
    generateAndSaveResearchNotes,
    /* mock research — local testing only, never a silent production researcher */
    MOCK_SOURCE_BANK,
    mockResearchAdapter,
    createMockValidResearchResponse,
    createMockBelowTargetResearchResponse,
    createMockInvalidResearchResponse
  };
})();
