document.addEventListener('DOMContentLoaded', function () {
    // 1. Tab Switching Logic
    window.switchTab = function (tabId) {
        // Hide all contents
        document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active'));
        // Deactivate all buttons
        document.querySelectorAll('.tab-btn').forEach(el => el.classList.remove('active'));

        // Show target content
        const targetContent = document.getElementById('tab-' + tabId);
        if (targetContent) targetContent.classList.add('active');

        // Activate button
        // Handle potential cleaner selector if data attribute is uniform
        const targetBtn = document.querySelector(`.tab-btn[data-tab="${tabId}"]`);
        if (targetBtn) targetBtn.classList.add('active');

        // Update URL without reload
        const url = new URL(window.location);
        url.searchParams.set('tab', tabId);
        window.history.pushState({}, '', url);
    };

    // Initialize Tab from URL
    const params = new URLSearchParams(window.location.search);
    const initialTab = params.get('tab') || 'appearance';
    switchTab(initialTab);

    // 2. Domain Selection Logic
    const domainOptions = document.querySelectorAll('.domain-option');
    if (domainOptions.length > 0) {
        domainOptions.forEach(option => {
            // If it's not disabled/locked
            if (!option.classList.contains('disabled')) {
                option.addEventListener('click', function (e) {
                    // Ignore clicks on input text or copy buttons
                    if (e.target.closest('input[type="text"]') || e.target.closest('.copy-btn')) {
                        return;
                    }

                    // Deselect all
                    domainOptions.forEach(o => o.classList.remove('selected'));

                    // Select current
                    this.classList.add('selected');

                    // Update Hidden Input if exists
                    const hiddenInput = document.getElementById('domainType');
                    if (hiddenInput) hiddenInput.value = this.dataset.type;

                    // Check Radio
                    const radio = this.querySelector('input[type="radio"]');
                    if (radio) radio.checked = true;
                });
            }
        });
    }

    // 3. Logo Type Logic
    window.updateLogoType = function (type) {
        // Update styling active state
        document.querySelectorAll('.logo-type-option').forEach(opt => opt.classList.remove('active'));
        const activeRadio = document.querySelector(`input[name="logo_type"][value="${type}"]`);
        if (activeRadio) {
            activeRadio.closest('.logo-type-option').classList.add('active');
        }

        // Show/Hide Fields
        const textGroup = document.getElementById('logoTextGroup');
        const imageGroup = document.getElementById('logoImageGroup');

        if (textGroup && imageGroup) {
            if (type === 'text') {
                textGroup.style.display = 'block';
                imageGroup.style.display = 'none';
            } else if (type === 'image') {
                textGroup.style.display = 'none';
                imageGroup.style.display = 'block';
            } else {
                textGroup.style.display = 'block';
                imageGroup.style.display = 'block';
            }
        }
    };

    // 4. Logo Preview & Remove
    window.previewLogo = function (input) {
        if (input.files && input.files[0]) {
            const reader = new FileReader();
            reader.onload = function (e) {
                const previewBox = document.getElementById('logoPreviewBox');
                if (previewBox) {
                    previewBox.innerHTML = `
                        <img src="${e.target.result}" alt="Logo Preview" id="logoPreviewImg">
                        <button type="button" class="logo-remove-btn" onclick="event.stopPropagation(); removeLogo()">
                            <iconify-icon icon="solar:trash-bin-trash-bold"></iconify-icon>
                        </button>`;
                }
                // Reset remove flag
                const removeInput = document.getElementById('removeLogoInput');
                if (removeInput) removeInput.value = '0';
            };
            reader.readAsDataURL(input.files[0]);
        }
    };

    window.removeLogo = function () {
        const previewBox = document.getElementById('logoPreviewBox');
        if (previewBox) {
            previewBox.innerHTML = `
                <div class="logo-placeholder" id="logoPlaceholder">
                    <iconify-icon icon="solar:gallery-add-bold"></iconify-icon>
                    <span>Clique para enviar uma imagem</span>
                </div>`;
        }
        const fileInput = document.getElementById('logoInput');
        if (fileInput) fileInput.value = '';

        // Set remove flag
        const removeInput = document.getElementById('removeLogoInput');
        if (removeInput) removeInput.value = '1';
    };

    // 5. Favicon Preview & Remove
    window.previewFavicon = function (input) {
        if (input.files && input.files[0]) {
            const reader = new FileReader();
            reader.onload = function (e) {
                const previewBox = document.getElementById('faviconPreviewBox');
                if (previewBox) {
                    previewBox.innerHTML = `
                        <img src="${e.target.result}" alt="Favicon Preview" id="faviconPreviewImg">
                        <button type="button" class="favicon-remove-btn" onclick="event.stopPropagation(); removeFavicon()">
                            <iconify-icon icon="solar:trash-bin-trash-bold"></iconify-icon>
                        </button>`;
                }
                // Reset remove flag
                const removeInput = document.getElementById('removeFaviconInput');
                if (removeInput) removeInput.value = '0';
            };
            reader.readAsDataURL(input.files[0]);
        }
    };

    window.removeFavicon = function () {
        const previewBox = document.getElementById('faviconPreviewBox');
        if (previewBox) {
            previewBox.innerHTML = `
                <div class="favicon-placeholder" id="faviconPlaceholder">
                    <iconify-icon icon="solar:bookmark-square-bold"></iconify-icon>
                    <span>32x32 px</span>
                </div>`;
        }
        const fileInput = document.getElementById('faviconInput');
        if (fileInput) fileInput.value = '';

        // Set remove flag
        const removeInput = document.getElementById('removeFaviconInput');
        if (removeInput) removeInput.value = '1';
    };

    // 6. Copy to Clipboard
    window.copyToClipboard = function (text, event) {
        event.preventDefault();
        event.stopPropagation();

        navigator.clipboard.writeText(text).then(() => {
            const btn = event.currentTarget;
            const originalIcon = btn.innerHTML;
            btn.innerHTML = '<iconify-icon icon="solar:check-circle-bold" style="color: var(--success);"></iconify-icon>';

            setTimeout(() => {
                btn.innerHTML = originalIcon;
            }, 2000);
        });
    };

    // 7. Auto-prefix Social URLs
    const socialInputs = [
        { name: 'instagram', prefix: 'https://www.instagram.com/' },
        { name: 'tiktok', prefix: 'https://www.tiktok.com/@' }
    ];

    socialInputs.forEach(item => {
        const input = document.querySelector(`input[name="${item.name}"]`);
        if (input) {
            input.addEventListener('blur', function () {
                let val = this.value.trim();

                // If it has content and doesn't start with http/https
                if (val && !val.startsWith('http')) {
                    // Remove @ if present at start (common for usernames)
                    if (val.startsWith('@')) val = val.substring(1);

                    // Add prefix
                    this.value = item.prefix + val;
                }
            });
        }
    });

    // 8. Social Image Logic
    window.previewSocialImage = function (input) {
        if (input.files && input.files[0]) {
            const reader = new FileReader();
            reader.onload = function (e) {
                const previewBox = document.getElementById('socialPreviewBox');
                if (previewBox) {
                    previewBox.innerHTML = `
                        <img src="${e.target.result}" alt="Social Preview" id="socialPreviewImg" style="width: 100%; height: 100%; object-fit: cover;">
                        <button type="button" class="logo-remove-btn" onclick="event.stopPropagation(); removeSocialImage()">
                            <iconify-icon icon="solar:trash-bin-trash-bold"></iconify-icon>
                        </button>`;
                }
                const removeInput = document.getElementById('removeSocialImageInput');
                if (removeInput) removeInput.value = '0';
            };
            reader.readAsDataURL(input.files[0]);
        }
    };

    window.removeSocialImage = function () {
        const previewBox = document.getElementById('socialPreviewBox');
        if (previewBox) {
            previewBox.innerHTML = `
                <div class="logo-placeholder" id="socialPlaceholder" style="flex-direction: column;">
                    <iconify-icon icon="solar:gallery-add-bold" style="font-size: 2.5rem; margin-bottom: 0.5rem;"></iconify-icon>
                    <span style="font-size: 0.9rem; text-align: center;">O tamanho recomendado para esta imagem é 1200x675px</span>
                </div>`;
        }
        const fileInput = document.getElementById('socialImageInput');
        if (fileInput) fileInput.value = '';

        const removeInput = document.getElementById('removeSocialImageInput');
        if (removeInput) removeInput.value = '1';
    };
});
