//go:build !darwin

package main

import (
	"context"
	"log"
	"runtime"

	dark "github.com/thiagokokada/dark-mode-go"
)

type iconThemeWatcher struct {
	cancel context.CancelFunc
}

func defaultIconMode() string {
	if runtime.GOOS == "windows" {
		return "mono"
	}
	return "color"
}

var (
	systemDark   bool
	themeWatcher *iconThemeWatcher
)

func setSystemDarkMode(dark bool) bool {
	iconMu.Lock()
	changed := systemDark != dark
	systemDark = dark
	iconMu.Unlock()
	return changed
}

func startIconThemeWatcher() {
	iconMu.Lock()
	if themeWatcher != nil {
		iconMu.Unlock()
		return
	}
	ctx, cancel := context.WithCancel(context.Background())
	watcher := &iconThemeWatcher{cancel: cancel}
	themeWatcher = watcher
	iconMu.Unlock()

	if isDark, err := dark.IsDarkMode(); err == nil {
		setSystemDarkMode(isDark)
	} else {
		log.Printf("icon theme detection failed: %v", err)
	}

	events, errs, err := dark.WatchDarkMode(ctx)
	if err != nil {
		log.Printf("icon theme watcher failed: %v", err)
		cancel()
		clearIconThemeWatcher(watcher)
		return
	}

	go func() {
		defer clearIconThemeWatcher(watcher)
		for events != nil || errs != nil {
			select {
			case isDark, ok := <-events:
				if !ok {
					events = nil
					continue
				}
				if setSystemDarkMode(isDark) && currentIconMode() == "mono" {
					initAlertIcon()
					refreshIcon()
				}
			case err, ok := <-errs:
				if !ok {
					errs = nil
					continue
				}
				if err != nil {
					log.Printf("icon theme watcher: %v", err)
				}
			}
		}
	}()
}

func stopIconThemeWatcher() {
	iconMu.Lock()
	watcher := themeWatcher
	if watcher == nil {
		iconMu.Unlock()
		return
	}
	themeWatcher = nil
	iconMu.Unlock()
	watcher.cancel()
}

func clearIconThemeWatcher(watcher *iconThemeWatcher) {
	iconMu.Lock()
	if themeWatcher == watcher {
		themeWatcher = nil
	}
	iconMu.Unlock()
}

func platformIconVariant(mode string) iconVariant {
	if mode != "mono" {
		return iconVariant{name: mode}
	}

	iconMu.RLock()
	dark := systemDark
	iconMu.RUnlock()
	if dark {
		return iconVariant{name: "white"}
	}
	return iconVariant{name: "black"}
}
