using System.Windows;
using System.Windows.Media;
using Microsoft.Win32;
using AxCopilot.Models;

namespace AxCopilot.Views;

public partial class LauncherWindow
{
    // ─── 테마 ────────────────────────────────────────────────────────────────

    // 지원 테마 이름 목록
    private static readonly HashSet<string> KnownThemes =
        new(StringComparer.OrdinalIgnoreCase)
        { "Dark", "Light", "OLED", "Nord", "Monokai", "Catppuccin", "Sepia", "Alfred", "AlfredLight", "Codex" };

    internal void ApplyTheme() =>
        ApplyTheme(_vm.ThemeSetting, _vm.CustomThemeColors);

    /// <summary>
    /// 테마를 즉시 교체합니다. 설정 창 미리보기에서도 호출됩니다.
    /// </summary>
    internal void ApplyTheme(string? themeKey, AxCopilot.Models.CustomThemeColors? customColors)
    {
        var appDicts = System.Windows.Application.Current.Resources.MergedDictionaries;
        // 기존 테마 딕셔너리 제거 (Source 기반 또는 커스텀 빌드)
        var existing = appDicts.FirstOrDefault(d =>
            d.Source?.ToString().Contains("/Themes/") == true || d.Contains("LauncherBackground"));
        if (existing != null)
            appDicts.Remove(existing);

        var setting = (themeKey ?? "system").ToLowerInvariant();

        if (setting == "custom" && customColors != null)
        {
            appDicts.Add(BuildCustomDictionary(customColors));
            UpdateSelectionGlow(); // 커스텀 테마도 AccentColor 적용
            return;
        }

        var themeName = GetEffectiveThemeName(setting);
        appDicts.Add(new ResourceDictionary
        {
            Source = new Uri($"pack://application:,,,/Themes/{themeName}.xaml")
        });
        UpdateSelectionGlow(); // 테마 변경 시 AccentColor 기반으로 글로우 색 갱신
    }

    private static string GetEffectiveThemeName(string setting) => setting switch
    {
        "dark"        => "Dark",
        "light"       => "Light",
        "oled"        => "OLED",
        "nord"        => "Nord",
        "monokai"     => "Monokai",
        "catppuccin"  => "Catppuccin",
        "sepia"       => "Sepia",
        "alfred"      => "Alfred",
        "alfredlight" => "AlfredLight",
        "codex"       => "Codex",
        _ => IsSystemDarkMode() ? "Dark" : "Light"  // "system" 또는 미지원 값
    };

    private static ResourceDictionary BuildCustomDictionary(CustomThemeColors c)
    {
        SolidColorBrush Brush(string hex)
        {
            var color = (Color)ColorConverter.ConvertFromString(hex);
            return new SolidColorBrush(color);
        }

        return new ResourceDictionary
        {
            { "LauncherBackground",     Brush(c.LauncherBackground) },
            { "ItemBackground",         Brush(c.ItemBackground) },
            { "ItemSelectedBackground",      Brush(c.ItemSelectedBackground) },
            { "ItemSelectedHoverBackground", LightenBrush(Brush(c.ItemSelectedBackground), 0.15) },
            { "ItemHoverBackground",         Brush(c.ItemHoverBackground) },
            { "PrimaryText",            Brush(c.PrimaryText) },
            { "SecondaryText",          Brush(c.SecondaryText) },
            { "PlaceholderText",        Brush(c.PlaceholderText) },
            { "AccentColor",            Brush(c.AccentColor) },
            { "SeparatorColor",         Brush(c.SeparatorColor) },
            { "HintBackground",         Brush(c.HintBackground) },
            { "HintText",               Brush(c.HintText) },
            { "BorderColor",            Brush(c.BorderColor) },
            { "ScrollbarThumb",         Brush(c.ScrollbarThumb) },
            { "ShadowColor",            (Color)ColorConverter.ConvertFromString(c.ShadowColor) },
            // 커스텀 테마: 사용자가 설정한 라운딩 적용
            { "WindowCornerRadius",     new CornerRadius(Math.Clamp(c.WindowCornerRadius, 0, 30)) },
            { "ItemCornerRadius",       new CornerRadius(Math.Clamp(c.ItemCornerRadius, 0, 20)) },
        };
    }

    /// <summary>SolidColorBrush를 지정 비율만큼 밝게 합니다.</summary>
    private static SolidColorBrush LightenBrush(SolidColorBrush brush, double amount)
    {
        var c = brush.Color;
        byte Clamp(int v) => (byte)Math.Min(255, Math.Max(0, v));
        return new SolidColorBrush(Color.FromRgb(
            Clamp(c.R + (int)(255 * amount)),
            Clamp(c.G + (int)(255 * amount)),
            Clamp(c.B + (int)(255 * amount))));
    }

    private static bool IsSystemDarkMode()
    {
        try
        {
            using var key = Registry.CurrentUser.OpenSubKey(
                @"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize");
            return key?.GetValue("AppsUseLightTheme") is int v && v == 0;
        }
        catch (Exception) { return true; }
    }
}
