'use client'

import { useEffect, useState } from 'react'
import { useParams, useRouter } from 'next/navigation'
import Link from 'next/link'
import {
  clonePublicHomepageLayout,
  clonePublicSitePageSections,
  resolvePublicHomepageLayout,
  type PublicHomepageLayout,
  type PublicHomepageSectionType,
  type PublicSitePageSections,
} from '@rentaldrivego/types'
import { HomepageLayoutEditor } from './HomepageLayoutEditor'

const API_BASE = '/api/v1'

interface CompanyDetail {
  id: string
  name: string
  slug: string
  email: string
  phone: string | null
  status: string
  subscriptionPaymentRef: string | null
  createdAt: string
  subscription: {
    plan: string
    billingPeriod: string
    status: string
    currency: string
    trialStartAt: string | null
    trialEndAt: string | null
    currentPeriodStart: string | null
    currentPeriodEnd: string | null
    cancelledAt: string | null
    cancelAtPeriodEnd: boolean
  } | null
  brand: {
    displayName: string
    tagline: string | null
    subdomain: string
    customDomain: string | null
    publicEmail: string | null
    publicPhone: string | null
    publicAddress: string | null
    publicCity: string | null
    publicCountry: string | null
    websiteUrl: string | null
    whatsappNumber: string | null
    defaultLocale: string
    defaultCurrency: string
    isListedOnMarketplace: boolean
    homePageConfig: {
      heroTitle: string | null
      heroDescription: string | null
      viewOffersLabel: string | null
      viewPricingLabel: string | null
      contactCompanyLabel: string | null
      activeOffersTitle: string | null
      seeAllOffersLabel: string | null
      noActiveOffersLabel: string | null
      publishedVehiclesTitle: string | null
      viewVehicleLabel: string | null
      pricingEyebrow: string | null
      pricingTitle: string | null
      pricingDescription: string | null
      showOffers: boolean
      showVehicles: boolean
      showPricing: boolean
      layout?: PublicHomepageLayout | null
    } | null
    menuConfig: {
      aboutLabel: string | null
      vehiclesLabel: string | null
      offersLabel: string | null
      pricingLabel: string | null
      blogLabel: string | null
      contactLabel: string | null
      bookCarLabel: string | null
      siteNavigationLabel: string | null
      showAbout: boolean
      showVehicles: boolean
      showOffers: boolean
      showPricing: boolean
      showBlog: boolean
      showContact: boolean
      pageSections?: PublicSitePageSections | null
    } | null
  } | null
  contractSettings: {
    legalName: string | null
    registrationNumber: string | null
    taxId: string | null
    terms: string
    fuelPolicyType: string
    lateFeePerHour: number | null
    taxRate: number | null
    signatureRequired: boolean
    showTax: boolean
  } | null
  accountingSettings: {
    reportingPeriod: string
    fiscalYearStart: number
    currency: string
    accountantEmail: string | null
    accountantName: string | null
    autoSendReport: boolean
    reportFormat: string
  } | null
  employees?: Array<{ id: string }>
  vehicles?: Array<{ id: string }>
  customers?: Array<{ id: string }>
  reservations?: Array<{ id: string }>
  _count?: { employees?: number; vehicles?: number; customers?: number; reservations?: number }
}

interface AuditLog {
  id: string
  action: string
  resource: string
  resourceId: string | null
  createdAt: string
  adminUser: { email: string } | null
}

interface FormState {
  company: {
    name: string
    slug: string
    email: string
    phone: string
    subscriptionPaymentRef: string
  }
  subscription: {
    plan: string
    billingPeriod: string
    status: string
    currency: string
    trialStartAt: string
    trialEndAt: string
    currentPeriodStart: string
    currentPeriodEnd: string
    cancelledAt: string
    cancelAtPeriodEnd: boolean
  }
  brand: {
    displayName: string
    tagline: string
    subdomain: string
    customDomain: string
    publicEmail: string
    publicPhone: string
    publicAddress: string
    publicCity: string
    publicCountry: string
    websiteUrl: string
    whatsappNumber: string
    defaultLocale: string
    defaultCurrency: string
    isListedOnMarketplace: boolean
    homePageConfig: {
      heroTitle: string
      heroDescription: string
      viewOffersLabel: string
      viewPricingLabel: string
      contactCompanyLabel: string
      activeOffersTitle: string
      seeAllOffersLabel: string
      noActiveOffersLabel: string
      publishedVehiclesTitle: string
      viewVehicleLabel: string
      pricingEyebrow: string
      pricingTitle: string
      pricingDescription: string
      showOffers: boolean
      showVehicles: boolean
      showPricing: boolean
      layout: PublicHomepageLayout
    }
    menuConfig: {
      aboutLabel: string
      vehiclesLabel: string
      offersLabel: string
      pricingLabel: string
      blogLabel: string
      contactLabel: string
      bookCarLabel: string
      siteNavigationLabel: string
      showAbout: boolean
      showVehicles: boolean
      showOffers: boolean
      showPricing: boolean
      showBlog: boolean
      showContact: boolean
      pageSections: PublicSitePageSections
    }
  }
  contractSettings: {
    legalName: string
    registrationNumber: string
    taxId: string
    terms: string
    fuelPolicyType: string
    lateFeePerHour: string
    taxRate: string
    signatureRequired: boolean
    showTax: boolean
  }
  accountingSettings: {
    reportingPeriod: string
    fiscalYearStart: string
    currency: string
    accountantEmail: string
    accountantName: string
    autoSendReport: boolean
    reportFormat: string
  }
}

type CompanyHomePageConfig = NonNullable<CompanyDetail['brand']>['homePageConfig']

const STATUS_COLORS: Record<string, string> = {
  ACTIVE: 'text-emerald-400',
  TRIALING: 'text-sky-400',
  SUSPENDED: 'text-red-400',
  PENDING: 'text-amber-400',
  CANCELLED: 'text-zinc-400',
  PAST_DUE: 'text-orange-400',
}

const PREVIEW_PRICING_PLANS = [
  { name: 'Starter', price: 'MAD 499', cadence: '/month' },
  { name: 'Growth', price: 'MAD 999', cadence: '/month', highlighted: true },
  { name: 'Pro', price: 'Custom', cadence: '' },
]

const HOMEPAGE_SECTION_ORDER: PublicHomepageSectionType[] = ['hero', 'offers', 'vehicles', 'pricing']

const PAGE_SECTION_GROUPS: Array<{
  page: keyof PublicSitePageSections
  label: string
  sections: Array<{ key: string; label: string }>
}> = [
  { page: 'home', label: 'Homepage', sections: [{ key: 'hero', label: 'Hero' }, { key: 'offers', label: 'Offers' }, { key: 'vehicles', label: 'Vehicles' }, { key: 'pricing', label: 'Pricing' }] },
  { page: 'about', label: 'About', sections: [{ key: 'hero', label: 'Hero' }, { key: 'highlights', label: 'Highlights' }, { key: 'details', label: 'Details' }] },
  { page: 'offers', label: 'Offers', sections: [{ key: 'header', label: 'Header' }, { key: 'grid', label: 'Offers grid' }] },
  { page: 'pricing', label: 'Pricing', sections: [{ key: 'hero', label: 'Hero' }, { key: 'plans', label: 'Plans' }, { key: 'payments', label: 'Payments' }, { key: 'faq', label: 'FAQ' }] },
  { page: 'vehicles', label: 'Vehicles', sections: [{ key: 'header', label: 'Header' }, { key: 'filters', label: 'Filters' }, { key: 'grid', label: 'Vehicle grid' }] },
  { page: 'vehicleDetail', label: 'Vehicle detail', sections: [{ key: 'gallery', label: 'Gallery' }, { key: 'summary', label: 'Summary card' }] },
  { page: 'blog', label: 'Blog', sections: [{ key: 'hero', label: 'Hero' }, { key: 'posts', label: 'Posts' }] },
  { page: 'contact', label: 'Contact', sections: [{ key: 'content', label: 'Content card' }] },
  { page: 'booking', label: 'Booking', sections: [{ key: 'content', label: 'Booking form' }] },
  { page: 'bookingConfirmation', label: 'Booking confirmation', sections: [{ key: 'hero', label: 'Confirmation header' }, { key: 'summary', label: 'Booking summary' }, { key: 'actions', label: 'Action buttons' }] },
]

const INPUT_CLASS = 'mt-1 w-full rounded-xl border border-zinc-700 bg-zinc-900 px-3 py-2 text-sm text-zinc-100 outline-none focus:border-emerald-500'
const LABEL_CLASS = 'text-xs font-medium uppercase tracking-wide text-zinc-500'

function getToken() {
  return localStorage.getItem('admin_token') ?? ''
}

function toDateInput(value: string | null | undefined) {
  return value ? new Date(value).toISOString().slice(0, 10) : ''
}

function toNullable(value: string) {
  const trimmed = value.trim()
  return trimmed ? trimmed : null
}

