"use client";

import { useEffect, useState } from "react";
import { ChevronUp, ChevronDown } from "lucide-react";
import { sfx } from "@/lib/sfx";
import clsx from "clsx";

/**
 * Pages like Reels scroll inside their own container rather than the window,
 * so find whichever element actually scrolls before driving it.
 */
function getScroller(): HTMLElement | Window {
  if (typeof document === "undefined") return window;
  // If the window itself scrolls, prefer that.
  if (document.body.scrollHeight > window.innerHeight + 40) return window;

  // Otherwise find the largest inner container that scrolls — pages like
  // Reels own their scrolling and sit outside <main>.
  let best: HTMLElement | null = null;
  document.querySelectorAll<HTMLElement>("body *").forEach((el) => {
    const style = getComputedStyle(el);
    if (!/auto|scroll/.test(style.overflowY)) return;
    if (el.scrollHeight <= el.clientHeight + 40) return;
    if (!best || el.clientHeight > best.clientHeight) best = el;
  });
  return best ?? window;
}

function scrollTopOf(s: HTMLElement | Window) {
  return s instanceof Window ? s.scrollY : s.scrollTop;
}

function scrollHeightOf(s: HTMLElement | Window) {
  return s instanceof Window ? document.body.scrollHeight : s.scrollHeight;
}

function viewportOf(s: HTMLElement | Window) {
  return s instanceof Window ? s.innerHeight : s.clientHeight;
}

/**
 * Jump-to-top / jump-to-bottom plus a hands-free auto-scroll, for reading
 * long feeds. Auto-scroll stops on any manual scroll up, so it never fights
 * the person.
 */
export function ScrollUpButton() {
  const [show, setShow] = useState(false);
  useEffect(() => {
    const s = getScroller();
    const onScroll = () => setShow(scrollTopOf(getScroller()) > 400);
    s.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => {
      s.removeEventListener("scroll", onScroll);
      window.removeEventListener("scroll", onScroll);
    };
  }, []);

  return (
    <button
      onClick={() => {
        getScroller().scrollTo({ top: 0, behavior: "smooth" });
        sfx.click();
      }}
      title="Back to top"
      className={clsx("sc-btn", !show && "opacity-40")}
    >
      <ChevronUp size={16} />
    </button>
  );
}

export function ScrollDownButton() {
  return (
    <button
      onClick={() => {
        const s = getScroller();
        s.scrollTo({ top: scrollHeightOf(s), behavior: "smooth" });
        sfx.click();
      }}
      title="Jump to bottom"
      className="sc-btn"
    >
      <ChevronDown size={16} />
    </button>
  );
}
