import { useEffect } from 'react';
import { invoke } from '@tauri-apps/api/core';
import { useAppStore, applyTypographyVars, DEFAULT_FONT_FAMILY, DEFAULT_TEXT_COLOR, DEFAULT_FONT_SIZE_INDEX_REAL } from './store/appStore';
import AppShell from './components/layout/AppShell';
import ConfigScreen from './components/config/ConfigScreen';

export default function App() {
  const {
    isConfigured, setIsConfigured, setUoRoot, setServuoScripts, setCenterMode,
    setFontFamily, setFontSizeIndex, setTextColor,
  } = useAppStore();

  useEffect(() => {
    async function loadConfig() {
      try {
        const uo = await invoke<string | null>('get_config', { key: 'uo_root' });
        const scripts = await invoke<string | null>('get_config', { key: 'seruo_scripts' });

        // Load typography settings (non-fatal — fall back to defaults)
        const fontFamily = await invoke<string | null>('get_config', { key: 'font_family' }).catch(() => null);
        const fontSizeIdx = await invoke<string | null>('get_config', { key: 'font_size_index' }).catch(() => null);
        const textColor = await invoke<string | null>('get_config', { key: 'text_color' }).catch(() => null);

        const resolvedFamily = fontFamily ?? DEFAULT_FONT_FAMILY;
        const resolvedIdx = fontSizeIdx != null ? parseInt(fontSizeIdx, 10) : DEFAULT_FONT_SIZE_INDEX_REAL;
        const resolvedColor = textColor ?? DEFAULT_TEXT_COLOR;

        setFontFamily(resolvedFamily);
        setFontSizeIndex(isNaN(resolvedIdx) ? DEFAULT_FONT_SIZE_INDEX_REAL : resolvedIdx);
        setTextColor(resolvedColor);
        applyTypographyVars(resolvedFamily, isNaN(resolvedIdx) ? DEFAULT_FONT_SIZE_INDEX_REAL : resolvedIdx, resolvedColor);

        if (uo && scripts) {
          setUoRoot(uo);
          setServuoScripts(scripts);
          setIsConfigured(true);
        } else {
          setCenterMode('config');
        }
      } catch (e) {
        console.error('Failed to load config:', e);
        setCenterMode('config');
      }
    }
    loadConfig();
  }, []);

  if (!isConfigured) {
    return <ConfigScreen />;
  }

  return <AppShell />;
}
