/* global window */
/* Atlas demo — questions, persona, and proposal templates. */

const ATLAS = {
  name: 'Atlas',
  intro: "Hi, I'm Atlas — I work with the Bastion team. I'd love to ask you five quick questions about your business so I can sketch what an AI sprint would actually look like for you. Press the mic when you're ready (or type if you'd rather).",
  ready: "Beautiful — let's start with the basics.",
  thinkingLines: [
    'thinking through that…',
    'noting that for the proposal…',
    'mapping that to what we usually do…',
    'considering the right sprint shape…',
  ],
  generating: "Alright — I have what I need. Let me draft a quick proposal based on what you told me. Give me about ten seconds.",
};

const QUESTIONS = [
  {
    id: 'business',
    topic: 'What you do',
    prompt: 'In one sentence — what does your business do, and who do you do it for?',
    placeholder: 'e.g. We sell handmade leather goods online and run a small wholesale operation for boutique retailers.',
    minWords: 5,
    // Canned fallback ack if Claude is unavailable
    ack: "Got it — clear picture. ",
  },
  {
    id: 'team',
    topic: 'Your team',
    prompt: "How many people on the team, and what are their roles? Don't overthink it — broad strokes are fine.",
    placeholder: 'e.g. 6 of us — me as founder, 2 ops, 1 customer support, 1 marketing, 1 part-time developer.',
    minWords: 3,
    ack: "Helpful — that gives me a sense of where AI can pull its weight. ",
  },
  {
    id: 'tools',
    topic: 'Your stack',
    prompt: "Which tools does your team actually live in day-to-day? Things like Shopify, HubSpot, Slack, GitHub, Notion — whatever's true for you.",
    placeholder: 'e.g. Shopify for the store, HubSpot for CRM, Slack for ops chatter, Notion for docs, Google Sheets for forecasting.',
    minWords: 3,
    ack: "Good stack to work with. ",
  },
  {
    id: 'pain',
    topic: 'The painful workflow',
    prompt: "Is there a workflow that feels painful or repetitive? Something you'd love to just hand off — even partly?",
    placeholder: 'e.g. Triaging customer Slack messages and tagging them to the right person. Eats 2+ hours a day.',
    minWords: 5,
    ack: "That's exactly the kind of thing we tend to ship first. ",
  },
  {
    id: 'ai_comfort',
    topic: 'You + AI',
    prompt: 'Last one — how comfortable is your team with AI today? Are you using anything right now, even casually?',
    placeholder: 'e.g. I use ChatGPT a lot personally. Team uses it here and there but nothing built into workflows.',
    minWords: 3,
    ack: "Good baseline. ",
  },
];

// Templated proposal — assembles from the user's answers + sensible Bastion defaults.
// Tries to feel custom by extracting tools, picking a sprint tier, mapping pain to layers.

function detectKeywords(text) {
  const t = (text || '').toLowerCase();
  return {
    shopify: /shopify/.test(t),
    hubspot: /hubspot/.test(t),
    salesforce: /salesforce/.test(t),
    slack: /slack/.test(t),
    discord: /discord/.test(t),
    notion: /notion/.test(t),
    github: /github|repo|code/.test(t),
    vercel: /vercel/.test(t),
    airtable: /airtable/.test(t),
    sheets: /google sheets|sheets|excel|spreadsheet/.test(t),
    gworkspace: /google workspace|gmail|gdocs|google docs/.test(t),
    support: /support|customer|tickets?|cs\b|cx\b/.test(t),
    sales: /sales|crm|leads?|pipeline|deals?/.test(t),
    dev: /dev|engineer|developer|repo|code|github/.test(t),
    ops: /\bops\b|operations|fulfillment/.test(t),
    marketing: /marketing|growth|ads|seo/.test(t),
    analytics: /ga4|gtm|analytics|tracking|reporting/.test(t),
  };
}

function extractTools(stackAnswer) {
  if (!stackAnswer) return [];
  const known = [
    'Shopify','HubSpot','Salesforce','Slack','Discord','Notion','GitHub','Vercel',
    'Airtable','Google Sheets','Google Workspace','Gmail','Linear','Asana','Trello',
    'Jira','Stripe','Klaviyo','Zendesk','Intercom','Webflow','WordPress','Squarespace',
    'Quickbooks','Xero','Mailchimp','Zapier','Make','n8n','ChatGPT','Claude','Codex',
  ];
  const t = stackAnswer.toLowerCase();
  const found = known.filter((k) => t.includes(k.toLowerCase()));
  return [...new Set(found)];
}

function pickSprintTier(answers) {
  const team = (answers.team || '').toLowerCase();
  const ai = (answers.ai_comfort || '').toLowerCase();
  const pain = (answers.pain || '').toLowerCase();
  const teamSizeMatch = team.match(/(\d+)/);
  const teamSize = teamSizeMatch ? parseInt(teamSizeMatch[1], 10) : 5;
  const aiExperienced = /built|workflow|automat|claude code|codex|api|custom/.test(ai);
  const painComplex = pain.length > 120 || /multiple|several|few different|many/.test(pain);
  if (!aiExperienced && teamSize <= 5 && !painComplex) return 0; // Starter
  if (aiExperienced && painComplex) return 2; // Operator Partner
  return 1; // Implementation
}

