import { headers } from "next/headers";
import { storefrontApi } from "@/lib/api";
import Navbar from "@/components/layout/Navbar";
import Footer from "@/components/layout/Footer";
import AnnouncementBar from "@/components/layout/AnnouncementBar";
import AuthHydrator from "@/components/auth/AuthHydrator";
import { getTemplate } from "@/lib/template";
import { resolveMediaUrl, getLocalizedText } from "@/lib/utils";
import { LanguageProvider } from "@/lib/language-context";
import { StorefrontConfigProvider } from "@/lib/storefront-config-context";
import {
  type Locale,
  DEFAULT_LOCALE,
  LOCALE_COOKIE,
  isRTL,
  getTranslations,
} from "@/lib/i18n";
import { SpeedInsights } from "@vercel/speed-insights/next";
import "./globals.css";

export const viewport = {
  width: "device-width",
  initialScale: 1,
  maximumScale: 5,
};

export default async function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const headersList = await headers();
  const tenantSlug = headersList.get("x-tenant-slug") || "";

  // Read cookies once
  const cookieHeader = headersList.get("cookie") ?? "";

  // Detect language from cookie
  const langCookie = cookieHeader.match(
    new RegExp(`${LOCALE_COOKIE}=([^;]+)`),
  )?.[1];
  const locale: Locale =
    langCookie === "en" || langCookie === "ar" ? langCookie : DEFAULT_LOCALE;

  // No tenant slug means this is a raw Vercel preview URL or unknown domain.
  // Render a simple "store not found" page without hitting the API.
  if (!tenantSlug) {
    const serverT = getTranslations(locale);
    return (
      <html lang={locale} dir={isRTL(locale) ? "rtl" : "ltr"}>
        <body
          style={{
            margin: 0,
            fontFamily: "system-ui, sans-serif",
            background: "#f9fafb",
          }}
        >
          <div
            style={{
              minHeight: "100vh",
              display: "flex",
              flexDirection: "column",
              alignItems: "center",
              justifyContent: "center",
              padding: "2rem",
              textAlign: "center",
            }}
          >
            <div style={{ fontSize: "3rem", marginBottom: "1rem" }}>🏪</div>
            <h1
              style={{
                fontSize: "1.5rem",
                fontWeight: 700,
                color: "#111827",
                margin: "0 0 0.5rem",
              }}
            >
              {serverT.common.storeNotFound}
            </h1>
            <p style={{ color: "#6b7280", maxWidth: "360px", lineHeight: 1.6 }}>
              {serverT.common.storeNotLinked}{" "}
              <strong>yourstore.shop.sellzaki.com</strong>.
            </p>
          </div>
        </body>
      </html>
    );
  }

  // Check for preview token in cookie (set by preview link from admin)
  const previewToken =
    cookieHeader.match(/sellzaki_preview=([^;]+)/)?.[1] ?? null;

  let storeName = "Online Store";
  let theme: Record<string, any> = {};
  let currency = "EGP";
  let isPublished = true;
  let templateId = "default";
  let websiteConfig: Record<string, any> = {};

  let staticPages: { title: string; title_ar?: string; slug: string }[] = [];
  let collections: { title: string; title_ar?: string; slug: string }[] = [];

  try {
    const extraHeaders: Record<string, string> = {};
    if (previewToken) extraHeaders["X-Sellzaki-Preview"] = previewToken;

    const config = await storefrontApi.getConfig(tenantSlug, extraHeaders);
    const { website: w } = config;
    storeName = w.name ?? storeName;
    theme = (w.theme_settings as any) ?? {};
    currency = (w as any).currency ?? "EGP";
    isPublished = w.is_published ?? true;
    templateId = (w as any).template_id ?? "default";
    staticPages = config.static_pages ?? [];
    collections = config.collections ?? [];
    websiteConfig = w as any;
  } catch {
    // Store not configured — render minimal shell
  }

  const template = getTemplate(templateId);
  const primaryColor = theme.primary_color || "#1FAF9A";
  const secondaryColor = theme.secondary_color || "#0D2B45";
  const font = (theme.font || "Inter").replace(/\s+/g, "+");

  const localizedLabel = (item: { title: string; title_ar?: string | null }) =>
    getLocalizedText(item.title, item.title_ar, locale);

  // Footer: manual links only; filter out empty, placeholder, or "test" links
  const footerLinks: { label: string; url: string }[] = (
    theme.footer_links ?? []
  ).filter((l: { label?: string; url?: string }) => {
    const label = (l.label?.trim() ?? "").toLowerCase();
    const url = l.url?.trim() ?? "";
    return url !== "" && label !== "" && label !== "test";
  });
  // Removed: pages and collections from footer
  // if (theme.show_pages_in_footer && staticPages.length > 0) {
  //   staticPages.forEach((p) =>
  //     footerLinks.push({ label: localizedLabel(p), url: `/pages/${p.slug}` }),
  //   );
  // }
  // if (theme.show_collections_in_footer && collections.length > 0) {
  //   collections.forEach((c) =>
  //     footerLinks.push({
  //       label: localizedLabel(c),
  //       url: `/collections/${c.slug}`,
  //     }),
  //   );
  // }

  // Extra nav links for header (pages + collections when enabled)
  // Pass raw data with both title and title_ar so client can switch instantly
  const extraNavLinks: { href: string; label: string; label_ar?: string }[] =
    [];
  if (theme.show_pages_in_nav && staticPages.length > 0) {
    staticPages.forEach((p) =>
      extraNavLinks.push({
        href: `/pages/${p.slug}`,
        label: p.title,
        label_ar: p.title_ar,
      }),
    );
  }
  if (theme.show_collections_in_nav && collections.length > 0) {
    collections.forEach((c) =>
      extraNavLinks.push({
        href: `/collections/${c.slug}`,
        label: c.title,
        label_ar: c.title_ar,
      }),
    );
  }
  const logoUrl: string | null = resolveMediaUrl(theme.logo_url ?? null);
  const logoWidth: number = theme.logo_width ?? 140;
  const logoHeight: number = theme.logo_height ?? 44;
  const announcementBar = theme.announcement_bar;
  const seo = theme.seo;

  // Boutique uses serif font pairing
  const serifFont = template.id === "boutique" ? "Cormorant+Garamond" : null;

  // Build dynamic metadata from SEO settings
  const pageTitle = seo?.title || storeName || "Online Store";
  const pageDescription = seo?.description || `Shop online at ${storeName}`;
  const pageKeywords = seo?.keywords || undefined;
  const ogImage = resolveMediaUrl(seo?.og_image_url) || logoUrl || undefined;

  // Load Arabic font when locale is ar
  const arabicFont = locale === "ar" ? "Cairo" : null;

  // Server-side translations for server components
  const serverT = getTranslations(locale);

  return (
    <html
      lang={locale}
      dir={isRTL(locale) ? "rtl" : "ltr"}
      data-template={template.id}
      suppressHydrationWarning
    >
      <head>
        <title>{pageTitle}</title>
        <meta name="description" content={pageDescription} />
        {pageKeywords && <meta name="keywords" content={pageKeywords} />}
        {logoUrl && <link rel="icon" href={logoUrl} type="image/png" />}
        {logoUrl && <link rel="apple-touch-icon" href={logoUrl} />}
        <meta property="og:title" content={pageTitle} />
        <meta property="og:description" content={pageDescription} />
        <meta property="og:type" content="website" />
        {ogImage && <meta property="og:image" content={ogImage} />}
        <meta name="twitter:card" content="summary_large_image" />
        <meta name="twitter:title" content={pageTitle} />
        <meta name="twitter:description" content={pageDescription} />
        {ogImage && <meta name="twitter:image" content={ogImage} />}
        <link rel="preconnect" href="https://fonts.googleapis.com" />
        <link
          rel="preconnect"
          href="https://fonts.gstatic.com"
          crossOrigin="anonymous"
        />
        <link
          href={`https://fonts.googleapis.com/css2?family=${font}:wght@400;500;600;700;900${
            serifFont ? `&family=${serifFont}:wght@300;400;600` : ""
          }${
            arabicFont && arabicFont !== font.replace(/\+/g, " ")
              ? `&family=${arabicFont}:wght@400;500;600;700`
              : ""
          }&display=swap`}
          rel="stylesheet"
        />
        <style>{`
          :root {
            --color-primary: ${primaryColor};
            --color-secondary: ${secondaryColor};
            --font-body: '${font.replace(/\+/g, " ")}', system-ui, sans-serif;
            ${
              serifFont
                ? `--font-serif: '${serifFont.replace(
                    /\+/g,
                    " ",
                  )}', Georgia, serif;`
                : ""
            }
            ${
              arabicFont
                ? `--font-arabic: '${arabicFont}', system-ui, sans-serif;`
                : ""
            }
          }

          body {
            font-family: var(--font-body);
            -webkit-font-smoothing: antialiased;
            -moz-osx-font-smoothing: grayscale;
            letter-spacing: -0.01em;
          }
          [lang="ar"] body, [lang="ar"] { font-family: var(--font-arabic, var(--font-body)); letter-spacing: 0; }

          /* ── Primary button ─────────────────────────────────────────────── */
          .btn-primary {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 0.5rem;
            background-color: var(--color-primary);
            color: #fff;
            font-weight: 600;
            letter-spacing: 0.01em;
            transition: filter 0.15s ease, transform 0.1s ease, box-shadow 0.15s ease;
            cursor: pointer;
          }
          [lang="ar"] .btn-primary { letter-spacing: 0; }
          .btn-primary:hover {
            filter: brightness(0.88);
            box-shadow: 0 4px 16px -4px color-mix(in srgb, var(--color-primary) 50%, transparent);
          }
          .btn-primary:active { transform: scale(0.98); }
          .btn-primary:disabled { opacity: 0.45; cursor: not-allowed; filter: none; transform: none; box-shadow: none; }

          /* ── Secondary button ───────────────────────────────────────────── */
          .btn-secondary {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 0.5rem;
            background-color: transparent;
            color: var(--color-secondary);
            border: 1.5px solid var(--color-secondary);
            font-weight: 600;
            letter-spacing: 0.01em;
            transition: background-color 0.15s ease, color 0.15s ease, transform 0.1s ease;
            cursor: pointer;
          }
          .btn-secondary:hover { background-color: var(--color-secondary); color: #fff; }
          .btn-secondary:active { transform: scale(0.98); }
          .btn-secondary:disabled { opacity: 0.45; cursor: not-allowed; }

          /* ── Input base ─────────────────────────────────────────────────── */
          .input-base {
            width: 100%;
            border: 1.5px solid #e5e7eb;
            border-radius: 0.75rem;
            padding: 0.65rem 0.875rem;
            font-size: 0.875rem;
            color: #111827;
            background-color: #fff;
            transition: border-color 0.15s ease, box-shadow 0.15s ease;
            outline: none;
          }
          .input-base::placeholder { color: #9ca3af; }
          .input-base:focus {
            border-color: var(--color-primary);
            box-shadow: 0 0 0 3px color-mix(in srgb, var(--color-primary) 15%, transparent);
          }

          /* ── Template-specific overrides ────────────────────────────────── */
          [data-template="boutique"] h1,
          [data-template="boutique"] h2,
          [data-template="boutique"] h3 {
            font-family: var(--font-serif, Georgia, serif);
          }
          [data-template="fashion"] .btn-primary,
          [data-template="fashion"] button.btn-primary,
          [data-template="fashion"] a.btn-primary {
            border-radius: 0 !important;
          }
          [data-template="modern-minimal"] .rounded-2xl,
          [data-template="modern-minimal"] .rounded-xl,
          [data-template="modern-minimal"] .rounded-lg,
          [data-template="modern-minimal"] .rounded-full {
            border-radius: 0 !important;
          }
          [data-template="modern-minimal"] .input-base {
            border-radius: 0 !important;
          }

          /* ── Badge utility ──────────────────────────────────────────────── */
          .badge {
            display: inline-flex;
            align-items: center;
            font-size: 0.65rem;
            font-weight: 700;
            letter-spacing: 0.06em;
            text-transform: uppercase;
            padding: 0.2rem 0.55rem;
            border-radius: 9999px;
          }
          .badge-primary {
            background-color: color-mix(in srgb, var(--color-primary) 12%, transparent);
            color: var(--color-primary);
          }
          .badge-sale {
            background-color: #fef2f2;
            color: #dc2626;
          }
          .badge-new {
            background-color: #f0fdf4;
            color: #16a34a;
          }
          .badge-out {
            background-color: #f9fafb;
            color: #6b7280;
          }
        `}</style>
      </head>
      <body
        className="bg-gray-50 text-gray-900 antialiased min-h-screen flex flex-col"
        suppressHydrationWarning
      >
        <StorefrontConfigProvider website={websiteConfig}>
          <LanguageProvider initialLocale={locale}>
            <a
              href="#main-content"
              className="sr-only focus:not-sr-only focus:absolute focus:top-4 focus:left-4 focus:z-[100] focus:px-4 focus:py-2 focus:bg-white focus:text-gray-900 focus:rounded-lg focus:shadow-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)]"
            >
              Skip to main content
            </a>
            <AuthHydrator />
            {!isPublished && (
              <div className="bg-amber-500 text-white text-center text-xs font-semibold py-2 px-4">
                {serverT.common.previewMode}
              </div>
            )}
            {announcementBar?.enabled && announcementBar.text && (
              <AnnouncementBar
                text={announcementBar.text}
                bgColor={announcementBar.bg_color || "#1FAF9A"}
                textColor={announcementBar.text_color || "#ffffff"}
                linkUrl={announcementBar.link_url || ""}
                dismissible={announcementBar.dismissible ?? true}
              />
            )}
            <Navbar
              storeName={storeName}
              logoUrl={logoUrl}
              logoWidth={logoWidth}
              logoHeight={logoHeight}
              template={template}
              extraNavLinks={extraNavLinks}
            />
            <main id="main-content" className="flex-1" tabIndex={-1}>{children}</main>
            <Footer
              storeName={storeName}
              footerLinks={footerLinks}
              template={template}
              rightsText={serverT.footer.rights}
            />
          </LanguageProvider>
        </StorefrontConfigProvider>
        <SpeedInsights />
      </body>
    </html>
  );
}
