'use client';

import { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react';
import { fetchPublicSettingsClient, getDefaultProjectName, getDefaultProjectTagline } from '@/lib/api';
import { mergePublicSettings, readCachedPublicSettings, writeCachedPublicSettings } from '@/lib/public-settings-cache';

interface PublicSettingsContextValue {
  projectName: string;
  projectTagline: string;
  isLoading: boolean;
  refreshPublicSettings: () => Promise<void>;
}

const PublicSettingsContext = createContext<PublicSettingsContextValue>({
  projectName: getDefaultProjectName(),
  projectTagline: getDefaultProjectTagline(),
  isLoading: true,
  refreshPublicSettings: async () => undefined
});

export function PublicSettingsProvider({
  children,
  initialSettings
}: {
  children: React.ReactNode;
  initialSettings: Record<string, string>;
}) {
  const [settings, setSettings] = useState<Record<string, string>>(() =>
    mergePublicSettings(readCachedPublicSettings(), initialSettings)
  );
  const [isLoading, setIsLoading] = useState(true);

  const refreshPublicSettings = useCallback(async () => {
    try {
      const next = await fetchPublicSettingsClient();
      setSettings((current) => mergePublicSettings(current, next));
      writeCachedPublicSettings(next);
    } catch {
      // Оставляем последние известные значения (кэш или SSR).
    } finally {
      setIsLoading(false);
    }
  }, []);

  useEffect(() => {
    const cached = readCachedPublicSettings();
    if (Object.keys(cached).length > 0) {
      setSettings((current) => mergePublicSettings(cached, initialSettings, current));
    }
  }, [initialSettings]);

  useEffect(() => {
    void refreshPublicSettings();
    const onFocus = () => void refreshPublicSettings();
    window.addEventListener('focus', onFocus);
    return () => window.removeEventListener('focus', onFocus);
  }, [refreshPublicSettings]);

  useEffect(() => {
    if (settings.PROJECT_NAME) {
      document.title = `Документация — ${settings.PROJECT_NAME}`;
    }
  }, [settings.PROJECT_NAME]);

  const value = useMemo(
    () => ({
      projectName: settings.PROJECT_NAME || getDefaultProjectName(),
      projectTagline: settings.PROJECT_TAGLINE || getDefaultProjectTagline(),
      isLoading,
      refreshPublicSettings
    }),
    [isLoading, refreshPublicSettings, settings.PROJECT_NAME, settings.PROJECT_TAGLINE]
  );

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

export function usePublicSettings() {
  return useContext(PublicSettingsContext);
}
