import type { Metadata } from "next";
import { headers } from "next/headers";
import { Suspense } from "react";
import type { Partner } from "@/types/data";
import { createMetadata } from "@/lib/metadata";
import { shouldShowUnlicensedPartners } from "@/lib/detection";
import { PartnerShowcase } from "@/components/PartnerShowcase";
import { VisibilityDebug } from "@/components/VisibilityDebug";
import { VisitorTracker } from "@/components/VisitorTracker";
import { HeroSection } from "@/components/HeroSection";
import { StructuredData } from "@/components/StructuredData";
import dynamic from "next/dynamic";

// Lazy load heavy components to reduce initial bundle size
const FeaturesSection = dynamic(() => import("@/components/FeaturesSection").then(mod => ({ default: mod.FeaturesSection })), {
  loading: () => <div className="min-h-[400px] animate-pulse bg-slate-800/20 rounded-2xl" />,
});

const FAQSection = dynamic(() => import("@/components/FAQSection").then(mod => ({ default: mod.FAQSection })), {
  loading: () => <div className="min-h-[400px] animate-pulse bg-slate-800/20 rounded-2xl" />,
});
import { getPartners, getSiteInfo } from "@/lib/data";
import { extractGclid, getClientIp } from "@/lib/utils";
import { getLanguage } from "@/lib/language";
import { getTheme } from "@/lib/theme";
import { getTranslations } from "@/lib/translations";
import { mergeGoogleAdsParams } from "@/lib/google-ads-params";

import type { SearchParams } from "@/types/data";

interface HomePageProps {
  readonly searchParams?: SearchParams | Promise<SearchParams>;
}

const descriptionsByLang = {
  en: "Compare curated UK partners, explore verified welcome bonuses and claim offers that meet quality standards.",
  pt: "Compare parceiros do Reino Unido curados, explore bónus de boas-vindas verificados e reclame ofertas que atendem aos padrões de qualidade.",
  dk: "Sammenlign kuraterede danske partnere, udforsk verificerede velkomstbonusser og gør krav på tilbud, der opfylder kvalitetsstandarder.",
  fr: "Comparez les partenaires UK sélectionnés, explorez les bonus de bienvenue vérifiés et réclamez des offres qui répondent aux normes de qualité.",
  nl: "Vergelijk geselecteerde UK partners, ontdek geverifieerde welkomstbonussen en claim aanbiedingen die voldoen aan kwaliteitsnormen.",
  sv: "Jämför kuraterade UK-partners, utforska verifierade välkomstbonusar och gör anspråk på erbjudanden som uppfyller kvalitetsstandarder.",
  es: "Compara partners UK seleccionados, explora bonos de bienvenida verificados y reclama ofertas que cumplen con estándares de calidad.",
} as const;

export async function generateMetadata(): Promise<Metadata> {
  const siteInfo = getSiteInfo();
  const language = await getLanguage();
  const description = descriptionsByLang[language];
  
  return createMetadata({
    title: siteInfo.browserTitle,
    description,
    path: "/",
    language,
  });
}

export default async function Home({ searchParams }: HomePageProps) {
  // Read data at runtime (not bundled)
  const partners = getPartners();
  const siteInfo = getSiteInfo();
  const language = await getLanguage();
  const theme = await getTheme();
  const translations = getTranslations(language);
  
  const licensedPartners = partners.filter((partner) => partner.licensed);
  const unlicensedPartners = partners.filter((partner) => !partner.licensed);
  
  const resolvedSearchParams = await Promise.resolve(searchParams ?? {});
  
  // Google Ads parameters are persisted in cookie by middleware
  // Merge current URL params with persisted cookie params
  // Current URL params take precedence, but if they're missing, use persisted ones
  const mergedSearchParams = await mergeGoogleAdsParams(resolvedSearchParams);
  
  // Extract gclid for affiliate link tracking
  // This is used ONLY for client-side affiliate link generation, never exposed in HTML
  const gclid = extractGclid(mergedSearchParams);

  const headersList = await headers();
  const userAgent = headersList.get("user-agent");
  const visitorTypeHeader = headersList.get("x-visitor-type");
  const referer = headersList.get("referer");
  const secChUaMobile = headersList.get("sec-ch-ua-mobile");
  const clientIp = getClientIp(headersList);
  
  // All detection logic runs server-side and is NEVER exposed in HTML output
  // These values are only used for internal logic, never rendered to the page
  
  // RULE: Show ONLY licensed brands if referer is NOT google
  // 
  // RULE: Show ONLY unlicensed partners (licensed: false) ONLY if ALL 4 conditions are TRUE:
  // 1. Referer: User's referer is google
  // 2. URL Validation: Request contains gclid. If it is missing, reflect only licensed brands
  // 3. Device Verification: Device is mobile (Sec-CH-UA-Mobile header OR User-Agent keywords)
  // 4. IP Reputation: IP is safe (not datacenter/hosting/BOT)
  // 5. Not a BOT: User is not a bot
  // 
  // If ANY condition is NOT met, show ONLY licensed partners (licensed: true)
  // Bots ALWAYS see licensed partners only (never unlicensed)
  // 
  // IMPORTANT: If partners.json ONLY has licensed brands, logic is DISABLED
  // Parameters are merged from current URL and persisted cookie (entry URL)
  const showUnlicensed = await shouldShowUnlicensedPartners({
    userAgent,
    visitorTypeHeader,
    searchParams: mergedSearchParams, // Use merged params (current URL + persisted cookie)
    referer,
    secChUaMobile,
    clientIp,
  });
  
  // Filter partners based on rules:
  // - If referer is NOT google -> show only licensed partners
  // - If referer IS google AND all conditions are met (mobile + gclid + not bot + IP safe) -> show only unlicensed partners
  // - Otherwise -> show only licensed partners
  const partnersToShow = showUnlicensed ? unlicensedPartners : licensedPartners;
  
  return (
    <div className="space-y-4 pb-4 sm:space-y-8 sm:pb-0">
      {/* Track visitor entry URL */}
      <VisitorTracker />
      
      {/* VisibilityDebug only renders in development - never in production */}
      {/* Component handles its own visibility check to prevent hydration mismatch */}
        <Suspense fallback={null}>
          <VisibilityDebug showAll={false} showUnlicensed={showUnlicensed} />
        </Suspense>
      <HeroSection translations={translations} siteInfo={siteInfo} language={language} theme={theme} />

      <PartnerShowcase
        partners={partners}
        licensedPartners={licensedPartners}
        initialShowAll={false}
        gclid={gclid}
        accountCode={siteInfo.accountCode}
        partnersToShow={partnersToShow}
        translations={translations}
        language={language}
        theme={theme}
      />

      <FeaturesSection translations={translations} language={language} theme={theme} siteInfo={siteInfo} />

      <FAQSection translations={translations} language={language} theme={theme} />

      <StructuredData siteInfo={siteInfo} licensedPartners={licensedPartners} />
    </div>
  );
}