// Map pain keywords to the 6 layers — return ordered set of slab keys we'd focus on.
function pickLayerFocus(answers) {
  const all = `${answers.pain} ${answers.tools} ${answers.business}`.toLowerCase();
  const order = [];
  const push = (k) => { if (!order.includes(k)) order.push(k); };
  // Pain almost always implies routines+wins
  push('routines'); push('wins');
  if (/repo|code|dev|github|cli|api/.test(all)) push('tools');
  if (/support|ticket|email|inbox|sales|crm|deal/.test(all)) push('knowledge');
  if (/team|onboard|train|adopt|comfort/.test(all)) push('training');
  push('mapping');
  return order.slice(0, 4);
}

const LAYERS = {
  mapping:   { n: '01', label: 'Map your systems' },
  training:  { n: '02', label: 'Train your team' },
  tools:     { n: '03', label: 'Build custom tooling' },
  knowledge: { n: '04', label: 'Build your knowledge base' },
  routines:  { n: '05', label: 'Create routines and automations' },
  wins:      { n: '06', label: 'Ship small wins' },
};

const TIERS_META = [
  { name: 'Starter Sprint',        duration: '1–2 weeks', why: 'Good fit — small team, clear first workflow, room to learn the habits before going deeper.' },
  { name: 'Implementation Sprint', duration: '2–4 weeks', why: 'Best fit — enough surface area for custom tooling + a real first win, without overcommitting.' },
  { name: 'Operator Partner',      duration: 'Ongoing',   why: 'Best fit — you already have AI in motion and the pain is deep enough to justify an embedded operator.' },
];

function buildProposalTemplate(answers) {
  const tools = extractTools(answers.tools);
  const tierIdx = pickSprintTier(answers);
  const tier = TIERS_META[tierIdx];
  const layerKeys = pickLayerFocus(answers);
  const layers = layerKeys.map((k) => LAYERS[k]);
  const k = detectKeywords([answers.pain, answers.tools, answers.business].join(' '));

  // Suggested first wins — pulled from pain + stack
  const wins = [];
  if (k.support || /triage|inbox|message/.test((answers.pain || '').toLowerCase())) {
    wins.push({ title: 'Slack triage assistant', body: 'A scoped agent that watches your support channel, drafts replies, routes by topic, and asks for approval before posting.' });
  }
  if (k.shopify) {
    wins.push({ title: 'Shopify ops runbook', body: "A Claude Code agent with read access to your Shopify orders + a CLI that can flag stuck fulfillment, refund risk, and inventory gaps." });
  }
  if (k.analytics) {
    wins.push({ title: 'GA4 / tracking audit', body: 'A Codex run that crawls your tracking implementation, surfaces broken events, and produces a fix-list with owners.' });
  }
  if (k.sales || k.hubspot) {
    wins.push({ title: 'Pipeline cleanup agent', body: 'A scheduled HubSpot run that flags stalled deals, drafts follow-ups for your reps to approve, and updates stages on confirmation.' });
  }
  if (k.dev || k.github) {
    wins.push({ title: 'Repo helper', body: 'Claude Code wired to your repos with scoped access, a custom CLI for diagnostics, and a Slack handoff for code-review drafts.' });
  }
  if (!wins.length) {
    wins.push({ title: 'Painful workflow first', body: `We'd start with the workflow you mentioned — wrap it in an inspect → propose → approve loop your team can run themselves.` });
  }

  return {
    business: answers.business,
    tools,
    tier,
    tierIdx,
    layers,
    wins: wins.slice(0, 3),
    pain: answers.pain,
  };
}

// AI prompt for Atlas's smart follow-up — short, warm, and uses the answer.
function atlasFollowupPrompt({ topic, prompt, answer, nextTopic, nextPrompt, isLast }) {
  return `You are Atlas, a friendly, encouraging AI consultant working with Bastion AI — a small consulting firm that helps small businesses put AI to work inside their tools. You speak warmly, like a thoughtful operator, never salesy. Audience may not be technical; adapt your tone but stay clear.

The visitor just answered the question "${topic}":
"""
${answer}
"""

Write a single response that does TWO things in 2 short sentences MAX (under 35 words total):
1. Acknowledge what they said with ONE specific detail you noticed (e.g. a tool, role, or workflow they mentioned). Not generic — actually use their words.
2. ${isLast ? "Tell them that's everything you needed, and you'll put a proposal together." : `Naturally transition into the next question: "${nextPrompt}"`}

Write it as plain text — no quotes, no formatting, no labels. Just Atlas speaking.`;
}

function atlasProposalIntroPrompt(answers, template) {
  return `You are Atlas, a friendly AI consultant at Bastion AI. The visitor just told you about their business. Write a SHORT (2-3 sentence, under 60 words) opening line for a custom proposal slab.

Their answers:
- Business: ${answers.business}
- Team: ${answers.team}
- Tools: ${answers.tools}
- Painful workflow: ${answers.pain}
- AI experience: ${answers.ai_comfort}

Suggested sprint: ${template.tier.name}

Write a warm, specific opening — name one thing you noticed about their setup that makes you confident a sprint would help. No filler. No "I think" or "I believe." Just speak plainly. Plain text only.`;
}

Object.assign(window, { ATLAS, QUESTIONS, LAYERS, TIERS_META, buildProposalTemplate, atlasFollowupPrompt, atlasProposalIntroPrompt, detectKeywords, extractTools, pickSprintTier });
