// ── State ─────────────────────────────────────────────────────────────
let currentConfig = {};
let isPageUnloading = false;

// ── DOM ref helper ───────────────────────────────────────────────────
const $ = (id) => document.getElementById(id);

// ── Bind form fields to config object ────────────────────────────────
const bindings = [
    // General
    { id: 'outputDir',         section: 'general', key: 'outputDir' },
    { id: 'previewUrl',        section: 'general', key: 'previewUrl' },
    { id: 'baseUrlSetting',    section: 'general', key: 'baseUrl' },
    { id: 'buildType',         section: 'general', key: 'buildType', isSelect: true },
    { id: 'cleanBeforeBuild',  section: 'general', key: 'cleanBeforeBuild', isCheck: true },

    // Optimization
    { id: 'compressJs',        section: 'optimization', key: 'compressJs', isCheck: true },
    { id: 'compressCss',       section: 'optimization', key: 'compressCss', isCheck: true },
    { id: 'compressHtml',      section: 'optimization', key: 'compressHtml', isCheck: true },
    { id: 'assetVersioning',   section: 'optimization', key: 'assetVersioning', isCheck: true },
    { id: 'minifyInline',      section: 'optimization', key: 'minifyInline', isCheck: true },
    { id: 'htmlDoctype',       section: 'optimization', key: 'htmlDoctype', isSelect: true },
    { id: 'charset',           section: 'optimization', key: 'charset', isSelect: true },

    // Advanced
    { id: 'preBuildHook',      section: 'advanced', key: 'preBuildHook' },
    { id: 'postBuildHook',     section: 'advanced', key: 'postBuildHook' },
    { id: 'filePermissions',   section: 'advanced', key: 'filePermissions' },
    { id: 'lineEndings',       section: 'advanced', key: 'lineEndings', isSelect: true },
    { id: 'errorReporting',    section: 'advanced', key: 'errorReporting', isSelect: true },
    { id: 'debugMode',         section: 'advanced', key: 'debugMode', isCheck: true },
    { id: 'versionLabel',      section: 'advanced', key: 'versionLabel' },
    { id: 'generateHtaccess',  section: 'advanced', key: 'generateHtaccess', isCheck: true },
    { id: 'generateWebConfig', section: 'advanced', key: 'generateWebConfig', isCheck: true },
    { id: 'generateRobotsTxt', section: 'advanced', key: 'generateRobotsTxt', isCheck: true },
    { id: 'standaloneInstaller', section: 'advanced', key: 'standaloneInstaller', isCheck: true },
];

function readConfig() {
    const cfg = { general: {}, optimization: {}, advanced: {} };
    for (const b of bindings) {
        const el = $(b.id);
        if (!el) continue;
        cfg[b.section][b.key] = b.isCheck ? el.checked : el.value;
    }
    return cfg;
}

function applyConfig(cfg) {
    if (!cfg) return;
    for (const b of bindings) {
        const el = $(b.id);
        if (!el) continue;
        const val = cfg[b.section]?.[b.key];
        if (val === undefined) continue;
        if (b.isCheck) el.checked = !!val;
        else el.value = val;
    }
}

// ── Environment presets ──────────────────────────────────────────────
// One-click sensible defaults; the user can still fine-tune every field.
const ENV_PRESETS = {
    development: {
        optimization: { compressJs: false, compressCss: false, compressHtml: false, assetVersioning: false, minifyInline: false },
        advanced:     { errorReporting: 'development', debugMode: true },
    },
    production: {
        optimization: { compressJs: true, compressCss: true, compressHtml: true, assetVersioning: true, minifyInline: true },
        advanced:     { errorReporting: 'production', debugMode: false },
    },
};

function applyPreset(name) {
    const preset = ENV_PRESETS[name];
    if (!preset) return;
    for (const b of bindings) {
        const v = preset[b.section]?.[b.key];
        if (v === undefined) continue;
        const el = $(b.id);
        if (!el) continue;
        if (b.isCheck) el.checked = !!v; else el.value = v;
    }
    document.querySelectorAll('.ob-preset').forEach((btn) => {
        btn.classList.toggle('is-active', btn.dataset.env === name);
    });
    scheduleAutoSave('optimization');
    scheduleAutoSave('advanced');
}

