/* Hostiva v6 — API client + helpers */
(function () {
    'use strict';
    const API_BASE = '../api/?r=';
    let csrfToken = null;

    async function getCsrf() {
        if (csrfToken) return csrfToken;
        try {
            const r = await fetch(API_BASE + 'csrf', { credentials: 'same-origin' });
            const j = await r.json();
            csrfToken = j.data && j.data.token;
        } catch {}
        return csrfToken;
    }

    async function api(route, params, method) {
        method = method || (params ? 'POST' : 'GET');
        let url = API_BASE + route;
        const opts = { method, credentials: 'same-origin', headers: {} };
        if (method === 'GET' && params) {
            const qs = new URLSearchParams(params).toString();
            url += '&' + qs;
        } else if (method !== 'GET') {
            const t = await getCsrf();
            opts.headers['Content-Type'] = 'application/json';
            opts.headers['X-CSRF-Token'] = t || '';
            opts.body = JSON.stringify(params || {});
        }
        const r = await fetch(url, opts);
        let j;
        try { j = await r.json(); } catch { j = { success: false, message: 'Invalid response' }; }
        if (!j.success && r.status === 401) {
            window.location.href = 'login.html'; return j;
        }
        if (!j.success && r.status === 403) toast('Permission denied', 'error');
        if (!j.success && r.status === 422) toast(j.message || 'Validation failed', 'error');
        if (!j.success && r.status >= 500) toast('Server error', 'error');
        return j;
    }

    function toast(msg, type) {
        type = type || 'info';
        const c = document.getElementById('toastContainer') || (() => {
            const d = document.createElement('div'); d.id = 'toastContainer'; d.className = 'toast-container';
            document.body.appendChild(d); return d;
        })();
        const t = document.createElement('div');
        t.className = 'toast ' + type;
        t.textContent = msg;
        c.appendChild(t);
        setTimeout(() => { t.style.opacity = '0'; t.style.transform = 'translateX(20px)'; }, 3500);
        setTimeout(() => t.remove(), 3800);
    }

    function modal(title, bodyHtml, footerHtml) {
        const m = document.createElement('div');
        m.className = 'modal-backdrop';
        m.innerHTML = `<div class="modal">
            <div class="modal-header"><h3>${title}</h3><button class="modal-close" onclick="this.closest('.modal-backdrop').remove()">×</button></div>
            <div class="modal-body">${bodyHtml}</div>
            ${footerHtml ? `<div class="modal-footer">${footerHtml}</div>` : ''}
        </div>`;
        m.addEventListener('click', (e) => { if (e.target === m) m.remove(); });
        document.body.appendChild(m);
        return m;
    }

    function fmtMoney(n, currency) {
        currency = currency || 'USD';
        return (Number(n) || 0).toLocaleString(undefined, { style: 'currency', currency, maximumFractionDigits: 0 });
    }
    function fmtDate(d) {
        if (!d) return '';
        return new Date(d).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' });
    }

    window.Hostiva = window.Hostiva || {};
    Object.assign(window.Hostiva, { api, toast, modal, fmtMoney, fmtDate, getCsrf });
})();
