import './bootstrap';
import Alpine from 'alpinejs';
import collapse from '@alpinejs/collapse';

// Register Alpine plugins
Alpine.plugin(collapse);

// Initialize Alpine.js
window.Alpine = Alpine;
Alpine.start();

// ====================================
// Dark Mode Handler
// ====================================
document.addEventListener('DOMContentLoaded', function() {
    // Check if dark mode preference exists in localStorage
    const darkMode = localStorage.getItem('darkMode') === 'true';
    
    if (darkMode) {
        document.documentElement.classList.add('dark');
    }
});

// ====================================
// Toast Notification System
// ====================================
window.showToast = function(message, type = 'info') {
    const toastContainer = document.getElementById('toast-container') || createToastContainer();
    
    const toast = document.createElement('div');
    toast.className = `toast toast-${type} animate-fadeIn`;
    
    const icons = {
        success: 'fa-check-circle',
        error: 'fa-times-circle',
        warning: 'fa-exclamation-triangle',
        info: 'fa-info-circle'
    };
    
    const colors = {
        success: 'bg-green-500',
        error: 'bg-red-500',
        warning: 'bg-yellow-500',
        info: 'bg-blue-500'
    };
    
    toast.innerHTML = `
        <div class="flex items-center space-x-3 p-4 rounded-lg shadow-lg ${colors[type]} text-white">
            <i class="fas ${icons[type]} text-xl"></i>
            <span class="flex-1">${message}</span>
            <button onclick="this.parentElement.parentElement.remove()" class="hover:bg-white/20 rounded p-1">
                <i class="fas fa-times"></i>
            </button>
        </div>
    `;
    
    toastContainer.appendChild(toast);
    
    // Auto remove after 5 seconds
    setTimeout(() => {
        toast.style.opacity = '0';
        setTimeout(() => toast.remove(), 300);
    }, 5000);
};

function createToastContainer() {
    const container = document.createElement('div');
    container.id = 'toast-container';
    container.className = 'fixed top-4 right-4 z-50 space-y-2';
    document.body.appendChild(container);
    return container;
}

// ====================================
// Confirmation Dialog
// ====================================
window.confirmAction = function(message, callback) {
    if (confirm(message)) {
        callback();
    }
};

// ====================================
// Loading Overlay
// ====================================
window.showLoading = function(message = 'Loading...') {
    const overlay = document.createElement('div');
    overlay.id = 'loading-overlay';
    overlay.className = 'fixed inset-0 bg-black/50 dark:bg-black/70 flex items-center justify-center z-50';
    overlay.innerHTML = `
        <div class="bg-white dark:bg-slate-800 rounded-lg p-6 shadow-xl">
            <div class="flex flex-col items-center space-y-3">
                <div class="spinner"></div>
                <p class="text-gray-700 dark:text-gray-300">${message}</p>
            </div>
        </div>
    `;
    document.body.appendChild(overlay);
};

window.hideLoading = function() {
    const overlay = document.getElementById('loading-overlay');
    if (overlay) {
        overlay.remove();
    }
};

// ====================================
// Form Validation Helper
// ====================================
window.validateForm = function(formId) {
    const form = document.getElementById(formId);
    if (!form) return false;
    
    const inputs = form.querySelectorAll('input[required], textarea[required], select[required]');
    let isValid = true;
    
    inputs.forEach(input => {
        if (!input.value.trim()) {
            input.classList.add('border-red-500');
            isValid = false;
        } else {
            input.classList.remove('border-red-500');
        }
    });
    
    if (!isValid) {
        showToast('Please fill all required fields', 'error');
    }
    
    return isValid;
};

// ====================================
// Auto-hide alerts
// ====================================
document.addEventListener('DOMContentLoaded', function() {
    const alerts = document.querySelectorAll('.alert[data-auto-hide="true"]');
    alerts.forEach(alert => {
        setTimeout(() => {
            alert.style.opacity = '0';
            setTimeout(() => alert.remove(), 300);
        }, 5000);
    });
});

