"use client";

import React, { useEffect, useState, useRef, Fragment } from "react";
import { motion, AnimatePresence } from "framer-motion";
import Image from "next/image";
import { MenuCategory, MenuItem as MenuItemType } from "@/data/menu";
import { CategoryNav } from "@/components/CategoryNav";
import { MenuItem } from "@/components/MenuItem";
import { AyrisFooterBadge } from "@/components/AyrisFooterBadge";
import { useTranslations, useLocale } from "next-intl";
import { useRouter, usePathname } from "@/i18n/routing";

export const CATEGORY_ICONS: Record<string, string> = {
  "kahvaltiliklar": "🌅",
  "kaseler": "🥗",
  "burger-ve-sandvic": "🍔",
  "pizzalar": "🍕",
  "makarnalar": "🍝",
  "baslangiclar": "🧆",
  "salatalar": "🥬",
  "ana-yemekler": "🍽️",
  "tatlilar": "🍮",
  "i̇mza-kokteyller": "🍹",
  "klasik-kokteyller": "🍸",
  "biralar": "🍺",
  "shotlar": "🥃",
  "sise-ve-kadeh-alkollu": "🥂",
  "saraplar": "🍷",
  "cerezler": "🥜",
  "alkolsuz-i̇cecekler": "🧃",
  "sicak-kahveler": "☕",
  "soguk-kahveler": "🧊",
  "ekstralar": "✨",
};

type SiteSettings = {
  logoUrl: string
  location: string
  restaurantName: string
  googleReviewUrl?: string
}

