/**
 * سودانا — Universal Pricing Loader v1
 *
 * Auto-applies live prices to any element with data-price-* attributes.
 * Drop into any page with: <script src="/assets/pricing-loader.js" defer></script>
 *
 * Supported attributes:
 *   data-price-plus       → Plus monthly price (SDG)
 *   data-price-pro        → Pro monthly price (SDG)
 *   data-rate             → USD→SDG exchange rate
 *   data-price-doc[=type] → Document price (default: contract)
 *   data-price-image[=size] → Image price (default: 1024x1024)
 *   data-price-video[=duration] → Video price (default: 15s)
 *   data-limit-ai[=plan]  → Daily AI limit (default: free)
 *   data-limit-booking[=plan] → Daily booking limit
 *   data-currency         → Currency suffix (e.g. "SDG", "ج.س")
 *
 * Numbers are formatted with Arabic-SD locale by default.
 *
 * Updates within ~50ms of page load.
 */

(function () {
    'use strict';

    const ENDPOINT = '/api/public/pricing.php';
    const CACHE_KEY = 'sudPricing_v1';
    const CACHE_TTL = 5 * 60 * 1000; // 5 minutes

    function fmt(n, locale) {
        if (n === undefined || n === null) return '—';
        return Number(n).toLocaleString(locale || 'ar-SD');
    }

    function applyPrices(data) {
        if (!data || !data.plans) return;

        const plans = data.plans || {};
        const rate = data.rate || 4100;
        const docs = data.docs || {};
        const images = data.images || [];
        const videos = data.videos || [];

        // ── Plan prices ──────────────────────────────
        document.querySelectorAll('[data-price-plus]').forEach(el => {
            const v = plans.plus?.sdg ?? plans.plus_sdg;
            if (v != null) el.textContent = fmt(v);
        });
        document.querySelectorAll('[data-price-pro]').forEach(el => {
            const v = plans.pro?.sdg ?? plans.pro_sdg;
            if (v != null) el.textContent = fmt(v);
        });

        // ── Exchange rate ────────────────────────────
        document.querySelectorAll('[data-rate]').forEach(el => {
            el.textContent = fmt(rate);
        });

        // ── Document prices ──────────────────────────
        document.querySelectorAll('[data-price-doc]').forEach(el => {
            const type = el.getAttribute('data-price-doc') || 'contract';
            const plan = el.getAttribute('data-plan') || 'free';
            const doc = docs[type];
            if (doc) {
                const key = `price_${plan}_sdg`;
                const v = doc[key] ?? doc.price_free_sdg;
                if (v != null) el.textContent = fmt(v);
            }
        });

        // ── Image prices ─────────────────────────────
        document.querySelectorAll('[data-price-image]').forEach(el => {
            const size = el.getAttribute('data-price-image') || '1024x1024';
            const plan = el.getAttribute('data-plan') || 'free';
            const img = images.find(i => i.size_key === size);
            if (img) {
                const v = img[`price_${plan}_sdg`] ?? img.price_free_sdg;
                if (v != null) el.textContent = fmt(v);
            }
        });

        // ── Video prices ─────────────────────────────
        document.querySelectorAll('[data-price-video]').forEach(el => {
            const dur = el.getAttribute('data-price-video') || '15s';
            const plan = el.getAttribute('data-plan') || 'free';
            const vid = videos.find(v => v.duration_key === dur);
            if (vid) {
                const v = vid[`price_${plan}_sdg`] ?? vid.price_free_sdg;
                if (v != null) el.textContent = fmt(v);
            }
        });

        // ── Daily limits ─────────────────────────────
        document.querySelectorAll('[data-limit-ai]').forEach(el => {
            const plan = el.getAttribute('data-limit-ai') || 'free';
            const v = plans[plan]?.ai_day;
            if (v != null) el.textContent = fmt(v);
        });
        document.querySelectorAll('[data-limit-booking]').forEach(el => {
            const plan = el.getAttribute('data-limit-booking') || 'free';
            const v = plans[plan]?.bookings_day;
            if (v != null) el.textContent = fmt(v);
        });

        // ── Doc credit ───────────────────────────────
        document.querySelectorAll('[data-credit]').forEach(el => {
            const plan = el.getAttribute('data-credit') || 'plus';
            const v = plans[plan]?.doc_credit_sdg;
            if (v != null) el.textContent = fmt(v);
        });

        // Fire event for pages that want to react
        window.dispatchEvent(new CustomEvent('sud:pricing-loaded', { detail: data }));
    }

    function readCache() {
        try {
            const raw = localStorage.getItem(CACHE_KEY);
            if (!raw) return null;
            const obj = JSON.parse(raw);
            if (Date.now() - obj.ts > CACHE_TTL) return null;
            return obj.data;
        } catch (e) { return null; }
    }

    function writeCache(data) {
        try {
            localStorage.setItem(CACHE_KEY, JSON.stringify({ ts: Date.now(), data }));
        } catch (e) { /* quota exceeded — silently ignore */ }
    }

    async function load() {
        // Apply cached version immediately if available (no flicker)
        const cached = readCache();
        if (cached) applyPrices(cached);

        try {
            const r = await fetch(ENDPOINT, { credentials: 'omit' });
            if (!r.ok) return;
            const data = await r.json();
            writeCache(data);
            applyPrices(data);
        } catch (e) {
            // Network failure — keep cached or default values
            console.warn('[pricing-loader] fetch failed', e);
        }
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', load);
    } else {
        load();
    }

    // Expose for manual refresh
    window.SudPricing = { reload: load, getCached: readCache };
})();
