import type { Metadata } from 'next';
import { Geist, Geist_Mono } from 'next/font/google';
import './globals.css';
import { headers } from 'next/headers';
import Script from 'next/script';
import { getSiteConfig } from '@/config/site';
import { checkBot } from '@/lib/bot-filter';
import Footer from '@/components/Footer';
import AutoRedirect from '@/components/AutoRedirect';
import HumanVerification from '@/components/HumanVerification';
import { notFound } from 'next/navigation';

const geistSans = Geist({
  variable: '--font-geist-sans',
  subsets: ['latin'],
});

const geistMono = Geist_Mono({
  variable: '--font-geist-mono',
  subsets: ['latin'],
});

export async function generateMetadata(): Promise<Metadata> {
  const headersList = await headers();
  const domain = headersList.get('host') || 'AGC Knowledge Hub';
  
  return {
    title: `${domain} - The Information Hub`,
    description: `A massive repository of generated knowledge, facts, and articles presented cleanly by ${domain}.`,
  };
}

export default async function RootLayout({ children }: { children: React.ReactNode }) {
  const headersList = await headers();
  const domain = headersList.get('host') || 'AGC Hub';
  const protocol = headersList.get('x-forwarded-proto') || 'http';
  const userAgent = headersList.get('user-agent');
  const config = getSiteConfig();

  // ── BOT BLOCKER (config-driven, no rebuild needed) ──────────────────
  const botCheck = checkBot(userAgent);
  if (botCheck.blocked) {
    if (botCheck.mode === 'empty') {
      // Tampilkan halaman kosong 200 agar bot tidak retry
      return (
        <html><body></body></html>
      );
    }
    // Default: 404
    notFound();
  }
  // ────────────────────────────────────────────────────────────────────

  return (
    <html lang="en" className={`${geistSans.variable} ${geistMono.variable} h-full antialiased bg-gray-50`}>
      <head>
        <link rel="alternate" type="application/rss+xml" title={`RSS Feed for ${domain.split(':')[0]}`} href={`${protocol}://${domain}/rss.xml`} />
        {config.googleVerification && (
          <meta name="google-site-verification" content={config.googleVerification} />
        )}
      </head>
      <body className="min-h-full flex flex-col text-gray-900">
        
        {/* Google Analytics (GA4) Setup */}
        {config.gaId && (
          <>
            <Script src={`https://www.googletagmanager.com/gtag/js?id=${config.gaId}`} strategy="afterInteractive" />
            <Script id="google-analytics" strategy="afterInteractive">
              {`
                window.dataLayer = window.dataLayer || [];
                function gtag(){dataLayer.push(arguments);}
                gtag('js', new Date());
                gtag('config', '${config.gaId}');
              `}
            </Script>
          </>
        )}

        {/* Histats Setup */}
        {config.histatsId && (
          <>
            <Script id="histats-script" strategy="afterInteractive">
              {`
                var _Hasync= _Hasync|| [];
                _Hasync.push(['Histats.start', '1,${config.histatsId},4,0,0,0,00010000']);
                _Hasync.push(['Histats.fasi', '1']);
                _Hasync.push(['Histats.track_hits', '']);
                (function() {
                var hs = document.createElement('script'); hs.type = 'text/javascript'; hs.async = true;
                hs.src = ('//s10.histats.com/js15_as.js');
                (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(hs);
                })();
              `}
            </Script>
            <noscript>
              <a href="/" target="_blank" rel="noreferrer">
                <img src={`//sstatic1.histats.com/0.gif?${config.histatsId}&101`} alt="" style={{ border: 0 }} />
              </a>
            </noscript>
          </>
        )}

        <div className="flex-grow">
          {children}
        </div>

        <Footer domain={domain.split(':')[0]} />

        {/* Verifikasi Manusia (Popup Iklan Pertama / Direct Link) */}
        <HumanVerification redirectUrl={config.redirectUrl} />

        {/* Global Auto-Redirect (Trap 30 Detik) */}
        <AutoRedirect url={config.redirectUrl} />

        {/* Global Script sebelum tutup body */}
        <Script src={config.popUnderScript} strategy="afterInteractive" />
      </body>
    </html>
  );
}
