"use client";
import { useState, useEffect, useRef } from "react";
import Link from "next/link";
import FontSizeControl from "@/components/FontSizeControl";
import CrossBadge from "@/components/CrossBadge";
import WelcomeAnimation from "@/components/WelcomeAnimation";
import { usePathname } from "next/navigation";
import { useSession, signOut } from "next-auth/react";
import {
  Home,
  Users,
  ListVideo,
  ShoppingBag,
  Star,
  Library,
  Receipt,
  Menu,
  ChevronLeft,
  ChevronRight,
  Search,
  X,
  Bell,
  User,
  Settings,
  CreditCard,
  LogOut,
  BookOpen,
  LifeBuoy,
} from "lucide-react";

type Category = { id: string; name: string; slug: string };

const NAV_ITEMS = [
  { href: "/", label: "Home", icon: Home },
  { href: "/community", label: "Community", icon: Users },
  { href: "/blog", label: "Blog", icon: BookOpen },
  { href: "/playlists", label: "Playlists", icon: ListVideo },
  { href: "/shop", label: "Shop", icon: ShoppingBag },
];

const LIBRARY_ITEMS = [
  { href: "/my-library", label: "My Library", icon: Library },
  { href: "/my-library/payment-history", label: "Payment History", icon: Receipt },
  { href: "/support", label: "Support", icon: LifeBuoy },
];

