// M5: Theme selector + model save/load wired.
using System.Windows;
using System.Windows.Controls;
using DansoriEQ.Core.Ai;
using DansoriEQ.Core.Security;
using Wpf.Ui.Appearance;

namespace DansoriEQ.App;

public partial class SettingsWindow : Wpf.Ui.Controls.FluentWindow
{
    private readonly ISecretStore _store;

    public SettingsWindow(ISecretStore store)
    {
        InitializeComponent();
        _store = store;
        RowClaude.Initialize(store, ProviderKeys.Claude,  "Claude API",            "https://console.anthropic.com/settings/keys");
        RowOpenAi.Initialize(store, ProviderKeys.OpenAi,  "ChatGPT (OpenAI) API",  "https://platform.openai.com/api-keys");
        RowGemini.Initialize(store, ProviderKeys.Gemini,  "Gemini API",            "https://aistudio.google.com/app/apikey");

        var s = AppSettings.Load();

        // Restore model selection
        if (s.AiModel?.Contains("opus") == true) CmbModel.SelectedIndex = 1;
        else CmbModel.SelectedIndex = 0;

        // Restore theme selection
        CmbTheme.SelectedIndex = s.Theme switch { "light" => 1, "system" => 2, _ => 0 };
    }

    private void CmbModel_SelectionChanged(object sender, SelectionChangedEventArgs e) => SaveModel();

    private void SaveModel()
    {
        var s = AppSettings.Load();
        s.AiModel = CmbModel.SelectedIndex == 1 ? "claude-opus-4-8" : "claude-sonnet-4-6";
        s.Save();
    }

    private void CmbTheme_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var s = AppSettings.Load();
        s.Theme = CmbTheme.SelectedIndex switch { 1 => "light", 2 => "system", _ => "dark" };
        s.Save();

        var theme = s.Theme switch { "light" => ApplicationTheme.Light, _ => ApplicationTheme.Dark };
        ApplicationThemeManager.Apply(theme);
    }

    private void BtnAiManager_Click(object sender, RoutedEventArgs e)
        => new AiManagerWindow(_store) { Owner = this }.ShowDialog();

    private void BtnSwitchRules_Click(object sender, RoutedEventArgs e)
        => new SwitchRulesWindow { Owner = this }.ShowDialog();

    private void BtnClose_Click(object sender, RoutedEventArgs e) => Close();
}
