'use client';

import { useEffect, useMemo, useState } from 'react';
import { Building2, GitBranch, BookOpen, Bot, Check, ChevronRight, ChevronLeft } from 'lucide-react';
import AppLogo from '@client/components/ui/AppLogo';
import { useLanguage } from '@client/contexts/LanguageContext';
import { usePublicBranding } from '@client/hooks/usePublicBranding';
import { COUNTRIES } from '@client/data/countries';
import { getAllTimezones, getBrowserTimezone } from '@client/data/timezones';

type MenuChoice = 'manual' | 'bulk' | 'later' | '';

interface AddressParts {
  country: string;
  line1: string;
  line2: string;
  city: string;
  region: string;
  postalCode: string;
}

function joinAddress(a: AddressParts): string {
  const countryName = COUNTRIES.find(c => c.code === a.country)?.name ?? a.country;
  return [a.line1, a.line2, a.city, a.region, a.postalCode, countryName]
    .map(s => s?.trim())
    .filter(Boolean)
    .join(', ');
}

export default function OnboardingPage() {
  const { t } = useLanguage();
  const { logoUrl, siteTitle } = usePublicBranding();
  const [currentStep, setCurrentStep] = useState(1);
  const [saving, setSaving] = useState(false);
  const [saveError, setSaveError] = useState<string | null>(null);

  const [form, setForm] = useState({
    restaurantName: '',
    cuisine: '',
    phone: '',
    website: '',
    branchName: '',
    address: {
      country: '',
      line1: '',
      line2: '',
      city: '',
      region: '',
      postalCode: '',
    } as AddressParts,
    timezone: '',
    openTime: '09:00',
    closeTime: '22:00',
    menuChoice: '' as MenuChoice,
    agentName: 'Alex',
    agentStyle: 'friendly',
    voiceEnabled: true,
    chatEnabled: true,
  });

  // Hydrate from sessionStorage (set by /register on signup) and fall back to /api/auth/me.
  useEffect(() => {
    let cancelled = false;
    const hydrate = async () => {
      let restaurantName = '';
      try {
        const raw = sessionStorage.getItem('pendingOnboarding');
        if (raw) {
          const parsed = JSON.parse(raw) as { restaurantName?: string; ownerName?: string };
          restaurantName = parsed.restaurantName || '';
          sessionStorage.removeItem('pendingOnboarding');
        }
      } catch { /* ignore */ }

      if (!restaurantName) {
        try {
          const r = await fetch('/api/auth/me', { credentials: 'include' });
          if (r.ok) {
            const data = await r.json();
            restaurantName = data?.user?.restaurants?.name || '';
          }
        } catch { /* ignore */ }
      }

      const tz = getBrowserTimezone();
      if (cancelled) return;
      setForm(prev => ({
        ...prev,
        restaurantName: prev.restaurantName || restaurantName,
        branchName: prev.branchName || (restaurantName ? `${restaurantName} — Main` : ''),
        timezone: prev.timezone || tz,
      }));
    };
    hydrate();
    return () => { cancelled = true; };
  }, []);

  const timezones = useMemo(() => getAllTimezones(), []);
  const timezoneGroups = useMemo(() => {
    const groups: Record<string, typeof timezones> = {};
    for (const tz of timezones) {
      (groups[tz.region] ||= []).push(tz);
    }
    return Object.entries(groups).sort((a, b) => a[0].localeCompare(b[0]));
  }, [timezones]);

  const steps = [
    { id: 1, title: t('onboarding.step1.title', 'Restaurant Profile'), icon: Building2, desc: t('onboarding.step1.desc', 'Tell us about your restaurant') },
    { id: 2, title: t('onboarding.step2.title', 'Branch Setup'), icon: GitBranch, desc: t('onboarding.step2.desc', 'Set up your first location') },
    { id: 3, title: t('onboarding.step3.title', 'Menu Intro'), icon: BookOpen, desc: t('onboarding.step3.desc', 'Add your first menu items') },
    { id: 4, title: t('onboarding.step4.title', 'AI Agent'), icon: Bot, desc: t('onboarding.step4.desc', 'Configure your AI assistant') },
  ];

  const progress = ((currentStep - 1) / (steps.length - 1)) * 100;

  // Persist what the user typed by calling existing endpoints. We do this once,
  // at the end of the wizard, so the four steps stay snappy and a back-button
  // mid-flow doesn't create half-baked records.
  const persistOnboarding = async () => {
    setSaveError(null);
    // Update the restaurant profile (name + cuisine + phone) — endpoint already
    // accepts these fields and is owned by the signed-in user.
    const restaurantPayload: Record<string, unknown> = {};
    if (form.restaurantName.trim()) restaurantPayload.name = form.restaurantName.trim();
    if (form.cuisine) restaurantPayload.cuisine_type = form.cuisine;
    if (form.phone.trim()) restaurantPayload.phone = form.phone.trim();

    if (Object.keys(restaurantPayload).length > 0) {
      const r = await fetch('/api/restaurant/profile', {
        method: 'PUT',
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(restaurantPayload),
      });
      if (!r.ok) throw new Error(`Restaurant update failed (${r.status})`);
    }

    // Look up the owning branch from /api/auth/me, then PATCH it with the
    // structured address (joined to a single TEXT string) and timezone.
    const branchPayload: Record<string, unknown> = {};
    if (form.branchName.trim()) branchPayload.name = form.branchName.trim();
    const addr = joinAddress(form.address);
    if (addr) branchPayload.address = addr;
    if (form.timezone) branchPayload.timezone = form.timezone;

    if (Object.keys(branchPayload).length > 0) {
      const me = await fetch('/api/auth/me', { credentials: 'include' });
      if (!me.ok) throw new Error(`Could not load your account (${me.status})`);
      const data = await me.json();
      const branchId: string | undefined = data?.user?.branches?.id;
      if (!branchId) throw new Error('No branch found on your account');
      const br = await fetch(`/api/branches/${branchId}`, {
        method: 'PATCH',
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(branchPayload),
      });
      if (!br.ok) throw new Error(`Branch update failed (${br.status})`);
    }
  };

  const handleNext = async () => {
    if (currentStep < steps.length) {
      setCurrentStep(s => s + 1);
      return;
    }
    // Final step: persist, then route based on the menu choice from Step 3.
    setSaving(true);
    try {
      await persistOnboarding();
    } catch (err) {
      setSaveError(err instanceof Error ? err.message : String(err));
      setSaving(false);
      return;
    }
    const dest = form.menuChoice === 'manual'
      ? '/menu-management?intro=manual'
      : form.menuChoice === 'bulk'
        ? '/menu-management?intro=bulk'
        : '/restaurant-dashboard';
    window.location.href = dest;
  };

  const handleBack = () => {
    if (currentStep > 1) setCurrentStep(s => s - 1);
  };

  return (
    <div className="min-h-screen flex" style={{ backgroundColor: 'hsl(var(--background))' }}>
      {/* Left sidebar */}
      <div className="hidden lg:flex lg:w-72 flex-col p-8" style={{ backgroundColor: 'hsl(var(--surface))', borderRight: '1px solid hsl(var(--border))' }}>
        <div className="flex items-center gap-2 mb-10">
          <AppLogo src={logoUrl || undefined} size={28} />
          <span className="font-bold text-lg" style={{ color: 'hsl(var(--foreground))' }}>{siteTitle}</span>
        </div>

        <div className="space-y-2">
          {steps.map(step => {
            const StepIcon = step.icon;
            const isCompleted = step.id < currentStep;
            const isActive = step.id === currentStep;
            return (
              <div
                key={step.id}
                className="flex items-center gap-3 p-3 rounded-xl transition-all"
                style={{ backgroundColor: isActive ? 'hsl(var(--primary-light))' : 'transparent' }}
              >
                <div
                  className="w-9 h-9 rounded-xl flex items-center justify-center shrink-0"
                  style={{
                    backgroundColor: isCompleted ? 'hsl(var(--success))' : isActive ? 'hsl(var(--primary))' : 'hsl(var(--muted))',
                  }}
                >
                  {isCompleted ? (
                    <Check size={16} className="text-white" />
                  ) : (
                    <StepIcon size={16} style={{ color: isActive ? 'white' : 'hsl(var(--muted-foreground))' }} />
                  )}
                </div>
                <div>
                  <p className="text-sm font-semibold" style={{ color: isActive ? 'hsl(var(--primary))' : 'hsl(var(--foreground))' }}>{step.title}</p>
                  <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{step.desc}</p>
                </div>
              </div>
            );
          })}
        </div>

        <div className="mt-auto">
          <div className="h-1.5 rounded-full overflow-hidden" style={{ backgroundColor: 'hsl(var(--muted))' }}>
            <div className="h-full rounded-full transition-all duration-500" style={{ width: `${progress}%`, backgroundColor: 'hsl(var(--primary))' }} />
          </div>
          <p className="text-xs mt-2" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('onboarding.stepOf', 'Step {{current}} of {{total}}', { current: currentStep, total: steps.length })}</p>
        </div>
      </div>

      {/* Main content */}
      <div className="flex-1 flex items-center justify-center p-6 lg:p-12">
        <div className="w-full max-w-lg">
          {/* Mobile progress */}
          <div className="lg:hidden mb-6">
            <div className="flex items-center justify-between mb-2">
              <span className="text-sm font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{steps[currentStep - 1].title}</span>
              <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{currentStep}/{steps.length}</span>
            </div>
            <div className="h-1.5 rounded-full overflow-hidden" style={{ backgroundColor: 'hsl(var(--muted))' }}>
              <div className="h-full rounded-full transition-all" style={{ width: `${(currentStep / steps.length) * 100}%`, backgroundColor: 'hsl(var(--primary))' }} />
            </div>
          </div>

          {/* Step 1: Restaurant Profile */}
          {currentStep === 1 && (
            <div>
              <h2 className="text-2xl font-bold mb-1" style={{ color: 'hsl(var(--foreground))' }}>{t('onboarding.step1.title', 'Restaurant Profile')}</h2>
              <p className="text-sm mb-6" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('onboarding.step1.subtitle', 'Basic information about your restaurant')}</p>
              <div className="space-y-4">
                <div>
                  <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('onboarding.restaurantName', 'Restaurant Name')} *</label>
                  <input className="input-base" placeholder={t('onboarding.restaurantNamePlaceholder', 'The Rustic Fork')} value={form.restaurantName} onChange={e => setForm({ ...form, restaurantName: e.target.value })} />
                </div>
                <div>
                  <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('onboarding.cuisineType', 'Cuisine Type')}</label>
                  <select className="input-base" value={form.cuisine} onChange={e => setForm({ ...form, cuisine: e.target.value })}>
                    <option value="">{t('onboarding.selectCuisine', 'Select cuisine type')}</option>
                    <option value="Italian">{t('onboarding.cuisine.italian', 'Italian')}</option>
                    <option value="American">{t('onboarding.cuisine.american', 'American')}</option>
                    <option value="Asian Fusion">{t('onboarding.cuisine.asianFusion', 'Asian Fusion')}</option>
                    <option value="Mexican">{t('onboarding.cuisine.mexican', 'Mexican')}</option>
                    <option value="Mediterranean">{t('onboarding.cuisine.mediterranean', 'Mediterranean')}</option>
                    <option value="Other">{t('onboarding.cuisine.other', 'Other')}</option>
                  </select>
                </div>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('onboarding.phoneNumber', 'Phone Number')}</label>
                    <input className="input-base" placeholder={t('onboarding.phonePlaceholder', '+1 (555) 000-0000')} value={form.phone} onChange={e => setForm({ ...form, phone: e.target.value })} />
                  </div>
                  <div>
                    <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('onboarding.website', 'Website (optional)')}</label>
                    <input className="input-base" placeholder={t('onboarding.websitePlaceholder', 'www.yourrestaurant.com')} value={form.website} onChange={e => setForm({ ...form, website: e.target.value })} />
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* Step 2: Branch Setup */}
          {currentStep === 2 && (
            <div>
              <h2 className="text-2xl font-bold mb-1" style={{ color: 'hsl(var(--foreground))' }}>{t('onboarding.step2.heading', 'First Branch Setup')}</h2>
              <p className="text-sm mb-6" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('onboarding.step2.subtitle', 'Set up your primary location')}</p>
              <div className="space-y-4">
                <div>
                  <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('onboarding.branchName', 'Branch Name')}</label>
                  <input className="input-base" placeholder={t('onboarding.branchNamePlaceholder', 'Main Branch / Downtown')} value={form.branchName} onChange={e => setForm({ ...form, branchName: e.target.value })} />
                </div>

                {/* Structured address */}
                <div className="space-y-3">
                  <div>
                    <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('onboarding.country', 'Country')}</label>
                    <select className="input-base" value={form.address.country} onChange={e => setForm({ ...form, address: { ...form.address, country: e.target.value } })}>
                      <option value="">{t('onboarding.selectCountry', 'Select a country')}</option>
                      {COUNTRIES.map(c => (
                        <option key={c.code} value={c.code}>{c.name}</option>
                      ))}
                    </select>
                  </div>
                  <div>
                    <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('onboarding.streetAddress', 'Street Address')}</label>
                    <input className="input-base" placeholder={t('onboarding.streetAddressPlaceholder', '123 Main Street')} value={form.address.line1} onChange={e => setForm({ ...form, address: { ...form.address, line1: e.target.value } })} />
                  </div>
                  <div>
                    <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('onboarding.streetAddress2', 'Apt / Suite / Unit (optional)')}</label>
                    <input className="input-base" placeholder={t('onboarding.streetAddress2Placeholder', 'Suite 200')} value={form.address.line2} onChange={e => setForm({ ...form, address: { ...form.address, line2: e.target.value } })} />
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('onboarding.city', 'City')}</label>
                      <input className="input-base" placeholder={t('onboarding.cityPlaceholder', 'San Francisco')} value={form.address.city} onChange={e => setForm({ ...form, address: { ...form.address, city: e.target.value } })} />
                    </div>
                    <div>
                      <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('onboarding.region', 'State / Region')}</label>
                      <input className="input-base" placeholder={t('onboarding.regionPlaceholder', 'CA')} value={form.address.region} onChange={e => setForm({ ...form, address: { ...form.address, region: e.target.value } })} />
                    </div>
                  </div>
                  <div>
                    <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('onboarding.postalCode', 'Postal Code')}</label>
                    <input className="input-base" placeholder={t('onboarding.postalCodePlaceholder', '94105')} value={form.address.postalCode} onChange={e => setForm({ ...form, address: { ...form.address, postalCode: e.target.value } })} />
                  </div>
                </div>

                <div>
                  <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('onboarding.timezone', 'Timezone')}</label>
                  <select className="input-base" value={form.timezone} onChange={e => setForm({ ...form, timezone: e.target.value })}>
                    {timezoneGroups.map(([region, zones]) => (
                      <optgroup key={region} label={region}>
                        {zones.map(z => (
                          <option key={z.zone} value={z.zone}>{z.label}</option>
                        ))}
                      </optgroup>
                    ))}
                  </select>
                </div>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('onboarding.openingTime', 'Opening Time')}</label>
                    <input type="time" className="input-base" value={form.openTime} onChange={e => setForm({ ...form, openTime: e.target.value })} />
                  </div>
                  <div>
                    <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('onboarding.closingTime', 'Closing Time')}</label>
                    <input type="time" className="input-base" value={form.closeTime} onChange={e => setForm({ ...form, closeTime: e.target.value })} />
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* Step 3: Menu Intro */}
          {currentStep === 3 && (
            <div>
              <h2 className="text-2xl font-bold mb-1" style={{ color: 'hsl(var(--foreground))' }}>{t('onboarding.step3.heading', 'Menu Setup')}</h2>
              <p className="text-sm mb-6" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('onboarding.step3.subtitle', 'Choose how you want to add your menu')}</p>
              <div className="space-y-3">
                {([
                  { id: 'manual' as const, title: t('onboarding.menu.manual', 'Add manually'), desc: t('onboarding.menu.manualDesc', 'Enter items one by one using our menu editor'), icon: '✏️' },
                  { id: 'bulk' as const, title: t('onboarding.menu.bulk', 'Bulk upload with AI'), desc: t('onboarding.menu.bulkDesc', 'Upload a PDF, image, or CSV — AI will extract items automatically'), icon: '🤖', recommended: true },
                  { id: 'later' as const, title: t('onboarding.menu.later', 'Skip for now'), desc: t('onboarding.menu.laterDesc', 'Set up your menu later from Menu Management'), icon: '⏭️' },
                ]).map(opt => {
                  const selected = form.menuChoice === opt.id;
                  return (
                    <div
                      key={opt.id}
                      role="button"
                      tabIndex={0}
                      className="flex items-start gap-4 p-4 rounded-xl border-2 cursor-pointer transition-all"
                      style={{
                        borderColor: selected ? 'hsl(var(--primary))' : 'hsl(var(--border))',
                        backgroundColor: selected ? 'hsl(var(--primary-light))' : 'hsl(var(--surface))',
                      }}
                      onClick={() => setForm({ ...form, menuChoice: opt.id })}
                      onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setForm({ ...form, menuChoice: opt.id }); } }}
                    >
                      <span className="text-2xl">{opt.icon}</span>
                      <div className="flex-1">
                        <div className="flex items-center gap-2">
                          <p className="font-semibold text-sm" style={{ color: 'hsl(var(--foreground))' }}>{opt.title}</p>
                          {'recommended' in opt && opt.recommended && <span className="badge badge-primary text-xs">{t('common.recommended', 'Recommended')}</span>}
                        </div>
                        <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>{opt.desc}</p>
                      </div>
                      {selected
                        ? <Check size={16} style={{ color: 'hsl(var(--primary))' }} />
                        : <ChevronRight size={16} style={{ color: 'hsl(var(--muted-foreground))' }} />}
                    </div>
                  );
                })}
              </div>
            </div>
          )}

          {/* Step 4: AI Agent */}
          {currentStep === 4 && (
            <div>
              <h2 className="text-2xl font-bold mb-1" style={{ color: 'hsl(var(--foreground))' }}>{t('onboarding.step4.heading', 'Configure AI Agent')}</h2>
              <p className="text-sm mb-6" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('onboarding.step4.subtitle', 'Personalize your AI assistant')}</p>
              <div className="space-y-4">
                <div>
                  <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('onboarding.agentName', 'Agent Name')}</label>
                  <input className="input-base" placeholder={t('onboarding.agentNamePlaceholder', 'Alex')} value={form.agentName} onChange={e => setForm({ ...form, agentName: e.target.value })} />
                  <p className="text-xs mt-1" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('onboarding.agentNameHint', 'Customers will see this name in conversations')}</p>
                </div>
                <div>
                  <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('onboarding.conversationStyle', 'Conversation Style')}</label>
                  <div className="grid grid-cols-3 gap-2">
                    {[
                      { id: 'friendly', label: t('onboarding.style.friendly', 'Friendly') },
                      { id: 'professional', label: t('onboarding.style.professional', 'Professional') },
                      { id: 'concise', label: t('onboarding.style.concise', 'Concise') },
                    ].map(style => (
                      <button
                        key={style.id}
                        type="button"
                        onClick={() => setForm({ ...form, agentStyle: style.id })}
                        className="py-2 px-3 rounded-lg border-2 text-sm font-medium transition-all"
                        style={{
                          borderColor: form.agentStyle === style.id ? 'hsl(var(--primary))' : 'hsl(var(--border))',
                          backgroundColor: form.agentStyle === style.id ? 'hsl(var(--primary-light))' : 'hsl(var(--surface))',
                          color: form.agentStyle === style.id ? 'hsl(var(--primary))' : 'hsl(var(--foreground-secondary))',
                        }}
                      >
                        {style.label}
                      </button>
                    ))}
                  </div>
                </div>
                <div className="card p-4 space-y-3">
                  <p className="text-xs font-semibold uppercase tracking-wider" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('onboarding.enableChannels', 'Enable Channels')}</p>
                  {[
                    { key: 'voiceEnabled', label: t('onboarding.channel.voice', 'Voice Agent'), desc: t('onboarding.channel.voiceDesc', 'Handle inbound phone calls') },
                    { key: 'chatEnabled', label: t('onboarding.channel.chat', 'Chat Agent'), desc: t('onboarding.channel.chatDesc', 'Web chat & messaging apps') },
                  ].map(ch => (
                    <div key={ch.key} className="flex items-center justify-between">
                      <div>
                        <p className="text-sm font-medium" style={{ color: 'hsl(var(--foreground))' }}>{ch.label}</p>
                        <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{ch.desc}</p>
                      </div>
                      <button
                        type="button"
                        onClick={() => setForm({ ...form, [ch.key]: !form[ch.key as keyof typeof form] })}
                        className="w-10 h-6 rounded-full transition-all relative"
                        style={{ backgroundColor: form[ch.key as keyof typeof form] ? 'hsl(var(--primary))' : 'hsl(var(--muted))' }}
                      >
                        <span
                          className="absolute top-1 w-4 h-4 bg-white rounded-full shadow transition-all"
                          style={{ left: form[ch.key as keyof typeof form] ? '22px' : '2px' }}
                        />
                      </button>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          )}

          {saveError && (
            <div className="mt-4 p-3 rounded-lg text-sm" style={{ backgroundColor: 'hsl(0, 84%, 97%)', color: 'hsl(0, 84%, 44%)', border: '1px solid hsl(0, 84%, 90%)' }}>
              {t('onboarding.saveFailed', 'Could not save your details, but you can continue and edit them later from Settings.')} <button type="button" className="underline ml-1" onClick={() => { setSaveError(null); window.location.href = '/restaurant-dashboard'; }}>{t('onboarding.continueAnyway', 'Continue anyway')}</button>
            </div>
          )}

          {/* Navigation */}
          <div className="flex items-center justify-between mt-8">
            <button
              onClick={handleBack}
              disabled={currentStep === 1 || saving}
              className="btn-secondary disabled:opacity-40"
            >
              <ChevronLeft size={16} /> {t('common.back', 'Back')}
            </button>
            <button onClick={handleNext} disabled={saving} className="btn-primary disabled:opacity-60">
              {currentStep === steps.length ? (
                <>{saving ? t('onboarding.saving', 'Saving…') : t('onboarding.goToDashboard', 'Go to Dashboard')} <ChevronRight size={16} /></>
              ) : (
                <>{t('common.continue', 'Continue')} <ChevronRight size={16} /></>
              )}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
