{ config, pkgs, inputs, lib, ... }:

# Stylix Integration Module
#
# This module handles base-level theming through Stylix:
# - Color scheme injection from the active theme's palette
# - Cursor configuration
# - Font configuration
# - GTK/GNOME theming
#
# App-specific theming is handled separately:
# - theme-loader.nix: Deploys theme's apps/ configs (btop, neovim, etc.)
# - waybar.nix: Generates waybar CSS from colorScheme
# - hyprland.nix: Handles hyprland border colors
#
# Stylix targets disabled here (we have custom implementations):
# - hyprland: Custom border/rule config
# - waybar: Custom CSS with theme colors

let
  nomarchyLib = import ../../lib { inherit lib; };
  assetsPath = ../palettes;

  activeThemeName = config.nomarchy.theme;

  # Use shared wallpaper resolver
  activeWallpaper = nomarchyLib.resolveWallpaper {
    wallpaperPath = config.nomarchy.wallpaper;
    themeName = activeThemeName;
    inherit assetsPath;
  };

  # Get palette using shared library
  currentPalette = nomarchyLib.getPalette activeThemeName;
in
{
  imports = [ inputs.stylix.homeModules.stylix ];

  xdg.configFile."nomarchy/current/background".source = activeWallpaper;

  stylix = {
    enable = lib.mkDefault true;
    enableReleaseChecks = lib.mkDefault false;
    autoEnable = lib.mkDefault false;  # Disable auto-detection, explicitly enable targets
    image = lib.mkDefault activeWallpaper;
    base16Scheme = lib.mkDefault currentPalette;

    # Use detected light mode state
    polarity = lib.mkDefault (if config.nomarchy.isLightMode then "light" else "dark");

    cursor = lib.mkDefault {
      package = config.nomarchy.cursor.package;
      name = config.nomarchy.cursor.name;
      size = 24;
    };

    fonts = lib.mkDefault {
      monospace = {
        package = pkgs.nerd-fonts.jetbrains-mono;
        name = config.nomarchy.fonts.monospace;
      };
      sansSerif = {
        package = pkgs.dejavu_fonts;
        name = "DejaVu Sans";
      };
      serif = {
        package = pkgs.dejavu_fonts;
        name = "DejaVu Serif";
      };
      emoji = {
        package = pkgs.noto-fonts-color-emoji;
        name = "Noto Color Emoji";
      };
      sizes = {
        applications = 11;
        terminal = 11;
        desktop = 11;
        popups = 11;
      };
    };

    # Enable theming for specific targets
    targets = lib.mkDefault {
      hyprland.enable = false; # We keep our custom hyprland config for borders/rules
      waybar.enable = false;   # We keep our custom waybar CSS
      neovim.enable = false;   # We deploy theme lua files via theme-loader instead
      neovide.enable = false;  # Neovide depends on neovim program module
      alacritty.enable = true;
      kitty.enable = true;
      gtk.enable = true;
      gnome.enable = true;
    };
  };

  # GTK Icon Theme configuration
  gtk = {
    enable = lib.mkDefault true;
    iconTheme = lib.mkDefault {
      package = pkgs.yaru-theme;
      name = config.nomarchy.iconsTheme;
    };
  };
}
