'use client'

import { Suspense, useEffect, useMemo, useState } from 'react'
import type { ReactNode } from 'react'
import { useRouter, useSearchParams } from 'next/navigation'
import {
  BarChart3,
  Building2,
  CreditCard,
  FileText,
  Lock,
  Palette,
  ShieldCheck,
  Tags,
} from 'lucide-react'
import { apiFetch } from '@/lib/api'
import { useDashboardI18n } from '@/components/I18nProvider'
import { getMoroccanCityOptions } from '@/lib/moroccanCities'

type SectionKey = 'company' | 'carplace' | 'payments' | 'rental-policies' | 'insurance' | 'pricing' | 'accounting'
type FeatureKey =
  | 'settings.company_profile'
  | 'settings.public_contact'
  | 'settings.locale_currency'
  | 'settings.carplace_listing'
  | 'settings.branding_basic'
  | 'settings.branding_custom'
  | 'settings.branding_hero'
  | 'settings.renter_payments'
  | 'settings.rental_policies_basic'
  | 'settings.additional_driver_fees'
  | 'settings.insurance_policies'
  | 'settings.pricing_rules'
  | 'settings.accounting_defaults'
  | 'settings.accounting_scheduled_delivery'
  | 'settings.accounting_advanced_formats'

interface MenuItem {
  menuKey: SectionKey
  sectionKey: SectionKey
  label: string
  description: string
  iconKey: string
  sortOrder: number
  state: 'ENABLED' | 'LOCKED'
  requiredPlan: 'GROWTH' | 'PRO' | null
}

interface Entitlement {
  available: boolean
  editable: boolean
  requiredPlan: 'GROWTH' | 'PRO' | null
  reason: string | null
}

interface Entitlements {
  plan: 'STARTER' | 'GROWTH' | 'PRO'
  subscriptionStatus: string
  accessLevel: 'full' | 'limited' | 'read_only' | 'none'
  currentPeriodEnd: string | null
  trialEndAt: string | null
  features: Record<FeatureKey, Entitlement>
}

interface BrandSettings {
  displayName: string
  tagline: string | null
  primaryColor: string
  accentColor?: string | null
  publicEmail: string | null
  publicPhone: string | null
  publicAddress?: string | null
  publicCity: string | null
  publicCountry?: string | null
  subdomain: string
  logoUrl?: string | null
  heroImageUrl?: string | null
  websiteUrl?: string | null
  whatsappNumber?: string | null
  paypalEmail: string | null
  amanpayMerchantId: string | null
  amanpaySecretKey?: string | null
  defaultLocale?: string
  defaultCurrency?: string
  isListedOnCarplace: boolean
}

interface ContractSettings {
  fuelPolicyType: string
  fuelPolicyNote: string | null
  additionalDriverCharge: 'FREE' | 'PER_DAY' | 'FLAT'
  additionalDriverDailyRate: number
  additionalDriverFlatRate: number
  damagePolicy: string
}

interface InsurancePolicy {
  id: string
  name: string
  type: string
  chargeType: string
  chargeValue: number
  isRequired: boolean
  isActive: boolean
}

interface PricingRule {
  id: string
  name: string
  type: string
  condition: string
  conditionValue: number
  adjustmentType: string
  adjustmentValue: number
  isActive: boolean
}

interface AccountingSettings {
  reportingPeriod: string
  accountantEmail: string | null
  accountantName: string | null
  autoSendReport: boolean
  reportFormat: string
}

const emptyInsurance = { name: '', type: 'BASIC', chargeType: 'PER_DAY', chargeValue: 0, isRequired: false, isActive: true }
const emptyRule = { name: '', type: 'SURCHARGE', condition: 'AGE_LESS_THAN', conditionValue: 25, adjustmentType: 'PERCENTAGE', adjustmentValue: 0, isActive: true }

const sectionIcons = {
  building: Building2,
  palette: Palette,
  'credit-card': CreditCard,
  'file-text': FileText,
  shield: ShieldCheck,
  tags: Tags,
  'bar-chart': BarChart3,
}

