"use client";

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

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

type OfficialMailGuideSidebarProps = {
  groups: GuideSidebarGroup[];
};

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

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

  useEffect(() => {
    const sectionIds = sectionIdsRef.current;
    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);
    };
  }, []);

  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 top-[60px] hidden w-[236px] border-r border-[#e8edf5] bg-white px-5 py-6 lg:block">
      <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>
  );
}
