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

type HeaderState = {
  title: React.ReactNode | null;
  left: React.ReactNode | null;
  mobileMenu: React.ReactNode | null;
};

type HeaderContextValue = {
  header: HeaderState;
  setHeader: (next: Partial<HeaderState>) => void;
  resetHeader: () => void;
};

const DEFAULT_HEADER: HeaderState = {
  title: null,
  left: null,
  mobileMenu: null,
};

const HeaderContext = createContext<HeaderContextValue | null>(null);

export const HeaderProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [header, setHeaderState] = useState<HeaderState>(DEFAULT_HEADER);

  const setHeader = useCallback((next: Partial<HeaderState>) => {
    setHeaderState((prev) => ({ ...prev, ...next }));
  }, []);

  const resetHeader = useCallback(() => {
    setHeaderState(DEFAULT_HEADER);
  }, []);

  const value = useMemo(() => ({ header, setHeader, resetHeader }), [header, setHeader, resetHeader]);

  return <HeaderContext.Provider value={value}>{children}</HeaderContext.Provider>;
};

export const useHeader = () => {
  const ctx = useContext(HeaderContext);
  if (!ctx) throw new Error('useHeader must be used within HeaderProvider');
  return ctx;
};
