/* global React */
// Data: 5 questions + opportunity library + mapping logic for AI Marketing Audit.
// Kept as pure data so editing later is painless.

const QUESTIONS = [
  {
    id: 'size',
    title: (<>How big is <em>your team?</em></>),
    sub: "So the recommendations fit your current shape, not a template. Works for startups and legacy companies.",
    options: [
      { id: '1',         label: 'Just me',             sub: 'Solo or founder-led' },
      { id: '2-10',      label: '2 to 10 people',      sub: 'Tight team, fast moves' },
      { id: '11-50',     label: '11 to 50 people',     sub: 'Building structure' },
      { id: '51-200',    label: '51 to 200 people',    sub: 'Scaling functions' },
      { id: '201-1000',  label: '201 to 1,000 people', sub: 'Multi-team coordination' },
      { id: '1000+',     label: '1,000+ people',       sub: 'Enterprise scale' },
    ],
  },
  {
    id: 'goal',
    title: (<>Primary marketing <em>goal right now?</em></>),
    sub: "Pick the one you'd defend in a board meeting.",
    options: [
      { id: 'pipeline',   label: 'Generate more qualified pipeline',  sub: 'Fill the top, raise the bar' },
      { id: 'conversion', label: 'Improve conversion and funnel efficiency', sub: 'Fewer leaks, better fit' },
      { id: 'content',    label: 'Scale content and thought leadership', sub: 'Voice, volume, consistency' },
      { id: 'brand',      label: 'Build brand and category awareness',  sub: 'Be remembered before you are googled' },
    ],
  },
  {
    id: 'maturity',
    title: (<>How is your team <em>using AI today?</em></>),
    sub: "Be honest. \"We tried ChatGPT twice\" is an answer.",
    options: [
      { id: 'none',    label: 'Not at all, still exploring',           sub: 'Curious but uncommitted' },
      { id: 'light',   label: 'Occasional use',                         sub: 'ChatGPT for drafts, etc.' },
      { id: 'partial', label: 'Some workflows automated',               sub: 'Custom GPTs, a Zap or two' },
      { id: 'heavy',   label: 'Heavily integrated across the stack',   sub: 'APIs, agents, dashboards' },
    ],
  },
  {
    id: 'timesink',
    title: (<>Where do you <em>lose the most time?</em></>),
    sub: "The part of the week that quietly eats the calendar.",
    options: [
      { id: 'content',    label: 'Content production',            sub: 'Blog, social, email' },
      { id: 'leads',      label: 'Lead qualification and routing', sub: 'MQL/SQL gymnastics' },
      { id: 'reporting',  label: 'Reporting and analytics',        sub: 'Dashboards, attribution, QBRs' },
      { id: 'campaigns',  label: 'Campaign planning and execution',sub: 'From brief to live' },
    ],
  },
  {
    id: 'blocker',
    title: (<>Biggest blocker to <em>using AI more?</em></>),
    sub: "What actually stops the next step, not what sounds good on a slide.",
    options: [
      { id: 'start',  label: "Don't know where to start",         sub: 'No map, no first domino' },
      { id: 'skills', label: "Team doesn't have the skills yet",   sub: 'Training gap, hiring gap' },
      { id: 'tools',  label: 'Tools feel overwhelming or disconnected', sub: 'Too many tabs, no system' },
      { id: 'roi',    label: 'Unclear ROI',                        sub: 'Finance wants a number' },
    ],
  },
];

