<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Installation — AliothPress</title>
    <link rel="stylesheet" href="/static/css/setup.css">
</head>
<body>
<!-- ═══ Transition overlay for PostgreSQL two-phase setup ═══ -->
<div class="setup-overlay" id="setup-overlay">
    <div class="big-spinner"></div>
    <div class="done-icon">&#x2705;</div>
    <h2 id="overlay-title">Setting up your CMS...</h2>
    <p id="overlay-subtitle">This takes a few seconds. Please don't close the browser.</p>
    <div class="overlay-error" id="overlay-error"></div>
</div>

<div class="wizard">
    <div class="wizard-header">
        <h1><img src="{{ url_for('static', filename='img/admin-star.png') }}" alt="" width="32" height="32" style="vertical-align:middle;margin-right:6px;margin-top:-2px;"> AliothPress</h1>
        <p data-i18n="header_subtitle">Installation Wizard</p>
        <div class="progress-bar">
            <div class="progress-step active" id="prog-1"></div>
            <div class="progress-step" id="prog-2"></div>
            <div class="progress-step" id="prog-3"></div>
            <div class="progress-step" id="prog-4"></div>
            <div class="progress-step" id="prog-5"></div>
        </div>
    </div>

    {% with messages = get_flashed_messages(with_categories=true) %}
        {% if messages %}
            <div style="padding: 20px 36px 0;">
            {% for category, message in messages %}
                <div class="alert alert-{{ category }}">{{ message }}</div>
            {% endfor %}
            </div>
        {% endif %}
    {% endwith %}

    <form method="POST" id="wizardForm">
    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
    <div class="wizard-body">

        <!-- ════════════════════ STEP 1: Language ════════════════════ -->
        <div class="step active" id="step-1">
            <div class="step-title" data-i18n="step1_title">Choose Your Language</div>
            <div class="step-subtitle" data-i18n="step1_subtitle">This will be the default language for your site and admin panel.</div>
            <input type="hidden" name="default_language" id="default_language" value="en">
            <div class="lang-grid">
                <!-- Latin script (alphabetical by native name) -->
                <div class="lang-option" data-lang="id" onclick="selectLang(this)">Bahasa Indonesia</div>
                <div class="lang-option" data-lang="cs" onclick="selectLang(this)">&#x10C;e&#x161;tina</div>
                <div class="lang-option" data-lang="da" onclick="selectLang(this)">Dansk</div>
                <div class="lang-option" data-lang="de" onclick="selectLang(this)">Deutsch</div>
                <div class="lang-option selected" data-lang="en" onclick="selectLang(this)">English</div>
                <div class="lang-option" data-lang="es" onclick="selectLang(this)">Espa&#xF1;ol</div>
                <div class="lang-option" data-lang="fr" onclick="selectLang(this)">Fran&#xE7;ais</div>
                <div class="lang-option" data-lang="hr" onclick="selectLang(this)">Hrvatski</div>
                <div class="lang-option" data-lang="it" onclick="selectLang(this)">Italiano</div>
                <div class="lang-option" data-lang="hu" onclick="selectLang(this)">Magyar</div>
                <div class="lang-option" data-lang="nl" onclick="selectLang(this)">Nederlands</div>
                <div class="lang-option" data-lang="nb" onclick="selectLang(this)">Norsk</div>
                <div class="lang-option" data-lang="pl" onclick="selectLang(this)">Polski</div>
                <div class="lang-option" data-lang="pt" onclick="selectLang(this)">Portugu&#xEA;s</div>
                <div class="lang-option" data-lang="ro" onclick="selectLang(this)">Rom&#xE2;n&#x103;</div>
                <div class="lang-option" data-lang="sk" onclick="selectLang(this)">Sloven&#x10D;ina</div>
                <div class="lang-option" data-lang="fi" onclick="selectLang(this)">Suomi</div>
                <div class="lang-option" data-lang="sv" onclick="selectLang(this)">Svenska</div>
                <div class="lang-option" data-lang="vi" onclick="selectLang(this)">Ti&#x1EBF;ng Vi&#x1EC7;t</div>
                <div class="lang-option" data-lang="tr" onclick="selectLang(this)">T&#xFC;rk&#xE7;e</div>
                <!-- Cyrillic (alphabetical) -->
                <div class="lang-option" data-lang="bg" onclick="selectLang(this)">&#x411;&#x44A;&#x43B;&#x433;&#x430;&#x440;&#x441;&#x43A;&#x438;</div>
                <div class="lang-option" data-lang="ru" onclick="selectLang(this)">&#x420;&#x443;&#x441;&#x441;&#x43A;&#x438;&#x439;</div>
                <div class="lang-option" data-lang="uk" onclick="selectLang(this)">&#x423;&#x43A;&#x440;&#x430;&#x457;&#x43D;&#x441;&#x44C;&#x43A;&#x430;</div>
                <!-- Greek -->
                <div class="lang-option" data-lang="el" onclick="selectLang(this)">&#x395;&#x3BB;&#x3BB;&#x3B7;&#x3BD;&#x3B9;&#x3BA;&#x3AC;</div>
                <!-- Other scripts -->
                <div class="lang-option" data-lang="hi" onclick="selectLang(this)">&#x939;&#x93F;&#x928;&#x94D;&#x926;&#x940;</div>
                <div class="lang-option" data-lang="th" onclick="selectLang(this)">&#xE44;&#xE17;&#xE22;</div>
                <div class="lang-option" data-lang="zh" onclick="selectLang(this)">&#x4E2D;&#x6587;</div>
                <div class="lang-option" data-lang="ja" onclick="selectLang(this)">&#x65E5;&#x672C;&#x8A9E;</div>
                <div class="lang-option" data-lang="ko" onclick="selectLang(this)">&#xD55C;&#xAD6D;&#xC5B4;</div>
                <div class="lang-option" data-lang="he" onclick="selectLang(this)">&#x5E2;&#x5D1;&#x5E8;&#x5D9;&#x5EA;</div>
                <div class="lang-option" data-lang="ar" onclick="selectLang(this)">&#x627;&#x644;&#x639;&#x631;&#x628;&#x64A;&#x629;</div>
            </div>
            <div class="info-hint" data-i18n="step1_hint">You can add more languages later in Settings. This sets the primary language for your content and interface.</div>
        </div>

        <!-- ════════════════════ STEP 2: License Agreement ════════════════════ -->
        <div class="step" id="step-2">
            <div class="step-title" data-i18n="eula_title">License Agreement</div>
            <div class="step-subtitle" data-i18n="eula_subtitle">Please read and accept the End-User License Agreement.</div>
            <div class="eula-box" id="eula-content">
                <div class="eula-loading" data-i18n="eula_loading">Loading license agreement...</div>
            </div>
            <label class="eula-agree">
                <input type="checkbox" id="eula_accepted" onchange="onEulaCheckbox()">
                <span data-i18n="eula_accept">I have read and accept the End-User License Agreement</span>
            </label>
        </div>

        <!-- ════════════════════ STEP 3: Database ════════════════════ -->
        <div class="step" id="step-3">
            <div class="step-title" data-i18n="step2_title">Database</div>
            <div class="step-subtitle" data-i18n="step2_subtitle">Choose where to store your site data.</div>

            <input type="hidden" name="db_type" id="db_type" value="sqlite">
            <!-- Hidden fields that get filled by auto-setup or manual input -->
            <input type="hidden" name="db_host" id="db_host" value="">
            <input type="hidden" name="db_port" id="db_port" value="5432">
            <input type="hidden" name="db_name" id="db_name" value="">
            <input type="hidden" name="db_user" id="db_user" value="">
            <input type="hidden" name="db_password" id="db_password" value="">

            <div class="db-selector">
                <div class="db-option selected" data-db="sqlite" onclick="selectDb(this)">
                    <div class="db-icon">&#x1F4C1;</div>
                    <div class="db-name">SQLite</div>
                    <div class="db-desc" data-i18n="db_sqlite_desc">Local / Testing</div>
                </div>
                <div class="db-option" data-db="postgresql_auto" onclick="selectDb(this)">
                    <div class="db-icon">&#x26A1;</div>
                    <div class="db-name" data-i18n="db_auto_name">Auto Setup</div>
                    <div class="db-desc" data-i18n="db_auto_desc">Fresh VPS</div>
                </div>
                <div class="db-option" data-db="postgresql" onclick="selectDb(this)">
                    <div class="db-icon">&#x1F418;</div>
                    <div class="db-name">PostgreSQL</div>
                    <div class="db-desc" data-i18n="db_pg_desc">I have a database</div>
                </div>
            </div>

            <!-- ── SQLite panel ── -->
            <div class="db-panel visible" id="panel-sqlite">
                <div class="info-hint" data-i18n="step2_sqlite_hint">SQLite requires no configuration &#x2014; perfect for trying out AliothPress locally. For a live website, use PostgreSQL.</div>
            </div>

            <!-- ── Auto-setup panel ── -->
            <div class="db-panel" id="panel-postgresql_auto">
                <div class="info-hint" data-i18n="step2_auto_hint">AliothPress will install PostgreSQL on this server and create a database automatically. Works on a fresh Ubuntu/Debian VPS (Hetzner Cloud, DigitalOcean, Linode).</div>
                <div class="form-group">
                    <label data-i18n="db_name">Database Name</label>
                    <input type="text" id="auto_db_name" value="aliothpress" placeholder="aliothpress">
                </div>
                <div class="form-group">
                    <label data-i18n="db_user">Username</label>
                    <input type="text" id="auto_db_user" value="aliothpress" placeholder="aliothpress">
                </div>
                <div style="text-align: center; margin-top: 4px;">
                    <button type="button" class="btn btn-sm btn-auto" id="btn-auto-install" onclick="autoInstallPg()">
                        <span data-i18n="btn_auto_install">&#x26A1; Install &amp; Create Database</span>
                    </button>
                </div>
                <div class="status-box" id="auto-status" style="display:none;"></div>
            </div>

            <!-- ── Manual PostgreSQL panel ── -->
            <div class="db-panel" id="panel-postgresql">
                <div class="info-hint" data-i18n="step2_pg_hint">Enter the connection details for your existing PostgreSQL database.</div>
                <div style="display:flex;gap:12px;">
                    <div class="form-group" style="flex:3;">
                        <label data-i18n="db_host">Database Host</label>
                        <input type="text" id="manual_db_host" placeholder="localhost">
                    </div>
                    <div class="form-group" style="flex:1;">
                        <label data-i18n="db_port">Port</label>
                        <input type="text" id="manual_db_port" value="5432" placeholder="5432">
                    </div>
                </div>
                <div class="form-group">
                    <label data-i18n="db_name">Database Name</label>
                    <input type="text" id="manual_db_name" placeholder="aliothpress">
                </div>
                <div class="form-group">
                    <label data-i18n="db_user">Username</label>
                    <input type="text" id="manual_db_user" placeholder="db_user">
                </div>
                <div class="form-group">
                    <label data-i18n="db_password">Password</label>
                    <input type="password" id="manual_db_password">
                </div>
                <div style="text-align: center;">
                    <button type="button" class="btn btn-sm btn-test" id="btn-test-db" onclick="testDbConnection()">
                        <span data-i18n="btn_test_connection">&#x1F50D; Test Connection</span>
                    </button>
                </div>
                <div class="test-result" id="test-result"></div>
            </div>
        </div>

        <!-- ════════════════════ STEP 4: Admin Account ════════════════════ -->
        <div class="step" id="step-4">
            <div class="step-title" data-i18n="step3_title">Admin Account</div>
            <div class="step-subtitle" data-i18n="step3_subtitle">Create the site owner account with full access.</div>
            <div class="form-group">
                <label data-i18n="username">Username</label>
                <input type="text" name="username" id="username" required autocomplete="username">
            </div>
            <div class="form-group">
                <label data-i18n="email">Email</label>
                <input type="email" name="email" id="email" required autocomplete="email">
                <div class="help-text" data-i18n="step3_email_hint">This is your login email. For sending site emails (invitations, notifications), you will configure a separate SMTP address in Settings after installation.</div>
            </div>
            <div class="form-group">
                <label data-i18n="password">Password</label>
                <input type="password" name="password" id="password" required minlength="8" autocomplete="new-password">
                <div class="help-text" data-i18n="password_hint">Min 8 chars, include uppercase, lowercase &amp; digit</div>
            </div>
            <div class="form-group">
                <label data-i18n="confirm_password">Confirm Password</label>
                <input type="password" name="confirm_password" id="confirm_password" required minlength="8" autocomplete="new-password">
            </div>
        </div>

        <!-- ════════════════════ STEP 5: Site Info ════════════════════ -->
        <div class="step" id="step-5">
            <div class="step-title" data-i18n="step4_title">Your Site</div>
            <div class="step-subtitle" data-i18n="step4_subtitle">You can change all of this later in Settings.</div>
            <div class="form-group">
                <label data-i18n="site_name">Site Name</label>
                <input type="text" name="site_name" id="site_name" placeholder="My Awesome Site">
            </div>
            <div class="form-group">
                <label data-i18n="site_tagline">Tagline</label>
                <input type="text" name="site_tagline" id="site_tagline" placeholder="A short description of your site">
            </div>
            <div class="form-group">
                <label data-i18n="license_key">License Key <span style="font-weight:400;color:#a0aec0;" data-i18n="license_optional">(optional)</span></label>
                <input type="text" name="license_key" id="license_key" placeholder="" autocomplete="off" style="font-family:monospace;">
                <div class="help-text" data-i18n="license_hint">If you purchased AliothPress, paste your key here. You can also do this later in Settings.</div>
            </div>
            <div style="background:#f7fafc;border-radius:8px;padding:16px;margin-top:20px;">
                <div style="font-weight:600;margin-bottom:10px;font-size:14px;color:#4a5568;" data-i18n="summary_title">Summary</div>
                <table class="summary-table">
                    <tr><td data-i18n="summary_lang">Language</td><td id="sum-lang">English</td></tr>
                    <tr><td data-i18n="summary_db">Database</td><td id="sum-db">SQLite</td></tr>
                    <tr><td data-i18n="summary_admin">Admin</td><td id="sum-admin">&#x2014;</td></tr>
                    <tr><td data-i18n="summary_site">Site</td><td id="sum-site">&#x2014;</td></tr>
                </table>
            </div>
        </div>

    </div>
    <div class="wizard-footer">
        <button type="button" class="btn btn-back btn-hidden" id="btn-back" onclick="prevStep()" data-i18n-value="back">Back</button>
        <button type="button" class="btn btn-next" id="btn-next" onclick="nextStep()" data-i18n-value="next">Next</button>
    </div>
    </form>
