import { browser } from "$app/environment";

const THEME_STORAGE_KEY = "kuldvillak-theme";
const THEME_CHANNEL_NAME = "kuldvillak-theme-sync";

// BroadcastChannel for syncing theme across windows
let channel: BroadcastChannel | null = null;
if (browser) {
    channel = new BroadcastChannel(THEME_CHANNEL_NAME);
}

// Default theme colors
export const DEFAULT_THEME = {
    primary: "#003B9B",
    secondary: "#FFAB00",
    text: "#FFFFFF",
    background: "#000000",
};

// Load initial values from localStorage
function getInitialTheme() {
    if (browser) {
        const saved = localStorage.getItem(THEME_STORAGE_KEY);
        if (saved) {
            try {
                const theme = JSON.parse(saved);
                return {
                    primary: theme.primary ?? DEFAULT_THEME.primary,
                    secondary: theme.secondary ?? DEFAULT_THEME.secondary,
                    text: theme.text ?? DEFAULT_THEME.text,
                    background: theme.background ?? DEFAULT_THEME.background,
                };
            } catch {
                // Ignore parse errors
            }
        }
    }
    return { ...DEFAULT_THEME };
}

const initialTheme = getInitialTheme();

// Current applied values (what's visually shown)
let primary = $state(initialTheme.primary);
let secondary = $state(initialTheme.secondary);
let text = $state(initialTheme.text);
let background = $state(initialTheme.background);

// Saved values (what's persisted to localStorage)
let savedPrimary = $state(initialTheme.primary);
let savedSecondary = $state(initialTheme.secondary);
let savedText = $state(initialTheme.text);
let savedBackground = $state(initialTheme.background);

function applyTheme(broadcast = true) {
    if (browser) {
        document.documentElement.style.setProperty("--kv-blue", primary);
        document.documentElement.style.setProperty("--kv-yellow", secondary);
        document.documentElement.style.setProperty("--kv-text", text);
        document.documentElement.style.setProperty("--kv-background", background);

        // Broadcast to other windows
        if (broadcast && channel) {
            channel.postMessage({ primary, secondary, text, background });
        }
    }
}

// Listen for theme changes from other windows
if (browser && channel) {
    channel.onmessage = (event) => {
        const { primary: p, secondary: s, text: t, background: b } = event.data;
        if (p) primary = p;
        if (s) secondary = s;
        if (t) text = t;
        if (b) background = b;
        applyTheme(false); // Don't re-broadcast
    };
}

// Save current values to localStorage
function save() {
    if (browser) {
        localStorage.setItem(THEME_STORAGE_KEY, JSON.stringify({
            primary,
            secondary,
            text,
            background
        }));
        // Update saved state
        savedPrimary = primary;
        savedSecondary = secondary;
        savedText = text;
        savedBackground = background;
    }
}

// Revert to last saved values (for cancel/close without saving)
function revert() {
    primary = savedPrimary;
    secondary = savedSecondary;
    text = savedText;
    background = savedBackground;
    applyTheme();
}

// Reset to default values (applies immediately for preview)
function resetToDefaults() {
    primary = DEFAULT_THEME.primary;
    secondary = DEFAULT_THEME.secondary;
    text = DEFAULT_THEME.text;
    background = DEFAULT_THEME.background;
    applyTheme();
}

// Reset and save (for full reset)
function reset() {
    resetToDefaults();
    save();
}

export const themeStore = {
    get primary() { return primary; },
    set primary(value: string) { primary = value; applyTheme(); },
    get secondary() { return secondary; },
    set secondary(value: string) { secondary = value; applyTheme(); },
    get text() { return text; },
    set text(value: string) { text = value; applyTheme(); },
    get background() { return background; },
    set background(value: string) { background = value; applyTheme(); },
    applyTheme,
    save,
    revert,
    reset,
    resetToDefaults,
};