// Opportunity library. Each has impact + effort + tags used for mapping.
const OPPORTUNITIES = {
  readiness: {
    id: 'readiness',
    title: 'AI readiness audit and 90-day plan',
    desc: 'A structured review of your stack, team, and workflows to map the three highest-leverage places to introduce AI, with a sequence, not a wish list.',
    impact: 'High', effort: 'Low',
  },
  contentPipeline: {
    id: 'contentPipeline',
    title: 'AI-assisted content production pipeline',
    desc: 'From brief to draft to publish in a single guided workflow. Custom prompts per content type, brand voice baked in, editor in the loop.',
    impact: 'High', effort: 'Medium',
  },
  repurpose: {
    id: 'repurpose',
    title: 'Repurposing workflow for long-form',
    desc: 'Turn one podcast, webinar, or essay into 8 to 12 downstream assets automatically. Social posts, newsletter cuts, clips, a landing page.',
    impact: 'Medium', effort: 'Low',
  },
  editorAI: {
    id: 'editorAI',
    title: 'Editorial AI assistant on brand voice',
    desc: 'A private assistant trained on your best-performing posts and style guide. Drafts and edits feel like your team, not generic output.',
    impact: 'Medium', effort: 'Medium',
  },
  leadScoring: {
    id: 'leadScoring',
    title: 'AI lead scoring with behavioral signals',
    desc: 'Score every lead against your ICP using firmographics plus in-product and site behavior. Stop routing great fits to the nurture pit.',
    impact: 'High', effort: 'Medium',
  },
  qualBot: {
    id: 'qualBot',
    title: 'Conversational qualification layer',
    desc: 'An on-site assistant that asks three sharp questions, routes the right ones to sales, and sends the rest to tailored follow-up. No forms.',
    impact: 'High', effort: 'Medium',
  },
  intentData: {
    id: 'intentData',
    title: 'Intent data integration',
    desc: 'Pipe third-party intent signals into your CRM and trigger real-time plays. Focus the team where interest is already warm.',
    impact: 'Medium', effort: 'High',
  },
  dashboards: {
    id: 'dashboards',
    title: 'AI-powered marketing dashboards',
    desc: 'One view that answers "what moved the number?" without a data analyst. Natural-language queries over your warehouse.',
    impact: 'High', effort: 'Medium',
  },
  weeklyInsights: {
    id: 'weeklyInsights',
    title: 'Automated weekly insights',
    desc: 'A Monday morning brief your team actually reads. Anomalies, wins, and the single thing to investigate this week, written in plain English.',
    impact: 'Medium', effort: 'Low',
  },
  anomaly: {
    id: 'anomaly',
    title: 'Anomaly detection on core funnels',
    desc: 'Catch a broken form, a collapsed channel, or a sudden spike before the end-of-month review does. Low noise, high signal.',
    impact: 'Medium', effort: 'Medium',
  },
  campaignCopilot: {
    id: 'campaignCopilot',
    title: 'Campaign planning copilot',
    desc: 'From quarterly theme to brief to channel plan in hours, not weeks. A template with teeth, tuned to your ICP and past wins.',
    impact: 'High', effort: 'Medium',
  },
  abTestAI: {
    id: 'abTestAI',
    title: 'AI-driven experimentation layer',
    desc: 'Generate, ship, and learn from small tests across copy, landing pages, and email. The agent writes variants; a human approves.',
    impact: 'Medium', effort: 'Medium',
  },
  brandNarrative: {
    id: 'brandNarrative',
    title: 'Narrative workshop and category map',
    desc: 'Before scaling content, lock the one-sentence story. Without it, every piece you publish pulls in a slightly different direction.',
    impact: 'High', effort: 'Low',
  },
  enablement: {
    id: 'enablement',
    title: 'Team AI enablement sprint',
    desc: 'A two-week sprint: shared prompt library, role-specific playbooks, and a weekly office hour. Skill ramps without disrupting the roadmap.',
    impact: 'Medium', effort: 'Low',
  },
  roiFramework: {
    id: 'roiFramework',
    title: 'AI ROI measurement framework',
    desc: 'A simple model that ties each AI initiative to pipeline, efficiency, or cycle time. Numbers finance will sign off on.',
    impact: 'High', effort: 'Low',
  },
};

