// ── Deploy to Demo — ask for the demo host's details ─────────────
// Credentials are used for this upload only; nothing is stored. For a server
// you use often, save a connection in the Deploy module instead.
async function askDemoCredentials() {
    const esc = (s) => String(s ?? '').replace(/"/g, '&quot;');
    const saved = (() => {
        try { return JSON.parse(sessionStorage.getItem('pp_demo_' + projectSlug) || '{}'); }
        catch (e) { return {}; }
    })();

    const { value: form } = await Swal.fire({
        title: 'Publish to your demo server',
        width: 560,
        html: `
            <div class="text-start small demo-form">
                <p class="text-muted mb-3">Enter the details of the server you want to publish this demo to.
                   These are used for this upload only and are not saved.</p>
                <div class="row g-2">
                    <div class="col-8">
                        <label class="form-label fw-semibold mb-1">Host</label>
                        <input id="dmHost" class="form-control form-control-sm" placeholder="demo.example.com" value="${esc(saved.host)}">
                    </div>
                    <div class="col-4">
                        <label class="form-label fw-semibold mb-1">Type</label>
                        <select id="dmProtocol" class="form-select form-select-sm">
                            <option value="ftp">FTP</option>
                            <option value="ftps">FTPS</option>
                            <option value="sftp">SFTP</option>
                        </select>
                    </div>
                    <div class="col-6">
                        <label class="form-label fw-semibold mb-1">Username</label>
                        <input id="dmUser" class="form-control form-control-sm" placeholder="username" value="${esc(saved.user)}">
                    </div>
                    <div class="col-6">
                        <label class="form-label fw-semibold mb-1">Password</label>
                        <input id="dmPass" type="password" class="form-control form-control-sm" placeholder="password">
                    </div>
                    <div class="col-8">
                        <label class="form-label fw-semibold mb-1">Folder on the server</label>
                        <input id="dmPath" class="form-control form-control-sm" placeholder="/public_html/demo" value="${esc(saved.path)}">
                    </div>
                    <div class="col-4">
                        <label class="form-label fw-semibold mb-1">Port</label>
                        <input id="dmPort" type="number" class="form-control form-control-sm" placeholder="21" value="${esc(saved.port)}">
                    </div>
                </div>
            </div>`,
        didOpen: () => {
            if (saved.protocol) document.getElementById('dmProtocol').value = saved.protocol;
        },
        showCancelButton: true,
        confirmButtonText: 'Publish demo',
        cancelButtonText: 'Cancel',
        reverseButtons: true,
        focusConfirm: false,
        preConfirm: () => {
            const v = (id) => (document.getElementById(id).value || '').trim();
            const data = {
                host: v('dmHost'), protocol: v('dmProtocol'), user: v('dmUser'),
                pass: document.getElementById('dmPass').value || '',
                path: v('dmPath'), port: v('dmPort'),
            };
            if (!data.host) { Swal.showValidationMessage('Please enter the demo server host.'); return false; }
            if (!data.user) { Swal.showValidationMessage('Please enter the username.'); return false; }
            return data;
        },
    });

    if (!form) return;

    // Remember everything except the password, to save re-typing this session.
    try {
        sessionStorage.setItem('pp_demo_' + projectSlug, JSON.stringify({
            host: form.host, protocol: form.protocol, user: form.user, path: form.path, port: form.port,
        }));
    } catch (e) { /* non-critical */ }

    runAction('deploy-demo', form);
}

// ── Initialisation ──────────────────────────────────────────────
document.addEventListener('DOMContentLoaded', () => {

    // Hydrate state from PHP-passed JSON
    lastBuild = finishedState?.lastBuild || null;
    buildHistory = finishedState?.history || [];

    renderHistory(buildHistory);
    renderStats(lastBuild);
    renderStatusBanner(lastBuild, buildHistory);

    // ── Tooltips on every action card ───────────────────────────
    if (window.bootstrap && bootstrap.Tooltip) {
        document.querySelectorAll('.finished-content [data-bs-toggle="tooltip"]').forEach((el) => {
            bootstrap.Tooltip.getOrCreateInstance(el, { delay: { show: 400, hide: 0 }, trigger: 'hover' });
        });
    }

    // ── Action card clicks ──────────────────────────────────────
    document.querySelectorAll('.action-card').forEach(card => {
        card.addEventListener('click', () => {
            const action = card.dataset.action;
            if (!action) return;

            // Preview: open the tab NOW (inside the click) so the browser doesn't
            // treat it as a popup, then point it at the URL once we have it.
            if (action === 'preview') {
                const win = window.open('', '_blank');
                runAction('preview', null, win);
                return;
            }

            if (action === 'deploy-demo') {
                askDemoCredentials();
                return;
            }

            if (action === 'reset-dashboard') {
                const go = () => runAction('reset-dashboard');
                if (window.Swal) {
                    Swal.fire({
                        title: 'Reset dashboard to factory default?',
                        text: 'Restores the shipped dashboard design (your current design is backed up first), then rebuilds the app.',
                        icon: 'warning', showCancelButton: true,
                        confirmButtonText: 'Reset & rebuild', confirmButtonColor: '#dc2626'
                    }).then((r) => { if (r.isConfirmed) go(); });
                } else if (confirm('Reset the dashboard to factory default and rebuild? Your current design is backed up first.')) {
                    go();
                }
                return;
            }

            runAction(action);
        });
    });

    // ── Refresh status button ───────────────────────────────────
    $('btnRefreshStatus')?.addEventListener('click', () => {
        renderHistory(buildHistory);
        renderStats(lastBuild);
        renderStatusBanner(lastBuild, buildHistory);
        showToast('Status refreshed.', 'info');
    });

    // ── Clear history ───────────────────────────────────────────
    $('btnClearHistory')?.addEventListener('click', async () => {
        const result = await Swal.fire({
            title: 'Clear build history?',
            text: 'This cannot be undone.',
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Clear',
            confirmButtonColor: '#dc3545',
        });
        if (!result.isConfirmed) return;

        buildHistory = [];
        lastBuild = null;
        renderHistory(buildHistory);
        renderStats(lastBuild);
        renderStatusBanner(lastBuild, buildHistory);
        await saveFinishedState({ lastBuild: null, history: [] }, true);
        showToast('Build history cleared.', 'info');
    });

    // ── Check if there are build stats to show on load ──────────
    if (lastBuild) {
        showToast('Last build: ' + new Date(lastBuild.time).toLocaleString(), 'info');
    }
});
