/**
 * PublicShell
 *
 * Shared shell for public-facing pages with an auth-aware header.
 */

"use client";

import type { ReactNode } from "react";
import { useCallback, useEffect, useRef, useState } from "react";
import Link from "next/link";
import { Logo } from "@/components/atoms/logo";
import { SiteFooter } from "@/components/organisms/SiteFooter";
import { useAuthStore } from "@/features/auth/stores/auth.store";
import {
  Wifi,
  Smartphone,
  Building2,
  Lock,
  Wrench,
  ChevronDown,
  ArrowRight,
  Menu,
  X,
  Globe,
} from "lucide-react";

export interface PublicShellProps {
  children: ReactNode;
}

export function PublicShell({ children }: PublicShellProps) {
  const isAuthenticated = useAuthStore(state => state.isAuthenticated);
  const hasCheckedAuth = useAuthStore(state => state.hasCheckedAuth);
  const checkAuth = useAuthStore(state => state.checkAuth);
  const [servicesOpen, setServicesOpen] = useState(false);
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const [isTouchDevice, setIsTouchDevice] = useState(false);
  const servicesDropdownRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!hasCheckedAuth) {
      void checkAuth();
    }
  }, [checkAuth, hasCheckedAuth]);

  // Detect touch device
  useEffect(() => {
    setIsTouchDevice("ontouchstart" in window || navigator.maxTouchPoints > 0);
  }, []);

  // Close dropdown when clicking outside
  useEffect(() => {
    if (!servicesOpen) return;

    function handleClickOutside(event: MouseEvent) {
      if (
        servicesDropdownRef.current &&
        !servicesDropdownRef.current.contains(event.target as Node)
      ) {
        setServicesOpen(false);
      }
    }

    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, [servicesOpen]);

  // Close mobile menu when route changes or on escape key
  useEffect(() => {
    function handleEscape(event: KeyboardEvent) {
      if (event.key === "Escape") {
        setMobileMenuOpen(false);
        setServicesOpen(false);
      }
    }
    document.addEventListener("keydown", handleEscape);
    return () => document.removeEventListener("keydown", handleEscape);
  }, []);

  // Prevent body scroll when mobile menu is open
  useEffect(() => {
    if (mobileMenuOpen) {
      document.body.style.overflow = "hidden";
    } else {
      document.body.style.overflow = "";
    }
    return () => {
      document.body.style.overflow = "";
    };
  }, [mobileMenuOpen]);

  const handleServicesClick = useCallback(
    (e: React.MouseEvent) => {
      if (isTouchDevice) {
        e.preventDefault();
        setServicesOpen(prev => !prev);
      }
    },
    [isTouchDevice]
  );

  const closeMobileMenu = useCallback(() => {
    setMobileMenuOpen(false);
    setServicesOpen(false);
  }, []);

  const serviceItems = [
    {
      href: "/services/internet",
      label: "Internet Plans",
      desc: "NTT Fiber up to 10Gbps",
      icon: <Wifi className="h-5 w-5" />,
      color: "bg-sky-50 text-sky-600",
    },
    {
      href: "/services/sim",
      label: "Phone Plans",
      desc: "Docomo network SIM cards",
      icon: <Smartphone className="h-5 w-5" />,
      color: "bg-emerald-50 text-emerald-600",
    },
    {
      href: "/services/business",
      label: "Business Solutions",
      desc: "Enterprise IT services",
      icon: <Building2 className="h-5 w-5" />,
      color: "bg-violet-50 text-violet-600",
    },
    {
      href: "/services/vpn",
      label: "VPN Service",
      desc: "US & UK server access",
      icon: <Lock className="h-5 w-5" />,
      color: "bg-amber-50 text-amber-600",
    },
    {
      href: "/services/onsite",
      label: "Onsite Support",
      desc: "Tech help at your location",
      icon: <Wrench className="h-5 w-5" />,
      color: "bg-slate-100 text-slate-600",
    },
  ];

  return (
    <div className="min-h-screen flex flex-col bg-background text-foreground">
      {/* Skip to main content link for accessibility */}
      <a
        href="#main-content"
        className="sr-only focus:not-sr-only focus:absolute focus:top-4 focus:left-4 focus:z-50 focus:px-4 focus:py-2 focus:bg-primary focus:text-primary-foreground focus:rounded-md"
      >
        Skip to main content
      </a>

      {/* Subtle background pattern - clean and minimal */}
      <div className="fixed inset-0 -z-10 bg-[radial-gradient(ellipse_at_top,_var(--tw-gradient-stops))] from-primary/5 via-background to-background" />

      <header className="sticky top-0 z-40 border-b border-border/40 bg-background/95 backdrop-blur-md supports-[backdrop-filter]:bg-background/80">
        <div className="max-w-[var(--cp-page-max-width)] mx-auto px-[var(--cp-page-padding)] h-16 grid grid-cols-[auto_1fr_auto] items-center gap-4">
          <Link href="/" className="inline-flex items-center gap-2.5 min-w-0 group">
            <span className="inline-flex items-center justify-center h-9 w-9 rounded-lg bg-primary/10 text-primary transition-colors group-hover:bg-primary/15">
              <Logo size={20} />
            </span>
            <span className="min-w-0 hidden sm:block">
              <span className="block text-base font-bold leading-none tracking-tight text-foreground">
                Assist Solution
              </span>
            </span>
          </Link>

          {/* Desktop Navigation */}
          <nav className="hidden md:flex items-center justify-center gap-1 sm:gap-3 text-sm font-semibold text-muted-foreground">
            <div
              ref={servicesDropdownRef}
              className="relative"
              onMouseEnter={() => !isTouchDevice && setServicesOpen(true)}
              onMouseLeave={() => !isTouchDevice && setServicesOpen(false)}
            >
              <Link
                href="/services"
                onClick={handleServicesClick}
                className="inline-flex items-center gap-1 px-3 py-2 rounded-md hover:text-foreground transition-colors"
                aria-expanded={servicesOpen}
                aria-haspopup="true"
              >
                Services
                <ChevronDown
                  className={`h-4 w-4 transition-transform duration-200 ${servicesOpen ? "rotate-180" : ""}`}
                />
              </Link>
              {servicesOpen && (
                <div className="absolute left-1/2 -translate-x-1/2 top-full pt-2 z-50">
                  {/* Arrow pointer */}
                  <div className="absolute left-1/2 -translate-x-1/2 -top-0 w-3 h-3 rotate-45 bg-white border-l border-t border-border/50" />

                  <div className="w-[420px] rounded-2xl border border-border/50 bg-white shadow-2xl overflow-hidden animate-in fade-in slide-in-from-top-2 duration-200">
                    {/* Header */}
                    <div className="px-5 py-3 bg-gradient-to-r from-primary/5 to-transparent border-b border-border/30">
                      <p className="text-xs font-semibold text-primary uppercase tracking-wider">
                        Browse Our Services
                      </p>
                    </div>

                    {/* Services Grid */}
                    <div className="p-3 grid grid-cols-2 gap-1">
                      {serviceItems.map(item => (
                        <Link
                          key={item.href}
                          href={item.href}
                          onClick={() => setServicesOpen(false)}
                          className="group flex items-start gap-3 rounded-xl p-3 hover:bg-muted/50 transition-all duration-150"
                        >
                          <div
                            className={`flex-shrink-0 flex items-center justify-center w-10 h-10 rounded-lg ${item.color} transition-transform group-hover:scale-110`}
                          >
                            {item.icon}
                          </div>
                          <div className="min-w-0 pt-0.5">
                            <p className="text-sm font-semibold text-foreground group-hover:text-primary transition-colors">
                              {item.label}
                            </p>
                            <p className="text-xs text-muted-foreground leading-snug">
                              {item.desc}
                            </p>
                          </div>
                        </Link>
                      ))}
                    </div>

                    {/* Footer CTA */}
                    <div className="px-5 py-3 bg-muted/30 border-t border-border/30">
                      <Link
                        href="/services"
                        onClick={() => setServicesOpen(false)}
                        className="inline-flex items-center gap-1.5 text-sm font-semibold text-primary hover:text-primary/80 transition-colors"
                      >
                        View all services
                        <ArrowRight className="h-4 w-4" />
                      </Link>
                    </div>
                  </div>
                </div>
              )}
            </div>
            <Link
              href="/about"
              className="inline-flex items-center px-3 py-2 rounded-md hover:text-foreground transition-colors"
            >
              About
            </Link>
            <Link
              href="/blog"
              className="inline-flex items-center px-3 py-2 rounded-md hover:text-foreground transition-colors"
            >
              Blog
            </Link>
            <Link
              href="/contact"
              className="inline-flex items-center px-3 py-2 rounded-md hover:text-foreground transition-colors"
            >
              Support
            </Link>
          </nav>

          {/* Mobile: Language indicator + hamburger */}
          <div className="flex md:hidden items-center justify-center">
            <div className="flex items-center gap-1 text-sm text-muted-foreground mr-2">
              <Globe className="h-4 w-4" />
              <span className="font-medium">EN</span>
            </div>
          </div>

          <div className="flex items-center gap-3 justify-self-end">
            {/* Language Selector - Desktop */}
            <div className="hidden md:flex items-center gap-1 text-sm text-muted-foreground">
              <Globe className="h-4 w-4" />
              <span className="font-medium">EN</span>
            </div>

            {/* Auth Buttons - Desktop */}
            {isAuthenticated ? (
              <Link
                href="/account"
                className="hidden md:inline-flex items-center justify-center rounded-full bg-primary px-4 py-2 text-sm font-semibold text-primary-foreground shadow hover:bg-primary/90 transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
              >
                My Account
              </Link>
            ) : (
              <div className="hidden md:flex items-center gap-2">
                <Link
                  href="/auth/login"
                  className="inline-flex items-center justify-center rounded-full border border-input bg-background px-4 py-2 text-sm font-semibold text-foreground shadow-sm transition-colors hover:bg-accent hover:text-accent-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
                >
                  Sign in
                </Link>
                <Link
                  href="/auth/get-started"
                  className="inline-flex items-center justify-center rounded-full bg-primary px-4 py-2 text-sm font-semibold text-primary-foreground shadow hover:bg-primary/90 transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
                >
                  Get Started
                </Link>
              </div>
            )}

            {/* Mobile Menu Button */}
            <button
              type="button"
              onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
              className="md:hidden inline-flex items-center justify-center w-10 h-10 rounded-md hover:bg-muted/50 transition-colors"
              aria-expanded={mobileMenuOpen}
              aria-label={mobileMenuOpen ? "Close menu" : "Open menu"}
            >
              {mobileMenuOpen ? <X className="h-6 w-6" /> : <Menu className="h-6 w-6" />}
            </button>
          </div>
        </div>
      </header>

      {/* Mobile Menu Overlay - Rendered outside header to avoid stacking context issues */}
      {mobileMenuOpen && (
        <div className="md:hidden fixed inset-0 top-16 z-50 bg-white animate-in fade-in duration-200 overflow-y-auto">
          <nav className="flex flex-col p-6 space-y-2">
            <div className="space-y-1">
              <p className="text-xs font-semibold text-primary uppercase tracking-wider px-3 py-2">
                Services
              </p>
              {serviceItems.map(item => (
                <Link
                  key={item.href}
                  href={item.href}
                  onClick={closeMobileMenu}
                  className="flex items-center gap-3 px-3 py-3 rounded-lg hover:bg-muted/50 transition-colors"
                >
                  <div
                    className={`flex-shrink-0 flex items-center justify-center w-10 h-10 rounded-lg ${item.color}`}
                  >
                    {item.icon}
                  </div>
                  <div>
                    <p className="text-sm font-semibold text-foreground">{item.label}</p>
                    <p className="text-xs text-muted-foreground">{item.desc}</p>
                  </div>
                </Link>
              ))}
            </div>

            <div className="border-t border-border/40 pt-4 space-y-1">
              <Link
                href="/about"
                onClick={closeMobileMenu}
                className="flex items-center px-3 py-3 rounded-lg text-base font-semibold text-foreground hover:bg-muted/50 transition-colors"
              >
                About
              </Link>
              <Link
                href="/blog"
                onClick={closeMobileMenu}
                className="flex items-center px-3 py-3 rounded-lg text-base font-semibold text-foreground hover:bg-muted/50 transition-colors"
              >
                Blog
              </Link>
              <Link
                href="/contact"
                onClick={closeMobileMenu}
                className="flex items-center px-3 py-3 rounded-lg text-base font-semibold text-foreground hover:bg-muted/50 transition-colors"
              >
                Support
              </Link>
            </div>

            <div className="border-t border-border/40 pt-4 space-y-3">
              {isAuthenticated ? (
                <Link
                  href="/account"
                  onClick={closeMobileMenu}
                  className="flex items-center justify-center rounded-full bg-primary px-6 py-3 text-base font-semibold text-primary-foreground shadow hover:bg-primary/90 transition-colors"
                >
                  My Account
                </Link>
              ) : (
                <>
                  <Link
                    href="/auth/get-started"
                    onClick={closeMobileMenu}
                    className="flex items-center justify-center rounded-full bg-primary px-6 py-3 text-base font-semibold text-primary-foreground shadow hover:bg-primary/90 transition-colors"
                  >
                    Get Started
                  </Link>
                  <Link
                    href="/auth/login"
                    onClick={closeMobileMenu}
                    className="flex items-center justify-center rounded-full border border-input bg-background px-6 py-3 text-base font-semibold text-foreground shadow-sm hover:bg-accent transition-colors"
                  >
                    Sign in
                  </Link>
                </>
              )}
            </div>
          </nav>
        </div>
      )}

      <main id="main-content" className="flex-1">
        <div className="max-w-[var(--cp-page-max-width)] mx-auto px-[var(--cp-page-padding)] pt-0 pb-0">
          {children}
        </div>
      </main>

      <SiteFooter />
    </div>
  );
}