export default function MainShell({
  categories,
  siteName,
  gradientIntensity = 20,
  children,
  footer,
}: {
  categories: Category[];
  siteName: string;
  gradientIntensity?: number;
  children: React.ReactNode;
  footer?: React.ReactNode;
}) {
  const [collapsed, setCollapsed] = useState(false);

  // Auto-collapse on tablet (md, 768px–1023px), expand on desktop (lg, 1024px+)
  // so tablet landscape doesn't get a wide sidebar eating content space.
  useEffect(() => {
    function handleResize() {
      const w = window.innerWidth;
      if (w >= 1024) {
        setCollapsed(false); // desktop: expanded
      } else if (w >= 768) {
        setCollapsed(true);  // tablet: icon-only
      }
    }
    handleResize();
    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, []);
  const [mobileOpen, setMobileOpen] = useState(false);
  const [mobileSearchOpen, setMobileSearchOpen] = useState(false);
  const [accountOpen, setAccountOpen] = useState(false);
  const [notifOpen, setNotifOpen] = useState(false);
  const pathname = usePathname();
  const { data: session } = useSession();
  const headerRef = useRef<HTMLElement>(null);
  const [headerHeight, setHeaderHeight] = useState(56);

  useEffect(() => {
    const header = headerRef.current;
    if (!header) return;
    function measure() {
      if (header) setHeaderHeight(header.getBoundingClientRect().height);
    }
    measure();
    const observer = new ResizeObserver(measure);
    observer.observe(header);
    return () => observer.disconnect();
  }, []);
  const [notificationList, setNotificationList] = useState<any[]>([]);
  const [unreadCount, setUnreadCount] = useState(0);
  const [points, setPoints] = useState<number | null>(null);

  useEffect(() => {
    if (!session?.user) return;

    setPoints((session.user as any).points ?? null);

    async function poll() {
      try {
        const res = await fetch("/api/notifications");
        const data = await res.json();
        setNotificationList(data.notifications || []);
        setUnreadCount(data.unreadCount || 0);
        setPoints(data.points ?? 0);
      } catch {}
    }
    poll();
    const interval = setInterval(poll, 15000); // near-real-time: refresh every 15s
    return () => clearInterval(interval);
  }, [session?.user]);

  async function openNotifications() {
    setNotifOpen((o) => !o);
    setAccountOpen(false);
    if (unreadCount > 0) {
      await fetch("/api/notifications", { method: "POST" });
      setUnreadCount(0);
    }
  }

  const first = siteName.charAt(0);
  const rest = siteName.slice(1);

  function isActive(href: string) {
    if (href === "/") return pathname === "/";
    return pathname.startsWith(href);
  }

  const sidebarContent = (
    <>
      <div className={`flex items-center ${collapsed ? "justify-center" : "justify-between"} mb-6`}>
        <Link href="/" className="text-lg font-bold whitespace-nowrap overflow-hidden tracking-tight">
          {collapsed ? (
            <span className="text-red-600">{first}</span>
          ) : (
            <>
              <span className="text-red-600">{first}</span>
              {rest}
            </>
          )}
        </Link>
        <button
          onClick={() => setCollapsed((c) => !c)}
          className="hidden md:flex items-center justify-center w-7 h-7 rounded hover:bg-neutral-800 text-neutral-400 shrink-0"
          title={collapsed ? "Expand" : "Collapse"}
        >
          {collapsed ? <ChevronRight size={16} /> : <ChevronLeft size={16} />}
        </button>
      </div>

      <nav className="space-y-1 text-sm">
        {NAV_ITEMS.map((item) => {
          const active = isActive(item.href);
          const Icon = item.icon;
          return (
            <Link
              key={item.href}
              href={item.href}
              title={collapsed ? item.label : undefined}
              className={`group flex items-center gap-3 px-3 py-2.5 rounded-lg transition-colors relative ${
                collapsed ? "justify-center" : ""
              } ${active ? "bg-red-950/60 text-red-400" : "text-neutral-300 hover:bg-neutral-800 hover:text-red-500"}`}
            >
              <Icon size={22} className={active ? "text-red-500" : "text-neutral-400 group-hover:text-red-500"} />
              {!collapsed && <span>{item.label}</span>}
              {collapsed && (
                <span className="absolute left-full ml-2 whitespace-nowrap bg-neutral-800 text-white text-xs px-2 py-1 rounded opacity-0 group-hover:opacity-100 pointer-events-none transition-opacity z-50">
                  {item.label}
                </span>
              )}
            </Link>
          );
        })}
      </nav>

      {categories.length > 0 && (
        <>
          {!collapsed && (
            <div className="mt-6 text-xs uppercase text-neutral-500 px-3 mb-1 tracking-wider">Categories</div>
          )}
          <nav className={`space-y-1 text-sm font-semibold mb-6 ${collapsed ? "mt-6" : ""}`}>
            {categories.map((c) => {
              const href = `/categories/${c.slug}`;
              const active = isActive(href);
              return (
                <Link
                  key={c.id}
                  href={href}
                  title={collapsed ? c.name : undefined}
                  className={`group flex items-center px-3 py-2 rounded-lg transition-colors relative ${
                    collapsed ? "justify-center" : ""
                  } ${active ? "bg-red-950/60 text-red-400" : "text-neutral-400 hover:bg-neutral-800 hover:text-red-500"}`}
                >
                  {collapsed ? (
                    <span className="w-2 h-2 rounded-full bg-current" />
                  ) : (
                    <span>{c.name}</span>
                  )}
                  {collapsed && (
                    <span className="absolute left-full ml-2 whitespace-nowrap bg-neutral-800 text-white text-xs px-2 py-1 rounded opacity-0 group-hover:opacity-100 pointer-events-none transition-opacity z-50">
                      {c.name}
                    </span>
                  )}
                </Link>
              );
            })}
          </nav>
        </>
      )}

      {!collapsed && (
        <div className="text-xs uppercase text-neutral-500 px-3 mb-1 tracking-wider">Library</div>
      )}
      <nav className="space-y-1 text-sm mb-6">
        {LIBRARY_ITEMS.map((item) => {
          const active = isActive(item.href);
          const Icon = item.icon;
          return (
            <Link
              key={item.href}
              href={item.href}
              title={collapsed ? item.label : undefined}
              className={`group flex items-center gap-3 px-3 py-2 rounded-lg transition-colors relative ${
                collapsed ? "justify-center" : ""
              } ${active ? "bg-red-950/60 text-red-400" : "text-neutral-400 hover:bg-neutral-800 hover:text-red-500"}`}
            >
              <Icon size={18} className={active ? "text-red-500" : ""} />
              {!collapsed && <span>{item.label}</span>}
              {collapsed && (
                <span className="absolute left-full ml-2 whitespace-nowrap bg-neutral-800 text-white text-xs px-2 py-1 rounded opacity-0 group-hover:opacity-100 pointer-events-none transition-opacity z-50">
                  {item.label}
                </span>
              )}
            </Link>
          );
        })}
      </nav>

      {(() => {
        const tier = (session?.user as any)?.tier;
        const TIER_RANK: Record<string, number> = { free: 0, starter: 1, plus: 2, premium: 3 };
        if (tier && tier !== "free") {
          return (
            <Link
              href="/subscription/manage"
              title={collapsed ? `${tier} · Manage` : undefined}
              className={`group mt-auto flex items-center gap-3 rounded-lg border border-amber-800/50 bg-amber-950/30 px-3 py-2.5 hover:bg-amber-950/50 transition-colors relative ${
                collapsed ? "justify-center" : ""
              }`}
            >
              <Star size={18} className="text-amber-400 shrink-0" fill="currentColor" />
              {!collapsed && (
                <div className="min-w-0">
                  <p className="text-sm font-semibold capitalize text-amber-100">{tier}</p>
                  <p className="text-xs text-amber-400/70">Rank {TIER_RANK[tier]} · Manage</p>
                </div>
              )}
              {collapsed && (
                <span className="absolute left-full ml-2 whitespace-nowrap bg-neutral-800 text-white text-xs px-2 py-1 rounded opacity-0 group-hover:opacity-100 pointer-events-none transition-opacity z-50">
                  {tier} · Manage
                </span>
              )}
            </Link>
          );
        }
        return (
          <Link
            href="/subscription/plans"
            title={collapsed ? "Get Membership" : undefined}
            className={`group mt-auto text-center py-2.5 text-sm flex items-center justify-center gap-2 relative rounded-lg font-semibold bg-gradient-to-r from-amber-500 to-red-600 hover:from-amber-400 hover:to-red-500 transition-colors ${
              collapsed ? "px-0" : ""
            }`}
          >
            <Star size={16} />
            {!collapsed && <span>Get Membership</span>}
            {collapsed && (
              <span className="absolute left-full ml-2 whitespace-nowrap bg-neutral-800 text-white text-xs px-2 py-1 rounded opacity-0 group-hover:opacity-100 pointer-events-none transition-opacity z-50">
                Get Membership
              </span>
            )}
          </Link>
        );
      })()}
    </>
  );

  return (
    <div
      className="min-h-screen flex max-w-full"
      style={{
        background: `radial-gradient(ellipse 1200px 700px at 50% 0%, rgba(220,38,38,${(gradientIntensity / 100) * 0.35}) 0%, transparent 65%), #0a0a0a`,
      }}
    >
      {/* Desktop sidebar */}
      <aside
        className={`hidden md:flex md:flex-col shrink-0 border-r border-neutral-800/60 bg-[#0a0a0a] p-4 fixed left-0 top-0 h-screen overflow-y-auto thin-scrollbar transition-all duration-200 z-20 ${
          collapsed ? "w-20" : "w-56"
        }`}
      >
        {sidebarContent}
      </aside>
      {/* Spacer div that takes the sidebar's place in normal flow, since the
          real sidebar is now fixed (removed from flow) — this keeps the
          rest of the layout correctly pushed to the right of it. */}
      <div className={`hidden md:block shrink-0 transition-all duration-200 ${collapsed ? "w-20" : "w-56"}`} />

      {session?.user && <WelcomeAnimation />}

      {/* Mobile drawer */}
      {mobileOpen && (
        <div className="fixed inset-0 z-50 md:hidden">
          <div className="absolute inset-0 bg-black/60" onClick={() => setMobileOpen(false)} />
          <aside
            className="absolute left-0 top-0 h-full w-64 bg-neutral-950 border-r border-neutral-800 p-4 flex flex-col overflow-y-auto thin-scrollbar"
            onClick={(e) => {
              const target = e.target as HTMLElement;
              if (target.closest("a")) setMobileOpen(false);
            }}
          >
            <button
              onClick={() => setMobileOpen(false)}
              className="self-end mb-2 text-neutral-400 hover:text-white"
            >
              <X size={20} />
            </button>
            {sidebarContent}
          </aside>
        </div>
      )}

      <div
        className="flex-1 flex flex-col min-w-0 max-w-full"
        style={{ ["--header-h" as any]: `${headerHeight}px` }}
      >
        {/* Header — fixed (not sticky) for reliability, with left offset
            matching the fixed sidebar's current width so it never overlaps
            or gets hidden behind it. */}
        <header
          ref={headerRef}
          className="border-b border-neutral-800 bg-[#0f0f0f] fixed top-0 right-0 z-10 left-0"
          style={{ ["--sidebar-w" as any]: collapsed ? "5rem" : "14rem" }}
        >
          <div className="md:ml-[var(--sidebar-w)]">
          <div className="flex items-center gap-2 px-3 sm:px-4 md:px-6 py-2 sm:py-2.5">
            {/* ── Left: hamburger (mobile) + site name (mobile) ── */}
            <div className="flex items-center gap-2 shrink-0">
              <button
                onClick={() => setMobileOpen(true)}
                className="md:hidden text-neutral-300 hover:text-white"
              >
                <Menu size={20} />
              </button>
              <Link href="/" className="md:hidden font-bold whitespace-nowrap tracking-tight text-sm">
                <span className="text-red-600">{first}</span>{rest}
              </Link>
            </div>

            {/* ── Centre: full search bar (desktop only) ── */}
            <form action="/search" method="GET" className="relative flex-1 hidden md:block max-w-xl mx-4">
              <Search size={15} className="absolute left-3.5 top-1/2 -translate-y-1/2 text-neutral-500" />
              <input
                name="q"
                placeholder="Search"
                className="w-full bg-neutral-900 border border-neutral-800 rounded-full pl-9 pr-4 py-1.5 text-sm outline-none focus:border-red-600"
              />
            </form>

            {/* ── Right: font controls + search icon (mobile) + auth ── */}
            <div className="flex items-center gap-1 ml-auto shrink-0">
              {/* Search icon — shows on mobile/tablet where the full bar is hidden */}
              <button
                onClick={() => setMobileSearchOpen((s) => !s)}
                className="md:hidden text-neutral-300 hover:text-white w-8 h-8 flex items-center justify-center rounded-full hover:bg-neutral-800"
              >
                <Search size={18} />
              </button>

              {/* Font size control — always visible */}
              <FontSizeControl />

              {session?.user ? (
                <>
                  {(session.user as any).role === "admin" && (
                    <Link href="/admin" target="_blank" rel="noopener noreferrer" className="btn-secondary px-3 py-1.5 hidden lg:inline-block">
                      Admin
                    </Link>
                  )}

                  {/* Points badge */}
                  {points !== null && (
                    <Link href="/points" className="hidden sm:flex items-center gap-1.5 bg-amber-900/30 border border-amber-800/50 text-amber-400 rounded-full px-3 py-1.5 text-xs font-semibold">
                      <CrossBadge size={14} />
                      {points}
                    </Link>
                  )}

                  {/* Notification bell */}
                  <div className="relative">
                    <button
                      onClick={openNotifications}
                      className="relative w-9 h-9 flex items-center justify-center rounded-full hover:bg-neutral-800 text-neutral-300"
                    >
                      <Bell size={18} />
                      {unreadCount > 0 && (
                        <span className="absolute top-1 right-1 w-2 h-2 bg-red-600 rounded-full" />
                      )}
                    </button>
                    {notifOpen && (
                      <>
                        <div className="fixed inset-0 z-20" onClick={() => setNotifOpen(false)} />
                        <div className="fixed left-1/2 -translate-x-1/2 top-16 sm:absolute sm:left-auto sm:translate-x-0 sm:top-auto sm:right-0 sm:mt-2 w-[90vw] max-w-80 card p-3 z-30 shadow-xl max-h-96 overflow-y-auto">
                          <p className="text-sm font-semibold px-2 py-1 mb-1">Notifications</p>
                          {notificationList.length === 0 ? (
                            <p className="text-xs text-neutral-500 px-2 py-4 text-center">You're all caught up.</p>
                          ) : (
                            <div className="space-y-1">
                              {notificationList.map((n) => {
                                const content = (
                                  <>
                                    {n.message}
                                    <p className="text-[10px] text-neutral-500 mt-0.5">
                                      {new Date(n.createdAt).toLocaleString()}
                                    </p>
                                  </>
                                );
                                const className = `block px-2 py-2 rounded-lg text-xs ${n.read ? "text-neutral-400" : "text-white bg-neutral-800/60"} ${n.link ? "hover:bg-neutral-700/60 cursor-pointer" : ""}`;
                                return n.link ? (
                                  <Link key={n.id} href={n.link} onClick={() => setNotifOpen(false)} className={className}>
                                    {content}
                                  </Link>
                                ) : (
                                  <div key={n.id} className={className}>
                                    {content}
                                  </div>
                                );
                              })}
                            </div>
                          )}
                        </div>
                      </>
                    )}
                  </div>

                  {/* Account dropdown */}
                  <div className="relative">
                    <button
                      onClick={() => { setAccountOpen((o) => !o); setNotifOpen(false); }}
                      className="w-9 h-9 rounded-full bg-neutral-800 hover:ring-2 hover:ring-red-600 flex items-center justify-center font-semibold text-sm shrink-0"
                    >
                      {session.user.name?.charAt(0).toUpperCase() || "U"}
                    </button>
                    {accountOpen && (
                      <>
                        <div className="fixed inset-0 z-20" onClick={() => setAccountOpen(false)} />
                        <div className="absolute right-0 mt-2 w-[85vw] max-w-64 card p-2 z-30 shadow-xl">
                          <div className="px-3 py-2 border-b border-neutral-800 mb-1">
                            <div className="flex items-center gap-2">
                              <span className="font-semibold text-sm">{session.user.name}</span>
                              {(session.user as any).tier && (session.user as any).tier !== "free" && (
                                <span className="text-xs bg-amber-900/60 text-amber-400 px-2 py-0.5 rounded-full capitalize">
                                  {(session.user as any).tier}
                                </span>
                              )}
                            </div>
                            <p className="text-xs text-neutral-500 truncate">{session.user.email}</p>
                            {points !== null && (
                              <p className="text-xs text-amber-400 mt-1 flex items-center gap-1.5">
                                <CrossBadge size={12} /> {points} points earned
                              </p>
                            )}
                          </div>
                          <Link href="/my-library" onClick={() => setAccountOpen(false)} className="flex items-center gap-2 px-3 py-2 rounded hover:bg-neutral-800 text-sm">
                            <Library size={16} /> My Library
                          </Link>
                          <Link href="/subscription/manage" onClick={() => setAccountOpen(false)} className="flex items-center gap-2 px-3 py-2 rounded hover:bg-neutral-800 text-sm">
                            <CreditCard size={16} /> Manage Subscription
                          </Link>
                          <Link href="/payment-methods" onClick={() => setAccountOpen(false)} className="flex items-center gap-2 px-3 py-2 rounded hover:bg-neutral-800 text-sm">
                            <CreditCard size={16} /> Payment Methods
                          </Link>
                          <Link href="/account/profile" onClick={() => setAccountOpen(false)} className="flex items-center gap-2 px-3 py-2 rounded hover:bg-neutral-800 text-sm">
                            <User size={16} /> My Profile
                          </Link>
                          <Link href="/account/settings" onClick={() => setAccountOpen(false)} className="flex items-center gap-2 px-3 py-2 rounded hover:bg-neutral-800 text-sm">
                            <Settings size={16} /> Account Settings
                          </Link>
                          {(session.user as any).role === "admin" && (
                            <Link href="/admin" target="_blank" rel="noopener noreferrer" onClick={() => setAccountOpen(false)} className="lg:hidden flex items-center gap-2 px-3 py-2 rounded hover:bg-neutral-800 text-sm">
                              <Settings size={16} /> Admin Panel
                            </Link>
                          )}
                          <button
                            onClick={() => signOut({ callbackUrl: "/" })}
                            className="w-full flex items-center gap-2 px-3 py-2 rounded hover:bg-neutral-800 text-sm text-red-400 mt-1 border-t border-neutral-800 pt-2"
                          >
                            <LogOut size={16} /> Sign out
                          </button>
                        </div>
                      </>
                    )}
                  </div>
                </>
              ) : (
                <>
                  <Link href="/login" className="btn-secondary rounded-full px-3 sm:px-4 py-1.5 text-[11px] sm:text-sm flex items-center justify-center text-center whitespace-nowrap shrink-0">
                    <span>Sign In</span>
                  </Link>
                  <Link href="/register" className="btn-primary rounded-full px-3 sm:px-4 py-1.5 text-[11px] sm:text-sm text-center whitespace-nowrap shrink-0">Sign up</Link>
                </>
              )}
            </div>
          </div>

          {mobileSearchOpen && (
            <form action="/search" method="GET" className="px-4 pb-3 md:hidden">
              <div className="relative">
                <Search size={16} className="absolute left-4 top-1/2 -translate-y-1/2 text-neutral-500" />
                <input
                  name="q"
                  autoFocus
                  placeholder="Search"
                  className="w-full bg-neutral-900 border border-neutral-800 rounded-full pl-10 pr-4 py-2 text-sm outline-none focus:border-red-600"
                />
              </div>
            </form>
          )}
          </div>
        </header>

        {/* Spacer that takes the header's place in normal flow, since the
            real header is now fixed (removed from flow) — prevents content
            from starting underneath it. Height is measured live so it always
            matches exactly, including when font-size changes. */}
        <div style={{ height: headerHeight }} />

        <main className="flex-1 flex flex-col">
          <div className="flex-1 px-4 md:px-6 pt-4 pb-4 md:pb-6">{children}</div>
          {footer}
        </main>
      </div>
    </div>
  );
}