function SettingsPageContent() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const { language } = useDashboardI18n()
  const isRtl = language === 'ar'
  const cityOptions = useMemo(() => getMoroccanCityOptions(language), [language])
  const copy = useMemo(() => ({
    en: {
      title: 'Settings', subtitle: 'Manage one settings area at a time. Access is resolved from your subscription and role.',
      loading: 'Loading settings...', save: 'Saving...', saved: 'Saved.', saveSection: 'Save section', currentPlan: 'Current plan',
      subscriptionStatus: 'Subscription status', manageSubscription: 'Manage subscription', requiredPlan: 'Requires',
      lockedTitle: 'This settings area is not included in your current plan.', lockedBody: 'Your saved configuration is preserved and becomes editable again after upgrade.',
      readOnly: 'This section is read-only while your subscription access is restricted.', companyHint: 'Default language affects Carplace text and generated contracts when available.',
      publicProfile: 'Public profile', carplaceBasics: 'Carplace basics', premiumBranding: 'Available on GROWTH',
      paymentsBody: 'Configure renter payment providers. Secret values are never shown after saving.',
      policies: 'Fuel and damage policies', additionalDriver: 'Additional-driver automation', insuranceNew: 'New insurance policy',
      pricingNew: 'New pricing rule', accountingSchedule: 'Scheduled delivery is available on PRO.', noItems: 'No records configured yet.',
      carplace: 'Listed on Carplace', logo: 'Logo', hero: 'Hero image', upload: 'Upload', active: 'Active', inactive: 'Inactive',
      labels: {
        displayName: 'Display name', tagline: 'Tagline', publicEmail: 'Public email', publicPhone: 'Public phone', whatsapp: 'WhatsApp number',
        city: 'City', country: 'Country', websiteUrl: 'Website URL', defaultLocale: 'Default language', defaultCurrency: 'Default currency',
        primaryColor: 'Primary color', accentColor: 'Accent color', amanpayMerchantId: 'AmanPay merchant ID', amanpaySecretKey: 'AmanPay secret key',
        paypalEmail: 'PayPal business email', fuelPolicyType: 'Fuel policy type', fuelPolicyNote: 'Fuel policy note', damagePolicy: 'Damage policy',
        additionalDriverCharge: 'Additional driver charge', dailyRate: 'Daily rate', flatRate: 'Flat rate', accountantName: 'Accountant name',
        accountantEmail: 'Accountant email', reportingPeriod: 'Reporting period', reportFormat: 'Report format', autoSend: 'Auto-send reports',
      },
    },
    fr: {
      title: 'Paramètres', subtitle: 'Gérez une section à la fois. L’accès vient de votre abonnement et de votre rôle.',
      loading: 'Chargement des paramètres...', save: 'Enregistrement...', saved: 'Enregistré.', saveSection: 'Enregistrer', currentPlan: 'Plan actuel',
      subscriptionStatus: 'Statut abonnement', manageSubscription: 'Gérer l’abonnement', requiredPlan: 'Requiert',
      lockedTitle: 'Cette section n’est pas incluse dans votre plan actuel.', lockedBody: 'La configuration enregistrée est conservée et redevient modifiable après mise à niveau.',
      readOnly: 'Cette section est en lecture seule pendant la restriction d’accès.', companyHint: 'La langue par défaut affecte la vitrine et les contrats générés si disponibles.',
      publicProfile: 'Profil public', carplaceBasics: 'Paramètres Carplace', premiumBranding: 'Disponible avec GROWTH',
      paymentsBody: 'Configurez les prestataires de paiement. Les secrets ne sont jamais affichés après enregistrement.',
      policies: 'Carburant et dommages', additionalDriver: 'Automatisation conducteur additionnel', insuranceNew: 'Nouvelle police',
      pricingNew: 'Nouvelle règle', accountingSchedule: 'L’envoi planifié est disponible avec PRO.', noItems: 'Aucun enregistrement.',
      carplace: 'Publié sur Carplace', logo: 'Logo', hero: 'Image principale', upload: 'Téléverser', active: 'Actif', inactive: 'Inactif',
      labels: {
        displayName: 'Nom affiché', tagline: 'Slogan', publicEmail: 'E-mail public', publicPhone: 'Téléphone public', whatsapp: 'Numéro WhatsApp',
        city: 'Ville', country: 'Pays', websiteUrl: 'Site web', defaultLocale: 'Langue par défaut', defaultCurrency: 'Devise par défaut',
        primaryColor: 'Couleur principale', accentColor: 'Couleur secondaire', amanpayMerchantId: 'ID marchand AmanPay', amanpaySecretKey: 'Clé secrète AmanPay',
        paypalEmail: 'Email PayPal business', fuelPolicyType: 'Type de politique carburant', fuelPolicyNote: 'Note carburant', damagePolicy: 'Politique dommages',
        additionalDriverCharge: 'Supplément conducteur', dailyRate: 'Tarif journalier', flatRate: 'Tarif fixe', accountantName: 'Nom du comptable',
        accountantEmail: 'E-mail du comptable', reportingPeriod: 'Période', reportFormat: 'Format', autoSend: 'Envoi automatique',
      },
    },
    ar: {
      title: 'الإعدادات', subtitle: 'إدارة قسم واحد في كل مرة. يتم تحديد الوصول من الاشتراك والدور.',
      loading: 'جارٍ تحميل الإعدادات...', save: 'جارٍ الحفظ...', saved: 'تم الحفظ.', saveSection: 'حفظ القسم', currentPlan: 'الخطة الحالية',
      subscriptionStatus: 'حالة الاشتراك', manageSubscription: 'إدارة الاشتراك', requiredPlan: 'يتطلب',
      lockedTitle: 'هذا القسم غير مشمول في خطتك الحالية.', lockedBody: 'يتم الاحتفاظ بالإعدادات المحفوظة وتعود قابلة للتعديل بعد الترقية.',
      readOnly: 'هذا القسم للقراءة فقط أثناء تقييد الوصول.', companyHint: 'تؤثر اللغة الافتراضية على الواجهة والعقود عند توفرها.',
      publicProfile: 'الملف العام', carplaceBasics: 'أساسيات الواجهة', premiumBranding: 'متاح في GROWTH',
      paymentsBody: 'إعداد مزودي دفع المستأجرين. لا يتم عرض المفاتيح السرية بعد الحفظ.',
      policies: 'سياسات الوقود والأضرار', additionalDriver: 'أتمتة السائق الإضافي', insuranceNew: 'سياسة تأمين جديدة',
      pricingNew: 'قاعدة تسعير جديدة', accountingSchedule: 'الإرسال المجدول متاح في PRO.', noItems: 'لا توجد سجلات بعد.',
      carplace: 'مدرج على Carplace', logo: 'الشعار', hero: 'صورة الواجهة', upload: 'رفع', active: 'نشط', inactive: 'غير نشط',
      labels: {
        displayName: 'اسم العرض', tagline: 'الشعار', publicEmail: 'البريد العام', publicPhone: 'الهاتف العام', whatsapp: 'رقم واتساب',
        city: 'المدينة', country: 'الدولة', websiteUrl: 'الموقع', defaultLocale: 'اللغة الافتراضية', defaultCurrency: 'العملة الافتراضية',
        primaryColor: 'اللون الأساسي', accentColor: 'لون التمييز', amanpayMerchantId: 'معرف تاجر AmanPay', amanpaySecretKey: 'مفتاح AmanPay السري',
        paypalEmail: 'بريد PayPal التجاري', fuelPolicyType: 'سياسة الوقود', fuelPolicyNote: 'ملاحظة الوقود', damagePolicy: 'سياسة الأضرار',
        additionalDriverCharge: 'رسوم السائق الإضافي', dailyRate: 'السعر اليومي', flatRate: 'السعر الثابت', accountantName: 'اسم المحاسب',
        accountantEmail: 'بريد المحاسب', reportingPeriod: 'فترة التقرير', reportFormat: 'تنسيق التقرير', autoSend: 'إرسال تلقائي',
      },
    },
  }[language]), [language])

  const [menu, setMenu] = useState<MenuItem[]>([])
  const [entitlements, setEntitlements] = useState<Entitlements | null>(null)
  const [brand, setBrand] = useState<BrandSettings | null>(null)
  const [contractSettings, setContractSettings] = useState<ContractSettings | null>(null)
  const [insurancePolicies, setInsurancePolicies] = useState<InsurancePolicy[]>([])
  const [pricingRules, setPricingRules] = useState<PricingRule[]>([])
  const [accountingSettings, setAccountingSettings] = useState<AccountingSettings | null>(null)
  const [newInsurance, setNewInsurance] = useState(emptyInsurance)
  const [newRule, setNewRule] = useState(emptyRule)
  const [saving, setSaving] = useState(false)
  const [uploadingAsset, setUploadingAsset] = useState<'logo' | 'hero' | null>(null)
  const [message, setMessage] = useState<string | null>(null)
  const [error, setError] = useState<string | null>(null)

  const requestedSection = searchParams.get('section') as SectionKey | null
  const activeItem = menu.find((item) => item.sectionKey === requestedSection) ?? menu.find((item) => item.state === 'ENABLED') ?? menu[0]
  const activeSection = activeItem?.sectionKey

  const feature = (key: FeatureKey) => entitlements?.features[key] ?? { available: false, editable: false, requiredPlan: null, reason: null }
  const canEdit = (key: FeatureKey) => feature(key).editable
  const isAvailable = (key: FeatureKey) => feature(key).available

  useEffect(() => {
    async function loadShell() {
      try {
        const [menuData, entitlementData] = await Promise.all([
          apiFetch<{ items: MenuItem[] }>(`/companies/me/settings-menu?locale=${language}`),
          apiFetch<Entitlements>('/companies/me/settings-entitlements'),
        ])
        setMenu(menuData.items)
        setEntitlements(entitlementData)
      } catch (err: any) {
        setError(err.message ?? 'Failed to load settings menu')
      }
    }
    loadShell()
  }, [language])

  useEffect(() => {
    if (!activeSection) return
    const allowed = menu.some((item) => item.sectionKey === activeSection)
    if (allowed && requestedSection === activeSection) return
    router.replace(`/settings?section=${activeSection}`)
  }, [activeSection, menu, requestedSection, router])

  useEffect(() => {
    async function loadSection() {
      try {
        if ((activeSection === 'company' || activeSection === 'carplace' || activeSection === 'payments') && !brand) {
          setBrand(await apiFetch<BrandSettings | null>('/companies/me/brand'))
        }
        if (activeSection === 'rental-policies' && !contractSettings) {
          setContractSettings(await apiFetch<ContractSettings | null>('/companies/me/contract-settings') ?? {
            fuelPolicyType: 'FULL_TO_FULL', fuelPolicyNote: '', additionalDriverCharge: 'FREE',
            additionalDriverDailyRate: 0, additionalDriverFlatRate: 0, damagePolicy: '',
          })
        }
        if (activeSection === 'insurance' && isAvailable('settings.insurance_policies') && insurancePolicies.length === 0) {
          setInsurancePolicies(await apiFetch<InsurancePolicy[]>('/companies/me/insurance-policies'))
        }
        if (activeSection === 'pricing' && isAvailable('settings.pricing_rules') && pricingRules.length === 0) {
          setPricingRules(await apiFetch<PricingRule[]>('/companies/me/pricing-rules'))
        }
        if (activeSection === 'accounting' && isAvailable('settings.accounting_defaults') && !accountingSettings) {
          setAccountingSettings(await apiFetch<AccountingSettings | null>('/companies/me/accounting-settings') ?? {
            reportingPeriod: 'MONTHLY', accountantEmail: '', accountantName: '', autoSendReport: false, reportFormat: 'CSV',
          })
        }
      } catch (err: any) {
        setError(err.message ?? 'Failed to load settings')
      }
    }
    loadSection()
  }, [activeSection, accountingSettings, brand, contractSettings, insurancePolicies.length, pricingRules.length, entitlements])

  async function saveBrand() {
    if (!brand) return
    setSaving(true); setError(null); setMessage(null)
    try {
      const updated = await apiFetch<BrandSettings>('/companies/me/brand', {
        method: 'PATCH',
        body: JSON.stringify({
          displayName: brand.displayName, tagline: brand.tagline || undefined,
          primaryColor: canEdit('settings.branding_custom') ? brand.primaryColor : undefined,
          accentColor: canEdit('settings.branding_custom') ? brand.accentColor || undefined : undefined,
          publicEmail: brand.publicEmail || undefined,
          publicPhone: brand.publicPhone || undefined, publicAddress: brand.publicAddress || undefined,
          publicCity: brand.publicCity || undefined, publicCountry: brand.publicCountry || undefined,
          websiteUrl: brand.websiteUrl || undefined, defaultLocale: brand.defaultLocale || undefined,
          whatsappNumber: brand.whatsappNumber || undefined, defaultCurrency: brand.defaultCurrency || undefined,
          isListedOnCarplace: brand.isListedOnCarplace,
          amanpayMerchantId: canEdit('settings.renter_payments') ? brand.amanpayMerchantId || undefined : undefined,
          amanpaySecretKey: canEdit('settings.renter_payments') ? brand.amanpaySecretKey || undefined : undefined,
          paypalEmail: canEdit('settings.renter_payments') ? brand.paypalEmail || undefined : undefined,
        }),
      })
      setBrand(updated); setMessage(copy.saved)
    } catch (err: any) {
      setError(err.message ?? 'Failed to save brand settings')
    } finally {
      setSaving(false)
    }
  }

  async function uploadBrandAsset(kind: 'logo' | 'hero', file: File | null) {
    if (!file) return
    setUploadingAsset(kind)
    try {
      const formData = new FormData()
      formData.append('file', file)
      setBrand(await apiFetch<BrandSettings>(`/companies/me/brand/${kind}`, { method: 'POST', body: formData }))
    } catch (err: any) {
      setError(err.message ?? `Failed to upload ${kind}`)
    } finally {
      setUploadingAsset(null)
    }
  }

  async function saveContractSettings() {
    if (!contractSettings) return
    setSaving(true); setError(null); setMessage(null)
    try {
      const body = canEdit('settings.additional_driver_fees')
        ? contractSettings
        : {
          fuelPolicyType: contractSettings.fuelPolicyType,
          fuelPolicyNote: contractSettings.fuelPolicyNote,
          damagePolicy: contractSettings.damagePolicy,
        }
      await apiFetch('/companies/me/contract-settings', { method: 'PATCH', body: JSON.stringify(body) })
      setMessage(copy.saved)
    } catch (err: any) {
      setError(err.message ?? 'Failed to save contract settings')
    } finally {
      setSaving(false)
    }
  }

  async function saveAccountingSettings() {
    if (!accountingSettings) return
    setSaving(true); setError(null); setMessage(null)
    try {
      const body = {
        reportingPeriod: accountingSettings.reportingPeriod,
        accountantEmail: accountingSettings.accountantEmail,
        accountantName: accountingSettings.accountantName,
        autoSendReport: canEdit('settings.accounting_scheduled_delivery') ? accountingSettings.autoSendReport : undefined,
        reportFormat: canEdit('settings.accounting_advanced_formats') || accountingSettings.reportFormat !== 'BOTH'
          ? accountingSettings.reportFormat
          : undefined,
      }
      await apiFetch('/companies/me/accounting-settings', { method: 'PATCH', body: JSON.stringify(body) })
      setMessage(copy.saved)
    } catch (err: any) {
      setError(err.message ?? 'Failed to save accounting settings')
    } finally {
      setSaving(false)
    }
  }

  async function createInsurance() {
    setSaving(true)
    try {
      await apiFetch('/companies/me/insurance-policies', { method: 'POST', body: JSON.stringify(newInsurance) })
      setNewInsurance(emptyInsurance)
      setInsurancePolicies(await apiFetch<InsurancePolicy[]>('/companies/me/insurance-policies'))
    } catch (err: any) {
      setError(err.message ?? 'Failed to create insurance policy')
    } finally {
      setSaving(false)
    }
  }

  async function createRule() {
    setSaving(true)
    try {
      await apiFetch('/companies/me/pricing-rules', { method: 'POST', body: JSON.stringify(newRule) })
      setNewRule(emptyRule)
      setPricingRules(await apiFetch<PricingRule[]>('/companies/me/pricing-rules'))
    } catch (err: any) {
      setError(err.message ?? 'Failed to create pricing rule')
    } finally {
      setSaving(false)
    }
  }

  if (!entitlements || !activeItem) return <div className="card p-6 text-sm text-slate-500">{copy.loading}</div>

  const activeLocked = activeItem.state === 'LOCKED'

  return (
    <div className="space-y-6" dir={isRtl ? 'rtl' : 'ltr'}>
      <div className="flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between">
        <div>
          <h2 className="text-xl font-semibold text-slate-900">{copy.title}</h2>
          <p className="mt-1 text-sm text-slate-500">{copy.subtitle}</p>
        </div>
        <div className="flex flex-wrap items-center gap-2 text-xs">
          <span className="rounded-full border border-slate-200 bg-white px-3 py-1.5 text-slate-600">{copy.currentPlan}: {entitlements.plan}</span>
          <span className="rounded-full border border-slate-200 bg-white px-3 py-1.5 text-slate-600">{copy.subscriptionStatus}: {entitlements.subscriptionStatus}</span>
          <a href="/subscription" className="btn-secondary py-1.5 text-xs">{copy.manageSubscription}</a>
        </div>
      </div>

      {error && <div className="rounded-lg border border-red-200 bg-red-50 p-4 text-sm text-red-700">{error}</div>}
      {message && <div className="rounded-lg border border-emerald-200 bg-emerald-50 p-4 text-sm text-emerald-700" aria-live="polite">{message}</div>}

      <div className="grid gap-6 lg:grid-cols-[280px_minmax(0,1fr)]">
        <nav className="card p-2" aria-label="Settings sections">
          <div className="flex gap-2 overflow-x-auto lg:block lg:space-y-1">
            {menu.map((item) => {
              const Icon = sectionIcons[item.iconKey as keyof typeof sectionIcons] ?? FileText
              const isActive = item.sectionKey === activeSection
              return (
                <button
                  key={item.sectionKey}
                  type="button"
                  onClick={() => router.push(`/settings?section=${item.sectionKey}`)}
                  aria-current={isActive ? 'page' : undefined}
                  className={`flex min-w-56 items-start gap-3 rounded-md px-3 py-3 text-left transition lg:w-full ${isActive ? 'bg-slate-900 text-white' : 'text-slate-600 hover:bg-slate-50'}`}
                >
                  <Icon className="mt-0.5 h-4 w-4 shrink-0" />
                  <span className="min-w-0 flex-1">
                    <span className="block text-sm font-medium">{item.label}</span>
                    <span className={`mt-0.5 block text-xs ${isActive ? 'text-slate-300' : 'text-slate-400'}`}>{item.description}</span>
                  </span>
                  {item.state === 'LOCKED' && <Lock className="mt-0.5 h-4 w-4 shrink-0" />}
                </button>
              )
            })}
          </div>
        </nav>

        <main className="min-w-0">
          <div className="mb-4">
            <h3 className="text-lg font-semibold text-slate-900">{activeItem.label}</h3>
            <p className="text-sm text-slate-500">{activeItem.description}</p>
          </div>

          {activeLocked ? (
            <LockedState copy={copy} item={activeItem} currentPlan={entitlements.plan} />
          ) : (
            <>
              {entitlements.accessLevel !== 'full' && <div className="mb-4 rounded-lg border border-amber-200 bg-amber-50 p-4 text-sm text-amber-800">{copy.readOnly}</div>}
              {activeSection === 'company' && brand && (
                <SectionCard onSave={saveBrand} saving={saving} copy={copy}>
                  <div className="grid gap-4 lg:grid-cols-2">
                    <Input label={copy.labels.displayName} value={brand.displayName} disabled={!canEdit('settings.company_profile')} onChange={(v) => setBrand({ ...brand, displayName: v })} />
                    <Input label={copy.labels.tagline} value={brand.tagline ?? ''} disabled={!canEdit('settings.company_profile')} onChange={(v) => setBrand({ ...brand, tagline: v })} />
                    <Input label={copy.labels.publicEmail} type="email" value={brand.publicEmail ?? ''} disabled={!canEdit('settings.public_contact')} onChange={(v) => setBrand({ ...brand, publicEmail: v })} />
                    <Input label={copy.labels.publicPhone} value={brand.publicPhone ?? ''} disabled={!canEdit('settings.public_contact')} onChange={(v) => setBrand({ ...brand, publicPhone: v })} />
                    <Input label={copy.labels.whatsapp} value={brand.whatsappNumber ?? ''} disabled={!canEdit('settings.public_contact')} onChange={(v) => setBrand({ ...brand, whatsappNumber: v })} />
                    <div>
                      <Label text={copy.labels.city} />
                      <input list="morocco-cities" className="input-field" value={brand.publicCity ?? ''} disabled={!canEdit('settings.public_contact')} onChange={(e) => setBrand({ ...brand, publicCity: e.target.value })} />
                      <datalist id="morocco-cities">{cityOptions.map((city) => <option key={city} value={city} />)}</datalist>
                    </div>
                    <Input label={copy.labels.country} value={brand.publicCountry ?? 'Morocco'} disabled={!canEdit('settings.public_contact')} onChange={(v) => setBrand({ ...brand, publicCountry: v })} />
                    <Input label={copy.labels.websiteUrl} value={brand.websiteUrl ?? ''} disabled={!canEdit('settings.public_contact')} onChange={(v) => setBrand({ ...brand, websiteUrl: v })} />
                    <Select label={copy.labels.defaultLocale} value={brand.defaultLocale ?? language} disabled={!canEdit('settings.locale_currency')} options={['en', 'fr', 'ar']} onChange={(v) => setBrand({ ...brand, defaultLocale: v })} />
                    <Select label={copy.labels.defaultCurrency} value={brand.defaultCurrency ?? 'MAD'} disabled={!canEdit('settings.locale_currency')} options={['MAD', 'EUR', 'USD']} onChange={(v) => setBrand({ ...brand, defaultCurrency: v })} />
                  </div>
                  <p className="mt-3 text-xs text-slate-500">{copy.companyHint}</p>
                </SectionCard>
              )}

              {activeSection === 'carplace' && brand && (
                <SectionCard onSave={saveBrand} saving={saving} copy={copy}>
                  <label className="flex items-center gap-2 text-sm font-medium text-slate-700">
                    <input type="checkbox" checked={brand.isListedOnCarplace} disabled={!canEdit('settings.carplace_listing')} onChange={(e) => setBrand({ ...brand, isListedOnCarplace: e.target.checked })} />
                    {copy.carplace}
                  </label>
                  <div className="mt-5 grid gap-4 lg:grid-cols-2">
                    <AssetField label={copy.logo} value={brand.logoUrl} disabled={!canEdit('settings.branding_basic')} uploading={uploadingAsset === 'logo'} copy={copy} onChange={(file) => uploadBrandAsset('logo', file)} />
                    <AssetField label={copy.hero} value={brand.heroImageUrl} disabled={!canEdit('settings.branding_hero')} uploading={uploadingAsset === 'hero'} copy={copy} onChange={(file) => uploadBrandAsset('hero', file)} />
                    <Input label={copy.labels.primaryColor} value={brand.primaryColor} disabled={!canEdit('settings.branding_custom')} onChange={(v) => setBrand({ ...brand, primaryColor: v })} />
                    <Input label={copy.labels.accentColor} value={brand.accentColor ?? ''} disabled={!canEdit('settings.branding_custom')} onChange={(v) => setBrand({ ...brand, accentColor: v })} />
                  </div>
                  {!isAvailable('settings.branding_custom') && <UpgradePanel title={copy.premiumBranding} />}
                </SectionCard>
              )}

              {activeSection === 'payments' && brand && (
                <SectionCard onSave={saveBrand} saving={saving} copy={copy} disabled={!canEdit('settings.renter_payments')}>
                  <p className="mb-4 text-sm text-slate-500">{copy.paymentsBody}</p>
                  <div className="grid gap-4 lg:grid-cols-2">
                    <Input label={copy.labels.amanpayMerchantId} value={brand.amanpayMerchantId ?? ''} disabled={!canEdit('settings.renter_payments')} onChange={(v) => setBrand({ ...brand, amanpayMerchantId: v })} />
                    <Input label={copy.labels.amanpaySecretKey} type="password" value={brand.amanpaySecretKey ?? ''} disabled={!canEdit('settings.renter_payments')} onChange={(v) => setBrand({ ...brand, amanpaySecretKey: v })} />
                    <Input label={copy.labels.paypalEmail} type="email" value={brand.paypalEmail ?? ''} disabled={!canEdit('settings.renter_payments')} onChange={(v) => setBrand({ ...brand, paypalEmail: v })} />
                  </div>
                </SectionCard>
              )}

              {activeSection === 'rental-policies' && contractSettings && (
                <SectionCard onSave={saveContractSettings} saving={saving} copy={copy}>
                  <div className="grid gap-4 lg:grid-cols-2">
                    <Select label={copy.labels.fuelPolicyType} value={contractSettings.fuelPolicyType} disabled={!canEdit('settings.rental_policies_basic')} options={['FULL_TO_FULL', 'FULL_TO_EMPTY', 'SAME_TO_SAME', 'PREPAID', 'FREE']} onChange={(v) => setContractSettings({ ...contractSettings, fuelPolicyType: v })} />
                    <Select label={copy.labels.additionalDriverCharge} value={contractSettings.additionalDriverCharge} disabled={!canEdit('settings.additional_driver_fees')} options={['FREE', 'PER_DAY', 'FLAT']} onChange={(v) => setContractSettings({ ...contractSettings, additionalDriverCharge: v as ContractSettings['additionalDriverCharge'] })} />
                    {contractSettings.additionalDriverCharge === 'PER_DAY' && <Input label={copy.labels.dailyRate} type="number" value={contractSettings.additionalDriverDailyRate} disabled={!canEdit('settings.additional_driver_fees')} onChange={(v) => setContractSettings({ ...contractSettings, additionalDriverDailyRate: Math.max(0, Number(v)) })} />}
                    {contractSettings.additionalDriverCharge === 'FLAT' && <Input label={copy.labels.flatRate} type="number" value={contractSettings.additionalDriverFlatRate} disabled={!canEdit('settings.additional_driver_fees')} onChange={(v) => setContractSettings({ ...contractSettings, additionalDriverFlatRate: Math.max(0, Number(v)) })} />}
                    <Textarea label={copy.labels.fuelPolicyNote} value={contractSettings.fuelPolicyNote ?? ''} disabled={!canEdit('settings.rental_policies_basic')} onChange={(v) => setContractSettings({ ...contractSettings, fuelPolicyNote: v })} />
                    <Textarea label={copy.labels.damagePolicy} value={contractSettings.damagePolicy ?? ''} disabled={!canEdit('settings.rental_policies_basic')} onChange={(v) => setContractSettings({ ...contractSettings, damagePolicy: v })} />
                  </div>
                  {!isAvailable('settings.additional_driver_fees') && <UpgradePanel title={copy.additionalDriver} />}
                </SectionCard>
              )}

              {activeSection === 'insurance' && <ListSection items={insurancePolicies} empty={copy.noItems} copy={copy} render={(policy) => `${policy.type} / ${policy.chargeType} / ${policy.chargeValue}`} formTitle={copy.insuranceNew} disabled={!canEdit('settings.insurance_policies')} fields={<>
                <input className="input-field" placeholder="Name" value={newInsurance.name} onChange={(e) => setNewInsurance({ ...newInsurance, name: e.target.value })} />
                <input className="input-field" placeholder="Charge value" type="number" value={newInsurance.chargeValue} onChange={(e) => setNewInsurance({ ...newInsurance, chargeValue: Math.max(0, Number(e.target.value)) })} />
              </>} onCreate={createInsurance} />}

              {activeSection === 'pricing' && <ListSection items={pricingRules} empty={copy.noItems} copy={copy} render={(rule) => `${rule.type} when ${rule.condition} ${rule.conditionValue}: ${rule.adjustmentType} ${rule.adjustmentValue}`} formTitle={copy.pricingNew} disabled={!canEdit('settings.pricing_rules')} fields={<>
                <input className="input-field" placeholder="Name" value={newRule.name} onChange={(e) => setNewRule({ ...newRule, name: e.target.value })} />
                <input className="input-field" placeholder="Adjustment" type="number" value={newRule.adjustmentValue} onChange={(e) => setNewRule({ ...newRule, adjustmentValue: Math.max(0, Number(e.target.value)) })} />
              </>} onCreate={createRule} />}

              {activeSection === 'accounting' && accountingSettings && (
                <SectionCard onSave={saveAccountingSettings} saving={saving} copy={copy} disabled={!canEdit('settings.accounting_defaults')}>
                  <div className="grid gap-4 lg:grid-cols-2">
                    <Select label={copy.labels.reportingPeriod} value={accountingSettings.reportingPeriod} disabled={!canEdit('settings.accounting_defaults')} options={['WEEKLY', 'MONTHLY', 'QUARTERLY', 'ANNUAL']} onChange={(v) => setAccountingSettings({ ...accountingSettings, reportingPeriod: v })} />
                    <Select label={copy.labels.reportFormat} value={accountingSettings.reportFormat} disabled={!canEdit('settings.accounting_defaults')} options={canEdit('settings.accounting_advanced_formats') ? ['CSV', 'PDF', 'BOTH'] : ['CSV', 'PDF']} onChange={(v) => setAccountingSettings({ ...accountingSettings, reportFormat: v })} />
                    <Input label={copy.labels.accountantName} value={accountingSettings.accountantName ?? ''} disabled={!canEdit('settings.accounting_defaults')} onChange={(v) => setAccountingSettings({ ...accountingSettings, accountantName: v })} />
                    <Input label={copy.labels.accountantEmail} type="email" value={accountingSettings.accountantEmail ?? ''} disabled={!canEdit('settings.accounting_defaults')} onChange={(v) => setAccountingSettings({ ...accountingSettings, accountantEmail: v })} />
                  </div>
                  <label className="mt-4 flex items-center gap-2 text-sm font-medium text-slate-700">
                    <input type="checkbox" checked={accountingSettings.autoSendReport} disabled={!canEdit('settings.accounting_scheduled_delivery')} onChange={(e) => setAccountingSettings({ ...accountingSettings, autoSendReport: e.target.checked })} />
                    {copy.labels.autoSend}
                  </label>
                  {!isAvailable('settings.accounting_scheduled_delivery') && <UpgradePanel title={copy.accountingSchedule} />}
                </SectionCard>
              )}
            </>
          )}
        </main>
      </div>
    </div>
  )
}

