import type { Metadata } from 'next'
import Link from 'next/link'
import './globals.css'
import { DEFAULT_COMPANY_SLUG, siteFetchOrDefault } from '@/lib/api'
import { getPublicSiteLanguage } from '@/lib/i18n.server'
import { getPublicSiteDictionary } from '@/lib/i18n'
import PublicLanguageSwitcher from '@/components/PublicLanguageSwitcher'
import PublicThemeSwitcher from '@/components/PublicThemeSwitcher'
import type { PublicSitePageSections } from '@rentaldrivego/types'

export const metadata: Metadata = {
  title: 'RentalDriveGo Public Site',
  description: 'Branded company booking site for RentalDriveGo tenants.',
}

interface BrandResponse {
  company: { slug: string; name: string }
  brand: {
    displayName: string
    tagline: string | null
    heroImageUrl: string | 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 | null
      showVehicles?: boolean | null
      showOffers?: boolean | null
      showPricing?: boolean | null
      showBlog?: boolean | null
      showContact?: boolean | null
      pageSections?: Partial<PublicSitePageSections> | null
    } | null
  } | null
}

function resolveText(value: string | null | undefined, fallback: string) {
  return value && value.trim() ? value : fallback
}

function resolveVisible(value: boolean | null | undefined) {
  return value ?? true
}

export default async function RootLayout({ children }: { children: React.ReactNode }) {
  const slug = DEFAULT_COMPANY_SLUG
  const language = getPublicSiteLanguage()
  const dict = getPublicSiteDictionary(language)
  const brand = await siteFetchOrDefault<BrandResponse | null>(
    `/site/${slug}/brand`,
    null,
  )

  const companyName = brand?.brand?.displayName ?? brand?.company.name ?? 'RentalDriveGo'
  const menuConfig = brand?.brand?.menuConfig ?? null
  const headerMenuItems = [
    { href: '/about', label: resolveText(menuConfig?.aboutLabel, dict.nav.about), visible: resolveVisible(menuConfig?.showAbout) },
    { href: '/vehicles', label: resolveText(menuConfig?.vehiclesLabel, dict.nav.vehicles), visible: resolveVisible(menuConfig?.showVehicles) },
    { href: '/offers', label: resolveText(menuConfig?.offersLabel, dict.nav.offers), visible: resolveVisible(menuConfig?.showOffers) },
    { href: '/pricing', label: resolveText(menuConfig?.pricingLabel, dict.nav.pricing), visible: resolveVisible(menuConfig?.showPricing) },
    { href: '/blog', label: resolveText(menuConfig?.blogLabel, dict.nav.blog), visible: resolveVisible(menuConfig?.showBlog) },
    { href: '/contact', label: resolveText(menuConfig?.contactLabel, dict.nav.contact), visible: resolveVisible(menuConfig?.showContact) },
  ]
  const footerLabel = resolveText(menuConfig?.siteNavigationLabel, dict.nav.siteNavigation)
  const bookCarLabel = resolveText(menuConfig?.bookCarLabel, dict.nav.bookCar)

  return (
    <html lang={dict.lang} dir={dict.dir} className="light" suppressHydrationWarning>
      <head>
        <script
          dangerouslySetInnerHTML={{
            __html:
              "(function(){try{var theme=localStorage.getItem('public-site-theme');if(theme!=='light'&&theme!=='dark'){theme=window.matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light'}document.documentElement.classList.remove('light','dark');document.documentElement.classList.add(theme);document.documentElement.style.colorScheme=theme}catch(e){}})();",
          }}
        />
      </head>
      <body suppressHydrationWarning>
        <header className="sticky top-0 z-30 border-b border-slate-200 bg-white/90 backdrop-blur-sm transition-colors dark:border-slate-800 dark:bg-slate-950/90">
          <div className="shell flex h-14 items-center justify-between gap-6">
            <Link
              href="/"
              className="flex items-center gap-2 text-lg font-black tracking-tight text-slate-900 dark:text-slate-100"
            >
              <span className="inline-flex h-7 w-7 items-center justify-center rounded-lg bg-sky-600 text-white text-xs font-black select-none">
                {companyName.charAt(0).toUpperCase()}
              </span>
              <span className="hidden sm:inline">{companyName}</span>
            </Link>

            <nav className="flex items-center gap-1">
              {headerMenuItems.filter((item) => item.visible).map((item) => (
                <NavLink key={item.href} href={item.href}>{item.label}</NavLink>
              ))}
            </nav>

            <div className="flex items-center gap-3">
              <PublicLanguageSwitcher currentLanguage={language} />
              <PublicThemeSwitcher currentLanguage={language} />
              <Link
                href="/vehicles"
                className="hidden rounded-full bg-slate-900 px-5 py-2 text-sm font-semibold text-white transition-colors hover:bg-slate-700 dark:bg-slate-100 dark:text-slate-950 dark:hover:bg-slate-200 sm:inline-flex"
              >
                {bookCarLabel}
              </Link>
            </div>
          </div>
        </header>

        {children}

        <footer className="mt-16 border-t border-stone-200 bg-white/90 px-4 py-4 backdrop-blur-md transition-colors dark:border-stone-800 dark:bg-slate-950/90">
          <div className="shell 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 dark:text-stone-500">
              {footerLabel}
            </p>
            <div className="flex flex-col items-center gap-3 sm:flex-row">
              <nav className="flex flex-wrap items-center justify-center gap-2 text-sm text-stone-500 dark:text-stone-400">
                {headerMenuItems.filter((item) => item.visible).map((item) => (
                  <Link key={item.href} href={item.href} className="rounded-full px-3 py-1.5 transition hover:bg-stone-100 hover:text-stone-900 dark:hover:bg-stone-800 dark:hover:text-stone-100">
                    {item.label}
                  </Link>
                ))}
              </nav>
              <p className="text-sm text-stone-500 dark:text-stone-400">
                &copy; {new Date().getFullYear()} {companyName}
              </p>
            </div>
          </div>
        </footer>
      </body>
    </html>
  )
}

function NavLink({ href, children }: { href: string; children: React.ReactNode }) {
  return (
    <Link
      href={href}
      className="rounded-lg px-3 py-2 text-sm font-medium text-slate-600 transition-colors hover:bg-slate-100 hover:text-slate-900 dark:text-slate-300 dark:hover:bg-slate-800 dark:hover:text-slate-100"
    >
      {children}
    </Link>
  )
}