</div>

<script>
/* ══════════════════════════════════════════════════════════════════
   STATE
   ══════════════════════════════════════════════════════════════════ */
var T={}, langNames={};

/* Themed notice modal — replaces the native browser popup so validation
   messages match the wizard's look. Fire-and-forget: callers keep their
   synchronous `return false`, the modal just shows. */
function suAlert(msg){
    var ov=document.createElement('div');
    ov.className='su-alert-overlay';
    var box=document.createElement('div');
    box.className='su-alert';
    var p=document.createElement('p');
    p.textContent=msg;
    var ok=document.createElement('button');
    ok.type='button';
    ok.className='su-alert-ok';
    ok.textContent='OK';
    box.appendChild(p); box.appendChild(ok); ov.appendChild(box);
    function close(){
        document.removeEventListener('keydown',onKey,true);
        if(ov.parentNode) ov.parentNode.removeChild(ov);
    }
    function onKey(e){ if(e.key==='Escape'||e.key==='Enter'){ e.preventDefault(); e.stopPropagation(); close(); } }
    ok.addEventListener('click',close);
    ov.addEventListener('mousedown',function(e){ if(e.target===ov) close(); });
    document.addEventListener('keydown',onKey,true);
    document.body.appendChild(ov);
    ok.focus();
}
var currentStep=1, totalSteps=5, currentLang='en';
var dbTestPassed=false, autoSetupDone=false;


