// ═══════════════════════════════════════════════════════════════════
// KINGDOMID COMMAND — New Client Onboarding Form
// Deploys a fully configured client in one submission
// ═══════════════════════════════════════════════════════════════════

import { useState, FormEvent, useRef, useCallback } from 'react';
import { useNavigate }         from 'react-router-dom';
import { apiGet, apiPost }     from '../lib/firebase';
import {
  CheckCircle, AlertCircle, Loader, ChevronRight,
  Cpu, Mail,
} from 'lucide-react';

const NICHES = [
  { value: 'christian_counseling', label: 'Christian Counseling Center',            desc: '15 pre-loaded FAQs, crisis protocol, trauma-informed tone, faith-based language, HIPAA-aware call flow' },
  { value: 'senior_care',          label: 'Senior Care / Home Care Agency',         desc: '15 pre-loaded FAQs, caregiver matching flow, dementia care protocol, veteran benefits handling, compassionate tone' },
  { value: 'medical_pediatric',    label: 'Medical / Pediatric Practice',           desc: '15 pre-loaded FAQs, emergency triage protocol, insurance verification flow, HIPAA-compliant, pediatric-friendly tone' },
  { value: 'chiropractic_pt',      label: 'Chiropractic / Physical Therapy',        desc: '15 pre-loaded FAQs, auto accident injury flow, insurance verification, pain-empathy tone, workers comp handling' },
  { value: 'christian_school',     label: 'Christian Private School',               desc: '15 pre-loaded FAQs, enrollment inquiry flow, tuition and financial aid handling, Kingdom-centered language' },
  { value: 'veterinary',           label: 'Veterinary Clinic',                      desc: '15 pre-loaded FAQs, emergency triage for pets, poison control referral, compassionate pet-parent tone' },
  { value: 'funeral_home',         label: 'Funeral Home',                           desc: '15 pre-loaded FAQs, grief-sensitive tone, first-call death protocol, pre-planning and veterans benefits flow' },
  { value: 'family_law',           label: 'Family Law Firm',                        desc: '15 pre-loaded FAQs, domestic violence safety protocol, no legal advice guardrails, empathetic intake flow' },
  { value: 'home_services',        label: 'Home Services (HVAC / Plumbing / Electrical)', desc: '15 pre-loaded FAQs, gas leak emergency protocol, dispatch urgency triage, trust-building Christian values tone' },
  { value: 'church_ministry',      label: 'Church / Ministry (1000+ members)',      desc: '15 pre-loaded FAQs, spiritual crisis protocol, small group connection flow, warm Spirit-filled welcome tone' },
  { value: 'other',                label: 'Other',                                  desc: 'General business configuration — customize FAQs and call flow after onboarding' },
];

const PLANS = [
  { value: 'starter', label: 'Starter', monthly: 797, setup: 497, desc: 'KingdomVoice + KingdomReach + KingdomCRM' },
  { value: 'growth',  label: 'Growth',  monthly: 1297, setup: 497, desc: '+ KingdomSchedule, KingdomReview, KingdomNurture' },
  { value: 'premium', label: 'Premium', monthly: 1997, setup: 497, desc: 'All 12 Kingdom systems included' },
  { value: 'custom',  label: 'Custom',  monthly: 0, setup: 497, desc: 'Enterprise / negotiated pricing' },
];

const VOICE_PROFILES = [
  { value: 'female_en', label: 'Female — English', short: 'Female English', desc: 'Warm, confident English-speaking receptionist', gender: 'female', language: 'en' },
  { value: 'male_en',   label: 'Male — English',   short: 'Male English',   desc: 'Professional, reassuring English-speaking receptionist', gender: 'male', language: 'en' },
  { value: 'female_es', label: 'Female — Spanish', short: 'Female Spanish', desc: 'Warm, natural Spanish-speaking receptionist', gender: 'female', language: 'es' },
  { value: 'male_es',   label: 'Male — Spanish',   short: 'Male Spanish',   desc: 'Professional, natural Spanish-speaking receptionist', gender: 'male', language: 'es' },
] as const;

const FAITH_CLOSINGS = [
  'Have a blessed day!',
  "We'll be keeping you in our prayers.",
  'God bless you.',
  "It's our honor to serve you.",
  'Thank you — and God bless!',
];

type Step = 'business' | 'owner' | 'plan' | 'faith' | 'review' | 'deploying' | 'done';