// Map a set of answers -> ordered list of opportunities with "why this matters" lines.
function buildOpportunityMap(answers) {
  const picked = []; // { opp, why }
  const seen = new Set();
  const add = (key, why) => {
    if (!key || seen.has(key)) return;
    if (!OPPORTUNITIES[key]) return;
    seen.add(key);
    picked.push({ opp: OPPORTUNITIES[key], why });
  };

  const a = answers; // { stage, goal, maturity, timesink, blocker }

  // Blocker-driven prepend (foundational moves first if needed)
  if (a.blocker === 'start') {
    add('readiness', "You told us you don't know where to start, so we lead with a map, not a tool.");
  }
  if (a.blocker === 'skills') {
    add('enablement', "The blocker is skills, not software. Ramp the team first, then layer the tools.");
  }
  if (a.blocker === 'roi') {
    add('roiFramework', "ROI is the blocker. Measurement has to exist before anything else is worth shipping.");
  }
  if (a.blocker === 'tools') {
    add('readiness', "Tool sprawl is the symptom. A short audit removes three tabs before adding any.");
  }

  // Timesink-driven core recommendations
  if (a.timesink === 'content') {
    add('contentPipeline', "Content production is your biggest time sink. This is the highest-impact system to fix.");
    add('repurpose', "One long-form piece becomes ten. Directly shrinks the weekly content load.");
    add('editorAI', "Keeps the voice consistent as output scales, so AI help doesn't flatten the writing.");
  }
  if (a.timesink === 'leads') {
    add('leadScoring', "You lose time on lead qualification. Scoring is the first place that time comes back.");
    add('qualBot', "An asynchronous qualifier means sales only sees the right shapes.");
    add('intentData', "Surface the accounts already leaning in, instead of scoring a cold list every week.");
  }
  if (a.timesink === 'reporting') {
    add('dashboards', "Reporting is eating your week. A natural-language dashboard takes the re-runs off your plate.");
    add('weeklyInsights', "A short Monday brief replaces three ad-hoc pulls every week.");
    add('anomaly', "Stop finding out something broke two weeks after it broke.");
  }
  if (a.timesink === 'campaigns') {
    add('campaignCopilot', "Campaign planning is the drag. A copilot turns weeks of planning into a reviewed draft in a day.");
    add('abTestAI', "Once campaigns ship faster, experimentation is how you compound the wins.");
  }

  // Goal-driven additions
  if (a.goal === 'pipeline') add('leadScoring', "Pipeline is the goal. Scoring focuses the team on the fits that convert.");
  if (a.goal === 'conversion') add('abTestAI', "Conversion lift comes from cadence of tests, not heroic redesigns.");
  if (a.goal === 'content') add('contentPipeline', "Scaling content without a system just scales the bottleneck.");
  if (a.goal === 'brand') add('brandNarrative', "Brand goals need the story locked before any AI scales the output.");

  // Maturity-driven additions
  if (a.maturity === 'none' || a.maturity === 'light') {
    add('enablement', "Early-stage AI use. A short enablement sprint unlocks the next two quarters.");
  }
  if (a.maturity === 'heavy') {
    add('anomaly', "You're already heavily integrated. Anomaly detection is the next tier of leverage.");
    add('roiFramework', "At this maturity, the conversation becomes ROI attribution. Get the framework right.");
  }

  // Size-driven nudge: small teams benefit from narrative, larger from measurement
  if (a.size === '1' || a.size === '2-10') {
    add('brandNarrative', "Smaller teams move faster when the narrative is crisp.");
  }
  if (a.size === '201-1000' || a.size === '1000+') {
    add('roiFramework', "At this size, finance reviews every line. A measurement framework protects the budget.");
  }

  // Trim to 3–5
  const MIN = 3, MAX = 5;
  let result = picked.slice(0, MAX);
  if (result.length < MIN) {
    // Fill with sensible defaults in priority order
    ['readiness','contentPipeline','leadScoring','dashboards','campaignCopilot']
      .forEach(k => { if (result.length < MIN && !seen.has(k)) { seen.add(k); result.push({ opp: OPPORTUNITIES[k], why: "A high-leverage default for most B2B SaaS teams right now." }); }});
  }
  return result;
}