/* ══════════════════════════════════════════════════════════════════
   LOAD TRANSLATIONS (JSON) THEN INITIALIZE
   ══════════════════════════════════════════════════════════════════ */
(function(){
    fetch('/static/i18n/setup.json')
    .then(function(r){ return r.json(); })
    .then(function(data){
        T=data.translations||data;
        langNames=data.langNames||{};
        init();
    })
    .catch(function(){
        /* Fallback: wizard works in English without translations */
        T={en:{}};
        langNames={en:'English'};
        init();
    });
})();

function init(){
    /* Prevent accidental form submission via Enter key when PostgreSQL is selected.
       Regular POST to /setup cannot switch SQLAlchemy engine mid-request — only
       the AJAX two-phase flow (/setup/finalize → restart → poll) works correctly. */
    var form=document.getElementById('wizardForm');
    if(form){
        form.addEventListener('submit',function(e){
            var dbType=document.getElementById('db_type').value;
            if(dbType==='postgresql'||dbType==='postgresql_auto'){
                e.preventDefault();
                if(currentStep===totalSteps){
                    syncDbFields();
                    finalizePgSetup();
                }
            }
        });
    }

    loadEula('en');
}


/* ══════════════════════════════════════════════════════════════════
   LANGUAGE SELECTION
   ══════════════════════════════════════════════════════════════════ */