const STEPS: { key: Step; label: string }[] = [
  { key: 'business', label: 'Business' },
  { key: 'owner',    label: 'Owner' },
  { key: 'plan',     label: 'Plan' },
  { key: 'faith',    label: 'Faith' },
  { key: 'review',   label: 'Review' },
];

const PLAN_LABEL: Record<string, string> = {
  starter: 'Starter — $797/mo + $497 setup',
  growth:  'Growth — $1,297/mo + $497 setup',
  premium: 'Premium — $1,997/mo + $497 setup',
  custom:  'Custom — $497 setup + negotiated monthly',
};

const NICHE_LABEL: Record<string, string> = {
  christian_counseling: 'Christian Counseling Center',
  senior_care:          'Senior Care / Home Care Agency',
  medical_pediatric:    'Medical / Pediatric Practice',
  chiropractic_pt:      'Chiropractic / Physical Therapy',
  christian_school:     'Christian Private School',
  veterinary:           'Veterinary Clinic',
  funeral_home:         'Funeral Home',
  family_law:           'Family Law Firm',
  home_services:        'Home Services',
  church_ministry:      'Church / Ministry',
  other:                'Other',
};

export default function NewClientPage() {
  const navigate              = useNavigate();
  const [step, setStep]       = useState<Step>('business');
  const [error, setError]     = useState('');
  const [result, setResult]   = useState<any>(null);
  const subdomainTimer        = useRef<ReturnType<typeof setTimeout> | null>(null);
  const [subdomainStatus, setSubdomainStatus] = useState<'idle' | 'checking' | 'available' | 'taken'>('idle');
  const [nicheOpen, setNicheOpen]           = useState(false);

  const [businessName, setBusinessName]     = useState('');
  const [niche, setNiche]                   = useState('christian_counseling');
  const [subdomain, setSubdomain]           = useState('');
  const [areaCode, setAreaCode]             = useState('');
  const [state, setState]                   = useState('');
  const [aiName, setAiName]                 = useState('Grace');
  const [voiceProfile, setVoiceProfile]     = useState<'female_en' | 'male_en' | 'female_es' | 'male_es'>('female_en');
  const selectedVoice = VOICE_PROFILES.find(v => v.value === voiceProfile) || VOICE_PROFILES[0];

  const [ownerName, setOwnerName]           = useState('');
  const [ownerEmail, setOwnerEmail]         = useState('');
  const [ownerPhone, setOwnerPhone]         = useState('');
  const [escalationNumber, setEscalation]   = useState('');

  const [subscriptionPlan, setPlan]         = useState('starter');
  const [languages, setLanguages]           = useState(['en']);

  const [faithAffiliation, setFaithAffil]  = useState('');
  const [faithClosing, setFaithClosing]     = useState('Have a blessed day!');
  const [scriptureInSms, setScriptureSms]  = useState(false);
  const [scriptureInEmail, setScriptureEmail] = useState(false);

  // ── Subdomain check ───────────────────────────────────────────────
  const checkSubdomain = useCallback(async (val: string) => {
    if (!val || val.length < 3) { setSubdomainStatus('idle'); return; }
    setSubdomainStatus('checking');
    try {
      const res = await apiGet<{ available: boolean; subdomain: string }>(
        `/api/onboarding/check-subdomain?subdomain=${encodeURIComponent(val)}`
      );
      setSubdomain(res.subdomain);
      setSubdomainStatus(res.available ? 'available' : 'taken');
    } catch {
      setSubdomainStatus('idle');
    }
  }, []);

  const handleBusinessNameChange = (val: string) => {
    setBusinessName(val);
    // Only auto-fill subdomain if user hasn't typed one manually
    if (!subdomain) {
      const slug = val.toLowerCase().replace(/[^a-z0-9]/g, '').slice(0, 20);
      if (slug) {
        setSubdomain(slug);
        if (subdomainTimer.current) clearTimeout(subdomainTimer.current);
        subdomainTimer.current = setTimeout(() => checkSubdomain(slug), 900);
      }
    }
  };

  const handleSubdomainChange = (val: string) => {
    const clean = val.toLowerCase().replace(/[^a-z0-9-]/g, '');
    setSubdomain(clean);
    setSubdomainStatus('idle');
    if (subdomainTimer.current) clearTimeout(subdomainTimer.current);
    if (clean.length >= 3) {
      subdomainTimer.current = setTimeout(() => checkSubdomain(clean), 600);
    }
  };

  // ── Deploy ────────────────────────────────────────────────────────
  const deploy = async () => {
    setStep('deploying');
    setError('');
    try {
      const res = await apiPost<any>('/api/onboarding/clients', {
        businessName,
        niche,
        ownerName,
        ownerEmail,
        ownerPhone,
        escalationNumber,
        subdomain,
        subscriptionPlan,
        areaCode,
        state,
        aiName,
        faithAffiliation,
        faithClosingPhrase: faithClosing,
        scriptureInSms,
        scriptureInEmail,
        languagesSupported: languages,
        voiceGender: selectedVoice.gender,
        voiceProfile,
        sendWelcomeEmail: true,
        accessLabel: 'Command Center',
      });
      setResult(res);
      setStep('done');
    } catch (err: any) {
      setError(err.message || 'Deployment failed');
      setStep('review');
    }
  };

  // ── Step indicator ────────────────────────────────────────────────
  const stepKeys  = STEPS.map(s => s.key);
  const currentIdx = stepKeys.indexOf(step as any);

  const StepIndicator = () => (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 36 }}>
      {STEPS.map((s, i) => {
        const done   = currentIdx > i;
        const active = currentIdx === i;
        return (
          <div key={s.key} style={{ display: 'flex', alignItems: 'center' }}>
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
              <div style={{
                width: 32, height: 32, borderRadius: '50%',
                background: done ? 'var(--success)' : active ? 'var(--navy)' : 'var(--gray-200)',
                color: done || active ? 'white' : 'var(--gray-400)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 16, fontWeight: 700, transition: 'all 0.2s',
              }}>
                {done ? <CheckCircle size={16} /> : i + 1}
              </div>
              <span style={{
                fontSize: 15, fontWeight: active ? 700 : 500, whiteSpace: 'nowrap',
                color: active ? 'var(--navy)' : 'var(--gray-400)',
              }}>{s.label}</span>
            </div>
            {i < STEPS.length - 1 && (
              <div style={{
                width: 40, height: 2, margin: '0 4px', marginBottom: 22,
                background: done ? 'var(--success)' : 'var(--gray-200)',
                transition: 'background 0.2s',
              }} />
            )}
          </div>
        );
      })}
    </div>
  );

  const isDeploying = step === 'deploying' || step === 'done';

  return (
    <div className="page-content">
      <div style={{ maxWidth: 680, margin: '0 auto' }}>
        {!isDeploying && (
          <button className="btn btn-ghost btn-sm" onClick={() => navigate('/clients')} style={{ marginBottom: 24 }}>
            ← Back to Clients
          </button>
        )}

        <div className="card">
          <div style={{
            background: 'linear-gradient(135deg, var(--navy) 0%, var(--navy-light) 100%)',
            padding: '28px 32px', borderBottom: '1px solid var(--gray-200)',
          }}>
            <h1 style={{ color: 'white', fontSize: '2rem', fontFamily: 'Inter, sans-serif', fontWeight: 700 }}>
              Onboard New Client
            </h1>
            <p style={{ color: 'rgba(255,255,255,0.6)', fontSize: 16, marginTop: 4 }}>
              Creates the workspace, AI receptionist, login access, and welcome email automatically
            </p>
          </div>

          <div className="card-body" style={{ padding: '36px 40px' }}>
            {!isDeploying && <StepIndicator />}

            {error && step !== 'review' && (
              <div className="alert alert-error" style={{ marginBottom: 20 }}>
                <AlertCircle size={18} />{error}
              </div>
            )}

            {/* ── STEP: BUSINESS ───────────────────────────────── */}
            {step === 'business' && (
              <>
                <h2 style={{ marginBottom: 6 }}>Business Information</h2>
                <p className="text-muted" style={{ marginBottom: 28 }}>Tell us about the business you're onboarding</p>

                <div className="form-group">
                  <label className="form-label">Business Name <span>*</span></label>
                  <input
                    className="form-input"
                    value={businessName}
                    onChange={e => handleBusinessNameChange(e.target.value)}
                    placeholder="Grace Counseling Center"
                    autoFocus
                  />
                </div>

                <div className="form-group" style={{ position: 'relative' }}>
                  <label className="form-label">Industry / Niche <span>*</span></label>
                  <div
                    onClick={() => setNicheOpen(o => !o)}
                    style={{
                      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                      padding: '9px 12px', border: '1.5px solid var(--gray-200)',
                      borderRadius: 'var(--radius-sm)', cursor: 'pointer', background: 'white',
                      fontSize: 15, color: 'var(--navy)', fontWeight: 500,
                    }}
                  >
                    <span>{NICHES.find(n => n.value === niche)?.label || 'Select a niche'}</span>
                    <span style={{ fontSize: 16, color: 'var(--gray-400)' }}>▼</span>
                  </div>
                  {nicheOpen && (
                    <div style={{
                      position: 'absolute', top: '100%', left: 0, right: 0, zIndex: 100,
                      background: 'white', border: '1.5px solid var(--gray-200)',
                      borderRadius: 'var(--radius-sm)', boxShadow: '0 8px 24px rgba(13,27,62,0.12)',
                      maxHeight: 340, overflowY: 'auto',
                    }}>
                      {NICHES.map(n => (
                        <div
                          key={n.value}
                          onClick={() => { setNiche(n.value); setNicheOpen(false); }}
                          style={{
                            padding: '10px 14px', cursor: 'pointer',
                            background: niche === n.value ? 'var(--tan)' : 'white',
                            borderBottom: '1px solid var(--gray-100)',
                            transition: 'background 0.1s',
                          }}
                          onMouseEnter={e => { if (niche !== n.value) (e.currentTarget as HTMLDivElement).style.background = 'var(--gray-100)'; }}
                          onMouseLeave={e => { (e.currentTarget as HTMLDivElement).style.background = niche === n.value ? 'var(--tan)' : 'white'; }}
                        >
                          <div style={{ fontWeight: 600, fontSize: 15, color: 'var(--navy)', marginBottom: 3 }}>
                            {niche === n.value && <span style={{ color: 'var(--gold)', marginRight: 6 }}>✓</span>}
                            {n.label}
                          </div>
                          <div style={{ fontSize: 15, color: 'var(--gray-600)', lineHeight: 1.5 }}>{n.desc}</div>
                        </div>
                      ))}
                    </div>
                  )}
                </div>

                <div className="form-group">
                  <label className="form-label">Client Subdomain <span>*</span></label>
                  <div style={{ position: 'relative' }}>
                    <input
                      className="form-input"
                      value={subdomain}
                      onChange={e => handleSubdomainChange(e.target.value)}
                      placeholder="gracecounseling"
                      style={{
                        paddingRight: 140,
                        borderColor: subdomainStatus === 'taken' ? 'var(--error)' : subdomainStatus === 'available' ? 'var(--success)' : undefined,
                      }}
                    />
                    <span style={{ position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)', fontSize: 15, color: 'var(--gray-400)' }}>
                      .kingdomid.app
                    </span>
                  </div>
                  {subdomainStatus === 'checking'  && <p className="form-hint">Checking availability...</p>}
                  {subdomainStatus === 'available' && <p style={{ fontSize: 16, color: 'var(--success)', marginTop: 5 }}>✓ Available — {subdomain}.kingdomid.app</p>}
                  {subdomainStatus === 'taken'     && <p className="form-error">✗ This subdomain is already taken</p>}
                </div>

                <div className="form-row">
                  <div className="form-group">
                    <label className="form-label">Area Code <span>*</span></label>
                    <input
                      className="form-input"
                      value={areaCode}
                      onChange={e => setAreaCode(e.target.value.replace(/\D/g, '').slice(0, 3))}
                      placeholder="615"
                      maxLength={3}
                      type="tel"
                      autoComplete="off"
                      inputMode="numeric"
                    />
                    <p className="form-hint">For their local phone number</p>
                  </div>
                  <div className="form-group">
                    <label className="form-label">State</label>
                    <input
                      className="form-input"
                      value={state}
                      onChange={e => setState(e.target.value.toUpperCase().slice(0, 2))}
                      placeholder="TN"
                      maxLength={2}
                      autoComplete="off"
                    />
                    <p className="form-hint">Fallback if area code unavailable</p>
                  </div>
                </div>

                <div className="form-group">
                  <label className="form-label">AI Receptionist Name</label>
                  <input
                    className="form-input"
                    value={aiName}
                    onChange={e => setAiName(e.target.value)}
                    placeholder="Grace"
                  />
                  <p className="form-hint">The name the AI uses when answering calls</p>
                </div>

                <div className="form-group">
                  <label className="form-label">AI Receptionist Voice <span>*</span></label>
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, minmax(0, 1fr))', gap: 12 }}>
                    {VOICE_PROFILES.map(v => (
                      <button
                        type="button"
                        key={v.value}
                        onClick={() => setVoiceProfile(v.value)}
                        style={{
                          textAlign: 'left', cursor: 'pointer', transition: 'all 0.15s',
                          border: `2px solid ${voiceProfile === v.value ? 'var(--gold)' : 'var(--gray-200)'}`,
                          borderRadius: 'var(--radius)', padding: '16px',
                          background: voiceProfile === v.value ? 'var(--tan)' : 'var(--surface)',
                          boxShadow: voiceProfile === v.value ? '0 8px 20px rgba(201,162,39,0.12)' : 'none',
                        }}
                      >
                        <div style={{ fontWeight: 800, fontSize: 17, color: 'var(--navy)', marginBottom: 5 }}>{v.label}</div>
                        <div style={{ fontSize: 15, color: 'var(--gray-500)', lineHeight: 1.45 }}>{v.desc}</div>
                      </button>
                    ))}
                  </div>
                  <p className="form-hint">Choose the dedicated voice profile this client will use. Additional languages can still be enabled below.</p>
                </div>

                <button
                  className="btn btn-primary"
                  onClick={() => {
                    if (!businessName || !subdomain || !areaCode) { setError('Please fill in all required fields'); return; }
                    if (subdomainStatus === 'taken') { setError('Please choose a different subdomain'); return; }
                    setError(''); setStep('owner');
                  }}
                >
                  Continue <ChevronRight size={16} />
                </button>
              </>
            )}

            {/* ── STEP: OWNER ──────────────────────────────────── */}
            {step === 'owner' && (
              <>
                <h2 style={{ marginBottom: 6 }}>Owner & Contact</h2>
                <p className="text-muted" style={{ marginBottom: 28 }}>The owner's email becomes their Command Center login and receives their secure welcome email</p>

                <div className="form-row">
                  <div className="form-group">
                    <label className="form-label">Owner Full Name <span>*</span></label>
                    <input className="form-input" value={ownerName} onChange={e => setOwnerName(e.target.value)} placeholder="Sarah Johnson" autoFocus />
                  </div>
                  <div className="form-group">
                    <label className="form-label">Owner Email <span>*</span></label>
                    <input type="email" className="form-input" value={ownerEmail} onChange={e => setOwnerEmail(e.target.value)} placeholder="sarah@gracecounseling.com" />
                  </div>
                </div>

                <div style={{ display: 'flex', gap: 14, padding: '16px 18px', borderRadius: 'var(--radius)', background: 'var(--info-bg)', border: '1px solid rgba(91,141,239,0.25)', marginBottom: 22 }}>
                  <Mail size={22} color="var(--info)" style={{ flexShrink: 0, marginTop: 2 }} />
                  <div>
                    <div style={{ fontWeight: 800, color: 'var(--navy)', fontSize: 16, marginBottom: 4 }}>Welcome email will be sent automatically</div>
                    <div style={{ color: 'var(--gray-600)', fontSize: 15, lineHeight: 1.55 }}>It will include the Command Center link, login email, temporary password, plan details, assigned phone number, and a guided next-step checklist.</div>
                  </div>
                </div>

                <div className="form-row">
                  <div className="form-group">
                    <label className="form-label">Owner Phone</label>
                    <input className="form-input" value={ownerPhone} onChange={e => setOwnerPhone(e.target.value)} placeholder="+1 615 555 0100" />
                  </div>
                  <div className="form-group">
                    <label className="form-label">Escalation Number <span>*</span></label>
                    <input className="form-input" value={escalationNumber} onChange={e => setEscalation(e.target.value)} placeholder="+1 615 555 0101" />
                    <p className="form-hint">AI transfers urgent calls here</p>
                  </div>
                </div>

                <div style={{ display: 'flex', gap: 12, marginTop: 8 }}>
                  <button className="btn btn-outline" onClick={() => setStep('business')}>Back</button>
                  <button className="btn btn-primary" onClick={() => {
                    if (!ownerName || !ownerEmail || !escalationNumber) { setError('Please fill in all required fields'); return; }
                    setError(''); setStep('plan');
                  }}>
                    Continue <ChevronRight size={16} />
                  </button>
                </div>
              </>
            )}

            {/* ── STEP: PLAN ───────────────────────────────────── */}
            {step === 'plan' && (
              <>
                <h2 style={{ marginBottom: 6 }}>Subscription Plan</h2>
                <p className="text-muted" style={{ marginBottom: 28 }}>Select the plan this client has subscribed to</p>

                <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginBottom: 24 }}>
                  {PLANS.map(p => (
                    <div
                      key={p.value}
                      onClick={() => setPlan(p.value)}
                      style={{
                        border: `2px solid ${subscriptionPlan === p.value ? 'var(--navy)' : 'var(--gray-200)'}`,
                        borderRadius: 'var(--radius)', padding: '16px 20px', cursor: 'pointer',
                        background: subscriptionPlan === p.value ? 'var(--tan)' : 'white',
                        transition: 'all 0.15s', display: 'flex', alignItems: 'center', gap: 16,
                      }}
                    >
                      <div style={{
                        width: 20, height: 20, borderRadius: '50%', flexShrink: 0,
                        border: `2px solid ${subscriptionPlan === p.value ? 'var(--navy)' : 'var(--gray-300)'}`,
                        background: subscriptionPlan === p.value ? 'var(--navy)' : 'white',
                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                      }}>
                        {subscriptionPlan === p.value && <div style={{ width: 8, height: 8, borderRadius: '50%', background: 'white' }} />}
                      </div>
                      <div>
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 12 }}>
                          <div style={{ fontWeight: 800, color: 'var(--navy)', fontSize: 18 }}>{p.label}</div>
                          <div style={{ fontWeight: 800, color: 'var(--gold-dark)', fontSize: 17 }}>{p.value === 'custom' ? 'Custom monthly' : `$${p.monthly.toLocaleString()}/mo`}</div>
                        </div>
                        <div style={{ fontSize: 15, color: 'var(--gray-500)', marginTop: 4 }}>{p.desc}</div>
                        <div style={{ fontSize: 14, color: 'var(--gray-500)', marginTop: 5 }}><strong>$497 one-time setup</strong></div>
                      </div>
                    </div>
                  ))}
                </div>

                {subscriptionPlan !== 'custom' && (() => {
                  const plan = PLANS.find(p => p.value === subscriptionPlan)!;
                  return (
                    <div style={{ background: 'var(--navy)', color: 'white', borderRadius: 'var(--radius)', padding: '18px 20px', marginBottom: 24, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                      <div>
                        <div style={{ fontSize: 14, color: 'rgba(255,255,255,0.62)', fontWeight: 700, textTransform: 'uppercase', letterSpacing: 1 }}>Total due at activation</div>
                        <div style={{ fontSize: 15, color: 'rgba(255,255,255,0.75)', marginTop: 4 }}>${plan.monthly.toLocaleString()} first month + $497 setup</div>
                      </div>
                      <div style={{ fontSize: 28, fontWeight: 900, color: 'var(--gold)' }}>${(plan.monthly + plan.setup).toLocaleString()}</div>
                    </div>
                  );
                })()}

                <div className="form-group">
                  <label className="form-label">Languages</label>
                  <div style={{ display: 'flex', gap: 12 }}>
                    {[{ val: 'en', label: '🇺🇸 English' }, { val: 'es', label: '🇪🇸 Spanish' }].map(lang => (
                      <label key={lang.val} style={{ display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer', fontSize: 16 }}>
                        <input
                          type="checkbox"
                          checked={languages.includes(lang.val)}
                          onChange={e => {
                            const next = e.target.checked ? [...languages, lang.val] : languages.filter(l => l !== lang.val);
                            if (next.length > 0) setLanguages(next);
                          }}
                        />
                        {lang.label}
                      </label>
                    ))}
                  </div>
                  <p className="form-hint">Deploy separate AI assistants for each language</p>
                </div>

                <div style={{ display: 'flex', gap: 12, marginTop: 8 }}>
                  <button className="btn btn-outline" onClick={() => setStep('owner')}>Back</button>
                  <button className="btn btn-primary" onClick={() => { setError(''); setStep('faith'); }}>
                    Continue <ChevronRight size={16} />
                  </button>
                </div>
              </>
            )}

            {/* ── STEP: FAITH ──────────────────────────────────── */}
            {step === 'faith' && (
              <>
                <h2 style={{ marginBottom: 6 }}>Faith Preferences</h2>
                <p className="text-muted" style={{ marginBottom: 28 }}>Customize how faith is expressed in every interaction</p>

                <div className="form-group">
                  <label className="form-label">Faith Affiliation</label>
                  <input
                    className="form-input"
                    value={faithAffiliation}
                    onChange={e => setFaithAffil(e.target.value)}
                    placeholder="Non-denominational, Baptist, etc."
                  />
                  <p className="form-hint">Optional — helps tailor language to their tradition</p>
                </div>

                <div className="form-group">
                  <label className="form-label">AI Closing Phrase</label>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                    {FAITH_CLOSINGS.map(phrase => (
                      <label key={phrase} style={{
                        display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer', fontSize: 16,
                        padding: '10px 14px', borderRadius: 'var(--radius-sm)',
                        background: faithClosing === phrase ? 'var(--tan)' : 'transparent',
                        border: `1.5px solid ${faithClosing === phrase ? 'var(--gold)' : 'var(--gray-200)'}`,
                      }}>
                        <input type="radio" name="faithClosing" value={phrase} checked={faithClosing === phrase} onChange={() => setFaithClosing(phrase)} />
                        {phrase}
                      </label>
                    ))}
                  </div>
                </div>

                <div style={{ display: 'flex', gap: 24, marginBottom: 24 }}>
                  <label className="toggle-wrap">
                    <button className={`toggle ${scriptureInSms ? 'on' : ''}`} onClick={() => setScriptureSms(v => !v)} />
                    <span style={{ fontSize: 16 }}>Include scripture in SMS</span>
                  </label>
                  <label className="toggle-wrap">
                    <button className={`toggle ${scriptureInEmail ? 'on' : ''}`} onClick={() => setScriptureEmail(v => !v)} />
                    <span style={{ fontSize: 16 }}>Include scripture in emails</span>
                  </label>
                </div>

                <div style={{ display: 'flex', gap: 12 }}>
                  <button className="btn btn-outline" onClick={() => setStep('plan')}>Back</button>
                  <button className="btn btn-primary" onClick={() => { setError(''); setStep('review'); }}>
                    Review & Deploy <ChevronRight size={16} />
                  </button>
                </div>
              </>
            )}

            {/* ── STEP: REVIEW ─────────────────────────────────── */}
            {step === 'review' && (
              <>
                <h2 style={{ marginBottom: 6 }}>Review & Deploy</h2>
                <p className="text-muted" style={{ marginBottom: 24 }}>Confirm everything looks right, then deploy</p>

                <div style={{ background: 'var(--tan)', borderRadius: 'var(--radius)', padding: '20px 24px', marginBottom: 24 }}>
                  {[
                    { label: 'Business',     value: businessName },
                    { label: 'Niche',        value: NICHE_LABEL[niche] || niche },
                    { label: 'Command Center', value: `https://${subdomain}.kingdomid.app` },
                    { label: 'Phone Area',   value: `Area code ${areaCode}${state ? ` / ${state}` : ''}` },
                    { label: 'AI Name',      value: aiName },
                    { label: 'Owner',        value: `${ownerName} (${ownerEmail})` },
                    { label: 'Escalation',   value: escalationNumber },
                    { label: 'Plan',         value: PLAN_LABEL[subscriptionPlan] },
                    { label: 'Languages',    value: languages.map(l => l === 'en' ? 'English' : 'Spanish').join(', ') },
                    { label: 'Faith Close',  value: faithClosing },
            { label: 'AI Voice',     value: selectedVoice.short },
                    { label: 'Welcome Email', value: ownerEmail },
                  ].map(row => (
                    <div key={row.label} style={{
                      display: 'flex', justifyContent: 'space-between', padding: '8px 0',
                      borderBottom: '1px solid var(--tan-dark)', fontSize: 16, gap: 16,
                    }}>
                      <span style={{ color: 'var(--gray-500)', fontWeight: 500, flexShrink: 0 }}>{row.label}</span>
                      <span style={{ color: 'var(--navy)', fontWeight: 600, textAlign: 'right' }}>{row.value}</span>
                    </div>
                  ))}
                </div>

                <div className="alert alert-info" style={{ marginBottom: 24 }}>
                  <Cpu size={18} style={{ flexShrink: 0 }} />
                  <div>
                    <strong>This will automatically:</strong>
                    <ul style={{ marginTop: 6, paddingLeft: 16, fontSize: 15 }}>
                      <li>Deploy {languages.length > 1 ? '2 VAPI AI assistants (EN + ES)' : '1 VAPI AI assistant (EN)'}</li>
                      <li>Provision a local phone number in area code {areaCode}</li>
                      <li>Create {ownerName}'s Command Center login at {subdomain}.kingdomid.app</li>
                      <li>Set up 5 default automation workflows</li>
                      <li>Send the Command Center welcome email and temporary login to {ownerEmail}</li>
                    </ul>
                  </div>
                </div>

                {error && (
                  <div className="alert alert-error" style={{ marginBottom: 16 }}>
                    <AlertCircle size={18} />{error}
                  </div>
                )}

                <div style={{ display: 'flex', gap: 12 }}>
                  <button className="btn btn-outline" onClick={() => setStep('faith')}>Back</button>
                  <button className="btn btn-gold btn-lg" onClick={deploy} style={{ flex: 1, justifyContent: 'center' }}>
                    🚀 Deploy {businessName}
                  </button>
                </div>
              </>
            )}

            {/* ── STEP: DEPLOYING ──────────────────────────────── */}
            {step === 'deploying' && (
              <div style={{ textAlign: 'center', padding: '40px 20px' }}>
                <div style={{
                  width: 72, height: 72, borderRadius: '50%', background: 'var(--tan)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 24px',
                }}>
                  <Loader size={32} color="var(--gold)" style={{ animation: 'spin 1s linear infinite' }} />
                </div>
                <h2 style={{ marginBottom: 8 }}>Deploying {businessName}...</h2>
                <p className="text-muted" style={{ maxWidth: 360, margin: '0 auto 32px' }}>
                  Setting up AI assistants, provisioning phone number, creating Command Center access. This takes about 15–30 seconds.
                </p>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 10, maxWidth: 300, margin: '0 auto' }}>
                  {['Creating client profile', 'Deploying AI assistant', 'Provisioning phone number', 'Setting up workflows', 'Sending Command Center welcome email'].map((item, i) => (
                    <div key={item} style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 16, color: 'var(--gray-600)' }}>
                      <Loader size={14} color="var(--gold)" style={{ animation: 'spin 1s linear infinite', animationDelay: `${i * 0.1}s` }} />
                      {item}
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* ── STEP: DONE ───────────────────────────────────── */}
            {step === 'done' && (
              <div style={{ textAlign: 'center', padding: '32px 20px' }}>
                <div style={{
                  width: 80, height: 80, borderRadius: '50%', background: 'var(--success-bg)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 24px',
                }}>
                  <CheckCircle size={40} color="var(--success)" />
                </div>
                <h2 style={{ marginBottom: 8 }}>🎉 {businessName} is Live!</h2>
                <p className="text-muted" style={{ marginBottom: 32 }}>The Command Center is ready and the welcome email has been sent to the client.</p>

                <div style={{ background: 'var(--tan)', borderRadius: 'var(--radius)', padding: '20px 24px', marginBottom: 28, textAlign: 'left' }}>
                  {[
                    { label: 'Command Center', value: result?.dashboardUrl },
                    { label: 'Welcome Email', value: ownerEmail },
                    { label: 'Plan', value: PLAN_LABEL[subscriptionPlan] },
                    { label: 'Phone Number',  value: result?.phoneNumber },
                    { label: 'Client ID',     value: result?.clientId },
                  ].map(row => (
                    <div key={row.label} style={{ display: 'flex', justifyContent: 'space-between', padding: '10px 0', borderBottom: '1px solid var(--tan-dark)', fontSize: 16 }}>
                      <span style={{ color: 'var(--gray-500)', fontWeight: 500 }}>{row.label}</span>
                      <span style={{ color: 'var(--navy)', fontWeight: 700 }}>{row.value}</span>
                    </div>
                  ))}
                </div>

                <div style={{ display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap' }}>
                  <button className="btn btn-outline" onClick={() => navigate('/clients')}>View All Clients</button>
                  <button className="btn btn-primary" onClick={() => navigate(`/clients/${result?.clientId}`)}>Open Client Record</button>
                  <button className="btn btn-gold" onClick={() => {
                    setStep('business');
                    setBusinessName(''); setOwnerName(''); setOwnerEmail('');
                    setOwnerPhone(''); setEscalation(''); setSubdomain('');
                    setAreaCode(''); setState(''); setVoiceProfile('female_en'); setResult(null);
                    setSubdomainStatus('idle');
                  }}>
                    + Onboard Another
                  </button>
                </div>
              </div>
            )}

          </div>
        </div>
      </div>
    </div>
  );
}
