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

    applyConfig(outputConfig);
    loadBuildInfo();
    initOutputTooltips();

    // ── Live change listeners → auto-save per section ──────────────
    const wire = (paneId, section) => {
        document.querySelectorAll(`#${paneId} input, #${paneId} select, #${paneId} textarea`).forEach((el) => {
            el.addEventListener('change', () => scheduleAutoSave(section));
            if (el.matches('input[type="text"], input[type="url"], textarea')) {
                el.addEventListener('blur', () => scheduleAutoSave(section));
            }
        });
    };
    wire('generalPane', 'general');
    wire('optimizationPane', 'optimization');
    wire('advancedPane', 'advanced');

    // ── Output-directory live status (re-check on edit) ─────────────
    $('outputDir')?.addEventListener('change', () => setTimeout(loadBuildInfo, 900));

    // ── Environment presets ─────────────────────────────────────────
    document.querySelectorAll('.ob-preset').forEach((btn) => {
        btn.addEventListener('click', () => applyPreset(btn.dataset.env));
    });

    // ── Refresh build info ──────────────────────────────────────────
    $('btnRefreshInfo')?.addEventListener('click', (e) => {
        const ic = e.currentTarget.querySelector('i');
        ic?.classList.add('spin');
        loadBuildInfo().finally(() => setTimeout(() => ic?.classList.remove('spin'), 500));
    });

    // ── Browse directory (suggested paths) ──────────────────────────
    $('btnBrowseDir')?.addEventListener('click', () => {
        Swal.fire({
            title: 'Output Directory',
            html: `
                <div class="text-start small">
                    <p class="mb-2">Enter the path where generated files should be written, or pick a suggestion:</p>
                    <div class="d-grid gap-1">
                        <button class="btn btn-sm btn-outline-secondary text-start suggest-path" data-path="../output">
                            <code>../output</code> — sibling of the app root
                        </button>
                        <button class="btn btn-sm btn-outline-secondary text-start suggest-path" data-path="./dist">
                            <code>./dist</code> — distribution folder
                        </button>
                        <button class="btn btn-sm btn-outline-secondary text-start suggest-path" data-path="/var/www/html/myapp">
                            <code>/var/www/html/myapp</code> — absolute server path
                        </button>
                    </div>
                </div>`,
            showConfirmButton: false,
            showCancelButton: true,
            cancelButtonText: 'Close',
        });
        document.querySelectorAll('.suggest-path').forEach((btn) => {
            btn.addEventListener('click', () => {
                $('outputDir').value = btn.dataset.path;
                Swal.close();
                scheduleAutoSave('general');
                setTimeout(loadBuildInfo, 900);
            });
        });
    });

    // ── Permission presets ──────────────────────────────────────────
    document.querySelectorAll('.preset-permission').forEach((item) => {
        item.addEventListener('click', (e) => {
            e.preventDefault();
            $('filePermissions').value = item.dataset.value;
            scheduleAutoSave('advanced');
        });
    });
});

// ── Bootstrap tooltips for every control ────────────────────────────
function initOutputTooltips() {
    if (!window.bootstrap || !bootstrap.Tooltip) return;
    document.querySelectorAll('[data-bs-toggle="tooltip"]').forEach((el) => {
        if (!bootstrap.Tooltip.getInstance(el)) {
            new bootstrap.Tooltip(el, {
                customClass: 'ob-tip',
                delay: { show: 300, hide: 0 },
                trigger: 'hover',
                container: 'body',
            });
        }
    });
}
