(function () {
    const deviceControls = document.querySelectorAll('.dfs_device_control');
    const previewBox = document.getElementById('dfs_preview_box');
    
    const savedDeviceType = localStorage.getItem('activeDevice') || 'desktop';

    function updatePreviewBoxWidth(activeDevice) {
        if (previewBox) {
            if (activeDevice.classList.contains('mobile')) {
                previewBox.style.maxWidth = '375px';
                previewBox.classList.add('mobile');
                previewBox.classList.remove('tablet', 'desktop');
            } else if (activeDevice.classList.contains('tablet')) {
                previewBox.style.maxWidth = '767px';
                previewBox.classList.add('tablet');
                previewBox.classList.remove('mobile', 'desktop');
            } else if (activeDevice.classList.contains('desktop')) {
                previewBox.style.maxWidth = '100%';
                previewBox.classList.add('desktop');
                previewBox.classList.remove('mobile', 'tablet');
            }
        }
    }

    if (deviceControls) {
        deviceControls.forEach(control => {
            control.addEventListener('click', () => {
                if (control.classList.contains('active')) return;

                deviceControls.forEach(c => c.classList.remove('active'));
                if(savedDeviceType) {
                    control.classList.add('active');
                }

                updatePreviewBoxWidth(control);

                if (control.classList.contains('mobile')) {
                    localStorage.setItem('activeDevice', 'mobile');
                } else if (control.classList.contains('tablet')) {
                    localStorage.setItem('activeDevice', 'tablet');
                } else if (control.classList.contains('desktop')) {
                    localStorage.setItem('activeDevice', 'desktop');
                }
            });
        });
    }

    const initialDevice = document.querySelector(`.dfs_device_control.${savedDeviceType}`);
    if (initialDevice) {
        initialDevice.classList.add('active');
        updatePreviewBoxWidth(initialDevice);
    }
})();