function resolvePreviewText(value: string, fallback: string) {
  const trimmed = value.trim()
  return trimmed ? trimmed : fallback
}

function resolveLegacyHomepageVisibility(
  config: CompanyHomePageConfig | null | undefined,
  type: Exclude<PublicHomepageSectionType, 'hero'>,
) {
  if (type === 'offers') return config?.showOffers ?? true
  if (type === 'vehicles') return config?.showVehicles ?? true
  return config?.showPricing ?? true
}

function buildHomepageLayout(company: CompanyDetail): PublicHomepageLayout {
  const pageSections = mergePageSectionsConfig(company.brand?.menuConfig?.pageSections)
  const visibleTypes = HOMEPAGE_SECTION_ORDER.filter((type) => {
    if (!pageSections.home[type]) return false
    if (type === 'hero') return true
    return resolveLegacyHomepageVisibility(company.brand?.homePageConfig ?? null, type)
  })

  return resolvePublicHomepageLayout(company.brand?.homePageConfig?.layout, visibleTypes)
}

function mergePageSectionsConfig(config?: PublicSitePageSections | null): PublicSitePageSections {
  const defaults = clonePublicSitePageSections()
  return {
    ...defaults,
    ...(config ?? {}),
    home: { ...defaults.home, ...(config?.home ?? {}) },
    about: { ...defaults.about, ...(config?.about ?? {}) },
    offers: { ...defaults.offers, ...(config?.offers ?? {}) },
    pricing: { ...defaults.pricing, ...(config?.pricing ?? {}) },
    vehicles: { ...defaults.vehicles, ...(config?.vehicles ?? {}) },
    vehicleDetail: { ...defaults.vehicleDetail, ...(config?.vehicleDetail ?? {}) },
    blog: { ...defaults.blog, ...(config?.blog ?? {}) },
    contact: { ...defaults.contact, ...(config?.contact ?? {}) },
    booking: { ...defaults.booking, ...(config?.booking ?? {}) },
    bookingConfirmation: {
      ...defaults.bookingConfirmation,
      ...(config?.bookingConfirmation ?? {}),
    },
  }
}

function createFormState(company: CompanyDetail): FormState {
  return {
    company: {
      name: company.name ?? '',
      slug: company.slug ?? '',
      email: company.email ?? '',
      phone: company.phone ?? '',
      subscriptionPaymentRef: company.subscriptionPaymentRef ?? '',
    },
    subscription: {
      plan: company.subscription?.plan ?? 'STARTER',
      billingPeriod: company.subscription?.billingPeriod ?? 'MONTHLY',
      status: company.subscription?.status ?? 'TRIALING',
      currency: company.subscription?.currency ?? 'MAD',
      trialStartAt: toDateInput(company.subscription?.trialStartAt),
      trialEndAt: toDateInput(company.subscription?.trialEndAt),
      currentPeriodStart: toDateInput(company.subscription?.currentPeriodStart),
      currentPeriodEnd: toDateInput(company.subscription?.currentPeriodEnd),
      cancelledAt: toDateInput(company.subscription?.cancelledAt),
      cancelAtPeriodEnd: company.subscription?.cancelAtPeriodEnd ?? false,
    },
    brand: {
      displayName: company.brand?.displayName ?? company.name ?? '',
      tagline: company.brand?.tagline ?? '',
      subdomain: company.brand?.subdomain ?? company.slug ?? '',
      customDomain: company.brand?.customDomain ?? '',
      publicEmail: company.brand?.publicEmail ?? '',
      publicPhone: company.brand?.publicPhone ?? '',
      publicAddress: company.brand?.publicAddress ?? '',
      publicCity: company.brand?.publicCity ?? '',
      publicCountry: company.brand?.publicCountry ?? '',
      websiteUrl: company.brand?.websiteUrl ?? '',
      whatsappNumber: company.brand?.whatsappNumber ?? '',
      defaultLocale: company.brand?.defaultLocale ?? 'en',
      defaultCurrency: company.brand?.defaultCurrency ?? 'MAD',
      isListedOnMarketplace: company.brand?.isListedOnMarketplace ?? true,
      homePageConfig: {
        heroTitle: company.brand?.homePageConfig?.heroTitle ?? '',
        heroDescription: company.brand?.homePageConfig?.heroDescription ?? '',
        viewOffersLabel: company.brand?.homePageConfig?.viewOffersLabel ?? '',
        viewPricingLabel: company.brand?.homePageConfig?.viewPricingLabel ?? '',
        contactCompanyLabel: company.brand?.homePageConfig?.contactCompanyLabel ?? '',
        activeOffersTitle: company.brand?.homePageConfig?.activeOffersTitle ?? '',
        seeAllOffersLabel: company.brand?.homePageConfig?.seeAllOffersLabel ?? '',
        noActiveOffersLabel: company.brand?.homePageConfig?.noActiveOffersLabel ?? '',
        publishedVehiclesTitle: company.brand?.homePageConfig?.publishedVehiclesTitle ?? '',
        viewVehicleLabel: company.brand?.homePageConfig?.viewVehicleLabel ?? '',
        pricingEyebrow: company.brand?.homePageConfig?.pricingEyebrow ?? '',
        pricingTitle: company.brand?.homePageConfig?.pricingTitle ?? '',
        pricingDescription: company.brand?.homePageConfig?.pricingDescription ?? '',
        showOffers: company.brand?.homePageConfig?.showOffers ?? true,
        showVehicles: company.brand?.homePageConfig?.showVehicles ?? true,
        showPricing: company.brand?.homePageConfig?.showPricing ?? true,
        layout: buildHomepageLayout(company),
      },
      menuConfig: {
        aboutLabel: company.brand?.menuConfig?.aboutLabel ?? '',
        vehiclesLabel: company.brand?.menuConfig?.vehiclesLabel ?? '',
        offersLabel: company.brand?.menuConfig?.offersLabel ?? '',
        pricingLabel: company.brand?.menuConfig?.pricingLabel ?? '',
        blogLabel: company.brand?.menuConfig?.blogLabel ?? '',
        contactLabel: company.brand?.menuConfig?.contactLabel ?? '',
        bookCarLabel: company.brand?.menuConfig?.bookCarLabel ?? '',
        siteNavigationLabel: company.brand?.menuConfig?.siteNavigationLabel ?? '',
        showAbout: company.brand?.menuConfig?.showAbout ?? true,
        showVehicles: company.brand?.menuConfig?.showVehicles ?? true,
        showOffers: company.brand?.menuConfig?.showOffers ?? true,
        showPricing: company.brand?.menuConfig?.showPricing ?? true,
        showBlog: company.brand?.menuConfig?.showBlog ?? true,
        showContact: company.brand?.menuConfig?.showContact ?? true,
        pageSections: mergePageSectionsConfig(company.brand?.menuConfig?.pageSections),
      },
    },
    contractSettings: {
      legalName: company.contractSettings?.legalName ?? '',
      registrationNumber: company.contractSettings?.registrationNumber ?? '',
      taxId: company.contractSettings?.taxId ?? '',
      terms: company.contractSettings?.terms ?? '',
      fuelPolicyType: company.contractSettings?.fuelPolicyType ?? 'FULL_TO_FULL',
      lateFeePerHour: company.contractSettings?.lateFeePerHour?.toString() ?? '',
      taxRate: company.contractSettings?.taxRate?.toString() ?? '',
      signatureRequired: company.contractSettings?.signatureRequired ?? true,
      showTax: company.contractSettings?.showTax ?? false,
    },
    accountingSettings: {
      reportingPeriod: company.accountingSettings?.reportingPeriod ?? 'MONTHLY',
      fiscalYearStart: company.accountingSettings?.fiscalYearStart?.toString() ?? '1',
      currency: company.accountingSettings?.currency ?? 'MAD',
      accountantEmail: company.accountingSettings?.accountantEmail ?? '',
      accountantName: company.accountingSettings?.accountantName ?? '',
      autoSendReport: company.accountingSettings?.autoSendReport ?? false,
      reportFormat: company.accountingSettings?.reportFormat ?? 'PDF',
    },
  }
}

