'use client';

import React, { createContext, useContext, useEffect, useRef, useState } from 'react';
import { cn } from '@/lib/utils';
import { IconButton } from '@/components/ui/button';
import { useRouter } from 'next/navigation';

const PolicyLayoutContext = createContext<{
  setTitle: (title: string) => void;
} | null>(null);

export const usePolicyLayout = () => {
  const context = useContext(PolicyLayoutContext);
  if (!context) {
    throw new Error('usePolicyLayout must be used within PolicyLayout');
  }
  return context;
};

const PolicyLayout = ({ children }: { children: React.ReactNode }) => {
  const [isBlur, setIsBlur] = useState(false);
  const containerRef = useRef<HTMLDivElement>(null);
  const [title, setTitle] = useState('');
  const router = useRouter();

  useEffect(() => {
    function handleScroll(event: Event) {
      const dom = event.target as HTMLElement;
      setIsBlur(dom.scrollTop > 0);
    }
    if (containerRef.current) {
      containerRef.current.addEventListener('scroll', handleScroll, { passive: true });
    }
    return () => {
      if (containerRef.current) {
        containerRef.current.removeEventListener('scroll', handleScroll);
      }
    };
  }, []);

  return (
    <PolicyLayoutContext.Provider value={{ setTitle }}>
      <div className="flex h-screen overflow-hidden bg-[url('/common-bg.png')] bg-cover bg-fixed bg-top bg-no-repeat">
        <div className="relative flex min-w-0 flex-1 flex-col">
          <header
            className={cn(
              'absolute z-40 flex h-16 w-full items-center justify-between px-8 transition-all',
              {
                'backdrop-blur-[10px]': isBlur,
              }
            )}
          >
            {isBlur && <div className="bg-background-default absolute inset-0 opacity-85" />}
            <div className="relative inset-0 flex w-full items-center justify-between">
              <div className="items-center justify-between inset-0 h-16 flex">
                <IconButton
                  variant="ghost"
                  size="large"
                  onClick={() => router.back()}
                  iconfont="icon-arrow-left"
                />
                <div className="txt-title-m">{title}</div>
                <div></div>
              </div>
            </div>
          </header>
          <main ref={containerRef} className="overflow-auto flex-1">
            <div className="min-h-full pt-16 w-full justify-center bg-[url('/common-bg.png')] bg-cover bg-fixed bg-top bg-no-repeat">
              {children}
            </div>
          </main>
        </div>
      </div>
    </PolicyLayoutContext.Provider>
  );
};

export default PolicyLayout;