// Human labels for answers, used in result meta + PDF
const ANSWER_LABELS = {
  size:     { '1': 'Just me', '2-10': '2 to 10', '11-50': '11 to 50', '51-200': '51 to 200', '201-1000': '201 to 1,000', '1000+': '1,000+' },
  goal:     { pipeline: 'Qualified pipeline', conversion: 'Funnel efficiency', content: 'Content scale', brand: 'Brand & category' },
  maturity: { none: 'Exploring', light: 'Occasional', partial: 'Partial', heavy: 'Integrated' },
  timesink: { content: 'Content production', leads: 'Lead qualification', reporting: 'Reporting', campaigns: 'Campaign execution' },
  blocker:  { start: 'No starting point', skills: 'Skills gap', tools: 'Tool sprawl', roi: 'Unclear ROI' },
};

// Tone shape derived from the user's own answers. Keeps the prompt feeling
// matched to where they actually are, instead of one generic voice for everyone.
function getTone(answers) {
  const m = answers.maturity, g = answers.goal, b = answers.blocker;

  let prelude;
  if (m === 'none' || m === 'light') {
    prelude = "Walk me through this carefully. Define terms when they could mean two things, and assume I'm bringing strong marketing instincts but limited hands-on AI experience.";
  } else if (m === 'partial') {
    prelude = "Be direct. Assume I run marketing day to day and have shipped a few AI workflows already. Skip the basics.";
  } else {
    prelude = "Treat this as a leverage analysis. Assume my team is technically fluent and already integrated. Show me where the next 10x sits, not where the next 10%.";
  }

  let firstAsk;
  if (b === 'start')       firstAsk = "Start with the single highest-leverage move I should make this month before doing anything else, and tell me why it's that one and not the next-best.";
  else if (b === 'skills') firstAsk = "Start with a two-week enablement plan to ramp the team. Tools come second.";
  else if (b === 'tools')  firstAsk = "Start with three things I should remove from my stack before adding anything new.";
  else if (b === 'roi')    firstAsk = "Start by defining the measurement framework. We won't ship anything until the metric is named.";
  else                     firstAsk = "Start with the single highest-leverage move and explain why it's that one.";

  let synthesisAsk;
  if (g === 'pipeline')        synthesisAsk = "Synthesize: which two opportunities, run together, will most directly raise qualified pipeline this quarter?";
  else if (g === 'conversion') synthesisAsk = "Synthesize: which two opportunities will compound to lift conversion across the funnel rather than at one stage?";
  else if (g === 'content')    synthesisAsk = "Synthesize: which two opportunities will let me produce more without flattening the brand voice?";
  else if (g === 'brand')      synthesisAsk = "Synthesize: which one opportunity should run first because it locks the narrative every other piece will lean on?";
  else                         synthesisAsk = "Synthesize: which two opportunities, run together, give the most leverage this quarter?";

  let close;
  if (m === 'none' || m === 'light') close = "If you use any acronym, define it inline the first time. Push back if any of my answers above sound off.";
  else if (m === 'partial')          close = "Skip preambles. Lead with the answer. Push back if any of my answers above sound off.";
  else                                close = "Pressure-test your top recommendation against one credible counter-argument before answering.";

  return { prelude, firstAsk, synthesisAsk, close };
}