function Label({ text }: { text: string }) {
  return <label className="mb-1.5 block text-sm font-medium text-slate-700">{text}</label>
}

function Input({ label, value, onChange, disabled, type = 'text' }: { label: string; value: string | number; onChange: (value: string) => void; disabled?: boolean; type?: string }) {
  return <div><Label text={label} /><input className="input-field" type={type} value={value} disabled={disabled} onChange={(event) => onChange(event.target.value)} /></div>
}

function Textarea({ label, value, onChange, disabled }: { label: string; value: string; onChange: (value: string) => void; disabled?: boolean }) {
  return <div className="lg:col-span-2"><Label text={label} /><textarea className="input-field min-h-24" value={value} disabled={disabled} onChange={(event) => onChange(event.target.value)} /></div>
}

function Select({ label, value, onChange, disabled, options }: { label: string; value: string; onChange: (value: string) => void; disabled?: boolean; options: string[] }) {
  return <div><Label text={label} /><select className="input-field" value={value} disabled={disabled} onChange={(event) => onChange(event.target.value)}>{options.map((option) => <option key={option} value={option}>{option}</option>)}</select></div>
}

function SectionCard({ children, onSave, saving, copy, disabled = false }: { children: ReactNode; onSave: () => void; saving: boolean; copy: any; disabled?: boolean }) {
  return <div className="card p-6"><div>{children}</div><div className="mt-6 flex justify-end"><button type="button" onClick={onSave} disabled={saving || disabled} className="btn-primary">{saving ? copy.save : copy.saveSection}</button></div></div>
}

