"use client";

import { useEffect } from "react";

/**
 * WordPress sitesindeki "floating pill" header efekti.
 * Scroll'da header küçülür, kenar yuvarlanır, gölge alır.
 * Mobilde scroll-down'da gizlenir, scroll-up'ta görünür.
 */
export function HeaderScrollEffect() {
  useEffect(() => {
    const wrap = document.getElementById("floating-header-wrap");
    const pillWrap = document.getElementById("header-pill-wrap");
    const header = document.getElementById("site-header");
    const navBar = document.getElementById("header-nav-bar");
    if (!wrap || !pillWrap || !header || !navBar) return;

    let lastY = 0;
    let ticking = false;

    wrap.style.transition = "transform 0.3s ease, opacity 0.3s ease";

    function applyScroll() {
      const y = window.scrollY;
      const mobile = window.innerWidth < 1024;
      const scrolled = y > 10;
      const goingDown = y > lastY;

      if (!mobile && pillWrap && header && navBar && wrap) {
        wrap.style.transform = "";
        wrap.style.opacity = "";
        // Pill modu için data-pill-hide elementlerini gizle/göster
        const hidables = document.querySelectorAll<HTMLElement>(
          '[data-pill-hide="true"]',
        );
        if (scrolled) {
          pillWrap.style.padding = "12px 16px 0";
          header.style.maxWidth = "1100px";
          header.style.borderRadius = "1rem";
          header.style.border = "1px solid #e5e7eb";
          header.style.boxShadow = "0 8px 24px rgba(0,0,0,0.08)";
          navBar.style.height = "52px";
          navBar.style.padding = "0 1.25rem";
          hidables.forEach((el) => {
            el.style.display = "none";
          });
        } else {
          pillWrap.style.padding = "";
          header.style.maxWidth = "";
          header.style.borderRadius = "";
          header.style.border = "";
          header.style.boxShadow = "";
          navBar.style.height = "";
          navBar.style.padding = "";
          hidables.forEach((el) => {
            el.style.display = "";
          });
        }
      }

      if (mobile && wrap && y > 80) {
        if (goingDown) {
          wrap.style.transform = "translateY(-110%)";
          wrap.style.opacity = "0";
        } else {
          wrap.style.transform = "";
          wrap.style.opacity = "";
        }
      } else if (mobile && wrap) {
        wrap.style.transform = "";
        wrap.style.opacity = "";
      }

      lastY = y;
      ticking = false;
    }

    function onScroll() {
      if (!ticking) {
        requestAnimationFrame(applyScroll);
        ticking = true;
      }
    }

    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", applyScroll);
    applyScroll();

    return () => {
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("resize", applyScroll);
    };
  }, []);

  return null;
}