var RTL_LANGS=['ar','he'];

function selectLang(el){
    document.querySelectorAll('.lang-option').forEach(function(o){o.classList.remove('selected');});
    el.classList.add('selected');
    currentLang=el.getAttribute('data-lang');
    document.getElementById('default_language').value=currentLang;
    applyTranslations();
    applyDirection();
    loadEula(currentLang);
    document.getElementById('eula_accepted').checked=false;
    onEulaCheckbox();
}

function applyDirection(){
    var isRtl=RTL_LANGS.indexOf(currentLang)!==-1;
    var wizard=document.querySelector('.wizard');
    var overlay=document.getElementById('setup-overlay');
    if(isRtl){
        wizard.classList.add('rtl');
        overlay.style.direction='rtl';
        document.documentElement.dir='rtl';
    }else{
        wizard.classList.remove('rtl');
        overlay.style.direction='ltr';
        document.documentElement.dir='ltr';
    }
}

function applyTranslations(){
    var t=T[currentLang]||T.en;
    document.querySelectorAll('[data-i18n]').forEach(function(el){
        var k=el.getAttribute('data-i18n');
        if(t[k]) el.textContent=t[k];
    });
    document.querySelectorAll('[data-i18n-value]').forEach(function(el){
        var k=el.getAttribute('data-i18n-value');
        if(t[k]) el.textContent=t[k];
    });
    document.documentElement.lang=currentLang;
}


