<script>
(function () {
    const state = document.querySelector('.sp-checkout #state');
    const city  = document.querySelector('.sp-checkout #city');

    if (!state || !city) return;

    fetch('/api/dz/states')
        .then(r => r.json())
        .then(states => {
            state.innerHTML = '<option value="">الولاية</option>';
            states.forEach(s => {
                const code = String(s.code).padStart(2, '0');
                const label = `${code} ${s.name} - ${s.ar_name || ''}`.trim();
                state.innerHTML += `<option value="${code}">${label}</option>`;
            });
        });

    state.addEventListener('change', () => {
        if (!state.value) return;

        fetch('/api/dz/cities/' + state.value)
            .then(r => r.json())
            .then(cities => {
                city.innerHTML = '<option value="">البلدية</option>';
                cities.forEach(c => {
                    city.innerHTML += `<option value="${c.id}">${c.name}</option>`;
                });
            });
    });
})();
</script>
