"use client";

import Image from "next/image";
import Link from "next/link";
import { useEffect, useMemo, useRef, useState } from "react";
import {
  categoryMenu,
  menuAssurances,
  menuCta,
  menuFeature,
} from "@/lib/category-menu";

/**
 * Categories mega-menu.
 *
 * Geometry is taken off the design: the panel spans the same 1200px container
 * as the header (its left edge lines up with the logo, its right with the
 * avatar), and splits into a 300 rail / 528 detail / 310 promo set of columns.
 * See `lib/category-menu.ts` for the provenance of the copy.
 */

function LineIcon({ d, size = 18 }: { d: string; size?: number }) {
  return (
    <svg
      width={size}
      height={size}
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth={1.5}
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <path d={d} />
    </svg>
  );
}

function ArrowCircle() {
  return (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" aria-hidden="true">
      <circle cx="12" cy="12" r="9" stroke="currentColor" strokeWidth="1.4" />
      <path
        d="M9.5 12h5M12.5 9.3l2.7 2.7-2.7 2.7"
        stroke="currentColor"
        strokeWidth="1.4"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

function PlayMark() {
  return (
    <span className="flex h-[30px] w-[30px] items-center justify-center rounded-full bg-white/25 backdrop-blur-[2px] ring-1 ring-white/60">
      <svg width="12" height="14" viewBox="0 0 12 14" aria-hidden="true">
        <path d="M0 0.8v12.4l11-6.2z" fill="#ffffff" />
      </svg>
    </span>
  );
}

export function CategoryMegaMenu({ onClose }: { onClose: () => void }) {
  const [activeId, setActiveId] = useState(categoryMenu[0].id);
  const active = useMemo(
    () => categoryMenu.find((c) => c.id === activeId) ?? categoryMenu[0],
    [activeId],
  );
  const panelRef = useRef<HTMLDivElement>(null);

  // Escape closes; focus moves into the panel so the menu is keyboard-usable.
  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") onClose();
    };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [onClose]);

  const activeLinkId = active.groups[0]?.links[0]?.label;

  return (
    <div
      ref={panelRef}
      role="dialog"
      aria-label="Product categories"
      className="absolute inset-x-0 top-full z-40 pt-[10px]"
    >
      <div className="mx-auto max-w-[1200px] px-4 lg:px-0">
        {/* The panel itself is the light grey; only the middle detail column is
            a white card sitting on it. Rail and promo columns read as grey.
            Below lg it becomes a single scrolling sheet — three columns cannot
            survive a phone, and the promo rail is the first thing to go. */}
        <div className="grid max-h-[calc(100dvh-140px)] grid-cols-1 gap-[16px] overflow-y-auto rounded-[16px] border border-black/5 bg-[#f4f5f7] p-[14px] shadow-[0_24px_60px_-24px_rgba(1,14,35,0.28)] md:grid-cols-[260px_minmax(0,1fr)] lg:max-h-none lg:grid-cols-[300px_minmax(0,1fr)_310px] lg:overflow-visible">
          {/* ---------------- category rail ---------------- */}
          {/* 44px rows on a 12px gap = the design's ~57px pitch. Tighter than
              this and the whole panel comes out short, because nine rows set
              the rail height and the rail sets the panel height. */}
          <ul className="-mx-[4px] flex snap-x gap-[8px] overflow-x-auto px-[4px] pb-[4px] [scrollbar-width:none] md:mx-0 md:flex-col md:gap-[12px] md:overflow-visible md:px-0 md:pb-0 [&::-webkit-scrollbar]:hidden">
            {categoryMenu.map((cat) => {
              const isActive = cat.id === active.id;
              return (
                <li key={cat.id}>
                  <button
                    type="button"
                    onMouseEnter={() => setActiveId(cat.id)}
                    onFocus={() => setActiveId(cat.id)}
                    onClick={() => setActiveId(cat.id)}
                    aria-current={isActive}
                    className={[
                      "flex h-[44px] w-max shrink-0 snap-start items-center gap-[10px] rounded-[10px] px-[12px] text-left text-[13px] whitespace-nowrap transition-colors md:w-full md:shrink md:whitespace-normal",
                      isActive
                        ? "bg-ink font-semibold text-white"
                        : "text-[#1a1a1a] hover:bg-[#f4f7fa]",
                    ].join(" ")}
                  >
                    <span className={isActive ? "text-white" : "text-[#6b7280]"}>
                      <LineIcon d={cat.icon} />
                    </span>
                    <span className="min-w-0 flex-1 truncate">{cat.name}</span>
                    <span
                      className={[
                        "shrink-0 text-[11px]",
                        isActive ? "text-white/60" : "text-[#9ca3af]",
                      ].join(" ")}
                    >
                      {cat.count}
                    </span>
                  </button>
                </li>
              );
            })}
          </ul>

          {/* ---------------- subcategory detail ---------------- */}
          <div className="rounded-[12px] border border-[#e9ecf2] bg-white p-[20px]">
            <p className="text-[10px] font-semibold tracking-[0.14em] text-[#29b6f6] uppercase">
              Category
            </p>
            <h3 className="mt-[10px] mb-[28px] text-[15px] font-bold text-[#1a1a1a]">
              {active.name}
            </h3>

            {/* The design stacks Garments + Footwear on the left and leaves
                Fabric & Trims alone on the right, so the split is explicit —
                CSS multi-column auto-flow puts the break in the wrong place. */}
            <div className="grid grid-cols-1 gap-x-[28px] sm:grid-cols-2">
              {[
                active.groups.slice(0, Math.ceil(active.groups.length / 2)),
                active.groups.slice(Math.ceil(active.groups.length / 2)),
              ].map((column, ci) => (
                <div key={ci}>
                  {column.map((group) => (
                    <div key={group.title} className="mb-[32px]">
                      <h4 className="mb-[10px] border-b border-[#e9ecf2] pb-[6px] text-[12px] font-semibold text-[#1a1a1a]">
                        {group.title}
                      </h4>
                      <ul className="flex flex-col gap-[2px]">
                        {group.links.map((link) => {
                          const highlight = link.label === activeLinkId;
                          return (
                            <li key={link.label}>
                              <Link
                                href={link.href}
                                onClick={onClose}
                                className={[
                                  "flex items-center gap-[8px] rounded-[6px] px-[8px] py-[6px] text-[12px] transition-colors",
                                  highlight
                                    ? "bg-[#eaf4fd] font-medium text-[#0652e0]"
                                    : "text-[#4b5563] hover:bg-[#f4f7fa] hover:text-[#0652e0]",
                                ].join(" ")}
                              >
                                <span
                                  className={[
                                    "h-[4px] w-[4px] shrink-0 rounded-full",
                                    highlight ? "bg-[#0652e0]" : "bg-[#c7cdd6]",
                                  ].join(" ")}
                                />
                                {link.label}
                              </Link>
                            </li>
                          );
                        })}
                      </ul>
                    </div>
                  ))}
                </div>
              ))}
            </div>
          </div>

          {/* ---------------- promo column ---------------- */}
          <div className="hidden flex-col gap-[16px] lg:flex">
            {active.products.length > 0 && (
              <>
                <ul className="grid grid-cols-3 gap-[8px]">
                  {active.products.map((p) => (
                    <li
                      key={p.name}
                      className="flex aspect-square items-center justify-center rounded-[10px] bg-[#e9f2fb]"
                    >
                      <Image
                        src={p.image}
                        alt={p.name}
                        width={220}
                        height={250}
                        className="h-[62%] w-auto object-contain"
                      />
                    </li>
                  ))}
                </ul>
                <div className="flex items-center justify-center gap-[5px]">
                  <span className="h-[3px] w-[22px] rounded-full bg-[#0652e0]" />
                  <span className="h-[3px] w-[8px] rounded-full bg-[#dbe3ea]" />
                  <span className="h-[3px] w-[8px] rounded-full bg-[#dbe3ea]" />
                </div>
              </>
            )}

            <Link
              href={menuFeature.href}
              onClick={onClose}
              className="group relative block overflow-hidden rounded-[10px]"
            >
              <Image
                src={menuFeature.image}
                alt=""
                width={344}
                height={192}
                className="h-[150px] w-full object-cover transition-transform duration-500 group-hover:scale-[1.04]"
              />
              <span className="absolute inset-0 bg-[linear-gradient(180deg,rgba(1,14,35,0.1)_38%,rgba(1,14,35,0.82)_100%)]" />
              <span className="absolute top-[8px] left-[8px] rounded-full bg-black/45 px-[7px] py-[2px] text-[8px] font-semibold tracking-[0.02em] text-white backdrop-blur-[2px]">
                {menuFeature.badge}
              </span>
              <span className="absolute inset-0 flex items-center justify-center">
                <PlayMark />
              </span>
              <span className="absolute inset-x-[12px] bottom-[10px] block">
                <span className="block text-[12px] font-bold text-white">
                  {menuFeature.title}
                </span>
                <span className="block text-[10px] leading-[14px] text-white/80">
                  {menuFeature.subtitle}
                </span>
              </span>
            </Link>

            <ul className="flex flex-col gap-[14px]">
              {menuAssurances.map((a) => (
                <li key={a.id} className="flex items-start gap-[9px]">
                  <span className="mt-[1px] shrink-0 text-[#0652e0]">
                    <LineIcon d={a.icon} size={15} />
                  </span>
                  <span className="min-w-0">
                    <span className="block text-[11px] font-semibold text-[#1a1a1a]">
                      {a.title}
                    </span>
                    <span className="block text-[10px] leading-[14px] text-[#6b7280]">
                      {a.body}
                    </span>
                  </span>
                </li>
              ))}
            </ul>

            <Link
              href={menuCta.href}
              onClick={onClose}
              className="mt-auto flex h-[48px] items-center justify-between rounded-full bg-ink px-[20px] text-[12px] font-bold text-white transition-transform duration-300 hover:scale-[1.02]"
            >
              {menuCta.label}
              <ArrowCircle />
            </Link>
          </div>
        </div>
      </div>
    </div>
  );
}