/* ══════════════════════════════════════════════════════════════════
   EULA LOADING
   ══════════════════════════════════════════════════════════════════ */
var eulaCache={};

function loadEula(lang){
    var box=document.getElementById('eula-content');
    var t=T[lang]||T.en;

    if(eulaCache[lang]){ box.innerHTML=eulaCache[lang]; return; }

    box.innerHTML='<div class="eula-loading">'+(t.eula_loading||'Loading...')+'</div>';

    fetch('/static/legal/eula_'+lang+'.html')
    .then(function(r){
        if(!r.ok) throw new Error('not found');
        return r.text();
    })
    .then(function(text){
        eulaCache[lang]=text;
        box.innerHTML=text;
    })
    .catch(function(){
        if(lang==='en'){
            box.innerHTML='<div class="eula-loading">'+(t.eula_load_error||'Could not load.')+'</div>';
            return;
        }
        fetch('/static/legal/eula_en.html')
        .then(function(r){ return r.ok ? r.text() : Promise.reject(); })
        .then(function(text){
            eulaCache[lang]=text;
            box.innerHTML=text;
        })
        .catch(function(){
            box.innerHTML='<div class="eula-loading">'+(t.eula_load_error||'Could not load.')+'</div>';
        });
    });
}

function onEulaCheckbox(){
    var cb=document.getElementById('eula_accepted');
    cb.closest('.eula-agree').style.background=cb.checked ? '#c6f6d5' : '';
}


/* ══════════════════════════════════════════════════════════════════
   DATABASE SELECTION
   ══════════════════════════════════════════════════════════════════ */
function selectDb(el){
    document.querySelectorAll('.db-option').forEach(function(o){o.classList.remove('selected');});
    el.classList.add('selected');
    var d=el.getAttribute('data-db');
    document.getElementById('db_type').value=d;

    document.querySelectorAll('.db-panel').forEach(function(p){p.classList.remove('visible');});
    var panel=document.getElementById('panel-'+d);
    if(panel) panel.classList.add('visible');

    dbTestPassed=false;
    autoSetupDone=false;
    var tr=document.getElementById('test-result');
    if(tr){tr.className='test-result'; tr.textContent='';}
}


/* ══════════════════════════════════════════════════════════════════
   SYNC HIDDEN FIELDS — called before form submit and on Next
   ══════════════════════════════════════════════════════════════════ */
