"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";

export default function MenuPage() {
  const router = useRouter();
  const [signingOut, setSigningOut] = useState(false);

  const menuItems = [
    { icon: "🏡", label: "Home", href: "/home" },
    { icon: "📝", label: "Activity", href: "/activity" },
    { icon: "🌿", label: "Growth", href: "/growth" },
    { icon: "🩺", label: "Medical", href: "/medical" },
    { icon: "📸", label: "Memories", href: "/memories" },
    { icon: "🔮", label: "AI Chat", href: "/ai" },
    { icon: "🌟", label: "Milestones", href: "/milestones" },
    { icon: "🧺", label: "Wardrobe", href: "/wardrobe" },
    { icon: "💞", label: "Circle", href: "/circle" },
  ];

  const handleSignOut = async () => {
    if (!confirm("Are you sure you want to sign out?")) return;
    setSigningOut(true);
    try {
      await fetch("/api/auth/signout", { method: "POST" });
      // Purge SW caches so a shared device can't see the previous user's
      // cached baby photos or shell state after login.
      if ("caches" in window) {
        const keys = await caches.keys();
        await Promise.all(keys.map((k) => caches.delete(k)));
      }
      router.push("/login");
    } catch (err) {
      console.error("Sign out failed:", err);
    }
    setSigningOut(false);
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-rose-50 to-amber-50 dark:from-gray-900 dark:to-gray-800 pb-28">
      {/* Header */}
      <div className="p-4 flex justify-between items-center">
        <h1 className="text-xl font-bold">Menu</h1>
        <button onClick={() => router.back()} className="p-2">✕</button>
      </div>

      {/* Menu Items */}
      <div className="px-4 space-y-2">
        {menuItems.map((item) => (
          <Link
            key={item.href}
            href={item.href}
            className="flex items-center gap-4 p-4 bg-white dark:bg-gray-800 rounded-xl"
          >
            <span className="text-2xl">{item.icon}</span>
            <span className="font-medium">{item.label}</span>
          </Link>
        ))}
      </div>

      {/* Bottom Section - Settings and Sign Out */}
      <div className="px-4 mt-4 space-y-2">
        <Link
          href="/settings"
          className="flex items-center gap-4 p-4 bg-white dark:bg-gray-800 rounded-xl"
        >
          <span className="text-2xl">⚙️</span>
          <span className="font-medium">Settings</span>
        </Link>
        <button
          onClick={handleSignOut}
          disabled={signingOut}
          className="w-full flex items-center gap-4 p-4 bg-red-50 dark:bg-red-900/20 text-red-600 dark:text-red-400 rounded-xl"
        >
          <span className="text-2xl">🚪</span>
          <span className="font-medium">{signingOut ? "Signing out..." : "Sign Out"}</span>
        </button>
      </div>
    </div>
  );
}