function AssetField({ label, value, disabled, uploading, copy, onChange }: { label: string; value?: string | null; disabled?: boolean; uploading: boolean; copy: any; onChange: (file: File | null) => void }) {
  return <label className="block"><Label text={label} />{value && <img src={value} alt="" className="mb-3 h-24 w-full rounded-md object-cover" />}<input type="file" accept="image/*" disabled={disabled} className="input-field" onChange={(event) => onChange(event.target.files?.[0] ?? null)} /><p className="mt-2 text-xs text-slate-500">{uploading ? copy.save : copy.upload}</p></label>
}

function UpgradePanel({ title }: { title: string }) {
  return <div className="mt-5 rounded-lg border border-slate-200 bg-slate-50 p-4 text-sm text-slate-600"><Lock className="mb-2 h-4 w-4" />{title}</div>
}

function LockedState({ copy, item, currentPlan }: { copy: any; item: MenuItem; currentPlan: string }) {
  return <div className="card p-8 text-center"><Lock className="mx-auto h-8 w-8 text-slate-400" /><h4 className="mt-4 text-base font-semibold text-slate-900">{copy.lockedTitle}</h4><p className="mx-auto mt-2 max-w-lg text-sm text-slate-500">{copy.lockedBody}</p><p className="mt-4 text-sm text-slate-600">{copy.currentPlan}: {currentPlan} · {copy.requiredPlan}: {item.requiredPlan}</p><a href="/subscription" className="btn-primary mt-5 inline-flex">{copy.manageSubscription}</a></div>
}