function syncDbFields(){
    var dbType=document.getElementById('db_type').value;
    if(dbType==='postgresql'){
        document.getElementById('db_host').value=document.getElementById('manual_db_host').value;
        document.getElementById('db_port').value=document.getElementById('manual_db_port').value;
        document.getElementById('db_name').value=document.getElementById('manual_db_name').value;
        document.getElementById('db_user').value=document.getElementById('manual_db_user').value;
        document.getElementById('db_password').value=document.getElementById('manual_db_password').value;
    }
}


/* ══════════════════════════════════════════════════════════════════
   TEST DB CONNECTION (Manual PostgreSQL)
   ══════════════════════════════════════════════════════════════════ */
function testDbConnection(){
    var t=T[currentLang]||T.en;
    var btn=document.getElementById('btn-test-db');
    var result=document.getElementById('test-result');

    var host=document.getElementById('manual_db_host').value.trim();
    var port=document.getElementById('manual_db_port').value.trim();
    var name=document.getElementById('manual_db_name').value.trim();
    var user=document.getElementById('manual_db_user').value.trim();
    var pass=document.getElementById('manual_db_password').value;

    if(!host||!name||!user){
        suAlert(t.err_db_fields);
        return;
    }

    btn.disabled=true;
    btn.innerHTML='<span class="spinner"></span> '+(t.testing);
    result.className='test-result'; result.textContent='';

    fetch('/setup/test-db',{
        method:'POST',
        headers:{'Content-Type':'application/json'},
        body:JSON.stringify({host:host,port:port,name:name,user:user,password:pass})
    })
    .then(function(r){return r.json();})
    .then(function(data){
        btn.disabled=false;
        btn.innerHTML='<span data-i18n="btn_test_connection">'+(t.btn_test_connection)+'</span>';
        if(data.ok){
            result.className='test-result ok';
            result.textContent='\u2705 '+(data.message||t.test_ok);
            dbTestPassed=true;
        }else{
            result.className='test-result fail';
            result.textContent='\u274c '+(t.test_fail)+': '+(data.error||'');
            dbTestPassed=false;
        }
    })
    .catch(function(err){
        btn.disabled=false;
        btn.innerHTML='<span data-i18n="btn_test_connection">'+(t.btn_test_connection)+'</span>';
        result.className='test-result fail';
        result.textContent='\u274c '+(t.test_fail)+': '+err.message;
        dbTestPassed=false;
    });
}


/* ══════════════════════════════════════════════════════════════════
   AUTO-INSTALL POSTGRESQL (Fresh VPS)
   ══════════════════════════════════════════════════════════════════ */
function autoInstallPg(){
    var t=T[currentLang]||T.en;
    var btn=document.getElementById('btn-auto-install');
    var statusBox=document.getElementById('auto-status');

    var dbName=document.getElementById('auto_db_name').value.trim()||'aliothpress';
    var dbUser=document.getElementById('auto_db_user').value.trim()||'aliothpress';

    btn.disabled=true;
    btn.innerHTML='<span class="spinner"></span> '+(t.installing);
    statusBox.style.display='block';
    statusBox.innerHTML='<div class="step-wait">'+(t.installing)+'</div>';

    fetch('/setup/install-postgres',{
        method:'POST',
        headers:{'Content-Type':'application/json'},
        body:JSON.stringify({name:dbName,user:dbUser})
    })
    .then(function(r){return r.json();})
    .then(function(data){
        btn.disabled=false;
        btn.innerHTML='<span data-i18n="btn_auto_install">'+(t.btn_auto_install)+'</span>';

        var html='';
        if(data.steps){
            data.steps.forEach(function(s){
                html+='<div class="step-ok">'+s+'</div>';
            });
        }

        if(data.ok){
            html+='<div class="step-ok" style="font-weight:600;margin-top:6px;">'+(t.auto_ok)+'</div>';
            statusBox.innerHTML=html;
            autoSetupDone=true;

            var c=data.credentials;
            document.getElementById('db_type').value='postgresql_auto';
            document.getElementById('db_host').value=c.host;
            document.getElementById('db_port').value=c.port;
            document.getElementById('db_name').value=c.name;
            document.getElementById('db_user').value=c.user;
            document.getElementById('db_password').value=c.password;

            btn.disabled=true;
            btn.style.opacity='0.6';
            btn.innerHTML='\u2705 '+(t.auto_ok);
        }else{
            html+='<div class="step-fail">'+(t.auto_fail)+': '+(data.error||'')+'</div>';
            statusBox.innerHTML=html;
            autoSetupDone=false;
        }
    })
    .catch(function(err){
        btn.disabled=false;
        btn.innerHTML='<span data-i18n="btn_auto_install">'+(t.btn_auto_install)+'</span>';
        statusBox.innerHTML='<div class="step-fail">'+(t.auto_fail)+': '+err.message+'</div>';
        autoSetupDone=false;
    });
}


