import { useState, useEffect } from 'preact/hooks';

export interface MoodleGPTConfig {
  apiKey?: string;
  code?: string;
  model?: string;
  baseURL?: string;
  maxTokens?: number;
  projectId?: string;
  timeoutValue?: number;
  logs?: boolean;
  title?: boolean;
  cursor?: boolean;
  typing?: boolean;
  mouseover?: boolean;
  infinite?: boolean;
  timeout?: boolean;
  history?: boolean;
  includeImages?: boolean;
  mode?: 'autocomplete' | 'clipboard';
}

export function useConfig() {
  const [config, setConfig] = useState<MoodleGPTConfig>({
    mode: 'autocomplete',
    title: true,
    cursor: true,
    timeout: true
  });
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    chrome.storage.sync.get(['moodleGPT']).then(storage => {
      if (storage.moodleGPT) {
        setConfig(prev => ({ ...prev, ...storage.moodleGPT }));
      }
      setLoading(false);
    });
  }, []);

  const saveConfig = async (newConfig: MoodleGPTConfig) => {
    const updated = { ...config, ...newConfig };
    setConfig(updated);
    await chrome.storage.sync.set({ moodleGPT: updated });
  };

  return { config, loading, saveConfig, setConfig };
}