// ====================================
// Table Search Filter
// ====================================
window.filterTable = function(inputId, tableId) {
    const input = document.getElementById(inputId);
    const table = document.getElementById(tableId);
    const filter = input.value.toUpperCase();
    const rows = table.getElementsByTagName('tr');
    
    for (let i = 1; i < rows.length; i++) {
        const row = rows[i];
        const cells = row.getElementsByTagName('td');
        let found = false;
        
        for (let j = 0; j < cells.length; j++) {
            const cell = cells[j];
            if (cell) {
                const textValue = cell.textContent || cell.innerText;
                if (textValue.toUpperCase().indexOf(filter) > -1) {
                    found = true;
                    break;
                }
            }
        }
        
        row.style.display = found ? '' : 'none';
    }
};

// ====================================
// Copy to Clipboard
// ====================================
window.copyToClipboard = function(text) {
    navigator.clipboard.writeText(text).then(() => {
        showToast('Copied to clipboard!', 'success');
    }).catch(() => {
        showToast('Failed to copy', 'error');
    });
};

// ====================================
// Print Function
// ====================================
window.printDiv = function(divId) {
    const printContents = document.getElementById(divId).innerHTML;
    const originalContents = document.body.innerHTML;
    
    document.body.innerHTML = printContents;
    window.print();
    document.body.innerHTML = originalContents;
    location.reload();
};

// ====================================
// Mobile Menu Height Fix (untuk iOS)
// ====================================
function setMobileMenuHeight() {
    const vh = window.innerHeight * 0.01;
    document.documentElement.style.setProperty('--vh', `${vh}px`);
}

window.addEventListener('resize', setMobileMenuHeight);
setMobileMenuHeight();

// ====================================
// Smooth Scroll
// ====================================
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function (e) {
        const href = this.getAttribute('href');
        if (href !== '#' && href !== '#!') {
            e.preventDefault();
            const target = document.querySelector(href);
            if (target) {
                target.scrollIntoView({
                    behavior: 'smooth',
                    block: 'start'
                });
            }
        }
    });
});

// ====================================
// Image Preview
// ====================================
window.previewImage = function(input, previewId) {
    const preview = document.getElementById(previewId);
    const file = input.files[0];
    const reader = new FileReader();
    
    reader.onloadend = function() {
        preview.src = reader.result;
        preview.classList.remove('hidden');
    };
    
    if (file) {
        reader.readAsDataURL(file);
    } else {
        preview.src = '';
        preview.classList.add('hidden');
    }
};

// ====================================
// Auto-save Draft (for forms)
// ====================================
window.enableAutoSave = function(formId, storageKey, interval = 30000) {
    const form = document.getElementById(formId);
    if (!form) return;
    
    // Load saved draft
    const savedData = localStorage.getItem(storageKey);
    if (savedData) {
        const data = JSON.parse(savedData);
        Object.keys(data).forEach(key => {
            const input = form.querySelector(`[name="${key}"]`);
            if (input) input.value = data[key];
        });
    }
    
    // Auto-save
    setInterval(() => {
        const formData = new FormData(form);
        const data = {};
        formData.forEach((value, key) => {
            data[key] = value;
        });
        localStorage.setItem(storageKey, JSON.stringify(data));
    }, interval);
    
    // Clear draft on submit
    form.addEventListener('submit', () => {
        localStorage.removeItem(storageKey);
    });
};

// ====================================
// Keyboard Shortcuts
// ====================================
document.addEventListener('keydown', function(e) {
    // Ctrl/Cmd + K: Focus search (if exists)
    if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
        e.preventDefault();
        const searchInput = document.querySelector('input[type="search"], input[placeholder*="Search"]');
        if (searchInput) searchInput.focus();
    }
    
    // Ctrl/Cmd + /: Toggle dark mode
    if ((e.ctrlKey || e.metaKey) && e.key === '/') {
        e.preventDefault();
        const event = new CustomEvent('toggle-dark-mode');
        window.dispatchEvent(event);
    }
});

// ====================================
// Export Helper Functions
// ====================================
window.KKD = {
    showToast,
    showLoading,
    hideLoading,
    confirmAction,
    validateForm,
    filterTable,
    copyToClipboard,
    printDiv,
    previewImage,
    enableAutoSave
};

console.log('🏥 KKD App Initialized');