/**
 * Wizard Step Definitions & Page Descriptions
 * 
 * Central source of truth for the setup wizard flow
 * and contextual help descriptions.
 * 
 * @package BoostBot
 */
import { t } from '@/lib/i18n'

export interface WizardStep {
  id: string
  name: string
  route: string // May contain {defaultBotId} placeholder
  isCritical: boolean
  scriptedMessage: string
}

/**
 * All wizard steps in order.
 * Routes with {defaultBotId} are resolved at runtime.
 */
export function getWizardSteps(): WizardStep[] {
  return [
    { id: 'start', name: t('Start Installation'), route: '/', isCritical: false, scriptedMessage: '' },
    { id: 'enable_bot', name: t('Enable Bot'), route: '/settings', isCritical: true, scriptedMessage: t('Hello! 👋 Let\'s start by enabling the bot on your website. This is the first and most important step — once active, it will appear to all visitors.') },
    { id: 'bots_overview', name: t('Bot Management'), route: '/bots', isCritical: false, scriptedMessage: t('Here you can see all your bots, create new ones, and edit settings. The "Service Agent" bot was created automatically — click on it to edit.') },
    { id: 'basic_details', name: t('Basic Details'), route: '/bots/{defaultBotId}?tab=basic', isCritical: true, scriptedMessage: t('Here you can give the bot a name, description, and decide if it\'s active. The bot name appears in the chat window header.') },
    { id: 'display_conditions', name: t('Display Conditions'), route: '/bots/{defaultBotId}?tab=display', isCritical: false, scriptedMessage: t('Display conditions let you choose exactly which pages the bot appears on — the entire site, homepage only, or specific pages.') },
    { id: 'appearance', name: t('Appearance'), route: '/bots/{defaultBotId}?tab=appearance', isCritical: true, scriptedMessage: t('Let\'s design the bot\'s appearance! 🎨 Colors, fonts, bubble size, animation — everything is customizable. If you have Elementor, you can import values automatically — we\'ll cover that later in the setup.') },
    { id: 'opening_message', name: t('Opening Message'), route: '/bots/{defaultBotId}?tab=opening', isCritical: false, scriptedMessage: t('The opening message is the first thing visitors see when they open the chat. You can set up FAQs or offer help suggestions.') },
    { id: 'behavior', name: t('Personality'), route: '/bots/{defaultBotId}?tab=behavior', isCritical: false, scriptedMessage: t('Here you define the bot\'s personality — tone of voice, system prompt, and creativity level. The personality affects how the bot communicates with customers.') },
    { id: 'widgets', name: t('Widgets'), route: '/bots/{defaultBotId}?tab=widgets', isCritical: false, scriptedMessage: t('Widgets are interactive tools the bot can display — contact forms, WhatsApp button, calendar, gallery and more. Assign the relevant ones to the bot.') },
    { id: 'knowledge_base', name: t('Knowledge Base'), route: '/knowledge-base', isCritical: true, scriptedMessage: t('The knowledge base is the heart of the bot! 🧠 Here you index your site\'s content so the bot can answer questions accurately based on your information.') },
    { id: 'business_card', name: t('Business Card'), route: '/brand-card', isCritical: true, scriptedMessage: t('The business card contains your business information — company name, services, hours of operation, and contact details. The bot uses this information to provide accurate answers.') },
    { id: 'integrations', name: t('Integrations'), route: '/integrations', isCritical: false, scriptedMessage: t('Connect external systems — Google Calendar for appointments, Webhook for Zapier/Make to receive leads, and API key for custom development.') },
    { id: 'global_rules', name: t('Global Rules'), route: '/bots', isCritical: true, scriptedMessage: t('Global rules apply to all bots — here you define rules the bot must follow, and forbidden topics it must not discuss. Open the "Global Rules" tab at the top of the page.') },
    { id: 'global_appearance_colors', name: t('Global Colors'), route: '/appearance-presets', isCritical: true, scriptedMessage: t('Global color values are shared across all appearance presets. 🎨 Open "Global Values" at the top of the page and switch to the "Colors" tab — if you have Elementor, you can import your site colors with one click.') },
    { id: 'global_appearance_typography', name: t('Global Typography'), route: '/appearance-presets', isCritical: true, scriptedMessage: t('Now switch to the "Typography" tab inside Global Values. ✏️ Here you set global fonts — and if you have Elementor, you can import your site fonts automatically.') },
    { id: 'general_settings', name: t('General Settings'), route: '/settings', isCritical: true, scriptedMessage: t('General plugin settings — enable/disable the bot, mobile settings, character limits, and low BoostCoin alerts. Review the settings and make sure everything is configured properly.') },
    { id: 'credits', name: 'BoostCoin', route: '/usage', isCritical: true, scriptedMessage: t('The bot runs on BoostCoin — each message consumes a certain amount. 💳 Here you can see your BoostCoin balance, usage history, and purchase additional BoostCoin.') },
    { id: 'conversations_preview', name: t('Conversations Preview'), route: '/conversations', isCritical: false, scriptedMessage: t('Here you can see all conversations with the bot — full history, search, and performance tracking. Once the bot starts working, this is the place to check it.') },
    { id: 'finish', name: t('Finish'), route: '/settings', isCritical: true, scriptedMessage: t('Excellent! 🎉 We\'ve completed all the steps. Check that everything is in order and click "Finish" to complete the installation and go to the dashboard.') },
  ]
}