// Build the ready-to-paste prompt, populated with the user's answers and
// their ranked opportunities. The user pastes this then pastes the context
// template (next function) below it.
function buildPrompt(answers, opportunityMap, followups) {
  const tone = getTone(answers);
  const size     = ANSWER_LABELS.size[answers.size]         || 'not specified';
  const goal     = ANSWER_LABELS.goal[answers.goal]         || 'not specified';
  const maturity = ANSWER_LABELS.maturity[answers.maturity] || 'not specified';
  const timesink = ANSWER_LABELS.timesink[answers.timesink] || 'not specified';
  const blocker  = ANSWER_LABELS.blocker[answers.blocker]   || 'not specified';

  const oppLines = opportunityMap.map(({ opp }, i) =>
    `  ${i + 1}. ${opp.title} (impact ${opp.impact.toLowerCase()}, effort ${opp.effort.toLowerCase()})`
  ).join('\n');

  const followupLines = (Array.isArray(followups) && followups.length > 0)
    ? followups.map(f => `- ${f.question}: ${f.answer}`)
    : [];

  return [
    `You are an AI marketing strategist working with me on my marketing program. ${tone.prelude}`,
    ``,
    `About my situation:`,
    `- Team size: ${size}`,
    `- My primary marketing goal: ${goal}`,
    `- Current AI maturity: ${maturity}`,
    `- Where I lose the most time: ${timesink}`,
    `- My biggest blocker: ${blocker}`,
    ...(followupLines.length > 0 ? ['', `Additional context I gave on follow-up:`, ...followupLines] : []),
    ``,
    `Below this prompt I've pasted the context you need about my team, stack, and recent results. Use it instead of asking me for it.`,
    ``,
    `What I need from you, in order:`,
    ``,
    `1. ${tone.firstAsk}`,
    ``,
    `2. Sequence the following ${opportunityMap.length} opportunities into a 30 / 60 / 90 day plan with a measurable outcome for each window:`,
    oppLines,
    ``,
    `3. For each opportunity, give me:`,
    `   - The smallest first move I can ship in 7 days.`,
    `   - Two named tools or services I can evaluate, with a one-line note on why each.`,
    `   - One leading indicator and one lagging indicator.`,
    `   - One thing I should NOT do that a less experienced marketer would.`,
    ``,
    `4. ${tone.synthesisAsk}`,
    ``,
    tone.close,
  ].join('\n');
}

// Static context template the user fills in and pastes after the prompt.
function buildContextTemplate() {
  return [
    `============================================================`,
    `CONTEXT. Paste this AFTER the prompt above, with your details filled in.`,
    `============================================================`,
    ``,
    `TEAM`,
    `- Marketing headcount:`,
    `- Roles (content, demand gen, ops, design):`,
    `- Closest in-house technical capacity (engineer, RevOps, none):`,
    ``,
    `CURRENT STACK`,
    `- CRM:`,
    `- Marketing automation:`,
    `- Analytics / attribution:`,
    `- Content / CMS:`,
    `- AI tools already in use:`,
    ``,
    `RECENT NUMBERS · last quarter, rough is fine`,
    `- Pipeline generated:`,
    `- Win rate:`,
    `- Top-of-funnel volume (sessions / leads / MQLs):`,
    `- Best-performing channel:`,
    `- Worst-performing channel:`,
    ``,
    `BRAND VOICE`,
    `- One paragraph in your brand voice (or a public URL that nails it):`,
    `- Two competitors whose voice you do NOT want to sound like:`,
    ``,
    `WHAT WORKED / WHAT DIDN'T · last six months`,
    `- Two campaigns that worked:`,
    `- Two that didn't:`,
    `- One thing the team is convinced of that you privately doubt:`,
    ``,
    `CONSTRAINTS`,
    `- New-tool budget per quarter:`,
    `- Weekly time the team can give this initiative:`,
    `- Off-limits (industries, tactics, channels, brand red lines):`,
    `============================================================`,
  ].join('\n');
}

// Industry options shown as a dropdown on the lead-capture form.
const INDUSTRIES = [
  { id: 'tech',         label: 'Tech / SaaS' },
  { id: 'industrial',   label: 'Industrial / Manufacturing' },
  { id: 'professional', label: 'Professional services' },
  { id: 'healthcare',   label: 'Healthcare / Life sciences' },
  { id: 'financial',    label: 'Financial services' },
  { id: 'retail',       label: 'Retail / Consumer' },
  { id: 'media',        label: 'Media / Marketing' },
  { id: 'education',    label: 'Education' },
  { id: 'other',        label: 'Other' },
];

Object.assign(window, { QUESTIONS, OPPORTUNITIES, buildOpportunityMap, ANSWER_LABELS, INDUSTRIES, getTone, buildPrompt, buildContextTemplate });
