import type { BotPhase, BotResponse, SessionContext, PainCategory } from '@/types/dalibot'

const solutionMap: Record<PainCategory, { headline: string; bullets: string[] }> = {
  design: {
    headline: "Design is where we shine.",
    bullets: [
      "High-converting business websites",
      "Booking and client intake pages",
      "Functional, branded UX — built for your industry",
    ],
  },
  data: {
    headline: "Data chaos is fixable.",
    bullets: [
      "Spreadsheet cleanup and automation",
      "Automated reporting and dashboards",
      "Python and Power Query workflows",
    ],
  },
  time: {
    headline: "Time is the real currency.",
    bullets: [
      "Custom micro-apps that replace manual steps",
      "Scheduling and admin automation",
      "End-to-end workflow simplification",
    ],
  },
}

export function dalibotFlow(
  phase: BotPhase,
  userInput: string,
  context: SessionContext
): BotResponse {
  const input = userInput.toLowerCase().trim()

  if (phase === 1) {
    // Identify bottleneck
    let pain: PainCategory | undefined

    if (input.includes('design') || input.includes('website') || input.includes('web')) {
      pain = 'design'
    } else if (input.includes('data') || input.includes('spreadsheet') || input.includes('report')) {
      pain = 'data'
    } else if (input.includes('time') || input.includes('manual') || input.includes('admin') || input.includes('slow')) {
      pain = 'time'
    }

    if (!pain) {
      return {
        content: "Got it. To point you in the right direction — is the biggest problem a Design issue (website, UX), a Data issue (spreadsheets, reports), or a Time issue (manual work, slow processes)?",
        quickReplies: ['Design', 'Data', 'Time'],
        nextPhase: 1,
      }
    }

    return {
      content: `Understood — ${pain === 'design' ? 'building the right digital presence' : pain === 'data' ? 'getting your data under control' : 'reclaiming time lost to manual work'} is a common pressure point for growing businesses. Let me ask a couple of quick questions to map the right solution.`,
      quickReplies: [],
      nextPhase: 2,
      sessionContext: { painCategory: pain },
    }
  }

  if (phase === 2) {
    // Gather context — ask what type of business
    if (!context.businessType) {
      return {
        content: "What type of business do you run? (e.g., roofing, cleaning, consulting, retail, logistics, tours, etc.)",
        quickReplies: ['Service business', 'Retail / E-commerce', 'Consulting / Freelance', 'Other'],
        nextPhase: 2,
        sessionContext: { businessType: userInput },
      }
    }

    if (context.businessType && !context.currentTools) {
      return {
        content: "What tools are you currently using? Even if it's just spreadsheets or nothing — that's useful to know.",
        quickReplies: ['Spreadsheets / Excel', 'QuickBooks', 'Google Workspace', 'No system yet'],
        nextPhase: 2,
        sessionContext: { currentTools: userInput, businessType: context.businessType || userInput },
      }
    }

    // Collect hours lost
    return {
      content: "Roughly how many hours per week would you say are lost to manual or repetitive work?",
      quickReplies: ['Under 5 hrs', '5–15 hrs', '15–30 hrs', '30+ hrs'],
      nextPhase: 3,
      sessionContext: { hoursLost: parseHoursFromInput(userInput) },
    }
  }

  if (phase === 3) {
    // Map solution
    const pain = context.painCategory || 'time'
    const solution = solutionMap[pain]
    const hours = parseHoursFromInput(userInput) || context.hoursLost || 10

    return {
      content: `Here's what I'd map for you:\n\n**${solution.headline}**\n\n${solution.bullets.map(b => `• ${b}`).join('\n')}\n\nBased on ${hours}+ hours/week of manual work, you're looking at a meaningful recovery in time and cost. Want to see the numbers?`,
      quickReplies: ['See ROI estimate', 'Book a free call', 'Tell me more'],
      nextPhase: 4,
      sessionContext: { hoursLost: hours },
    }
  }

  // Phase 4 — CTA
  if (input.includes('roi') || input.includes('estimate') || input.includes('numbers') || input.includes('calculator')) {
    return {
      content: "Perfect. Head to the ROI Calculator on this page — plug in your hours and hourly rate, and I'll show you the projected savings. Then book a call when you're ready.",
      quickReplies: ['Book a free call', 'Keep exploring'],
      nextPhase: 4,
      showCTA: true,
      ctaType: 'roi',
    }
  }

  return {
    content: "Ready to map this out properly? Book a free 30-minute strategy session — we'll look at your workflow, identify the highest-impact improvements, and outline exactly what a custom system would look like for your business.",
    quickReplies: ['Book a call now', 'Not yet, keep exploring'],
    nextPhase: 4,
    showCTA: true,
    ctaType: 'booking',
  }
}

function parseHoursFromInput(input: string): number {
  if (input.includes('30+') || input.includes('30 plus')) return 35
  if (input.includes('15') || input.includes('15–30')) return 22
  if (input.includes('5–15') || input.includes('5-15')) return 10
  if (input.includes('under 5') || input.includes('less than 5')) return 3

  const match = input.match(/\d+/)
  return match ? parseInt(match[0]) : 0
}
