/**
 * Thinkrax Central — front-end helpers.
 *
 * Livewire ships Alpine, so nothing is imported here. The panel is
 * server-rendered; all this file does is remember the theme, print invoices
 * without navigating away, and surface toasts.
 */

/* ------------------------------------------------------------------ theme */

const THEME_KEY = 'thinkrax.theme';

function applyTheme(mode) {
    const root = document.documentElement;
    const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
    const dark = mode === 'dark' || (mode === 'system' && prefersDark);

    root.classList.toggle('dark', dark);
}

function initTheme() {
    const configured = document.documentElement.dataset.themeMode || 'system';
    const override = window.sessionStorage.getItem(THEME_KEY);

    applyTheme(override || configured);

    window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
        const current = window.sessionStorage.getItem(THEME_KEY) || document.documentElement.dataset.themeMode;

        if (current === 'system') applyTheme('system');
    });
}

window.thinkraxSetTheme = (mode) => {
    window.sessionStorage.setItem(THEME_KEY, mode);
    applyTheme(mode);
};

/* --------------------------------------------------------------- printing */

/**
 * Print a receipt without navigating away from the till.
 *
 * A hidden iframe is used instead of window.open() because pop-up blockers
 * silently kill the second variant, and a cashier never sees the error.
 */
window.thinkraxPrint = (url) => {
    const existing = document.getElementById('thinkrax-print-frame');

    if (existing) existing.remove();

    const frame = document.createElement('iframe');
    frame.id = 'thinkrax-print-frame';
    frame.style.cssText = 'position:fixed;right:0;bottom:0;width:0;height:0;border:0;';
    frame.src = url;

    frame.onload = () => {
        try {
            frame.contentWindow.focus();
            frame.contentWindow.print();
        } catch (error) {
            window.open(url, '_blank');
        }
    };

    document.body.appendChild(frame);
};


/* ------------------------------------------------------------------- boot */

/*
 * Toasts need no wiring here: Livewire mirrors `$this->dispatch('toast', …)`
 * onto the browser window, and the Alpine host component listens for it.
 */
initTheme();
