"use client";

import { useState, useEffect, useMemo } from "react";
import { useGetPagesQuery } from "@/api/blog.api";

function scrollTo(id: string) {
  const el = document.getElementById(id);
  if (el) el.scrollIntoView({ behavior: "smooth", block: "start" });
}

function formatUpdated(iso: string): string {
  return new Date(iso).toLocaleDateString("en-US", {
    month: "long",
    year: "numeric",
  });
}

export default function Legal() {
  const { data, isLoading } = useGetPagesQuery();
  const pages = useMemo(() => data?.data ?? [], [data]);

  const [active, setActive] = useState("");

  useEffect(() => {
    if (pages.length === 0) return;
    // Default the highlight to the first section until the observer kicks in.
    setActive((prev) => prev || pages[0].code);

    const observer = new IntersectionObserver(
      (entries) => {
        for (const entry of entries) {
          if (entry.isIntersecting) setActive(entry.target.id);
        }
      },
      { rootMargin: "-30% 0px -60% 0px", threshold: 0 },
    );
    pages.forEach(({ code }) => {
      const el = document.getElementById(code);
      if (el) observer.observe(el);
    });
    return () => observer.disconnect();
  }, [pages]);

  // Arriving via /legal#terms-conditions: the target section doesn't exist
  // until the data loads, so the browser's native hash scroll is a no-op. Once
  // the sections are rendered, scroll to the hash ourselves — and again on any
  // later hash change (e.g. clicking another footer link while already here).
  useEffect(() => {
    if (pages.length === 0) return;

    const scrollToHash = () => {
      const code = decodeURIComponent(window.location.hash.slice(1));
      if (!code) return;
      const el = document.getElementById(code);
      if (!el) return;
      el.scrollIntoView({ behavior: "smooth", block: "start" });
      setActive(code);
    };

    // Defer one frame so the freshly-rendered sections are in the DOM.
    const raf = requestAnimationFrame(scrollToHash);
    window.addEventListener("hashchange", scrollToHash);
    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener("hashchange", scrollToHash);
    };
  }, [pages]);

  return (
    <div style={{ backgroundColor: "#f3f4f6" }}>
      <div className="flex flex-col lg:flex-row gap-6 w-full max-w-268.5 mx-auto py-6 sm:py-10 px-4">

        {/* ── Left: content ── */}
        <div className="w-full lg:w-162.5 lg:shrink-0 space-y-6 sm:space-y-10">
          {isLoading ? (
            Array.from({ length: 3 }).map((_, i) => (
              <div
                key={i}
                className="bg-white rounded-2xl px-5 sm:px-8 py-6 sm:py-8 animate-pulse space-y-4"
              >
                <div className="h-7 w-1/3 bg-gray-200 rounded" />
                <div className="h-3 w-1/2 bg-gray-100 rounded" />
                <div className="h-4 w-full bg-gray-100 rounded" />
                <div className="h-4 w-5/6 bg-gray-100 rounded" />
              </div>
            ))
          ) : pages.length === 0 ? (
            <div className="bg-white rounded-2xl px-8 py-14 text-center text-sm text-gray-400">
              No content available.
            </div>
          ) : (
            pages.map((page) => (
              <div
                key={page.id}
                id={page.code}
                className="bg-white rounded-2xl px-5 sm:px-8 py-6 sm:py-8 scroll-mt-24"
              >
                <h2 className="text-2xl font-bold text-gray-900 mb-1">
                  {page.title}
                </h2>
                <p className="text-xs text-gray-400 mb-7">
                  Last Updated: {formatUpdated(page.updatedAt)} · www.myseatime.com
                </p>
                <div
                  className="text-[15px] text-gray-700 leading-relaxed [&_h3]:font-semibold [&_h3]:text-gray-900 [&_h3]:mt-6 [&_h3]:mb-1 [&>h3:first-child]:mt-0 [&_p]:mb-4 [&_p:last-child]:mb-0 [&_a]:text-blue-500 hover:[&_a]:underline"
                  dangerouslySetInnerHTML={{ __html: page.limitedContent ?? "" }}
                />
              </div>
            ))
          )}
        </div>

        {/* ── Right: sticky index (above content on mobile) ── */}
        <div className="w-full lg:flex-1 order-first lg:order-0">
          <div className="lg:sticky lg:top-24 bg-white rounded-2xl px-5 py-5">
            <p className="text-[11px] font-bold text-gray-400 uppercase tracking-widest mb-4">On this page</p>
            <ul className="space-y-1">
              {pages.map((page) => (
                <li key={page.id}>
                  <button
                    type="button"
                    onClick={() => scrollTo(page.code)}
                    className={`w-full text-left px-3 py-2.5 rounded-xl text-sm transition-all ${
                      active === page.code
                        ? "bg-blue-50 text-blue-600 font-semibold"
                        : "text-gray-600 hover:bg-gray-50 hover:text-gray-900 font-medium"
                    }`}
                  >
                    {page.title}
                  </button>
                </li>
              ))}
            </ul>
          </div>
        </div>

      </div>
    </div>
  );
}