/**
 * Resolve a step route by replacing {defaultBotId} with actual bot ID.
 * If no bot ID is available, falls back to /bots (the bot list page)
 * so the user can select a bot to edit.
 */
export function resolveStepRoute(route: string, botId: number | null): string {
  if (!route.includes('{defaultBotId}')) return route
  if (!botId) {
    // No bot found — redirect to bots list instead of a broken URL
    return '/bots'
  }
  return route.replace('{defaultBotId}', String(botId))
}

/**
 * Page descriptions for the contextual help button.
 * Maps route patterns to translated descriptions.
 */
export interface PageDescription {
  pattern: string | RegExp
  tab?: string // Optional query param match
  name: string
  description: string
}

export function getPageDescriptions(): PageDescription[] {
  return [
    { pattern: /^\/bots\/\d+$/, tab: 'basic', name: t('Basic Details'), description: t('Bot name, description, slug, and whether it is active and set as default.') },
    { pattern: /^\/bots\/\d+$/, tab: 'display', name: t('Display Conditions'), description: t('Choose which pages the bot appears on — all pages, homepage only, or specific pages.') },
    { pattern: /^\/bots\/\d+$/, tab: 'appearance', name: t('Appearance'), description: t('Bot design — colors, fonts, bubble size, animation, and overall style. You can import values from Elementor.') },
    { pattern: /^\/bots\/\d+$/, tab: 'opening', name: t('Opening Message'), description: t('The first message visitors see — FAQs or help suggestions.') },
    { pattern: /^\/bots\/\d+$/, tab: 'behavior', name: t('Personality'), description: t('Bot personality, tone of voice, system prompt, and creativity level.') },
    { pattern: /^\/bots\/\d+$/, tab: 'widgets', name: t('Widgets'), description: t('Assign interactive widgets to the bot — forms, WhatsApp, calendar, gallery and more.') },
    { pattern: /^\/bots\/\d+$/, tab: 'advanced', name: t('Advanced'), description: t('Response length limits, contact lists, and additional advanced settings.') },
    { pattern: /^\/bots\/\d+$/, name: t('Edit Bot'), description: t('Edit all bot settings — name, appearance, opening message, behavior and more.') },
    { pattern: /^\/personalities\/\d+$/, name: t('Edit Personality'), description: t('Edit the system prompt, select a tone, and set personality traits for a specific personality.') },
    { pattern: /^\/widgets\/\d+$/, name: t('Edit Widget'), description: t('Edit widget settings — fields, design, messages, and bot assignments.') },
    { pattern: /^\/appearance-presets\/\d+$/, name: t('Edit Appearance Preset'), description: t('Edit colors, fonts, sizes, animations, and every design element of the chat.') },
    { pattern: /^\/opening-screen-presets\/\d+$/, name: t('Edit Opening Message'), description: t('Edit opening text, questions, quick action buttons, and AI instructions.') },
    { pattern: /^\/leads\/\d+$/, name: t('Lead Details'), description: t('View details of a specific lead — submitted information, source, linked conversation, and status.') },
    { pattern: /^\/conversations\/[^/]+$/, name: t('Conversation Details'), description: t('View a full conversation — messages, metadata, and timeline.') },
    { pattern: '/', name: t('Dashboard'), description: t('General overview of your bot — statistics, recent leads, and performance metrics.') },
    { pattern: '/bots', name: t('Bots'), description: t('Manage your bots. Here you can create new bots, edit settings, and enable or disable bots.') },
    { pattern: '/personalities', name: t('Personalities'), description: t('Manage bot personalities — prompts, tone of voice, and different personality traits.') },
    { pattern: '/contact-lists', name: t('Contact Lists'), description: t('Manage contacts — create lists, add contacts, and assign to widgets like the calendar.') },
    { pattern: '/widgets', name: t('Widgets'), description: t('Manage interactive widgets — dynamic forms, WhatsApp, calendar, gallery and more.') },
    { pattern: '/appearance-presets', name: t('Appearance Presets'), description: t('Ready-made design templates. Create, edit, and assign to bots. Includes global values.') },
    { pattern: '/opening-screen-presets', name: t('Opening Messages'), description: t('Templates for the bot\'s opening message — FAQs, help suggestions, or custom configuration.') },
    { pattern: '/meetings', name: t('Meetings'), description: t('View meetings booked through the bot, export to CSV, and manage calendar.') },
    { pattern: '/leads', name: t('Leads'), description: t('Manage leads received from chat forms — status, contact details, and export.') },
    { pattern: '/conversations', name: t('Conversations'), description: t('View all conversations with the bot — history, search, and deletion.') },
    { pattern: '/knowledge-base', name: t('Knowledge Base'), description: t('Index your site content so the bot can answer questions. Scan, index, and manage content.') },
    { pattern: '/brand-card', name: t('Business Card'), description: t('Business information — company name, services, hours of operation, and contact details. The bot uses this information.') },
    { pattern: '/integrations', name: t('Integrations'), description: t('Connect to external systems — Google Calendar, Webhook for leads and events, and API key.') },
    { pattern: '/analytics', name: t('Analytics'), description: t('Statistical data — traffic sources, widget performance, conversion funnel, and bot comparison.') },
    { pattern: '/usage', name: t('Usage & Costs'), description: t('Track BoostCoin usage, consumption history, pricing, and purchase additional BoostCoin.') },
    { pattern: '/settings', name: t('Settings'), description: t('General plugin settings — enable bot, character limits, global rules, and setup wizard.') },
    { pattern: '/updates', name: t('Updates'), description: t('Check for and install plugin updates.') },
  ]
}

/**
 * Get the page description for the current route.
 */
export function getPageDescription(pathname: string, searchParams: URLSearchParams): PageDescription | null {
  const tab = searchParams.get('tab') || undefined

  for (const desc of getPageDescriptions()) {
    if (desc.pattern instanceof RegExp) {
      if (desc.pattern.test(pathname)) {
        // If this descriptor has a tab requirement, check it
        if (desc.tab) {
          if (tab === desc.tab) return desc
          // Don't return yet, keep looking
          continue
        }
        // No tab requirement — match (generic fallback for detail pages)
        return desc
      }
    } else {
      // Exact string match
      if (pathname === desc.pattern) return desc
    }
  }

  return null
}
