"use client";

import { useEffect, useState } from "react";

type Dot = { id: string; label: string };

function buildDots(hasAbout: boolean, hasComments: boolean): Dot[] {
  const dots: Dot[] = [{ id: "", label: "Back to top" }];
  if (hasAbout) dots.push({ id: "about-me", label: "About me" });
  if (hasComments) dots.push({ id: "comments", label: "Comments" });
  return dots;
}

export default function ProfileScrollNav({
  hasAbout,
  hasComments,
  showHint = true,
}: {
  hasAbout: boolean;
  hasComments: boolean;
  showHint?: boolean;
}) {
  const [active, setActive] = useState(0);
  const [visible, setVisible] = useState(true);

  useEffect(() => {
    let frame = 0;
    const measure = () => {
      frame = 0;
      const y = window.scrollY;
      setVisible(y < window.innerHeight * 0.35);
      const dots = buildDots(hasAbout, hasComments);
      let current = 0;

      // Bottom-of-page check: guarantees the final dot activates if scrolled near bottom
      const isNearBottom = window.innerHeight + y >= document.documentElement.scrollHeight - 60;
      if (isNearBottom && dots.length > 1) {
        current = dots.length - 1;
      } else {
        for (let i = 1; i < dots.length; i++) {
          const el = document.getElementById(dots[i].id);
          if (el) {
            const rect = el.getBoundingClientRect();
            // Activate when section enters the upper 55% of the viewport
            if (rect.top <= window.innerHeight * 0.55) {
              current = i;
            }
          }
        }
      }
      setActive(current);
    };
    const onScroll = () => {
      if (!frame) frame = window.requestAnimationFrame(measure);
    };
    measure();
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll);
    return () => {
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("resize", onScroll);
      if (frame) window.cancelAnimationFrame(frame);
    };
  }, [hasAbout, hasComments]);

  const dots = buildDots(hasAbout, hasComments);
  const hintTarget = hasAbout ? "#about-me" : "#comments";
  const hintVisible = showHint && visible;

  const go = (dot: Dot) => {
    if (!dot.id) {
      window.scrollTo({ top: 0, behavior: "smooth" });
      return;
    }
    document.getElementById(dot.id)?.scrollIntoView({ behavior: "smooth", block: "start" });
  };

  return (
    <>
      <a
        href={hintTarget}
        aria-label="Scroll down for more"
        style={{
          position: "fixed",
          bottom: 26,
          left: "50%",
          zIndex: 70,
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
          gap: 5,
          fontFamily: 'Georgia, "Playfair Display", "Merriweather", serif',
          fontSize: 15,
          fontWeight: 700,
          letterSpacing: ".01em",
          color: "var(--profile-text, #7c0707)",
          textShadow: "0 1px 10px rgba(0,0,0,.45)",
          textDecoration: "none",
          transform: "translateX(-50%)",
          opacity: hintVisible ? 1 : 0,
          pointerEvents: hintVisible ? "auto" : "none",
          transition: "opacity .35s ease",
          animation: "scrollHintBounce 1.6s ease-in-out infinite",
        }}
      >
        Scroll for more
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
          <path d="M12 4v15m0 0 5.5-5.5M12 19l-5.5-5.5" />
        </svg>
      </a>

      {dots.length > 1 && (
        <nav aria-label="Page sections" className="pfDots" style={{ position: "fixed", right: 16, top: "50%", transform: "translateY(-50%)", zIndex: 70, display: "grid", gap: 11 }}>
          {dots.map((dot, i) => (
            <button
              key={dot.id || "top"}
              type="button"
              className="pfDot"
              aria-label={dot.label}
              aria-current={active === i ? "true" : undefined}
              onClick={() => go(dot)}
              style={{
                width: 7,
                height: active === i ? 20 : 7,
                padding: 0,
                borderRadius: 999,
                border: "none",
                cursor: "pointer",
                background: "var(--profile-text, #000000)",
                opacity: active === i ? 1 : 0.35,
                transition: "height 0.25s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.25s ease",
              }}
            />
          ))}
        </nav>
      )}
    </>
  );
}
