import { createContext, useContext, useEffect, useState, type ReactNode } from 'react';
import { fetchSiteContent, type SiteData } from '../api/client';
import { SITE, SERVICES, FAQ_CATEGORIES, EVENTS, STORIES, CAREER_ROLES } from '../data/content';

const defaultContent: SiteData = {
  site: SITE,
  services: SERVICES,
  faqCategories: FAQ_CATEGORIES,
  events: EVENTS,
  stories: STORIES,
  careerRoles: CAREER_ROLES,
  fromDb: false,
};

interface ContentContextType extends SiteData {
  reloadContent: () => Promise<void>;
  loading: boolean;
}

const ContentContext = createContext<ContentContextType>({
  ...defaultContent,
  reloadContent: async () => {},
  loading: false,
});

export function ContentProvider({ children }: { children: ReactNode }) {
  const [content, setContent] = useState<SiteData>(defaultContent);
  const [loading, setLoading] = useState(false);

  function applyDatabaseTheme(site: any) {
    if (typeof document === 'undefined' || !site) return;
    if (site.theme) document.documentElement.setAttribute('data-theme', site.theme);
    if (site.fontSize) document.documentElement.setAttribute('data-font-size', site.fontSize);
    document.documentElement.setAttribute('data-high-contrast', site.highContrast ? 'true' : 'false');
    document.documentElement.setAttribute('data-dyslexic', site.dyslexicFont ? 'true' : 'false');
  }

  async function loadData() {
    setLoading(true);
    try {
      const data = await fetchSiteContent();
      setContent(data);
      if (data.site) {
        applyDatabaseTheme(data.site);
      }
    } catch (err) {
      console.info('Using static content fallback.');
      applyDatabaseTheme(SITE);
    } finally {
      setLoading(false);
    }
  }

  async function reloadContent() {
    await loadData();
    if (typeof window !== 'undefined') {
      window.dispatchEvent(new Event('embrace_content_updated'));
      try {
        const channel = new BroadcastChannel('embrace_cms_sync');
        channel.postMessage('content_updated');
        channel.close();
      } catch (e) {
        // BroadcastChannel fallback
      }
    }
  }

  useEffect(() => {
    loadData();

    if (typeof window !== 'undefined') {
      const handleLocalUpdate = () => {
        loadData();
      };
      window.addEventListener('embrace_content_updated', handleLocalUpdate);
      window.addEventListener('focus', handleLocalUpdate);

      let channel: BroadcastChannel | null = null;
      try {
        channel = new BroadcastChannel('embrace_cms_sync');
        channel.onmessage = () => {
          loadData();
        };
      } catch (e) {
        // BroadcastChannel unsupported
      }

      return () => {
        window.removeEventListener('embrace_content_updated', handleLocalUpdate);
        window.removeEventListener('focus', handleLocalUpdate);
        if (channel) channel.close();
      };
    }
  }, []);

  return (
    <ContentContext.Provider value={{ ...content, reloadContent, loading }}>
      {children}
    </ContentContext.Provider>
  );
}

export function useSiteContent() {
  return useContext(ContentContext);
}