export default function AdminCompanyDetailPage() {
  const { id } = useParams<{ id: string }>()
  const router = useRouter()
  const [company, setCompany] = useState<CompanyDetail | null>(null)
  const [form, setForm] = useState<FormState | null>(null)
  const [auditLogs, setAuditLogs] = useState<AuditLog[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [actioning, setActioning] = useState(false)
  const [saving, setSaving] = useState(false)
  const [savedMessage, setSavedMessage] = useState<string | null>(null)
  const [deleteConfirm, setDeleteConfirm] = useState(false)

  async function fetchData() {
    const headers = { Authorization: `Bearer ${getToken()}` }
    try {
      const [cRes, aRes] = await Promise.all([
        fetch(`${API_BASE}/admin/companies/${id}`, { headers, cache: 'no-store' }),
        fetch(`${API_BASE}/admin/audit-logs?entityId=${id}&pageSize=10`, { headers, cache: 'no-store' }),
      ])
      const cJson = await cRes.json()
      const aJson = await aRes.json()
      if (!cRes.ok) throw new Error(cJson?.message ?? 'Not found')
      setCompany(cJson.data)
      setForm(createFormState(cJson.data))
      setAuditLogs(aJson.data ?? [])
      setError(null)
    } catch (err: any) {
      setError(err.message)
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => { fetchData() }, [id])

  function updateSection<K extends keyof FormState>(section: K, patch: Partial<FormState[K]>) {
    setForm((current) => current ? { ...current, [section]: { ...current[section], ...patch } } : current)
  }

  function updateBrandConfig<K extends keyof FormState['brand'] & ('homePageConfig' | 'menuConfig')>(
    section: K,
    patch: Partial<FormState['brand'][K]>,
  ) {
    setForm((current) => current ? {
      ...current,
      brand: {
        ...current.brand,
        [section]: {
          ...current.brand[section],
          ...patch,
        },
      },
    } : current)
  }

  function updateHomepageLayout(layout: PublicHomepageLayout) {
    setForm((current) => current ? {
      ...current,
      brand: {
        ...current.brand,
        homePageConfig: {
          ...current.brand.homePageConfig,
          layout,
        },
      },
    } : current)
  }

  function addHomepageSection(type: PublicHomepageSectionType) {
    setForm((current) => {
      if (!current) return current
      if (current.brand.homePageConfig.layout.items.some((item) => item.type === type)) return current
      const fallback = clonePublicHomepageLayout().items.find((item) => item.type === type)
      if (!fallback) return current

      return {
        ...current,
        brand: {
          ...current.brand,
          homePageConfig: {
            ...current.brand.homePageConfig,
            showOffers: type === 'offers' ? true : current.brand.homePageConfig.showOffers,
            showVehicles: type === 'vehicles' ? true : current.brand.homePageConfig.showVehicles,
            showPricing: type === 'pricing' ? true : current.brand.homePageConfig.showPricing,
            layout: {
              items: [...current.brand.homePageConfig.layout.items, fallback],
            },
          },
          menuConfig: {
            ...current.brand.menuConfig,
            pageSections: {
              ...current.brand.menuConfig.pageSections,
              home: {
                ...current.brand.menuConfig.pageSections.home,
                [type]: true,
              },
            },
          },
        },
      }
    })
  }

  function removeHomepageSection(type: PublicHomepageSectionType) {
    setForm((current) => current ? {
      ...current,
      brand: {
        ...current.brand,
        homePageConfig: {
          ...current.brand.homePageConfig,
          showOffers: type === 'offers' ? false : current.brand.homePageConfig.showOffers,
          showVehicles: type === 'vehicles' ? false : current.brand.homePageConfig.showVehicles,
          showPricing: type === 'pricing' ? false : current.brand.homePageConfig.showPricing,
          layout: {
            items: current.brand.homePageConfig.layout.items.filter((item) => item.type !== type),
          },
        },
        menuConfig: {
          ...current.brand.menuConfig,
          pageSections: {
            ...current.brand.menuConfig.pageSections,
            home: {
              ...current.brand.menuConfig.pageSections.home,
              [type]: false,
            },
          },
        },
      },
    } : current)
  }

  function updatePageSection<
    P extends keyof PublicSitePageSections,
    S extends keyof PublicSitePageSections[P]
  >(page: P, section: S, value: boolean) {
    setForm((current) => {
      if (!current) return current

      const next = {
        ...current,
        brand: {
          ...current.brand,
          menuConfig: {
            ...current.brand.menuConfig,
            pageSections: {
              ...current.brand.menuConfig.pageSections,
              [page]: {
                ...current.brand.menuConfig.pageSections[page],
                [section]: value,
              },
            },
          },
        },
      }

      if (page !== 'home') return next

      const homepageSection = section as PublicHomepageSectionType
      const nextItems = value
        ? next.brand.homePageConfig.layout.items.some((item) => item.type === homepageSection)
          ? next.brand.homePageConfig.layout.items
          : [...next.brand.homePageConfig.layout.items, clonePublicHomepageLayout().items.find((item) => item.type === homepageSection)!]
        : next.brand.homePageConfig.layout.items.filter((item) => item.type !== homepageSection)

      return {
        ...next,
        brand: {
          ...next.brand,
          homePageConfig: {
            ...next.brand.homePageConfig,
            showOffers: homepageSection === 'offers' ? value : next.brand.homePageConfig.showOffers,
            showVehicles: homepageSection === 'vehicles' ? value : next.brand.homePageConfig.showVehicles,
            showPricing: homepageSection === 'pricing' ? value : next.brand.homePageConfig.showPricing,
            layout: { items: nextItems },
          },
        },
      }
    })
  }

  function getPageSectionValue<
    P extends keyof PublicSitePageSections,
    S extends keyof PublicSitePageSections[P]
  >(page: P, section: S) {
    return form?.brand.menuConfig.pageSections[page][section] ?? false
  }

  async function saveChanges() {
    if (!form) return
    setSaving(true)
    setSavedMessage(null)
    setError(null)
    try {
      const res = await fetch(`${API_BASE}/admin/companies/${id}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${getToken()}` },
        body: JSON.stringify({
          company: {
            name: form.company.name,
            slug: form.company.slug,
            email: form.company.email,
            phone: toNullable(form.company.phone),
            subscriptionPaymentRef: toNullable(form.company.subscriptionPaymentRef),
          },
          subscription: {
            plan: form.subscription.plan,
            billingPeriod: form.subscription.billingPeriod,
            status: form.subscription.status,
            currency: form.subscription.currency,
            trialStartAt: toNullable(form.subscription.trialStartAt),
            trialEndAt: toNullable(form.subscription.trialEndAt),
            currentPeriodStart: toNullable(form.subscription.currentPeriodStart),
            currentPeriodEnd: toNullable(form.subscription.currentPeriodEnd),
            cancelledAt: toNullable(form.subscription.cancelledAt),
            cancelAtPeriodEnd: form.subscription.cancelAtPeriodEnd,
          },
          brand: {
            displayName: form.brand.displayName,
            tagline: toNullable(form.brand.tagline),
            subdomain: form.brand.subdomain,
            customDomain: toNullable(form.brand.customDomain),
            publicEmail: toNullable(form.brand.publicEmail),
            publicPhone: toNullable(form.brand.publicPhone),
            publicAddress: toNullable(form.brand.publicAddress),
            publicCity: toNullable(form.brand.publicCity),
            publicCountry: toNullable(form.brand.publicCountry),
            websiteUrl: toNullable(form.brand.websiteUrl),
            whatsappNumber: toNullable(form.brand.whatsappNumber),
            defaultLocale: form.brand.defaultLocale,
            defaultCurrency: form.brand.defaultCurrency,
            isListedOnMarketplace: form.brand.isListedOnMarketplace,
            homePageConfig: {
              heroTitle: toNullable(form.brand.homePageConfig.heroTitle),
              heroDescription: toNullable(form.brand.homePageConfig.heroDescription),
              viewOffersLabel: toNullable(form.brand.homePageConfig.viewOffersLabel),
              viewPricingLabel: toNullable(form.brand.homePageConfig.viewPricingLabel),
              contactCompanyLabel: toNullable(form.brand.homePageConfig.contactCompanyLabel),
              activeOffersTitle: toNullable(form.brand.homePageConfig.activeOffersTitle),
              seeAllOffersLabel: toNullable(form.brand.homePageConfig.seeAllOffersLabel),
              noActiveOffersLabel: toNullable(form.brand.homePageConfig.noActiveOffersLabel),
              publishedVehiclesTitle: toNullable(form.brand.homePageConfig.publishedVehiclesTitle),
              viewVehicleLabel: toNullable(form.brand.homePageConfig.viewVehicleLabel),
              pricingEyebrow: toNullable(form.brand.homePageConfig.pricingEyebrow),
              pricingTitle: toNullable(form.brand.homePageConfig.pricingTitle),
              pricingDescription: toNullable(form.brand.homePageConfig.pricingDescription),
              showOffers: form.brand.homePageConfig.showOffers,
              showVehicles: form.brand.homePageConfig.showVehicles,
              showPricing: form.brand.homePageConfig.showPricing,
              layout: form.brand.homePageConfig.layout,
            },
            menuConfig: {
              aboutLabel: toNullable(form.brand.menuConfig.aboutLabel),
              vehiclesLabel: toNullable(form.brand.menuConfig.vehiclesLabel),
              offersLabel: toNullable(form.brand.menuConfig.offersLabel),
              pricingLabel: toNullable(form.brand.menuConfig.pricingLabel),
              blogLabel: toNullable(form.brand.menuConfig.blogLabel),
              contactLabel: toNullable(form.brand.menuConfig.contactLabel),
              bookCarLabel: toNullable(form.brand.menuConfig.bookCarLabel),
              siteNavigationLabel: toNullable(form.brand.menuConfig.siteNavigationLabel),
              showAbout: form.brand.menuConfig.showAbout,
              showVehicles: form.brand.menuConfig.showVehicles,
              showOffers: form.brand.menuConfig.showOffers,
              showPricing: form.brand.menuConfig.showPricing,
              showBlog: form.brand.menuConfig.showBlog,
              showContact: form.brand.menuConfig.showContact,
              pageSections: form.brand.menuConfig.pageSections,
            },
          },
          contractSettings: {
            legalName: toNullable(form.contractSettings.legalName),
            registrationNumber: toNullable(form.contractSettings.registrationNumber),
            taxId: toNullable(form.contractSettings.taxId),
            terms: form.contractSettings.terms,
            fuelPolicyType: form.contractSettings.fuelPolicyType,
            lateFeePerHour: form.contractSettings.lateFeePerHour ? Number(form.contractSettings.lateFeePerHour) : null,
            taxRate: form.contractSettings.taxRate ? Number(form.contractSettings.taxRate) : null,
            signatureRequired: form.contractSettings.signatureRequired,
            showTax: form.contractSettings.showTax,
          },
          accountingSettings: {
            reportingPeriod: form.accountingSettings.reportingPeriod,
            fiscalYearStart: Number(form.accountingSettings.fiscalYearStart || 1),
            currency: form.accountingSettings.currency,
            accountantEmail: toNullable(form.accountingSettings.accountantEmail),
            accountantName: toNullable(form.accountingSettings.accountantName),
            autoSendReport: form.accountingSettings.autoSendReport,
            reportFormat: form.accountingSettings.reportFormat,
          },
        }),
      })
      const json = await res.json()
      if (!res.ok) throw new Error(json?.message ?? 'Save failed')
      setCompany(json.data)
      setForm(createFormState(json.data))
      setSavedMessage('Company settings updated.')
      await fetchData()
    } catch (err: any) {
      setError(err.message)
    } finally {
      setSaving(false)
    }
  }

  async function changeStatus(status: string) {
    setActioning(true)
    setError(null)
    try {
      const res = await fetch(`${API_BASE}/admin/companies/${id}/status`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${getToken()}` },
        body: JSON.stringify({ status }),
      })
      const json = await res.json()
      if (!res.ok) throw new Error(json?.message ?? 'Action failed')
      await fetchData()
    } catch (err: any) {
      setError(err.message)
    } finally {
      setActioning(false)
    }
  }

  async function deleteCompany() {
    setActioning(true)
    try {
      const res = await fetch(`${API_BASE}/admin/companies/${id}`, {
        method: 'DELETE',
        headers: { Authorization: `Bearer ${getToken()}` },
      })
      const json = await res.json()
      if (!res.ok) throw new Error(json?.message ?? 'Delete failed')
      router.push('/dashboard/companies')
    } catch (err: any) {
      setError(err.message)
      setActioning(false)
    }
  }

  if (loading) return <div className="shell py-16 text-center text-zinc-500">Loading…</div>
  if (error && !company) return <div className="shell py-16 text-center text-red-400">{error}</div>
  if (!company || !form) return null

  const counts = {
    employees: company._count?.employees ?? company.employees?.length ?? 0,
    vehicles: company._count?.vehicles ?? company.vehicles?.length ?? 0,
    customers: company._count?.customers ?? company.customers?.length ?? 0,
    reservations: company._count?.reservations ?? company.reservations?.length ?? 0,
  }
  const previewCompanyName = form.brand.displayName.trim() || form.company.name.trim() || company.name
  const previewTagline = resolvePreviewText(
    form.brand.tagline,
    'This company uses RentalDriveGo to publish vehicles, run bookings, and accept direct rental payments.',
  )
  const previewHeroTitle = resolvePreviewText(form.brand.homePageConfig.heroTitle, previewTagline)
  const previewHeroDescription = resolvePreviewText(
    form.brand.homePageConfig.heroDescription,
    'Manage direct bookings, highlight active offers, and turn your fleet into a modern rental storefront.',
  )
  const previewOffersLabel = resolvePreviewText(form.brand.homePageConfig.viewOffersLabel, 'View offers')
  const previewPricingLabel = resolvePreviewText(form.brand.homePageConfig.viewPricingLabel, 'View pricing')
  const previewContactLabel = resolvePreviewText(form.brand.homePageConfig.contactCompanyLabel, 'Contact company')
  const previewOffersTitle = resolvePreviewText(form.brand.homePageConfig.activeOffersTitle, 'Active offers')
  const previewSeeAllOffersLabel = resolvePreviewText(form.brand.homePageConfig.seeAllOffersLabel, 'See all offers')
  const previewNoOffersLabel = resolvePreviewText(form.brand.homePageConfig.noActiveOffersLabel, 'No active offers right now')
  const previewVehiclesTitle = resolvePreviewText(form.brand.homePageConfig.publishedVehiclesTitle, 'Published vehicles')
  const previewViewVehicleLabel = resolvePreviewText(form.brand.homePageConfig.viewVehicleLabel, 'View vehicle')
  const previewPricingEyebrow = resolvePreviewText(form.brand.homePageConfig.pricingEyebrow, 'Pricing')
  const previewPricingTitle = resolvePreviewText(form.brand.homePageConfig.pricingTitle, 'Plans for every fleet size')
  const previewPricingDescription = resolvePreviewText(
    form.brand.homePageConfig.pricingDescription,
    'Showcase transparent pricing and make it easy for renters to understand the value of booking direct.',
  )
  const previewBookCarLabel = resolvePreviewText(form.brand.menuConfig.bookCarLabel, 'Book car')
  const previewFooterLabel = resolvePreviewText(form.brand.menuConfig.siteNavigationLabel, 'Site navigation')
  const homepageLayout = resolvePublicHomepageLayout(
    form.brand.homePageConfig.layout,
    form.brand.homePageConfig.layout.items.map((item) => item.type),
  )
  const availableHomepageSections = HOMEPAGE_SECTION_ORDER.filter(
    (type) => !homepageLayout.items.some((item) => item.type === type),
  )
  const previewMenuItems = [
    { label: resolvePreviewText(form.brand.menuConfig.aboutLabel, 'About'), visible: form.brand.menuConfig.showAbout },
    { label: resolvePreviewText(form.brand.menuConfig.vehiclesLabel, 'Vehicles'), visible: form.brand.menuConfig.showVehicles },
    { label: resolvePreviewText(form.brand.menuConfig.offersLabel, 'Offers'), visible: form.brand.menuConfig.showOffers },
    { label: resolvePreviewText(form.brand.menuConfig.pricingLabel, 'Pricing'), visible: form.brand.menuConfig.showPricing },
    { label: resolvePreviewText(form.brand.menuConfig.blogLabel, 'Blog'), visible: form.brand.menuConfig.showBlog },
    { label: resolvePreviewText(form.brand.menuConfig.contactLabel, 'Contact'), visible: form.brand.menuConfig.showContact },
  ].filter((item) => item.visible)

  function renderHomepagePreviewSection(type: PublicHomepageSectionType) {
    if (type === 'hero') {
      return (
        <section className="grid h-full gap-6 lg:grid-cols-[1.15fr_0.85fr] lg:items-center">
          <div>
            <p className="text-sm font-semibold uppercase tracking-[0.18em] text-sky-700">{previewCompanyName}</p>
            <h4 className="mt-5 text-4xl font-black tracking-tight text-slate-900">{previewHeroTitle}</h4>
            <p className="mt-5 max-w-2xl text-base leading-8 text-slate-600">{previewHeroDescription}</p>
            <div className="mt-8 flex flex-wrap gap-3">
              <span className="rounded-full bg-slate-900 px-5 py-3 text-sm font-semibold text-white">{previewOffersLabel}</span>
              <span className="rounded-full border border-sky-200 bg-sky-50 px-5 py-3 text-sm font-semibold text-sky-800">{previewPricingLabel}</span>
              <span className="rounded-full border border-slate-300 px-5 py-3 text-sm font-semibold text-slate-700">{previewContactLabel}</span>
            </div>
          </div>
          <div className="flex min-h-72 items-center justify-center rounded-[1.5rem] bg-slate-100 p-8 text-center text-sm leading-7 text-slate-500">
            Hero image preview area.
            <br />
            Published brand media will render here on the public site.
          </div>
        </section>
      )
    }

    if (type === 'offers') {
      return (
        <section className="h-full">
          <div className="flex items-center justify-between gap-3">
            <h4 className="text-2xl font-bold text-slate-900">{previewOffersTitle}</h4>
            <span className="text-sm font-semibold text-sky-700">{previewSeeAllOffersLabel}</span>
          </div>
          <div className="mt-4 grid gap-4 md:grid-cols-2">
            <div className="rounded-[1.5rem] border border-slate-200 bg-white p-5 shadow-sm">
              <p className="text-xs font-semibold uppercase tracking-[0.16em] text-sky-700">Sample offer</p>
              <h5 className="mt-3 text-lg font-semibold text-slate-900">Weekend escape</h5>
              <p className="mt-3 text-3xl font-black text-sky-700">15%</p>
            </div>
            <div className="rounded-[1.5rem] border border-dashed border-slate-300 bg-white p-5 text-sm text-slate-500 shadow-sm">
              {previewNoOffersLabel}
            </div>
          </div>
        </section>
      )
    }

    if (type === 'vehicles') {
      return (
        <section className="h-full">
          <div className="flex items-center justify-between gap-3">
            <h4 className="text-2xl font-bold text-slate-900">{previewVehiclesTitle}</h4>
            <p className="text-sm text-slate-500">{counts.vehicles} published vehicles</p>
          </div>
          <div className="mt-4 grid gap-5 md:grid-cols-2">
            {[1, 2].map((index) => (
              <article key={index} className="overflow-hidden rounded-[1.5rem] border border-slate-200 bg-white shadow-sm">
                <div className="aspect-[16/10] bg-[linear-gradient(135deg,#e2e8f0,#f8fafc)]" />
                <div className="p-5">
                  <h5 className="text-xl font-bold text-slate-900">Vehicle {index}</h5>
                  <p className="mt-1 text-sm text-slate-500">Category</p>
                  <div className="mt-4 flex items-end justify-between gap-3">
                    <p className="text-xl font-black text-slate-900">MAD 850/day</p>
                    <span className="rounded-full bg-slate-900 px-4 py-2 text-sm font-semibold text-white">{previewViewVehicleLabel}</span>
                  </div>
                </div>
              </article>
            ))}
          </div>
        </section>
      )
    }

    return (
      <section className="h-full space-y-6">
        <div className="flex flex-col gap-3 md:flex-row md:items-end md:justify-between">
          <div>
            <p className="text-sm font-semibold uppercase tracking-[0.18em] text-sky-700">{previewPricingEyebrow}</p>
            <h4 className="mt-2 text-3xl font-black tracking-tight text-slate-900">{previewPricingTitle}</h4>
            <p className="mt-3 max-w-3xl text-sm leading-7 text-slate-600">{previewPricingDescription}</p>
          </div>
          <span className="rounded-full border border-slate-300 px-5 py-2.5 text-sm font-semibold text-slate-700">
            {previewPricingLabel}
          </span>
        </div>

        <div className="grid gap-6 lg:grid-cols-2">
          {PREVIEW_PRICING_PLANS.slice(0, 2).map((plan) => (
            <article
              key={plan.name}
              className={`rounded-[1.5rem] border bg-white p-8 shadow-sm ${plan.highlighted ? 'border-sky-300 shadow-lg shadow-sky-100' : 'border-slate-200'}`}
            >
              <div className="flex items-start justify-between gap-4">
                <div>
                  <h5 className="text-2xl font-black text-slate-900">{plan.name}</h5>
                  <p className="mt-3 text-sm leading-6 text-slate-600">Pricing copy preview for the public homepage.</p>
                </div>
                {plan.highlighted ? (
                  <span className="rounded-full bg-sky-100 px-3 py-1 text-xs font-semibold uppercase tracking-[0.16em] text-sky-800">
                    Popular
                  </span>
                ) : null}
              </div>
              <div className="mt-8 flex items-end gap-2">
                <span className="text-4xl font-black tracking-tight text-slate-900">{plan.price}</span>
                {plan.cadence ? <span className="pb-1 text-sm text-slate-500">{plan.cadence}</span> : null}
              </div>
            </article>
          ))}
        </div>
      </section>
    )
  }

  return (
    <div className="shell space-y-6 py-8">
      <div className="flex items-center justify-between gap-3">
        <Link href="/dashboard/companies" className="text-sm text-zinc-500 hover:text-zinc-300">← Companies</Link>
        <button
          onClick={saveChanges}
          disabled={saving}
          className="rounded-xl bg-emerald-600 px-4 py-2 text-sm font-semibold text-white transition-colors hover:bg-emerald-500 disabled:opacity-50"
        >
          {saving ? 'Saving…' : 'Save changes'}
        </button>
      </div>

      <div className="flex items-start justify-between gap-4">
        <div>
          <h1 className="text-3xl font-black">{company.name}</h1>
          <p className="mt-1 font-mono text-sm text-zinc-400">{company.slug}</p>
        </div>
        <span className={`text-sm font-semibold ${STATUS_COLORS[company.status] ?? 'text-zinc-400'}`}>{company.status}</span>
      </div>

      {error && <div className="panel p-4 text-sm text-red-400">{error}</div>}
      {savedMessage && <div className="panel p-4 text-sm text-emerald-400">{savedMessage}</div>}

      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
        {[
          { label: 'Employees', value: counts.employees },
          { label: 'Vehicles', value: counts.vehicles },
          { label: 'Customers', value: counts.customers },
          { label: 'Reservations', value: counts.reservations },
        ].map((kpi) => (
          <div key={kpi.label} className="panel p-5">
            <p className="text-xs text-zinc-500">{kpi.label}</p>
            <p className="mt-1 text-2xl font-black">{kpi.value}</p>
          </div>
        ))}
      </div>

      <div className="grid gap-6 xl:grid-cols-2">
        <section className="panel p-6">
          <h2 className="text-base font-semibold">Company</h2>
          <div className="mt-4 grid gap-4 md:grid-cols-2">
            <label>
              <span className={LABEL_CLASS}>Name</span>
              <input className={INPUT_CLASS} value={form.company.name} onChange={(e) => updateSection('company', { name: e.target.value })} />
            </label>
            <label>
              <span className={LABEL_CLASS}>Slug</span>
              <input className={INPUT_CLASS} value={form.company.slug} onChange={(e) => updateSection('company', { slug: e.target.value })} />
            </label>
            <label>
              <span className={LABEL_CLASS}>Email</span>
              <input className={INPUT_CLASS} type="email" value={form.company.email} onChange={(e) => updateSection('company', { email: e.target.value })} />
            </label>
            <label>
              <span className={LABEL_CLASS}>Phone</span>
              <input className={INPUT_CLASS} value={form.company.phone} onChange={(e) => updateSection('company', { phone: e.target.value })} />
            </label>
            <label className="md:col-span-2">
              <span className={LABEL_CLASS}>Subscription payment ref</span>
              <input className={INPUT_CLASS} value={form.company.subscriptionPaymentRef} onChange={(e) => updateSection('company', { subscriptionPaymentRef: e.target.value })} />
            </label>
          </div>
        </section>

        <section className="panel p-6">
          <h2 className="text-base font-semibold">Subscription</h2>
          <div className="mt-4 grid gap-4 md:grid-cols-2">
            <label>
              <span className={LABEL_CLASS}>Plan</span>
              <select className={INPUT_CLASS} value={form.subscription.plan} onChange={(e) => updateSection('subscription', { plan: e.target.value })}>
                <option value="STARTER">STARTER</option>
                <option value="GROWTH">GROWTH</option>
                <option value="PRO">PRO</option>
              </select>
            </label>
            <label>
              <span className={LABEL_CLASS}>Billing period</span>
              <select className={INPUT_CLASS} value={form.subscription.billingPeriod} onChange={(e) => updateSection('subscription', { billingPeriod: e.target.value })}>
                <option value="MONTHLY">MONTHLY</option>
                <option value="ANNUAL">ANNUAL</option>
              </select>
            </label>
            <label>
              <span className={LABEL_CLASS}>Status</span>
              <select className={INPUT_CLASS} value={form.subscription.status} onChange={(e) => updateSection('subscription', { status: e.target.value })}>
                <option value="TRIALING">TRIALING</option>
                <option value="ACTIVE">ACTIVE</option>
                <option value="PAST_DUE">PAST_DUE</option>
                <option value="CANCELLED">CANCELLED</option>
                <option value="UNPAID">UNPAID</option>
              </select>
            </label>
            <label>
              <span className={LABEL_CLASS}>Currency</span>
              <select className={INPUT_CLASS} value={form.subscription.currency} onChange={(e) => updateSection('subscription', { currency: e.target.value })}>
                <option value="MAD">MAD</option>
                <option value="USD">USD</option>
                <option value="EUR">EUR</option>
              </select>
            </label>
            <label>
              <span className={LABEL_CLASS}>Trial start</span>
              <input className={INPUT_CLASS} type="date" value={form.subscription.trialStartAt} onChange={(e) => updateSection('subscription', { trialStartAt: e.target.value })} />
            </label>
            <label>
              <span className={LABEL_CLASS}>Trial end</span>
              <input className={INPUT_CLASS} type="date" value={form.subscription.trialEndAt} onChange={(e) => updateSection('subscription', { trialEndAt: e.target.value })} />
            </label>
            <label>
              <span className={LABEL_CLASS}>Period start</span>
              <input className={INPUT_CLASS} type="date" value={form.subscription.currentPeriodStart} onChange={(e) => updateSection('subscription', { currentPeriodStart: e.target.value })} />
            </label>
            <label>
              <span className={LABEL_CLASS}>Period end</span>
              <input className={INPUT_CLASS} type="date" value={form.subscription.currentPeriodEnd} onChange={(e) => updateSection('subscription', { currentPeriodEnd: e.target.value })} />
            </label>
            <label>
              <span className={LABEL_CLASS}>Cancelled at</span>
              <input className={INPUT_CLASS} type="date" value={form.subscription.cancelledAt} onChange={(e) => updateSection('subscription', { cancelledAt: e.target.value })} />
            </label>
            <label className="flex items-center gap-3 pt-7 text-sm text-zinc-300">
              <input type="checkbox" checked={form.subscription.cancelAtPeriodEnd} onChange={(e) => updateSection('subscription', { cancelAtPeriodEnd: e.target.checked })} />
              Cancel at period end
            </label>
          </div>
        </section>

        <section className="panel p-6">
          <h2 className="text-base font-semibold">Brand and public profile</h2>
          <div className="mt-4 grid gap-4 md:grid-cols-2">
            <label>
              <span className={LABEL_CLASS}>Display name</span>
              <input className={INPUT_CLASS} value={form.brand.displayName} onChange={(e) => updateSection('brand', { displayName: e.target.value })} />
            </label>
            <label>
              <span className={LABEL_CLASS}>Subdomain</span>
              <input className={INPUT_CLASS} value={form.brand.subdomain} onChange={(e) => updateSection('brand', { subdomain: e.target.value })} />
            </label>
            <label className="md:col-span-2">
              <span className={LABEL_CLASS}>Tagline</span>
              <input className={INPUT_CLASS} value={form.brand.tagline} onChange={(e) => updateSection('brand', { tagline: e.target.value })} />
            </label>
            <label>
              <span className={LABEL_CLASS}>Public email</span>
              <input className={INPUT_CLASS} type="email" value={form.brand.publicEmail} onChange={(e) => updateSection('brand', { publicEmail: e.target.value })} />
            </label>
            <label>
              <span className={LABEL_CLASS}>Public phone</span>
              <input className={INPUT_CLASS} value={form.brand.publicPhone} onChange={(e) => updateSection('brand', { publicPhone: e.target.value })} />
            </label>
            <label>
              <span className={LABEL_CLASS}>Custom domain</span>
              <input className={INPUT_CLASS} value={form.brand.customDomain} onChange={(e) => updateSection('brand', { customDomain: e.target.value })} />
            </label>
            <label>
              <span className={LABEL_CLASS}>Website URL</span>
              <input className={INPUT_CLASS} type="url" value={form.brand.websiteUrl} onChange={(e) => updateSection('brand', { websiteUrl: e.target.value })} />
            </label>
            <label>
              <span className={LABEL_CLASS}>WhatsApp</span>
              <input className={INPUT_CLASS} value={form.brand.whatsappNumber} onChange={(e) => updateSection('brand', { whatsappNumber: e.target.value })} />
            </label>
            <label>
              <span className={LABEL_CLASS}>Locale</span>
              <input className={INPUT_CLASS} value={form.brand.defaultLocale} onChange={(e) => updateSection('brand', { defaultLocale: e.target.value })} />
            </label>
            <label>
              <span className={LABEL_CLASS}>Brand currency</span>
              <select className={INPUT_CLASS} value={form.brand.defaultCurrency} onChange={(e) => updateSection('brand', { defaultCurrency: e.target.value })}>
                <option value="MAD">MAD</option>
                <option value="USD">USD</option>
                <option value="EUR">EUR</option>
              </select>
            </label>
            <label>
              <span className={LABEL_CLASS}>City</span>
              <input className={INPUT_CLASS} value={form.brand.publicCity} onChange={(e) => updateSection('brand', { publicCity: e.target.value })} />
            </label>
            <label>
              <span className={LABEL_CLASS}>Country</span>
              <input className={INPUT_CLASS} value={form.brand.publicCountry} onChange={(e) => updateSection('brand', { publicCountry: e.target.value })} />
            </label>
            <label className="md:col-span-2">
              <span className={LABEL_CLASS}>Address</span>
              <input className={INPUT_CLASS} value={form.brand.publicAddress} onChange={(e) => updateSection('brand', { publicAddress: e.target.value })} />
            </label>
            <label className="flex items-center gap-3 pt-7 text-sm text-zinc-300">
              <input type="checkbox" checked={form.brand.isListedOnMarketplace} onChange={(e) => updateSection('brand', { isListedOnMarketplace: e.target.checked })} />
              Listed on marketplace
            </label>
          </div>
        </section>

        <section id="site-config" className="panel p-6 xl:col-span-2">
          <div className="flex items-start justify-between gap-4">
            <div>
              <h2 className="text-base font-semibold">Public site homepage and menu</h2>
              <p className="mt-1 text-sm text-zinc-500">Blank text fields fall back to the default localized copy on the public site.</p>
            </div>
          </div>

          <div className="mt-6 grid gap-6 xl:grid-cols-2">
            <div className="space-y-4">
              <h3 className="text-sm font-semibold text-zinc-200">Homepage content</h3>
              <div className="grid gap-4 md:grid-cols-2">
                <label className="md:col-span-2">
                  <span className={LABEL_CLASS}>Hero title</span>
                  <input className={INPUT_CLASS} value={form.brand.homePageConfig.heroTitle} onChange={(e) => updateBrandConfig('homePageConfig', { heroTitle: e.target.value })} />
                </label>
                <label className="md:col-span-2">
                  <span className={LABEL_CLASS}>Hero description</span>
                  <textarea className={`${INPUT_CLASS} min-h-24`} value={form.brand.homePageConfig.heroDescription} onChange={(e) => updateBrandConfig('homePageConfig', { heroDescription: e.target.value })} />
                </label>
                <label>
                  <span className={LABEL_CLASS}>Offers button label</span>
                  <input className={INPUT_CLASS} value={form.brand.homePageConfig.viewOffersLabel} onChange={(e) => updateBrandConfig('homePageConfig', { viewOffersLabel: e.target.value })} />
                </label>
                <label>
                  <span className={LABEL_CLASS}>Pricing button label</span>
                  <input className={INPUT_CLASS} value={form.brand.homePageConfig.viewPricingLabel} onChange={(e) => updateBrandConfig('homePageConfig', { viewPricingLabel: e.target.value })} />
                </label>
                <label className="md:col-span-2">
                  <span className={LABEL_CLASS}>Contact button label</span>
                  <input className={INPUT_CLASS} value={form.brand.homePageConfig.contactCompanyLabel} onChange={(e) => updateBrandConfig('homePageConfig', { contactCompanyLabel: e.target.value })} />
                </label>
                <label>
                  <span className={LABEL_CLASS}>Offers section title</span>
                  <input className={INPUT_CLASS} value={form.brand.homePageConfig.activeOffersTitle} onChange={(e) => updateBrandConfig('homePageConfig', { activeOffersTitle: e.target.value })} />
                </label>
                <label>
                  <span className={LABEL_CLASS}>See all offers label</span>
                  <input className={INPUT_CLASS} value={form.brand.homePageConfig.seeAllOffersLabel} onChange={(e) => updateBrandConfig('homePageConfig', { seeAllOffersLabel: e.target.value })} />
                </label>
                <label className="md:col-span-2">
                  <span className={LABEL_CLASS}>No active offers text</span>
                  <input className={INPUT_CLASS} value={form.brand.homePageConfig.noActiveOffersLabel} onChange={(e) => updateBrandConfig('homePageConfig', { noActiveOffersLabel: e.target.value })} />
                </label>
                <label>
                  <span className={LABEL_CLASS}>Vehicles section title</span>
                  <input className={INPUT_CLASS} value={form.brand.homePageConfig.publishedVehiclesTitle} onChange={(e) => updateBrandConfig('homePageConfig', { publishedVehiclesTitle: e.target.value })} />
                </label>
                <label>
                  <span className={LABEL_CLASS}>View vehicle label</span>
                  <input className={INPUT_CLASS} value={form.brand.homePageConfig.viewVehicleLabel} onChange={(e) => updateBrandConfig('homePageConfig', { viewVehicleLabel: e.target.value })} />
                </label>
                <label>
                  <span className={LABEL_CLASS}>Pricing eyebrow</span>
                  <input className={INPUT_CLASS} value={form.brand.homePageConfig.pricingEyebrow} onChange={(e) => updateBrandConfig('homePageConfig', { pricingEyebrow: e.target.value })} />
                </label>
                <label>
                  <span className={LABEL_CLASS}>Pricing title</span>
                  <input className={INPUT_CLASS} value={form.brand.homePageConfig.pricingTitle} onChange={(e) => updateBrandConfig('homePageConfig', { pricingTitle: e.target.value })} />
                </label>
                <label className="md:col-span-2">
                  <span className={LABEL_CLASS}>Pricing description</span>
                  <textarea className={`${INPUT_CLASS} min-h-24`} value={form.brand.homePageConfig.pricingDescription} onChange={(e) => updateBrandConfig('homePageConfig', { pricingDescription: e.target.value })} />
                </label>
              </div>

              <HomepageLayoutEditor
                layout={homepageLayout}
                availableSections={availableHomepageSections}
                onChange={updateHomepageLayout}
                onAddSection={addHomepageSection}
                onRemoveSection={removeHomepageSection}
              />
            </div>

            <div className="space-y-4">
              <h3 className="text-sm font-semibold text-zinc-200">Navigation menu</h3>
              <div className="grid gap-4 md:grid-cols-2">
                <label>
                  <span className={LABEL_CLASS}>About label</span>
                  <input className={INPUT_CLASS} value={form.brand.menuConfig.aboutLabel} onChange={(e) => updateBrandConfig('menuConfig', { aboutLabel: e.target.value })} />
                </label>
                <label className="flex items-center gap-3 pt-7 text-sm text-zinc-300">
                  <input type="checkbox" checked={form.brand.menuConfig.showAbout} onChange={(e) => updateBrandConfig('menuConfig', { showAbout: e.target.checked })} />
                  Show About
                </label>
                <label>
                  <span className={LABEL_CLASS}>Vehicles label</span>
                  <input className={INPUT_CLASS} value={form.brand.menuConfig.vehiclesLabel} onChange={(e) => updateBrandConfig('menuConfig', { vehiclesLabel: e.target.value })} />
                </label>
                <label className="flex items-center gap-3 pt-7 text-sm text-zinc-300">
                  <input type="checkbox" checked={form.brand.menuConfig.showVehicles} onChange={(e) => updateBrandConfig('menuConfig', { showVehicles: e.target.checked })} />
                  Show Vehicles
                </label>
                <label>
                  <span className={LABEL_CLASS}>Offers label</span>
                  <input className={INPUT_CLASS} value={form.brand.menuConfig.offersLabel} onChange={(e) => updateBrandConfig('menuConfig', { offersLabel: e.target.value })} />
                </label>
                <label className="flex items-center gap-3 pt-7 text-sm text-zinc-300">
                  <input type="checkbox" checked={form.brand.menuConfig.showOffers} onChange={(e) => updateBrandConfig('menuConfig', { showOffers: e.target.checked })} />
                  Show Offers
                </label>
                <label>
                  <span className={LABEL_CLASS}>Pricing label</span>
                  <input className={INPUT_CLASS} value={form.brand.menuConfig.pricingLabel} onChange={(e) => updateBrandConfig('menuConfig', { pricingLabel: e.target.value })} />
                </label>
                <label className="flex items-center gap-3 pt-7 text-sm text-zinc-300">
                  <input type="checkbox" checked={form.brand.menuConfig.showPricing} onChange={(e) => updateBrandConfig('menuConfig', { showPricing: e.target.checked })} />
                  Show Pricing
                </label>
                <label>
                  <span className={LABEL_CLASS}>Blog label</span>
                  <input className={INPUT_CLASS} value={form.brand.menuConfig.blogLabel} onChange={(e) => updateBrandConfig('menuConfig', { blogLabel: e.target.value })} />
                </label>
                <label className="flex items-center gap-3 pt-7 text-sm text-zinc-300">
                  <input type="checkbox" checked={form.brand.menuConfig.showBlog} onChange={(e) => updateBrandConfig('menuConfig', { showBlog: e.target.checked })} />
                  Show Blog
                </label>
                <label>
                  <span className={LABEL_CLASS}>Contact label</span>
                  <input className={INPUT_CLASS} value={form.brand.menuConfig.contactLabel} onChange={(e) => updateBrandConfig('menuConfig', { contactLabel: e.target.value })} />
                </label>
                <label className="flex items-center gap-3 pt-7 text-sm text-zinc-300">
                  <input type="checkbox" checked={form.brand.menuConfig.showContact} onChange={(e) => updateBrandConfig('menuConfig', { showContact: e.target.checked })} />
                  Show Contact
                </label>
                <label>
                  <span className={LABEL_CLASS}>Book car button label</span>
                  <input className={INPUT_CLASS} value={form.brand.menuConfig.bookCarLabel} onChange={(e) => updateBrandConfig('menuConfig', { bookCarLabel: e.target.value })} />
                </label>
                <label>
                  <span className={LABEL_CLASS}>Footer navigation label</span>
                  <input className={INPUT_CLASS} value={form.brand.menuConfig.siteNavigationLabel} onChange={(e) => updateBrandConfig('menuConfig', { siteNavigationLabel: e.target.value })} />
                </label>
              </div>

              <div className="rounded-2xl border border-zinc-800 bg-zinc-950/60 p-4">
                <h4 className="text-sm font-semibold text-zinc-100">Page sections</h4>
                <p className="mt-1 text-xs text-zinc-500">Turn sections on or off across every public page.</p>
                <div className="mt-4 grid gap-4">
                  {PAGE_SECTION_GROUPS.map((group) => (
                    <div key={group.page} className="rounded-xl border border-zinc-800 bg-zinc-900/50 p-4">
                      <p className="text-xs font-semibold uppercase tracking-[0.16em] text-zinc-500">{group.label}</p>
                      <div className="mt-3 grid gap-3 md:grid-cols-2">
                        {group.sections.map((section) => (
                          <label key={section.key} className="flex items-center gap-3 text-sm text-zinc-300">
                            <input
                              type="checkbox"
                              checked={getPageSectionValue(group.page, section.key as keyof PublicSitePageSections[typeof group.page])}
                              onChange={(e) => updatePageSection(group.page, section.key as keyof PublicSitePageSections[typeof group.page], e.target.checked)}
                            />
                            {section.label}
                          </label>
                        ))}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </div>

          <div className="mt-8 rounded-[2rem] border border-zinc-800 bg-zinc-950 p-4">
            <div className="flex items-center justify-between gap-4 border-b border-zinc-800 px-2 pb-4">
              <div>
                <h3 className="text-sm font-semibold text-zinc-100">Live homepage preview</h3>
                <p className="mt-1 text-xs text-zinc-500">Unsaved changes appear here instantly before you publish them.</p>
              </div>
              <span className="rounded-full border border-emerald-500/30 bg-emerald-500/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-emerald-300">
                Draft preview
              </span>
            </div>

            <div className="mt-4 overflow-hidden rounded-[1.75rem] border border-sky-100 bg-[linear-gradient(180deg,#eff6ff,white_28%)] shadow-2xl shadow-black/20">
              <div className="border-b border-slate-200 bg-white/90 px-5 py-4 backdrop-blur-sm">
                <div className="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
                  <div className="flex items-center gap-3">
                    <span className="inline-flex h-9 w-9 items-center justify-center rounded-xl bg-sky-600 text-sm font-black text-white">
                      {previewCompanyName.charAt(0).toUpperCase()}
                    </span>
                    <div>
                      <p className="text-sm font-black tracking-tight text-slate-900">{previewCompanyName}</p>
                      <p className="text-xs text-slate-500">{form.brand.subdomain || form.company.slug || company.slug}.rentaldrivego.com</p>
                    </div>
                  </div>
                  <nav className="flex flex-wrap items-center gap-2 text-sm text-slate-600">
                    {previewMenuItems.map((item) => (
                      <span key={item.label} className="rounded-lg px-3 py-2 transition-colors hover:bg-slate-100 hover:text-slate-900">
                        {item.label}
                      </span>
                    ))}
                  </nav>
                  <span className="inline-flex rounded-full bg-slate-900 px-5 py-2 text-sm font-semibold text-white">
                    {previewBookCarLabel}
                  </span>
                </div>
              </div>

              <div className="px-5 py-8 lg:px-8">
                <div className="grid gap-6 lg:hidden">
                  {homepageLayout.items.map((item) => (
                    <div key={`mobile-${item.id}`} className="rounded-[1.5rem] border border-slate-200 bg-white p-5 shadow-sm">
                      {renderHomepagePreviewSection(item.type)}
                    </div>
                  ))}
                </div>

                <div
                  className="relative hidden lg:block"
                  style={{ height: `${homepageLayout.items.reduce((max, item) => Math.max(max, item.y + item.h - 1), 1) * 72}px` }}
                >
                  {homepageLayout.items.map((item) => (
                    <div
                      key={item.id}
                      className="absolute rounded-[1.75rem] border border-slate-200/80 bg-white/92 p-6 shadow-lg shadow-slate-200/70"
                      style={{
                        left: `${((item.x - 1) / 12) * 100}%`,
                        top: `${(item.y - 1) * 72}px`,
                        width: `${(item.w / 12) * 100}%`,
                        height: `${item.h * 72}px`,
                      }}
                    >
                      {renderHomepagePreviewSection(item.type)}
                    </div>
                  ))}
                </div>
              </div>

              <div className="border-t border-stone-200 bg-white/90 px-5 py-4 backdrop-blur-md">
                <div className="flex flex-col items-center justify-between gap-3 lg:flex-row">
                  <p className="text-xs font-medium uppercase tracking-[0.16em] text-stone-400">{previewFooterLabel}</p>
                  <div className="flex flex-col items-center gap-3 sm:flex-row">
                    <div className="flex flex-wrap items-center justify-center gap-2 text-sm text-stone-500">
                      {previewMenuItems.map((item) => (
                        <span key={`${item.label}-footer`} className="rounded-full px-3 py-1.5 transition hover:bg-stone-100 hover:text-stone-900">
                          {item.label}
                        </span>
                      ))}
                    </div>
                    <p className="text-sm text-stone-500">&copy; {new Date().getFullYear()} {previewCompanyName}</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </section>

        <section className="panel p-6">
          <h2 className="text-base font-semibold">Operations and finance</h2>
          <div className="mt-4 grid gap-6">
            <div className="grid gap-4 md:grid-cols-2">
              <label>
                <span className={LABEL_CLASS}>Legal name</span>
                <input className={INPUT_CLASS} value={form.contractSettings.legalName} onChange={(e) => updateSection('contractSettings', { legalName: e.target.value })} />
              </label>
              <label>
                <span className={LABEL_CLASS}>Registration number</span>
                <input className={INPUT_CLASS} value={form.contractSettings.registrationNumber} onChange={(e) => updateSection('contractSettings', { registrationNumber: e.target.value })} />
              </label>
              <label>
                <span className={LABEL_CLASS}>Tax ID</span>
                <input className={INPUT_CLASS} value={form.contractSettings.taxId} onChange={(e) => updateSection('contractSettings', { taxId: e.target.value })} />
              </label>
              <label>
                <span className={LABEL_CLASS}>Fuel policy type</span>
                <select className={INPUT_CLASS} value={form.contractSettings.fuelPolicyType} onChange={(e) => updateSection('contractSettings', { fuelPolicyType: e.target.value })}>
                  <option value="FULL_TO_FULL">FULL_TO_FULL</option>
                  <option value="FULL_TO_EMPTY">FULL_TO_EMPTY</option>
                  <option value="SAME_TO_SAME">SAME_TO_SAME</option>
                  <option value="PREPAID">PREPAID</option>
                  <option value="FREE">FREE</option>
                </select>
              </label>
              <label>
                <span className={LABEL_CLASS}>Late fee per hour</span>
                <input className={INPUT_CLASS} type="number" value={form.contractSettings.lateFeePerHour} onChange={(e) => updateSection('contractSettings', { lateFeePerHour: e.target.value })} />
              </label>
              <label>
                <span className={LABEL_CLASS}>Tax rate</span>
                <input className={INPUT_CLASS} type="number" step="0.01" value={form.contractSettings.taxRate} onChange={(e) => updateSection('contractSettings', { taxRate: e.target.value })} />
              </label>
              <label className="flex items-center gap-3 pt-7 text-sm text-zinc-300">
                <input type="checkbox" checked={form.contractSettings.signatureRequired} onChange={(e) => updateSection('contractSettings', { signatureRequired: e.target.checked })} />
                Signature required
              </label>
              <label className="flex items-center gap-3 pt-7 text-sm text-zinc-300">
                <input type="checkbox" checked={form.contractSettings.showTax} onChange={(e) => updateSection('contractSettings', { showTax: e.target.checked })} />
                Show tax on documents
              </label>
              <label className="md:col-span-2">
                <span className={LABEL_CLASS}>Terms</span>
                <textarea className={`${INPUT_CLASS} min-h-28`} value={form.contractSettings.terms} onChange={(e) => updateSection('contractSettings', { terms: e.target.value })} />
              </label>
            </div>

            <div className="border-t border-zinc-800 pt-6">
              <h3 className="text-sm font-semibold text-zinc-200">Accounting settings</h3>
              <div className="mt-4 grid gap-4 md:grid-cols-2">
                <label>
                  <span className={LABEL_CLASS}>Reporting period</span>
                  <select className={INPUT_CLASS} value={form.accountingSettings.reportingPeriod} onChange={(e) => updateSection('accountingSettings', { reportingPeriod: e.target.value })}>
                    <option value="WEEKLY">WEEKLY</option>
                    <option value="MONTHLY">MONTHLY</option>
                    <option value="QUARTERLY">QUARTERLY</option>
                    <option value="ANNUAL">ANNUAL</option>
                  </select>
                </label>
                <label>
                  <span className={LABEL_CLASS}>Fiscal year start month</span>
                  <input className={INPUT_CLASS} type="number" min="1" max="12" value={form.accountingSettings.fiscalYearStart} onChange={(e) => updateSection('accountingSettings', { fiscalYearStart: e.target.value })} />
                </label>
                <label>
                  <span className={LABEL_CLASS}>Accounting currency</span>
                  <select className={INPUT_CLASS} value={form.accountingSettings.currency} onChange={(e) => updateSection('accountingSettings', { currency: e.target.value })}>
                    <option value="MAD">MAD</option>
                    <option value="USD">USD</option>
                    <option value="EUR">EUR</option>
                  </select>
                </label>
                <label>
                  <span className={LABEL_CLASS}>Report format</span>
                  <select className={INPUT_CLASS} value={form.accountingSettings.reportFormat} onChange={(e) => updateSection('accountingSettings', { reportFormat: e.target.value })}>
                    <option value="PDF">PDF</option>
                    <option value="CSV">CSV</option>
                    <option value="BOTH">BOTH</option>
                  </select>
                </label>
                <label>
                  <span className={LABEL_CLASS}>Accountant name</span>
                  <input className={INPUT_CLASS} value={form.accountingSettings.accountantName} onChange={(e) => updateSection('accountingSettings', { accountantName: e.target.value })} />
                </label>
                <label>
                  <span className={LABEL_CLASS}>Accountant email</span>
                  <input className={INPUT_CLASS} type="email" value={form.accountingSettings.accountantEmail} onChange={(e) => updateSection('accountingSettings', { accountantEmail: e.target.value })} />
                </label>
                <label className="flex items-center gap-3 pt-7 text-sm text-zinc-300">
                  <input type="checkbox" checked={form.accountingSettings.autoSendReport} onChange={(e) => updateSection('accountingSettings', { autoSendReport: e.target.checked })} />
                  Auto-send reports
                </label>
              </div>
            </div>
          </div>
        </section>
      </div>

      <div className="grid gap-6 lg:grid-cols-2">
        <div className="panel p-6 space-y-4">
          <h2 className="text-base font-semibold">Admin actions</h2>
          <div className="space-y-3">
            {company.status === 'SUSPENDED' ? (
              <button onClick={() => changeStatus('ACTIVE')} disabled={actioning} className="w-full rounded-xl bg-emerald-900/40 py-2.5 text-sm font-semibold text-emerald-400 transition-colors hover:bg-emerald-900/60 disabled:opacity-50">
                Reactivate company
              </button>
            ) : (
              <button onClick={() => changeStatus('SUSPENDED')} disabled={actioning} className="w-full rounded-xl bg-red-950/40 py-2.5 text-sm font-semibold text-red-400 transition-colors hover:bg-red-950/60 disabled:opacity-50">
                Suspend company
              </button>
            )}
            {!deleteConfirm ? (
              <button onClick={() => setDeleteConfirm(true)} className="w-full rounded-xl bg-zinc-800 py-2.5 text-sm font-semibold text-zinc-400 transition-colors hover:bg-zinc-700">
                Delete company
              </button>
            ) : (
              <div className="space-y-3 rounded-xl border border-red-900/50 p-4">
                <p className="text-sm font-medium text-red-400">This will permanently delete all company data. Are you sure?</p>
                <div className="flex gap-2">
                  <button onClick={() => setDeleteConfirm(false)} className="flex-1 rounded-lg bg-zinc-800 py-2 text-sm text-zinc-300">Cancel</button>
                  <button onClick={deleteCompany} disabled={actioning} className="flex-1 rounded-lg bg-red-700 py-2 text-sm font-semibold text-white hover:bg-red-600 disabled:opacity-50">Delete</button>
                </div>
              </div>
            )}
          </div>
        </div>

        {auditLogs.length > 0 && (
          <div className="panel overflow-hidden">
            <div className="border-b border-zinc-800 px-6 py-4">
              <h2 className="text-sm font-semibold">Recent audit events</h2>
            </div>
            <div className="divide-y divide-zinc-800/60">
              {auditLogs.map((log) => (
                <div key={log.id} className="flex items-center justify-between px-6 py-3 text-sm">
                  <div>
                    <span className="font-medium text-zinc-200">{log.action}</span>
                    <span className="ml-2 text-zinc-500">{log.resource}</span>
                    {log.adminUser?.email ? <span className="ml-2 text-zinc-600">{log.adminUser.email}</span> : null}
                  </div>
                  <span className="text-xs text-zinc-600">{new Date(log.createdAt).toLocaleString()}</span>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  )
}
