// planwisewp/assets/js/admin-pw.js
jQuery(document).ready(function($){
    
    // 1. Settings Reset Confirmation
    $('#planwisewp-reset-button-confirm').on('click', function(e) {
        // A szöveget a wp_localize_script-ből kapjuk meg
        const confirmMsg = (typeof planwisewpAdminParams !== 'undefined' && planwisewpAdminParams.resetConfirm) 
            ? planwisewpAdminParams.resetConfirm 
            : 'Are you absolutely sure you want to reset all settings?';

        if (!confirm(confirmMsg)) {
            e.preventDefault();
        }
    });

    // 2. Settings Form Save (TinyMCE fix)
    $('form').submit(function(){
        if (typeof tinymce !== 'undefined') {
            if (tinymce.get('planwisewp_tooltip_content')) {
                tinymce.get('planwisewp_tooltip_content').save();
            }
            if (tinymce.get('planwisewp_logged_out_message')) {
                tinymce.get('planwisewp_logged_out_message').save();
            }
            if (tinymce.get('planwisewp_limit_message_individual')) {
                tinymce.get('planwisewp_limit_message_individual').save();
            }
        }
    });

    // 3. Unit System Change Handler
    const CM_PER_INCH_ADMIN = 2.54;

    function getValueForInputAdmin(cmValue, targetUnitSystem) {
        if (isNaN(cmValue)) return 0;
        let value = 0;
        if (targetUnitSystem === 'imperial') {
            value = parseFloat(cmValue) / CM_PER_INCH_ADMIN;
            return Math.round(value * 10) / 10;
        } else { 
            value = parseFloat(cmValue);
            return Math.round(value);
        }
    }

    $('input[name="planwisewp_unit_system"]').on('change', function() {
        const newUnitSystem = $(this).val(); 
        const newUnitLabel = (newUnitSystem === 'metric') ? 'cm' : 'in';

        $('.free-default-size-input').each(function() {
            const $input = $(this);
            const cmValue = parseFloat($input.data('cm-value'));
            const displayValue = getValueForInputAdmin(cmValue, newUnitSystem);
            $input.val(displayValue);

            $input.closest('td').find('.unit-label').text(newUnitLabel);
            $input.closest('tr').find('th label').text(function(index, oldText) {
                    return oldText.replace(/\([^)]+\):/, '(' + newUnitLabel + '):');
            });
        });
    });

    // 4. Date Filter Logic
    const form = document.getElementById('date-filter-form'); 
    if (form) {
        const startDateInput = document.getElementById('start_date'); 
        const endDateInput = document.getElementById('end_date');
        document.querySelectorAll('.date-btn').forEach(button => { 
            button.addEventListener('click', function() {
                const period = this.getAttribute('data-period');
                const today = new Date(); 
                let startDate = new Date(); 
                let endDate = new Date();
                
                if (period === 'all') { 
                    startDateInput.value = ''; 
                    endDateInput.value = ''; 
                    form.submit(); 
                    return; 
                }
                if (period === 'this_month') { 
                    startDate = new Date(today.getFullYear(), today.getMonth(), 1); 
                    endDate = new Date(today.getFullYear(), today.getMonth() + 1, 0); 
                } 
                else if (period === 'prev_month') { 
                    startDate.setMonth(startDate.getMonth() - 1); 
                    startDate.setDate(1); 
                    endDate = new Date(startDate.getFullYear(), startDate.getMonth() + 1, 0); 
                } 
                else { 
                    const days = parseInt(period, 10); 
                    if (!isNaN(days)) { 
                        startDate.setDate(today.getDate() - (days - 1)); 
                        endDate = today; 
                    } else { 
                        startDate = today; 
                        endDate = today; 
                    } 
                }
                const formatDate = (date) => { return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`; }
                startDateInput.value = formatDate(startDate); 
                endDateInput.value = formatDate(endDate);
                form.submit();
            });
        });
    }

    // 5. JSON Modal Logic
    const modal = document.getElementById('json-modal');
    if (modal) {
        const modalContent = modal.querySelector('pre');
        const closeBtn = document.getElementById('json-modal-close');
        const viewBtns = document.querySelectorAll('.view-json-btn');
        
        viewBtns.forEach(btn => {
            btn.addEventListener('click', function(e) {
                e.preventDefault();
                const jsonString = this.getAttribute('data-json');
                try {
                    const jsonObj = JSON.parse(jsonString);
                    if (jsonObj && typeof jsonObj === 'object' && jsonObj.rooms !== undefined) {
                        modalContent.textContent = JSON.stringify(jsonObj, null, 2);
                    } else {
                        // Translation handled via PHP if needed, or simple English fallback
                        modalContent.textContent = 'Error: Invalid project data format.';
                    }
                    modal.style.display = 'block';
                } catch (err) { 
                    modalContent.textContent = 'Error parsing JSON data.\n\n' + jsonString;
                    modal.style.display = 'block'; 
                    console.error(err); 
                }
            });
        });
        if(closeBtn) { 
            closeBtn.onclick = function() { modal.style.display = 'none'; } 
        }
        window.onclick = function(event) { 
            if (event.target == modal) { modal.style.display = 'none'; } 
        }
    }
});