(function () {
    'use strict';

    let selectedType = null;

    document.addEventListener('DOMContentLoaded', function () {

        // ✅ STEP-1 LOAD হলে আগের template selection clear করো
        sessionStorage.removeItem('trstemp_template_id');
        sessionStorage.removeItem('trstemp_template_name');
        sessionStorage.removeItem('trstemp_template_access_type');
        

        const cards = document.querySelectorAll('.website-type-card');
        if (!cards.length) return;

        // Click handler
        cards.forEach(card => {
            card.addEventListener('click', function () {
                selectType(card, true); // user action
            });
        });

        // Step 1: Try restore from server
        restoreSelection(cards);
    });

    function selectType(card, shouldSave = false) {

        document.querySelectorAll('.website-type-card')
            .forEach(c => c.classList.remove('selected'));

        card.classList.add('selected');
        selectedType = card.dataset.type;

        const typeName = card.querySelector('h3').innerText;

        document.getElementById('selected-type-name').innerText = typeName;
        document.getElementById('selected-type-info').style.display = 'block';

        const details = trstempStep1.details[selectedType] || [];
        document.getElementById('selected-type-details').innerHTML =
            details.map(d => `<div class="detail-item">✓ ${d}</div>`).join('');

        // Save locally
        sessionStorage.setItem('trstemp_website_type', selectedType);

        // Save to server ONLY on user click
        if (!shouldSave) return;

        fetch(trstempStep1.ajaxurl, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body:
                'action=trstemp_save_step_data' +
                '&step=' + trstempStep1.step +
                '&data=' + encodeURIComponent(JSON.stringify({
                    website_type: selectedType,
                    website_type_name: typeName
                }))
        });
    }

    function restoreSelection(cards) {

        // ✅ Case 1: Check sessionStorage first (immediate)
        const sessionType = sessionStorage.getItem('trstemp_website_type');
        if (sessionType) {
            const sessionCard = document.querySelector(
                `.website-type-card[data-type="${sessionType}"]`
            );
            if (sessionCard) {
                selectType(sessionCard, false);
                return;
            }
        }

        // ✅ Case 2: Check server data
        fetch(trstempStep1.ajaxurl, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: 'action=trstemp_get_step_data&step=' + trstempStep1.step
        })
        .then(res => res.json())
        .then(res => {

            if (res.success && res.data && res.data.website_type) {

                const savedCard = document.querySelector(
                    `.website-type-card[data-type="${res.data.website_type}"]`
                );

                if (savedCard) {
                    selectType(savedCard, false);
                    return;
                }
            }

            // ✅ Case 3: No saved data → auto select FIRST card
            selectType(cards[0], false);
        })
        .catch(() => {
            // Safety fallback → auto select first
            selectType(cards[0], false);
        });
    }

})();