/* ══════════════════════════════════════════════════════════════════
   WIZARD NAVIGATION
   ══════════════════════════════════════════════════════════════════ */
function showStep(n){
    document.querySelectorAll('.step').forEach(function(s){s.classList.remove('active');});
    document.getElementById('step-'+n).classList.add('active');
    for(var i=1;i<=totalSteps;i++){
        var p=document.getElementById('prog-'+i);
        p.classList.remove('active','done');
        if(i<n) p.classList.add('done');
        if(i===n) p.classList.add('active');
    }
    var t=T[currentLang]||T.en;
    var bb=document.getElementById('btn-back'),bn=document.getElementById('btn-next');
    bb.classList.toggle('btn-hidden',n===1);
    if(n===totalSteps){
        bn.textContent=t.launch;
        bn.className='btn btn-launch';
        bn.onclick=function(){
            syncDbFields();
            var dbType=document.getElementById('db_type').value;
            if(dbType==='postgresql'||dbType==='postgresql_auto'){
                finalizePgSetup();
            }else{
                document.getElementById('wizardForm').submit();
            }
        };
        updateSummary();
    }else{
        bn.textContent=t.next;
        bn.className='btn btn-next';
        bn.onclick=nextStep;
    }
    currentStep=n;
}


/* ══════════════════════════════════════════════════════════════════
   TWO-PHASE SETUP (PostgreSQL)
   ══════════════════════════════════════════════════════════════════ */
function finalizePgSetup(){
    if(!validateStep(4)) return;   /* Admin account */
    if(!validateStep(3)) return;   /* Database */

    var t=T[currentLang]||T.en;
    var overlay=document.getElementById('setup-overlay');
    document.getElementById('overlay-title').textContent=t.configuring_title||'Setting up your CMS...';
    document.getElementById('overlay-subtitle').textContent=t.configuring_subtitle||'This takes a few seconds. Please don\u2019t close the browser.';
    document.getElementById('overlay-error').style.display='none';
    overlay.classList.remove('done');
    overlay.classList.add('visible');

    var payload={
        db_type: document.getElementById('db_type').value,
        db_host: document.getElementById('db_host').value,
        db_port: document.getElementById('db_port').value,
        db_name: document.getElementById('db_name').value,
        db_user: document.getElementById('db_user').value,
        db_password: document.getElementById('db_password').value,
        username: document.getElementById('username').value,
        email: document.getElementById('email').value,
        password: document.getElementById('password').value,
        confirm_password: document.getElementById('confirm_password').value,
        default_language: document.getElementById('default_language').value,
        site_name: (document.getElementById('site_name')||{}).value||'',
        site_tagline: (document.getElementById('site_tagline')||{}).value||'',
        license_key: (document.getElementById('license_key')||{}).value||''
    };

    fetch('/setup/finalize',{
        method:'POST',
        headers:{'Content-Type':'application/json'},
        body:JSON.stringify(payload)
    })
    .then(function(r){ return r.json(); })
    .then(function(data){
        if(!data.ok){
            showOverlayError(data.error||'Unknown error');
            return;
        }
        if(data.restart){
            setTimeout(function(){ pollHealth(0); }, 2000);
        }else{
            showOverlayDone();
        }
    })
    .catch(function(err){
        /* Network error is EXPECTED when the server restarts itself
           (Gunicorn dies before sending the response).
           Start polling — the setup data was already saved to disk. */
        setTimeout(function(){ pollHealth(0); }, 3000);
    });
}

