"use client";

import { type MouseEvent, useEffect, useState } from "react";

export type GuideSidebarGroup = {
  label: string;
  items: Array<{
    href: string;
    label: string;
  }>;
};

type OfficialMailGuideSidebarProps = {
  groups: GuideSidebarGroup[];
  localeSuggestionVisible?: boolean;
};

function getSectionIds(groups: GuideSidebarGroup[]) {
  return groups
    .flatMap((group) => group.items)
    .map((item) => item.href.replace(/^#/, ""))
    .filter(Boolean);
}

export function OfficialMailGuideSidebar({
  groups,
  localeSuggestionVisible = false,
}: OfficialMailGuideSidebarProps) {
  const [sectionIds] = useState(() => getSectionIds(groups));
  const [activeHref, setActiveHref] = useState(() => {
    const firstId = sectionIds[0];
    return firstId ? `#${firstId}` : "";
  });

  useEffect(() => {
    let frameId = 0;

    const syncActiveSection = () => {
      frameId = 0;
      const readY = window.scrollY + 110;
      let nextId = sectionIds[0] ?? "";

      for (const sectionId of sectionIds) {
        const section = document.getElementById(sectionId);
        if (!section) continue;
        if (section.offsetTop <= readY) {
          nextId = sectionId;
        }
      }

      const documentBottom =
        window.innerHeight + window.scrollY >= document.documentElement.scrollHeight - 4;
      if (documentBottom) {
        nextId = sectionIds[sectionIds.length - 1] ?? nextId;
      }

      if (nextId) {
        setActiveHref((current) => (current === `#${nextId}` ? current : `#${nextId}`));
      }
    };

    const requestSync = () => {
      if (frameId) return;
      frameId = window.requestAnimationFrame(syncActiveSection);
    };

    syncActiveSection();
    window.addEventListener("scroll", requestSync, { passive: true });
    window.addEventListener("resize", requestSync);
    window.addEventListener("hashchange", requestSync);

    return () => {
      if (frameId) {
        window.cancelAnimationFrame(frameId);
      }
      window.removeEventListener("scroll", requestSync);
      window.removeEventListener("resize", requestSync);
      window.removeEventListener("hashchange", requestSync);
    };
  }, [sectionIds]);

  const handleClick = (event: MouseEvent<HTMLAnchorElement>, href: string) => {
    const targetId = href.replace(/^#/, "");
    const target = document.getElementById(targetId);
    if (!target) return;

    event.preventDefault();
    setActiveHref(href);
    target.scrollIntoView({ behavior: "smooth", block: "start" });
    window.history.pushState(null, "", href);
  };

  return (
    <aside
      className={`fixed bottom-0 left-0 hidden w-[236px] border-r border-[#e8edf5] bg-white px-5 py-6 lg:block ${
        localeSuggestionVisible ? "top-[108px]" : "top-[60px]"
      }`}
    >
      <nav className="h-full overflow-y-auto pr-1">
        {groups.map((group, groupIndex) => (
          <div key={group.label} className={groupIndex === 0 ? "" : "mt-7"}>
            <p className="px-3 text-[12px] font-bold uppercase tracking-[0.12em] text-[#8b95a1]">
              {group.label}
            </p>
            <div className="mt-2 space-y-1">
              {group.items.map((item) => {
                const isActive = activeHref === item.href;
                return (
                  <a
                    key={item.href}
                    href={item.href}
                    aria-current={isActive ? "location" : undefined}
                    onClick={(event) => handleClick(event, item.href)}
                    className={`block rounded-[10px] px-3 py-2.5 text-[14px] font-semibold transition-colors ${
                      isActive
                        ? "bg-[#f2f4f6] text-[#191f28]"
                        : "text-[#6b7684] hover:bg-[#f6f8fb] hover:text-[#3182f6]"
                    }`}
                  >
                    {item.label}
                  </a>
                );
              })}
            </div>
          </div>
        ))}
      </nav>
    </aside>
  );
}

export function OfficialMailGuideMobileMenu({ groups }: OfficialMailGuideSidebarProps) {
  const [isOpen, setIsOpen] = useState(false);

  const handleClick = (event: MouseEvent<HTMLAnchorElement>, href: string) => {
    const target = document.getElementById(href.replace(/^#/, ""));
    if (!target) return;

    event.preventDefault();
    setIsOpen(false);
    target.scrollIntoView({ behavior: "smooth", block: "start" });
    window.history.pushState(null, "", href);
  };

  return (
    <div className="relative md:hidden">
      <button
        type="button"
        aria-label={isOpen ? "가이드 메뉴 닫기" : "가이드 메뉴 열기"}
        aria-expanded={isOpen}
        onClick={() => setIsOpen((current) => !current)}
        className="inline-flex h-10 w-10 items-center justify-center rounded-[12px] text-[#4e5968] transition-colors hover:bg-[#f6f8fb]"
      >
        {isOpen ? (
          <svg viewBox="0 0 24 24" fill="none" className="h-5 w-5" aria-hidden="true">
            <path d="m6 6 12 12M18 6 6 18" stroke="currentColor" strokeLinecap="round" strokeWidth="1.8" />
          </svg>
        ) : (
          <svg viewBox="0 0 24 24" fill="none" className="h-5 w-5" aria-hidden="true">
            <path d="M4.5 7h15M4.5 12h15M4.5 17h15" stroke="currentColor" strokeLinecap="round" strokeWidth="1.8" />
          </svg>
        )}
      </button>

      {isOpen ? (
        <div className="absolute right-0 top-[calc(100%+8px)] max-h-[calc(100vh-84px)] w-[min(300px,calc(100vw-40px))] overflow-y-auto rounded-[16px] border border-[#e5e8ef] bg-white p-3 shadow-[0_18px_48px_rgba(15,23,42,0.14)]">
          {groups.map((group, groupIndex) => (
            <div key={group.label} className={groupIndex === 0 ? "" : "mt-4 border-t border-[#edf1f7] pt-4"}>
              <p className="px-2 text-[11px] font-bold uppercase tracking-[0.12em] text-[#8b95a1]">{group.label}</p>
              <div className="mt-1.5 space-y-0.5">
                {group.items.map((item) => (
                  <a
                    key={item.href}
                    href={item.href}
                    onClick={(event) => handleClick(event, item.href)}
                    className="block rounded-[9px] px-2 py-2 text-[14px] font-semibold text-[#4e5968] transition-colors hover:bg-[#f6f8fb] hover:text-[#3182f6]"
                  >
                    {item.label}
                  </a>
                ))}
              </div>
            </div>
          ))}
        </div>
      ) : null}
    </div>
  );
}