// ── Build information (real data from the server) ─────────────────────
async function loadBuildInfo() {
    try {
        const res = await fetch(`${baseUrl}/project/${projectSlug}/output/info`, {
            headers: { 'Accept': 'application/json' },
        });
        const json = await res.json();
        if (!json || !json.success) return;
        renderBuildInfo(json.info || {});
    } catch (_) { /* silent — info is non-critical */ }
}

function renderBuildInfo(info) {
    const setText = (id, v) => { const el = $(id); if (el) el.textContent = v; };
    const b = info.lastBuild || null;

    setText('lastBuildTime', b && b.time ? relativeTime(b.time) : 'Never');
    setText('filesGenerated', b && b.files ? Number(b.files).toLocaleString() : '—');
    setText('buildDuration', b && b.duration ? (Math.round(b.duration * 100) / 100) + ' s' : '—');
    setText('buildSize', b && b.size ? b.size : (info.dir && info.dir.sizeHuman ? info.dir.sizeHuman : '—'));

    // Output-directory status badge
    const badge = $('buildStatusBadge');
    if (badge && info.dir) {
        const d = info.dir;
        let cls = 'muted', icon = 'dash-circle', txt = 'No output yet';
        if (!d.exists)        { cls = 'muted'; icon = 'folder-x'; txt = 'Output directory not created yet'; }
        else if (!d.writable) { cls = 'bad';   icon = 'lock';     txt = 'Output directory is not writable'; }
        else                  { cls = 'ok';    icon = 'check-circle-fill'; txt = `Output ready · ${d.fileCount ?? 0} files`; }
        badge.className = 'ob-status-badge ' + cls;
        badge.innerHTML = `<i class="bi bi-${icon}"></i> ${txt}`;
        badge.hidden = false;
    }

    // Inline badge next to the output-dir field
    const inline = $('outputDirStatus');
    if (inline && info.dir) {
        const d = info.dir;
        if (!d.configured) { inline.hidden = true; }
        else {
            let cls = d.exists ? (d.writable ? 'ok' : 'bad') : 'warn';
            let icon = d.exists ? (d.writable ? 'check-circle-fill' : 'lock') : 'folder-plus';
            let txt = d.exists ? (d.writable ? 'exists · writable' : 'not writable') : 'will be created on build';
            inline.className = 'ob-status-badge ' + cls;
            inline.innerHTML = `<i class="bi bi-${icon}"></i> ${txt}`;
            inline.hidden = false;
        }
    }
}

function relativeTime(iso) {
    const then = new Date(iso), now = new Date();
    if (isNaN(then)) return iso;
    const s = Math.floor((now - then) / 1000);
    if (s < 60)   return 'just now';
    if (s < 3600) return Math.floor(s / 60) + ' min ago';
    if (s < 86400) return Math.floor(s / 3600) + ' hr ago';
    const d = Math.floor(s / 86400);
    if (d < 30)  return d + (d === 1 ? ' day ago' : ' days ago');
    return then.toLocaleDateString();
}

// ── Utility ──────────────────────────────────────────────────────────
function htmlEscape(str) {
    if (!str) return '';
    return String(str).replace(/&/g, '&amp;').replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

function markDirty() {
    const el = $('lastSavedIndicator');
    if (!el) return;
    el.className = 'ob-save-pill is-dirty';
    el.innerHTML = '<i class="bi bi-cloud-arrow-up"></i> <span class="ob-save-text">Unsaved changes…</span>';
}

function markSaving() {
    const el = $('lastSavedIndicator');
    if (!el) return;
    el.className = 'ob-save-pill is-saving';
    el.innerHTML = '<i class="bi bi-arrow-repeat"></i> <span class="ob-save-text">Saving…</span>';
}

function markSaved() {
    const el = $('lastSavedIndicator');
    if (!el) return;
    el.className = 'ob-save-pill';
    el.innerHTML = '<i class="bi bi-cloud-check"></i> <span class="ob-save-text">Saved ' + new Date().toLocaleTimeString() + '</span>';
}

// ── Page unload guard ─────────────────────────────────────────────────
window.addEventListener('pagehide', () => { isPageUnloading = true; });
window.addEventListener('beforeunload', () => { isPageUnloading = true; });