function ListSection<T extends { id: string; name: string; isActive: boolean }>({ items, empty, copy, render, formTitle, disabled, fields, onCreate }: { items: T[]; empty: string; copy: any; render: (item: T) => string; formTitle: string; disabled?: boolean; fields: ReactNode; onCreate: () => void }) {
  return <div className="card p-6"><div className="space-y-3">{items.map((item) => <div key={item.id} className="flex items-center justify-between rounded-lg border border-slate-200 px-4 py-3 text-sm"><div><p className="font-medium text-slate-900">{item.name}</p><p className="text-slate-500">{render(item)}</p></div><span className={item.isActive ? 'badge-green' : 'badge-gray'}>{item.isActive ? copy.active : copy.inactive}</span></div>)}{items.length === 0 && <p className="text-sm text-slate-500">{empty}</p>}</div><div className="mt-6 border-t border-slate-100 pt-5"><h4 className="mb-3 text-sm font-semibold text-slate-900">{formTitle}</h4><div className="grid gap-3 sm:grid-cols-2">{fields}</div><button type="button" disabled={disabled} onClick={onCreate} className="btn-primary mt-4">{copy.saveSection}</button></div></div>
}

export default function SettingsPage() {
  return (
    <Suspense fallback={<div className="card p-6 text-sm text-slate-500">Loading settings...</div>}>
      <SettingsPageContent />
    </Suspense>
  )
}
