'use client';

import { createContext, useContext, useState, useCallback, useEffect } from 'react';

interface PageHeader {
  title: string;
  subtitle: string;
}

interface PageHeaderContextValue extends PageHeader {
  setPageHeader: (title: string, subtitle: string) => void;
}

const PageHeaderContext = createContext<PageHeaderContextValue>({
  title: '',
  subtitle: '',
  setPageHeader: () => {},
});

export function PageHeaderProvider({ children }: { children: React.ReactNode }) {
  const [header, setHeader] = useState<PageHeader>({ title: '', subtitle: '' });

  const setPageHeader = useCallback((title: string, subtitle: string) => {
    setHeader({ title, subtitle });
  }, []);

  return (
    <PageHeaderContext.Provider value={{ ...header, setPageHeader }}>
      {children}
    </PageHeaderContext.Provider>
  );
}

export function usePageHeader(title?: string, subtitle?: string) {
  const ctx = useContext(PageHeaderContext);

  useEffect(() => {
    if (title !== undefined) {
      ctx.setPageHeader(title, subtitle ?? '');
    }
  }, [title, subtitle]);

  return ctx;
}
