/** 
 * offline_queue.js
 * Unified offline queue for AtulyaSolar PWA
 * Handles POST/PUT requests when offline and syncs them when online/SW sync event triggers.
 */

window.OfflineQueue = (function () {

    const STORAGE_KEY = 'asolar_offline_queue_v1';

    function loadQueue() {
        try {
            const raw = localStorage.getItem(STORAGE_KEY);
            return raw ? JSON.parse(raw) : [];
        } catch (e) {
            console.warn("Queue load failed", e);
            return [];
        }
    }

    function saveQueue(q) {
        localStorage.setItem(STORAGE_KEY, JSON.stringify(q));
    }

    function enqueue(api, payload, method = 'POST') {
        const q = loadQueue();
        const entry = {
            id: Date.now(),
            api,
            payload,
            method,
            added_at: new Date().toISOString(),
            status: 'pending'
        };
        q.push(entry);
        saveQueue(q);
        console.log("[OfflineQueue] Added:", entry);
        showToast("Saved offline. Will sync when online.");
        return entry;
    }

    async function trySync() {
        if (!navigator.onLine) return;

        const q = loadQueue();
        if (!q.length) return;

        console.log("[OfflineQueue] Sync start. Items:", q.length);

        const remaining = [];

        for (const item of q) {
            try {
                const res = await fetch(item.api, {
                    method: item.method,
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(item.payload)
                });

                if (!res.ok) {
                    console.warn("[OfflineQueue] Sync failed", item);
                    remaining.push(item);
                    continue;
                }

                const data = await res.json();
                console.log("[OfflineQueue] Synced:", data);

            } catch (e) {
                console.warn("[OfflineQueue] Error syncing", item, e);
                remaining.push(item);
            }
        }

        saveQueue(remaining);
        if (remaining.length === 0) {
            showToast("All offline data synced successfully.");
        }
    }

    // UI toast utility
    function showToast(msg) {
        let t = document.createElement("div");
        t.className = "as-toast";
        t.textContent = msg;
        Object.assign(t.style, {
            position: 'fixed',
            bottom: '70px',
            left: '50%',
            transform: 'translateX(-50%)',
            background: '#0b6b4f',
            padding: '10px 20px',
            color: '#fff',
            borderRadius: '6px',
            zIndex: 99999,
            fontSize: '14px',
            boxShadow: '0 4px 10px rgba(0,0,0,0.15)',
            opacity: 1,
            transition: 'opacity .7s',
        });
        document.body.appendChild(t);
        setTimeout(() => t.style.opacity = 0, 2500);
        setTimeout(() => t.remove(), 3300);
    }

    // Listen for online event
    window.addEventListener('online', trySync);

    return {
        enqueue,
        trySync
    };

})();
