"use client";
import { ReactNode, useEffect } from "react";
import Preloader from "./Preloader";
import ScrollToTop from "./ScrollToTop";
import { usePathname } from "next/navigation";

interface LayoutWrapperProps {
  children: ReactNode;
}

const LayoutWrapper = ({ children }: LayoutWrapperProps) => {
  const pathname = usePathname();

  useEffect(() => {
    // Force scroll to top on every pathname change - runs FIRST
    window.history.scrollRestoration = 'manual';
    
    // Immediate scroll
    window.scrollTo(0, 0);
    document.documentElement.scrollTop = 0;
    document.body.scrollTop = 0;
    
    // Disable any smooth scroll temporarily
    const html = document.documentElement;
    const body = document.body;
    const originalHtmlScroll = html.style.scrollBehavior;
    const originalBodyScroll = body.style.scrollBehavior;
    
    html.style.scrollBehavior = 'auto';
    body.style.scrollBehavior = 'auto';
    
    // Multiple forced scrolls
    const scrollInterval = setInterval(() => {
      window.scrollTo(0, 0);
      document.documentElement.scrollTop = 0;
      document.body.scrollTop = 0;
    }, 10);
    
    // Clean up after 300ms
    const cleanup = setTimeout(() => {
      clearInterval(scrollInterval);
      html.style.scrollBehavior = originalHtmlScroll;
      body.style.scrollBehavior = originalBodyScroll;
    }, 300);
    
    return () => {
      clearInterval(scrollInterval);
      clearTimeout(cleanup);
    };
  }, [pathname]);

  return (
    <>
      <ScrollToTop />
      <Preloader>
        {children}
      </Preloader>
    </>
  );
};

export default LayoutWrapper;