function pollHealth(attempts){
    if(attempts>30){
        showOverlayError('Server did not restart in time. Please refresh the page.');
        return;
    }
    fetch('/setup/health',{method:'GET',cache:'no-store'})
    .then(function(r){
        if(!r.ok) throw new Error('not ready');
        return r.json();
    })
    .then(function(data){
        if(data.ready && data.has_users){
            showOverlayDone();
        }else if(data.ready && !data.has_users){
            setTimeout(function(){ pollHealth(attempts+1); }, 2000);
        }else{
            setTimeout(function(){ pollHealth(attempts+1); }, 2000);
        }
    })
    .catch(function(){
        setTimeout(function(){ pollHealth(attempts+1); }, 2000);
    });
}

function showOverlayDone(){
    var t=T[currentLang]||T.en;
    var overlay=document.getElementById('setup-overlay');
    document.getElementById('overlay-title').textContent=t.configuring_done||'Done! Redirecting...';
    document.getElementById('overlay-subtitle').textContent='';
    overlay.classList.add('done');
    setTimeout(function(){ window.location.href='/admin'; }, 1500);
}

function showOverlayError(msg){
    var t=T[currentLang]||T.en;
    document.getElementById('overlay-title').textContent=t.configuring_error||'Setup failed';
    document.getElementById('overlay-subtitle').textContent='';
    var errBox=document.getElementById('overlay-error');
    errBox.textContent=msg;
    errBox.style.display='block';
    document.getElementById('setup-overlay').onclick=function(){
        document.getElementById('setup-overlay').classList.remove('visible');
        document.getElementById('setup-overlay').onclick=null;
    };
}

function nextStep(){
    if(!validateStep(currentStep)) return;
    if(currentStep===3) syncDbFields();      /* Sync DB fields when leaving Database step */
    if(currentStep<totalSteps) showStep(currentStep+1);
}

function prevStep(){
    if(currentStep>1) showStep(currentStep-1);
}

function validateStep(n){
    var t=T[currentLang]||T.en;
    /* Step 2: EULA */
    if(n===2){
        if(!document.getElementById('eula_accepted').checked){
            suAlert(t.err_eula||'Please accept the license agreement to continue.');
            return false;
        }
    }
    /* Step 3: Database */
    if(n===3){
        var dbType=document.getElementById('db_type').value;
        if(dbType==='postgresql'){
            var h=document.getElementById('manual_db_host').value.trim();
            var nm=document.getElementById('manual_db_name').value.trim();
            var u=document.getElementById('manual_db_user').value.trim();
            if(!h||!nm||!u){suAlert(t.err_db_fields);return false;}
        }
        if(dbType==='postgresql_auto' && !autoSetupDone){
            suAlert(t.err_db_test||'Please run Auto Setup first.');
            return false;
        }
    }
    /* Step 4: Admin account */
    if(n===4){
        var un=document.getElementById('username').value.trim();
        var em=document.getElementById('email').value.trim();
        var pw=document.getElementById('password').value;
        var pw2=document.getElementById('confirm_password').value;
        if(!un){suAlert(t.err_username);return false;}
        if(!em||em.indexOf('@')===-1){suAlert(t.err_email);return false;}
        if(pw.length<8){suAlert(t.err_pw_len);return false;}
        if(!/[A-Z]/.test(pw)||!/[a-z]/.test(pw)||!/[0-9]/.test(pw)){suAlert(t.err_pw_weak||'Password must include uppercase, lowercase and a digit.');return false;}
        if(pw!==pw2){suAlert(t.err_pw_match);return false;}
    }
    return true;
}

function updateSummary(){
    document.getElementById('sum-lang').textContent=langNames[currentLang]||currentLang;
    var d=document.getElementById('db_type').value;
    if(d==='sqlite'){
        document.getElementById('sum-db').textContent='SQLite';
    }else if(d==='postgresql_auto'){
        document.getElementById('sum-db').textContent='PostgreSQL (auto: '+(document.getElementById('db_name').value||'aliothpress')+')';
    }else{
        document.getElementById('sum-db').textContent='PostgreSQL ('+(document.getElementById('manual_db_name').value||'\u2014')+')';
    }
    document.getElementById('sum-admin').textContent=document.getElementById('username').value||'\u2014';
    document.getElementById('sum-site').textContent=document.getElementById('site_name').value||'\u2014';
}
</script>
</body>
</html>