export default function MenuClient({ initialCategories, siteSettings }: { initialCategories: MenuCategory[], siteSettings: SiteSettings }) {
  const [activeCategoryId, setActiveCategoryId] = useState<string>(
    initialCategories[0]?.id || ""
  );
  const [selectedItem, setSelectedItem] = useState<MenuItemType | null>(null);
  const [showReviewModal, setShowReviewModal] = useState<boolean>(false);
  const sectionRefs = useRef<(HTMLElement | null)[]>([]);
  const t = useTranslations("Menu");
  const locale = useLocale();
  const router = useRouter();
  const pathname = usePathname();

  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        const hit = entries.find((e) => e.isIntersecting);
        if (hit) setActiveCategoryId(hit.target.id);
      },
      { root: null, rootMargin: "-100px 0px -62% 0px", threshold: 0 }
    );

    sectionRefs.current.forEach((ref) => ref && observer.observe(ref));
    return () => observer.disconnect();
  }, []);

  useEffect(() => {
    if (siteSettings.googleReviewUrl) {
      const lastSeenStr = localStorage.getItem('lastSeenReviewModal');
      const now = new Date().getTime();
      const THIRTY_MINUTES = 30 * 60 * 1000; // 30 dakika (milisaniye cinsinden)

      if (!lastSeenStr || (now - parseInt(lastSeenStr, 10)) > THIRTY_MINUTES) {
        const timer = setTimeout(() => {
          setShowReviewModal(true);
          localStorage.setItem('lastSeenReviewModal', now.toString());
        }, 1500);
        return () => clearTimeout(timer);
      }
    }
  }, [siteSettings.googleReviewUrl]);

  useEffect(() => {
    if (selectedItem) {
      document.body.style.overflow = "hidden";
    } else {
      document.body.style.overflow = "unset";
    }
    return () => {
      document.body.style.overflow = "unset";
    };
  }, [selectedItem]);

  return (
    <div className="min-h-screen" style={{ background: "var(--cream)" }}>

      {/* ── Hero ─────────────────────────────────────── */}
      <header className="relative overflow-hidden bg-stone-900">
        {/* Background Image */}
        <div
          className="absolute inset-0 z-0 opacity-80"
          style={{
            backgroundImage: "url('/header-bg.jpg')",
            backgroundSize: "cover",
            backgroundPosition: "center"
          }}
        />

        {/* Dark overlay to make text readable */}
        <div className="absolute inset-0 z-0 bg-gradient-to-b from-black/60 via-black/40 to-black/80" />

        {/* hero content */}
        <div className="relative z-10 flex flex-col items-center text-center px-6 pt-16 pb-20">
          <motion.div
            initial={{ opacity: 0, y: 24 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.9, ease: [0.16, 1, 0.3, 1] }}
            className="flex flex-col items-center"
          >
            <p
              className="text-[10px] tracking-[0.38em] uppercase mb-8 font-sans font-medium"
              style={{ color: "rgba(255,220,160,1)" }}
            >
              Akyaka · Muğla
            </p>

            {/* Logo */}
            <img
              src="/logo.png"
              alt="Moy Beach"
              className="w-64 md:w-80 object-contain drop-shadow-lg"
              style={{ filter: 'brightness(0) invert(1)' }}
            />

            <div
              className="flex items-center gap-3 my-5"
              style={{ color: "rgba(255,190,100,0.35)" }}
            >
              <div className="h-px w-14" style={{ background: "currentColor" }} />
              <span className="text-base">✦</span>
              <div className="h-px w-14" style={{ background: "currentColor" }} />
            </div>

            <p
              className="text-xs font-sans tracking-wide"
              style={{ color: "rgba(255,218,168,0.5)" }}
            >
              {t('subtitle')}
            </p>

            <div className="mt-8 flex items-center gap-4">
              {['tr', 'en', 'ru', 'de'].map((l, index) => (
                <React.Fragment key={l}>
                  <button
                    onClick={() => router.replace(pathname, { locale: l })}
                    className={`text-[11px] font-sans tracking-[0.25em] uppercase transition-all duration-300 ${locale === l
                      ? 'text-white opacity-100 scale-105'
                      : 'text-white/40 hover:text-white/70 hover:scale-100'
                      }`}
                  >
                    {l}
                  </button>
                  {index < 3 && (
                    <div className="w-px h-3" style={{ background: "rgba(255,190,100,0.2)" }} />
                  )}
                </React.Fragment>
              ))}
            </div>
          </motion.div>
        </div>

        {/* wave transition */}
        <div className="absolute bottom-0 left-0 right-0 translate-y-px">
          <svg
            viewBox="0 0 1440 52"
            preserveAspectRatio="none"
            className="w-full h-[52px]"
            xmlns="http://www.w3.org/2000/svg"
          >
            <path
              d="M0 52L80 44C160 36 320 20 480 18C640 16 800 28 960 32C1120 36 1280 32 1360 30L1440 28V52H1360C1280 52 1120 52 960 52C800 52 640 52 480 52C320 52 160 52 80 52H0Z"
              fill="#FAF8F3"
            />
          </svg>
        </div>
      </header>

      {/* ── Category Nav ─────────────────────────────── */}
      <CategoryNav
        categories={initialCategories}
        activeCategoryId={activeCategoryId}
        icons={CATEGORY_ICONS}
      />

      {/* ── Menu Sections ────────────────────────────── */}
      <main className="pb-28">
        {initialCategories.map((category, index) => (
          <motion.section
            key={category.id}
            id={category.id}
            ref={(el) => { sectionRefs.current[index] = el; }}
            className="pt-10 px-4 max-w-lg mx-auto scroll-mt-[62px]"
            initial={{ opacity: 0, y: 14 }}
            whileInView={{ opacity: 1, y: 0 }}
            viewport={{ once: true, margin: "-50px" }}
            transition={{ duration: 0.5, ease: [0.16, 1, 0.3, 1] }}
          >
            {/* section header */}
            <div
              className="flex items-center gap-2.5 mb-4 pb-3 border-b"
              style={{ borderColor: "var(--sand-border)" }}
            >
              <span className="text-xl leading-none select-none">
                {CATEGORY_ICONS[category.id] ?? "🍽️"}
              </span>
              <h2
                className="font-display text-[22px] leading-tight font-semibold italic uppercase tracking-wider"
                style={{ color: "var(--stone-ink)" }}
              >
                {category.title}
              </h2>
            </div>

            <div>
              {category.items.map((item, idx) => (
                <MenuItem key={idx} item={item} onClick={() => setSelectedItem(item)} />
              ))}
            </div>
          </motion.section>
        ))}
      </main>

      {/* ── Footer ───────────────────────────────────── */}
      <footer
        className="py-12 text-center"
        style={{ background: "var(--hero-from)" }}
      >
        <div className="flex flex-col items-center gap-1">
          {/* Footer Logo */}
          <img
            src="/logo.png"
            alt="Moy Beach"
            className="w-36 object-contain opacity-70 mb-2"
            style={{ filter: 'brightness(0) invert(1)' }}
          />
          <p
            className="text-[10px] font-sans tracking-[0.3em] uppercase mt-1"
            style={{ color: "rgba(255,200,130,0.35)" }}
          >
            Akyaka, Muğla
          </p>
          <div
            className="flex items-center gap-3 my-4"
            style={{ color: "rgba(160,100,50,0.4)" }}
          >
            <div className="h-px w-10" style={{ background: "currentColor" }} />
            <span className="text-xs">✦</span>
            <div className="h-px w-10" style={{ background: "currentColor" }} />
          </div>
          <p
            className="text-[11px] font-sans"
            style={{ color: "rgba(120,90,60,0.5)" }}
          >
            © 2026 {siteSettings.restaurantName}. {t('allRightsReserved')}
          </p>
          <AyrisFooterBadge />
        </div>
      </footer>

      {/* ── Modal ────────────────────────────────────── */}
      <AnimatePresence>
        {selectedItem && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40 backdrop-blur-sm"
            onClick={() => setSelectedItem(null)}
          >
            <motion.div
              initial={{ y: 50, opacity: 0, scale: 0.95 }}
              animate={{ y: 0, opacity: 1, scale: 1 }}
              exit={{ y: 20, opacity: 0, scale: 0.95 }}
              className="bg-white rounded-2xl overflow-hidden w-full max-w-sm shadow-xl"
              onClick={(e) => e.stopPropagation()}
            >
              {selectedItem.image && (
                <div className="w-full h-80 relative">
                  <Image
                    src={selectedItem.image}
                    alt={selectedItem.name}
                    fill
                    sizes="(max-width: 768px) 100vw, 400px"
                    unoptimized={selectedItem.image.startsWith('/')}
                    className="object-cover"
                  />
                  <button
                    className="absolute top-3 right-3 bg-black/50 text-white w-8 h-8 rounded-full flex items-center justify-center backdrop-blur-md transition-colors hover:bg-black/70"
                    onClick={() => setSelectedItem(null)}
                  >
                    ✕
                  </button>
                </div>
              )}
              <div className="p-5">
                <div className="flex justify-between items-start gap-4 mb-2">
                  <h3 className="text-xl font-semibold font-sans" style={{ color: "var(--stone-ink)" }}>
                    {selectedItem.name}
                  </h3>
                  <span className="shrink-0 text-lg font-semibold font-sans tabular-nums" style={{ color: "var(--amber)" }}>
                    {selectedItem.price}
                  </span>
                </div>
                <p className="text-[14px] leading-relaxed font-sans" style={{ color: "var(--stone-muted)" }}>
                  {selectedItem.description}
                </p>
              </div>
            </motion.div>
          </motion.div>
        )}

        {/* Google Review Modal */}
        {showReviewModal && siteSettings.googleReviewUrl && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 z-[60] flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm"
            onClick={() => setShowReviewModal(false)}
          >
            <motion.div
              initial={{ y: 50, opacity: 0, scale: 0.95 }}
              animate={{ y: 0, opacity: 1, scale: 1 }}
              exit={{ y: 20, opacity: 0, scale: 0.95 }}
              className="bg-white rounded-2xl overflow-hidden w-full max-w-sm shadow-xl p-6 text-center relative"
              onClick={(e) => e.stopPropagation()}
            >
              <button
                className="absolute top-3 right-3 text-gray-400 hover:text-gray-600 transition-colors"
                onClick={() => setShowReviewModal(false)}
              >
                ✕
              </button>

              <div className="w-16 h-16 bg-white rounded-full flex items-center justify-center mx-auto mb-4 shadow-sm border border-gray-100">
                <svg viewBox="0 0 48 48" className="w-8 h-8">
                  <path fill="#EA4335" d="M24 9.5c3.54 0 6.71 1.22 9.21 3.6l6.85-6.85C35.9 2.38 30.47 0 24 0 14.62 0 6.51 5.38 2.56 13.22l7.98 6.19C12.43 13.72 17.74 9.5 24 9.5z" />
                  <path fill="#4285F4" d="M46.98 24.55c0-1.57-.15-3.09-.38-4.55H24v9.02h12.94c-.58 2.96-2.26 5.48-4.78 7.18l7.73 6c4.51-4.18 7.09-10.36 7.09-17.65z" />
                  <path fill="#FBBC05" d="M10.53 28.59c-.48-1.45-.76-2.99-.76-4.59s.27-3.14.76-4.59l-7.98-6.19C.92 16.46 0 20.12 0 24c0 3.88.92 7.54 2.56 10.78l7.97-6.19z" />
                  <path fill="#34A853" d="M24 48c6.48 0 11.93-2.13 15.89-5.81l-7.73-6c-2.15 1.45-4.92 2.3-8.16 2.3-6.26 0-11.57-4.22-13.47-9.91l-7.98 6.19C6.51 42.62 14.62 48 24 48z" />
                  <path fill="none" d="M0 0h48v48H0z" />
                </svg>
              </div>

              <h3 className="text-xl font-bold font-sans text-gray-900 mb-2">
                {t('reviewTitle')}
              </h3>
              <p className="text-sm text-gray-600 mb-6 font-sans">
                {t('reviewDesc')}
              </p>

              <a
                href={siteSettings.googleReviewUrl}
                target="_blank"
                rel="noopener noreferrer"
                onClick={() => setShowReviewModal(false)}
                className="block w-full py-3 px-4 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-xl transition-colors font-sans"
              >
                {t('reviewBtn')}
              </a>

              <button
                onClick={() => setShowReviewModal(false)}
                className="mt-4 text-sm font-medium text-gray-400 hover:text-gray-600 font-sans"
              >
                {t('reviewLater')}
              </button>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
