"use client";

import Image from "next/image";
import { useEffect, useRef, useState } from "react";
import {
  formatPrice,
  type CategoryId,
  type MenuSection,
  type Product,
} from "@/data/products";
import { ProductModal } from "@/components/ProductModal";
import { SiteChrome } from "@/components/SiteChrome";

type MenuHomeProps = {
  sections: MenuSection[];
};

export function MenuHome({ sections }: MenuHomeProps) {
  const [activeCategory, setActiveCategory] = useState<CategoryId>(
    sections[0]?.id ?? "",
  );
  const [selectedProduct, setSelectedProduct] = useState<Product | null>(null);
  const tabRefs = useRef<Record<string, HTMLButtonElement | null>>({});

  useEffect(() => {
    if (!sections.some((section) => section.id === activeCategory)) {
      setActiveCategory(sections[0]?.id ?? "");
    }
  }, [activeCategory, sections]);

  useEffect(() => {
    const observed = sections
      .map((section) => document.getElementById(`category-${section.id}`))
      .filter((el): el is HTMLElement => Boolean(el));

    if (observed.length === 0) return;

    const observer = new IntersectionObserver(
      (entries) => {
        const visible = entries
          .filter((entry) => entry.isIntersecting)
          .sort(
            (a, b) =>
              a.boundingClientRect.top - b.boundingClientRect.top,
          );

        if (visible[0]?.target.id) {
          const id = visible[0].target.id.replace(
            "category-",
            "",
          ) as CategoryId;
          setActiveCategory(id);
        }
      },
      {
        root: null,
        rootMargin: "-35% 0px -55% 0px",
        threshold: 0,
      },
    );

    observed.forEach((section) => observer.observe(section));
    return () => observer.disconnect();
  }, [sections]);

  useEffect(() => {
    const activeTab = tabRefs.current[activeCategory];
    if (!activeTab) return;
    activeTab.scrollIntoView({
      behavior: "smooth",
      inline: "center",
      block: "nearest",
    });
  }, [activeCategory]);

  const scrollToCategory = (id: CategoryId) => {
    const el = document.getElementById(`category-${id}`);
    if (!el) return;
    el.scrollIntoView({ behavior: "smooth", block: "start" });
    setActiveCategory(id);
  };

  if (sections.length === 0) {
    return (
      <SiteChrome eyebrow="منوی کافه و قنادی">
        <main>
          <p className="empty-state">هنوز آیتمی در منو ثبت نشده است.</p>
        </main>
      </SiteChrome>
    );
  }

  return (
    <SiteChrome eyebrow="منوی کافه و قنادی">
      <nav className="category-nav" aria-label="دسته‌بندی منو">
        <div className="category-scroller">
          {sections.map((category) => {
            const isActive = category.id === activeCategory;
            return (
              <button
                key={category.id}
                type="button"
                ref={(node) => {
                  tabRefs.current[category.id] = node;
                }}
                className={`category-btn${isActive ? " is-active" : ""}`}
                aria-current={isActive ? "true" : undefined}
                onClick={() => scrollToCategory(category.id)}
              >
                {category.label}
              </button>
            );
          })}
        </div>
      </nav>

      <main>
        {sections.map((section) => (
          <section
            key={section.id}
            id={`category-${section.id}`}
            className="category-section"
            aria-labelledby={`heading-${section.id}`}
          >
            <h2 id={`heading-${section.id}`} className="category-section__title">
              {section.label}
            </h2>
            <div className="product-grid">
              {section.products.map((product, index) => (
                <article
                  key={product.id}
                  className="product-card"
                  style={{ animationDelay: `${Math.min(index, 8) * 40}ms` }}
                >
                  <button
                    type="button"
                    className="product-card__button"
                    onClick={() => setSelectedProduct(product)}
                  >
                    <div className="product-card__media">
                      <Image
                        src={product.images[0] ?? "/product-placeholder.svg"}
                        alt={product.name}
                        width={240}
                        height={240}
                        sizes="(max-width: 504px) 48vw, 240px"
                      />
                    </div>
                    <h3 className="product-card__title">{product.name}</h3>
                    {product.nameEn ? (
                      <p className="product-card__title-en" lang="en" dir="ltr">
                        {product.nameEn}
                      </p>
                    ) : null}
                    <p className="product-card__price">
                      {product.price != null ? (
                        <>
                          <span className="product-card__price-value">
                            {formatPrice(product.price)}
                          </span>
                          <span className="product-card__price-unit">تومان</span>
                        </>
                      ) : (
                        <span className="product-card__price-value">—</span>
                      )}
                    </p>
                  </button>
                </article>
              ))}
            </div>
          </section>
        ))}
      </main>

      {selectedProduct ? (
        <ProductModal
          product={selectedProduct}
          onClose={() => setSelectedProduct(null)}
        />
      ) : null}
    </SiteChrome>
  );
}
