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

type HeadProps = {
  title?: string;
  description?: string;
  children?: React.ReactNode;
};

// Create a context to manage document head
const HeadContext = createContext<{
  updateHead: (props: HeadProps) => void;
}>({
  updateHead: () => {},
});

// Provider component that will wrap the application
export const HeadProvider = ({ children }: { children: React.ReactNode }) => {
  const updateHead = ({ title, description }: HeadProps) => {
    if (title) {
      document.title = title;
    }
    
    if (description) {
      // Find existing description meta tag or create a new one
      let metaDescription = document.querySelector('meta[name="description"]');
      if (!metaDescription) {
        metaDescription = document.createElement('meta');
        metaDescription.setAttribute('name', 'description');
        document.head.appendChild(metaDescription);
      }
      metaDescription.setAttribute('content', description);
    }
  };

  return (
    <HeadContext.Provider value={{ updateHead }}>
      {children}
    </HeadContext.Provider>
  );
};

// Component to use in pages for setting title and description
const PageHead = ({ title, description }: HeadProps) => {
  const { updateHead } = useContext(HeadContext);
  
  useEffect(() => {
    updateHead({ title, description });
    
    // Cleanup is not typically needed, but could reset title if desired
    return () => {};
  }, [title, description, updateHead]);
  
  // This component doesn't render anything
  return null;
};

export default PageHead;