/**
 * 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;
}

const SERVICE_ITEMS = [
  {
    href: "/services/internet",
    label: "Internet Plans",
    desc: "NTT Fiber up to 10Gbps",
    icon: <Wifi className="h-5 w-5" />,
    color: "bg-info-soft text-info",
  },
  {
    href: "/services/sim",
    label: "Phone Plans",
    desc: "Docomo network SIM cards",
    icon: <Smartphone className="h-5 w-5" />,
    color: "bg-success-soft text-success",
  },
  {
    href: "/services/business",
    label: "Business Solutions",
    desc: "Enterprise IT services",
    icon: <Building2 className="h-5 w-5" />,
    color: "bg-primary-soft text-primary",
  },
  {
    href: "/services/vpn",
    label: "VPN Service",
    desc: "US & UK server access",
    icon: <Lock className="h-5 w-5" />,
    color: "bg-warning-soft text-warning",
  },
  {
    href: "/services/onsite",
    label: "Onsite Support",
    desc: "Tech help at your location",
    icon: <Wrench className="h-5 w-5" />,
    color: "bg-muted text-muted-foreground",
  },
];

const NAV_LINKS = [
  { href: "/about", label: "About" },
  { href: "/blog", label: "Blog" },
  { href: "/support", label: "Support" },
  { href: "/contact", label: "Contact" },
];

function ServicesDropdown({
  open,
  onClose,
  serviceItems,
}: {
  open: boolean;
  onClose: () => void;
  serviceItems: typeof SERVICE_ITEMS;
}) {
  if (!open) return null;
  return (
    <div className="absolute left-1/2 -translate-x-1/2 top-full pt-2 z-50">
      <div className="absolute left-1/2 -translate-x-1/2 -top-0 w-3 h-3 rotate-45 bg-card border-l border-t border-border/50" />
      <div className="w-[420px] rounded-2xl border border-border/50 bg-card shadow-[var(--cp-shadow-3)] overflow-hidden animate-in fade-in slide-in-from-top-2 duration-200">
        <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>
        <div className="p-3 grid grid-cols-2 gap-1">
          {serviceItems.map(item => (
            <Link
              key={item.href}
              href={item.href}
              onClick={onClose}
              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>
        <div className="px-5 py-3 bg-muted/30 border-t border-border/30">
          <Link
            href="/services"
            onClick={onClose}
            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>
  );
}

function MobileMenu({
  serviceItems,
  isAuthenticated,
  onClose,
}: {
  serviceItems: typeof SERVICE_ITEMS;
  isAuthenticated: boolean;
  onClose: () => void;
}) {
  return (
    <div
      className="md:hidden fixed inset-0 top-[72px] z-50 bg-background animate-in slide-in-from-right-full duration-300 ease-out overflow-hidden"
      style={{ paddingBottom: "env(safe-area-inset-bottom, 0px)" }}
    >
      <nav className="flex flex-col h-full overflow-y-auto overscroll-contain">
        <div className="px-4 pt-4 pb-2">
          <p className="text-xs font-semibold text-primary uppercase tracking-wider px-3 py-2">
            Services
          </p>
          <div className="space-y-1">
            {serviceItems.map((item, index) => (
              <Link
                key={item.href}
                href={item.href}
                onClick={onClose}
                className="flex items-center gap-3 px-3 py-3.5 rounded-xl hover:bg-muted/50 active:bg-muted/70 transition-colors"
                style={{ animationDelay: `${index * 50}ms` }}
              >
                <div
                  className={`flex-shrink-0 flex items-center justify-center w-11 h-11 rounded-xl ${item.color}`}
                >
                  {item.icon}
                </div>
                <div className="min-w-0 flex-1">
                  <p className="text-base font-semibold text-foreground">{item.label}</p>
                  <p className="text-sm text-muted-foreground">{item.desc}</p>
                </div>
              </Link>
            ))}
          </div>
        </div>
        <div className="px-4 py-2 border-t border-border/40">
          <div className="space-y-1">
            {NAV_LINKS.map(link => (
              <Link
                key={link.href}
                href={link.href}
                onClick={onClose}
                className="flex items-center px-3 py-3.5 rounded-xl text-base font-semibold text-foreground hover:bg-muted/50 active:bg-muted/70 transition-colors"
              >
                {link.label}
              </Link>
            ))}
          </div>
        </div>
        <div
          className="mt-auto px-4 py-4 border-t border-border/40 bg-background"
          style={{ paddingBottom: "calc(1rem + env(safe-area-inset-bottom, 0px))" }}
        >
          <div className="space-y-3">
            {isAuthenticated ? (
              <Link
                href="/account"
                onClick={onClose}
                className="flex items-center justify-center rounded-full bg-primary px-6 py-3.5 text-base font-semibold text-primary-foreground shadow-lg hover:bg-primary/90 active:bg-primary/80 transition-colors"
              >
                My Account
              </Link>
            ) : (
              <>
                <Link
                  href="/auth/get-started"
                  onClick={onClose}
                  className="flex items-center justify-center rounded-full bg-primary px-6 py-3.5 text-base font-semibold text-primary-foreground shadow-lg hover:bg-primary/90 active:bg-primary/80 transition-colors"
                >
                  Get Started
                </Link>
                <Link
                  href="/auth/login"
                  onClick={onClose}
                  className="flex items-center justify-center rounded-full border border-input bg-background px-6 py-3.5 text-base font-semibold text-foreground shadow-sm hover:bg-accent active:bg-accent/80 transition-colors"
                >
                  Sign in
                </Link>
              </>
            )}
          </div>
        </div>
      </nav>
    </div>
  );
}

function usePublicShellEffects({
  servicesDropdownRef,
  servicesOpen,
  setServicesOpen,
  mobileMenuOpen,
  setMobileMenuOpen,
}: {
  servicesDropdownRef: React.RefObject<HTMLDivElement | null>;
  servicesOpen: boolean;
  setServicesOpen: (v: boolean) => void;
  mobileMenuOpen: boolean;
  setMobileMenuOpen: (v: boolean) => void;
}) {
  const hasCheckedAuth = useAuthStore(state => state.hasCheckedAuth);
  const checkAuth = useAuthStore(state => state.checkAuth);
  const [isTouchDevice, setIsTouchDevice] = useState(false);

  useEffect(() => {
    if (!hasCheckedAuth) void checkAuth();
  }, [checkAuth, hasCheckedAuth]);
  useEffect(() => {
    setIsTouchDevice("ontouchstart" in window || navigator.maxTouchPoints > 0);
  }, []);
  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, servicesDropdownRef, setServicesOpen]);
  useEffect(() => {
    function handleEscape(event: KeyboardEvent) {
      if (event.key === "Escape") {
        setMobileMenuOpen(false);
        setServicesOpen(false);
      }
    }
    document.addEventListener("keydown", handleEscape);
    return () => document.removeEventListener("keydown", handleEscape);
  }, [setMobileMenuOpen, setServicesOpen]);
  useEffect(() => {
    document.body.style.overflow = mobileMenuOpen ? "hidden" : "";
    return () => {
      document.body.style.overflow = "";
    };
  }, [mobileMenuOpen]);

  return { isTouchDevice };
}

function HeaderAuthButtons({
  isAuthenticated,
  mobileMenuOpen,
  setMobileMenuOpen,
}: {
  isAuthenticated: boolean;
  mobileMenuOpen: boolean;
  setMobileMenuOpen: (v: boolean) => void;
}) {
  return (
    <div className="flex items-center gap-1.5 sm:gap-3 justify-self-end">
      <button
        type="button"
        className="inline-flex items-center gap-1 px-2 sm:px-2.5 py-1.5 rounded-lg text-sm text-muted-foreground hover:text-foreground hover:bg-muted/50 active:bg-muted/70 transition-colors"
      >
        <Globe className="h-4 w-4" />
        <span className="font-medium">EN</span>
      </button>
      {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>
      )}
      {isAuthenticated ? (
        <Link
          href="/account"
          className="md:hidden inline-flex items-center justify-center h-9 px-3 rounded-full bg-primary text-sm font-semibold text-primary-foreground shadow hover:bg-primary/90 active:bg-primary/80 transition-colors"
        >
          Account
        </Link>
      ) : (
        <Link
          href="/auth/login"
          className="md:hidden inline-flex items-center justify-center h-9 px-3 rounded-full bg-primary text-sm font-semibold text-primary-foreground shadow hover:bg-primary/90 active:bg-primary/80 transition-colors"
        >
          Sign in
        </Link>
      )}
      <button
        type="button"
        onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
        className="md:hidden inline-flex items-center justify-center w-11 h-11 rounded-xl hover:bg-muted/50 active:bg-muted/70 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>
  );
}

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

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

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

  return (
    <div className="min-h-screen flex flex-col bg-background text-foreground">
      <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>
      <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-space-md)] sm:px-[var(--cp-page-padding)] h-[72px] grid grid-cols-[auto_1fr_auto] items-center gap-3 sm:gap-4">
          <Link href="/" className="inline-flex items-center gap-2 sm: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 Solutions
              </span>
            </span>
          </Link>
          <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>
              <ServicesDropdown
                open={servicesOpen}
                onClose={() => setServicesOpen(false)}
                serviceItems={SERVICE_ITEMS}
              />
            </div>
            {NAV_LINKS.map(link => (
              <Link
                key={link.href}
                href={link.href}
                className="inline-flex items-center px-3 py-2 rounded-md hover:text-foreground transition-colors"
              >
                {link.label}
              </Link>
            ))}
          </nav>

          <div className="md:hidden" />
          <HeaderAuthButtons
            isAuthenticated={isAuthenticated}
            mobileMenuOpen={mobileMenuOpen}
            setMobileMenuOpen={setMobileMenuOpen}
          />
        </div>
      </header>

      {mobileMenuOpen && (
        <MobileMenu
          serviceItems={SERVICE_ITEMS}
          isAuthenticated={isAuthenticated}
          onClose={closeMobileMenu}
        />
      )}

      <main id="main-content" className="flex-1">
        {children}
      </main>

      <SiteFooter />
    </div>
  );
}
