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

    // Profile form submission
    // const profileForm = document.getElementById('profileForm');
    // if (profileForm) {
    //     profileForm.addEventListener('submit', async (e) => {
    //         e.preventDefault();
    //         const formData = new FormData(e.target);

    //         try {
    //             const response = await fetch('/company/update-profile', {
    //                 method: 'POST',
    //                 body: formData
    //             });

    //             const data = await response.json();
    //             if (data.success) {
    //                 showNotification('Profile updated successfully', 'success');
    //             } else {
    //                 showNotification(data.error || 'Failed to update profile', 'error');
    //             }
    //         } catch (error) {
    //             showNotification('An error occurred while updating profile', 'error');
    //         }
    //     });
    // }

    // Add to your existing JavaScript
    document.getElementById('profileForm').addEventListener('submit', async (e) => {
        e.preventDefault();

        const formData = new FormData(e.target);

        try {
            const response = await fetch('/company/update-profile', {
                method: 'POST',
                body: formData
            });

            const data = await response.json();
            if (data.success) {
                // alert('Profile updated successfully');
                console.log('sdfssdas');
                
                showNotification('Profile updated successfully!', 'success');
                // location.reload();
            } else {
                // showNotification('Profile updated successfully!', 'success');
                showNotification('rror updating profile: ' +  + data.error, 'error');

                // alert('Error updating profile: ' + data.error);
            }
        } catch (error) {
            console.error('Error:', error);
            alert('Error updating profile');
        }
    });

    // Handle file deletion
    document.querySelectorAll('.delete-file').forEach(button => {
        button.addEventListener('click', async () => {
            if (confirm('Are you sure you want to delete this file?')) {
                const docId = button.dataset.id;
                try {
                    const response = await fetch(`/company/delete-document/${docId}`, {
                        method: 'DELETE'
                    });
                    if (response.ok) {
                        button.parentElement.remove();
                    }
                } catch (error) {
                    console.error('Error:', error);
                }
            }
        });
    });


    // URL Crawler
    const crawlUrlsBtn = document.getElementById('crawlUrlsBtn');
    if (crawlUrlsBtn) {
        crawlUrlsBtn.addEventListener('click', async () => {
            const websiteUrl = document.getElementById('websiteUrl-input').value;
            const companyId = document.getElementById('companyId').value;

            if (!websiteUrl) {
                showNotification('Please enter a website URL', 'error');
                return;
            }

            try {
                const response = await fetch(`/api/${companyId}/refresh-urls`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ websiteUrl })
                });
                const data = await response.json();
                if (data.success) {
                    showNotification('Website URLs crawled successfully!', 'success');
                } else {
                    showNotification(data.error, 'error');
                }
            } catch (error) {
                showNotification('Error crawling URLs: ' + error, 'error');
            }
        });
    }

    // Initialize dropdowns, modals, and other interactive elements
});

function initializeUI() {
    const userProfile = document.querySelector('.user-profile');
    const profileTrigger = userProfile.querySelector('.profile-trigger');

    profileTrigger.addEventListener('click', (e) => {
        e.stopPropagation();
        console.log(profileTrigger);
        
        userProfile.classList.toggle('active');
    });

    // Close profile dropdown when clicking outside
    document.addEventListener('click', () => {
        userProfile.classList.remove('active');
    });

    // Toggle sub-navigation
    document.querySelectorAll('.nav-item').forEach(item => {
        const link = item.querySelector('.nav-link');
        const subNav = item.querySelector('.sub-nav');

        if (subNav) {
            link.addEventListener('click', (e) => {
                e.preventDefault();
                item.classList.toggle('active');
                subNav.classList.toggle('active');
            });
        }
    });

    // Dropdown functionality
    document.querySelectorAll('.custom-dropdown').forEach(dropdown => {
        const trigger = dropdown.querySelector('.dropdown-trigger');
        const menu = dropdown.querySelector('.dropdown-menu');
        const items = dropdown.querySelectorAll('.dropdown-item');
        const triggerText = trigger.querySelector('span');

        trigger.addEventListener('click', () => {
            dropdown.classList.toggle('active');
        });

        items.forEach(item => {
            item.addEventListener('click', () => {
                triggerText.textContent = item.textContent;
                items.forEach(i => i.classList.remove('active'));
                item.classList.add('active');
                dropdown.classList.remove('active');
            });
        });

        // Close dropdown when clicking outside
        document.addEventListener('click', (e) => {
            if (!dropdown.contains(e.target)) {
                dropdown.classList.remove('active');
            }
        });
    });
}

function showNotification(message, type = 'info') {
    // Create toaster container if it doesn't exist
    let toasterContainer = document.getElementById('toaster-container');
    if (!toasterContainer) {
        toasterContainer = document.createElement('div');
        toasterContainer.id = 'toaster-container';
        document.body.appendChild(toasterContainer);
    }

    // Create toast element
    const toast = document.createElement('div');
    toast.className = `toast toast-${type}`;
    toast.innerHTML = `
        <div class="toast-content">
            <span class="toast-message">${message}</span>
        </div>
    `;

    // Add toast to container
    toasterContainer.appendChild(toast);

    // Remove toast after 3 seconds
    setTimeout(() => {
        toast.classList.add('toast-fade-out');
        setTimeout(() => {
            toast.remove();
        }, 300);
    }, 3000);
} 