<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pengajuan Izin - Sistem Absensi</title>
    <link rel="stylesheet" href="{{ asset('components/popup.css') }}">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: Arial, sans-serif;
            background-color: #f5f5f5;
            width: 100%;
            max-width: 393px;
            min-height: 100vh;
            margin: 0 auto;
            overflow-y: auto;
            padding-bottom: 80px;
        }
        
        @media (min-width: 394px) {
            body {
                box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
            }
        }
        
        /* Header */
        .header {
            background: linear-gradient(135deg, #1ec7e6, #0ea5e9);
            color: white;
            padding: 50px 20px 30px 20px;
            position: sticky;
            top: 0;
            z-index: 10;
        }
        .header-content {
            display: flex;
            align-items: center;
            gap: 15px;
            position: relative;
            z-index: 11;
        }
        .back-btn {
            background: rgba(255, 255, 255, 0.2);
            color: white;
            border: none;
            padding: 10px;
            border-radius: 50%;
            font-size: 18px;
            cursor: pointer;
            width: 40px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
            z-index: 1000;
            position: relative;
            user-select: none;
            -webkit-tap-highlight-color: transparent;
            flex-shrink: 0;
            text-decoration: none;
        }
        .back-btn:hover {
            background: rgba(255, 255, 255, 0.3);
            transform: scale(1.1);
        }
        .back-btn:active {
            transform: scale(0.95);
        }
        .back-btn:focus {
            outline: 2px solid rgba(255, 255, 255, 0.5);
            outline-offset: 2px;
        }
        .header-title {
            flex: 1;
        }
        .header-title h1 {
            font-size: 20px;
            font-weight: 600;
        }
        .header-title p {
            font-size: 14px;
            opacity: 0.8;
            margin-top: 4px;
        }
        
        /* Content */
        .content {
            padding: 20px;
        }
        
        /* Leave Balance Card */
        .balance-card {
            background: white;
            border-radius: 16px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
        }
        .balance-header {
            text-align: center;
            margin-bottom: 16px;
        }
        .balance-title {
            font-size: 16px;
            font-weight: 600;
            color: #333;
            margin-bottom: 8px;
        }
        .balance-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 16px;
        }
        .balance-item {
            text-align: center;
            padding: 12px;
            border-radius: 12px;
            background: #f8fafc;
        }
        .balance-number {
            font-size: 20px;
            font-weight: bold;
            color: #1ec7e6;
            margin-bottom: 4px;
        }
        .balance-label {
            font-size: 12px;
            color: #6b7280;
        }
        
        /* Form Section */
        .form-section {
            background: white;
            border-radius: 16px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
        }
        .section-title {
            font-size: 16px;
            font-weight: 600;
            color: #333;
            margin-bottom: 16px;
        }
        .form-group {
            margin-bottom: 16px;
        }
        .form-label {
            display: block;
            font-size: 14px;
            font-weight: 500;
            color: #374151;
            margin-bottom: 6px;
        }
        .form-input {
            width: 100%;
            padding: 12px 16px;
            border: 1px solid #e5e7eb;
            border-radius: 8px;
            font-size: 14px;
            background: #f9fafb;
            transition: all 0.2s ease;
        }
        .form-input:focus {
            outline: none;
            border-color: #1ec7e6;
            background: white;
            box-shadow: 0 0 0 3px rgba(30, 199, 230, 0.1);
        }
        .form-select {
            width: 100%;
            padding: 12px 16px;
            border: 1px solid #e5e7eb;
            border-radius: 8px;
            font-size: 14px;
            background: white;
            cursor: pointer;
        }
        .form-textarea {
            width: 100%;
            padding: 12px 16px;
            border: 1px solid #e5e7eb;
            border-radius: 8px;
            font-size: 14px;
            background: #f9fafb;
            resize: none;
            height: 80px;
        }
        .date-range {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 12px;
        }
        
        /* Leave Type Cards */
        .leave-types {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 12px;
            margin-bottom: 16px;
        }
        .leave-type {
            padding: 16px;
            border: 2px solid #e5e7eb;
            border-radius: 12px;
            text-align: center;
            cursor: pointer;
            transition: all 0.2s ease;
            background: white;
            user-select: none;
            position: relative;
            min-height: 80px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
        }
        .leave-type:hover {
            border-color: #94a3b8;
            background: #f8fafc;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }
        .leave-type.selected {
            border-color: #1ec7e6;
            background: #f0faff;
            transform: translateY(-2px);
            box-shadow: 0 4px 16px rgba(30, 199, 230, 0.2);
        }
        .leave-type.emergency {
            border: 2px solid #f59e0b;
            background: #fef3c7;
            position: relative;
            animation: pulse-emergency 2s infinite;
        }
        .leave-type.emergency.selected {
            border-color: #d97706;
            background: #fbbf24;
        }
        .leave-type.emergency::after {
            content: "URGENT";
            position: absolute;
            top: -8px;
            right: -8px;
            background: #dc2626;
            color: white;
            font-size: 8px;
            padding: 2px 6px;
            border-radius: 10px;
            font-weight: bold;
        }
        @keyframes pulse-emergency {
            0%, 100% { transform: scale(1); }
            50% { transform: scale(1.02); }
        }
        .leave-type-icon {
            font-size: 24px;
            margin-bottom: 8px;
        }
        .leave-type-name {
            font-size: 14px;
            font-weight: 500;
            color: #333;
        }
        
        /* Submit Button */
        .submit-btn {
            width: 100%;
            background: linear-gradient(135deg, #1ec7e6, #0ea5e9);
            color: white;
            border: none;
            padding: 16px;
            border-radius: 12px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-top: 20px;
            position: relative;
            z-index: 1;
            min-height: 48px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .submit-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(30, 199, 230, 0.4);
            background: linear-gradient(135deg, #0ea5e9, #1ec7e6);
        }
        .submit-btn:active {
            transform: translateY(0);
            box-shadow: 0 2px 8px rgba(30, 199, 230, 0.3);
        }
        .submit-btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }
        
        /* Make sure buttons are clickable */
        .submit-btn, .leave-type {
            pointer-events: auto;
            user-select: none;
        }
        
        /* Upload Area */
        .upload-area {
            border: 2px dashed #d1d5db;
            border-radius: 12px;
            padding: 20px;
            text-align: center;
            background: #f9fafb;
            transition: all 0.3s ease;
            cursor: pointer;
        }
        .upload-area:hover {
            border-color: #1ec7e6;
            background: #f0faff;
        }
        .upload-icon {
            font-size: 32px;
            margin-bottom: 8px;
        }
        .upload-text {
            color: #6b7280;
            font-size: 14px;
        }
        .upload-text strong {
            color: #1ec7e6;
        }
        .file-preview {
            margin-top: 12px;
            padding: 12px;
            background: #f0faff;
            border-radius: 8px;
            border: 1px solid #1ec7e6;
            font-size: 14px;
            color: #0369a1;
        }
        
        /* Admin Notes Section */
        .admin-note-info {
            background: #f0f9ff;
            border-radius: 8px;
            padding: 8px 12px;
            margin-bottom: 8px;
            border-left: 4px solid #1ec7e6;
        }
        
        /* Recent Requests */
        .recent-section {
            background: white;
            border-radius: 16px;
            padding: 20px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
        }
        .request-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 0;
            border-bottom: 1px solid #f3f4f6;
        }
        .request-item:last-child {
            border-bottom: none;
        }
        .request-info h4 {
            font-size: 14px;
            font-weight: 500;
            color: #333;
            margin-bottom: 4px;
        }
        .request-info p {
            font-size: 12px;
            color: #6b7280;
        }
        .request-status {
            padding: 4px 8px;
            border-radius: 8px;
            font-size: 11px;
            font-weight: 500;
        }
        .status-pending {
            background: #fef3c7;
            color: #d97706;
        }
        .status-approved {
            background: #dcfce7;
            color: #16a34a;
        }
        .status-rejected {
            background: #fee2e2;
            color: #dc2626;
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="header-content">
            <a href="{{ route('dashboard') }}" class="back-btn">←</a>
            <div class="header-title">
                <h1>Pengajuan Izin</h1>
                <p>Ajukan cuti dan izin Anda</p>
            </div>
        </div>
    </div>

    <div class="content">
        <!-- Leave Balance -->
        <div class="balance-card">
            <div class="balance-header">
                <h3 class="balance-title">Sisa Cuti Anda Tahun {{ now()->year }}</h3>
            </div>
            <div class="balance-grid">
                <div class="balance-item">
                    <div class="balance-number">{{ $leaveBalance['annual'] }}</div>
                    <div class="balance-label">Cuti Tahunan</div>
                </div>
                <div class="balance-item">
                    <div class="balance-number">{{ $leaveBalance['sick'] }}</div>
                    <div class="balance-label">Cuti Sakit</div>
                </div>
                <div class="balance-item">
                    <div class="balance-number">{{ $leaveBalance['special'] }}</div>
                    <div class="balance-label">Cuti Khusus</div>
                </div>
            </div>
        </div>

        <!-- Leave Request Form -->
        <div class="form-section">
            <h3 class="section-title">Ajukan Izin Baru</h3>
            
            <form id="leaveForm" action="{{ route('complaints.store') }}" method="POST" enctype="multipart/form-data">
                @csrf
                <div class="form-group">
                    <label class="form-label">Jenis Izin</label>
                    <div class="leave-types">
                        <!-- Data attribute diubah menjadi data-category -->
                        <div class="leave-type" data-category="cuti">
                            <div class="leave-type-icon">🏖️</div>
                            <div class="leave-type-name">Cuti Tahunan</div>
                        </div>

                        <div class="leave-type" data-category="sakit">
                            <div class="leave-type-icon">🏥</div>
                            <div class="leave-type-name">Izin Sakit</div>
                        </div>

                        <div class="leave-type emergency" data-category="mendadak">
                            <div class="leave-type-icon">⚡</div>
                            <div class="leave-type-name">Izin Mendadak</div>
                        </div>

                        <div class="leave-type" data-category="keluarga">
                            <div class="leave-type-icon">👨‍👩‍👧‍👦</div>
                            <div class="leave-type-name">Urusan Keluarga</div>
                        </div>

                        <div class="leave-type" data-category="pribadi">
                            <div class="leave-type-icon">👤</div>
                            <div class="leave-type-name">Izin Pribadi</div>
                        </div>

                        <div class="leave-type" data-category="lainnya">
                            <div class="leave-type-icon">📄</div>
                            <div class="leave-type-name">Lainnya</div>
                        </div>
                    </div>

                    <input type="hidden" name="category" id="categoryInput" required>
                </div>

                <div class="form-group">
                    <label class="form-label">Periode Izin</label>
                    <div class="date-range">
                        <input type="date" class="form-input" name="start_date" id="startDate" required>
                        <input type="date" class="form-input" name="end_date" id="endDate" required>
                    </div>
                </div>

                <div class="form-group">
                    <label class="form-label">Judul Pengajuan</label>
                    <input type="text" class="form-input" name="title" id="title" placeholder="Contoh: Cuti Liburan Akhir Tahun" required>
                </div>

                <div class="form-group">
                    <label class="form-label">Alasan Izin</label>
                    <textarea class="form-textarea" name="description" id="reason" placeholder="Jelaskan alasan pengajuan izin Anda..." required></textarea>
                </div>

                <!-- Upload Surat MC & Bukti Pendukung -->
                <div class="form-group" id="uploadSection" style="display: none;">
                    <label class="form-label" id="uploadLabel">Upload Bukti Pendukung</label>
                    <div class="upload-info" id="uploadInfo" style="display: none;"></div>
                    <div class="upload-area">
                        <input type="file" class="form-input" name="attachment" id="attachment" accept="image/*,.pdf,.doc,.docx" style="display: none;">
                        <div class="upload-placeholder" onclick="document.getElementById('attachment').click();">
                            <div class="upload-icon" id="uploadIcon">📎</div>
                            <div class="upload-text" id="uploadText">
                                <strong>Klik untuk upload</strong><br>
                                <small>Foto, PDF, atau dokumen (max 5MB)</small>
                            </div>
                        </div>
                        <div class="file-preview" id="filePreview" style="display: none;"></div>
                    </div>
                </div>

                <!-- Catatan untuk Admin (khusus sakit) -->
                <div class="form-group" id="adminNotesSection" style="display: none;">
                    <label class="form-label">Catatan untuk Admin</label>
                    <div class="admin-note-info">
                        <small style="color: #6b7280; display: block; margin-bottom: 8px;">
                            💡 Informasi ini akan membantu admin memproses pengajuan Anda dengan lebih baik
                        </small>
                    </div>
                    <textarea class="form-textarea" name="admin_notes" id="adminNotes" placeholder="Contoh: Sakit demam tinggi, sudah ke dokter, perlu istirahat 2 hari..." style="min-height: 80px;"></textarea>
                </div>

                <input type="hidden" name="priority" value="medium" id="priorityInput">

                <button type="submit" class="submit-btn" id="submitBtn">Ajukan Izin</button>
            </form>
        </div>

        <!-- Recent Requests -->
        <div class="recent-section">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px;">
                <h3 class="section-title" style="margin:0;">Riwayat Pengajuan</h3>
                <button onclick="location.reload()" style="background:#e5e7eb;border:none;padding:6px 12px;border-radius:6px;font-size:12px;cursor:pointer;">
                    🔄 Refresh
                </button>
            </div>
            
            @if(isset($complaints))
                @if($complaints->count() > 0)
                    <div id="recentRequests">
                        @foreach($complaints as $complaint)
                            <div class="request-item" style="display:block;padding:16px;border-bottom:1px solid #f3f4f6">
                                <div style="display:flex;justify-content:space-between;align-items:start;margin-bottom:8px">
                                    <div class="request-info" style="flex:1">
                                        <h4 style="font-size:15px;font-weight:600;color:#333;margin-bottom:4px">{{ $complaint->title }}</h4>
                                        <p style="font-size:13px;color:#6b7280;margin:0">
                                            {{ ucfirst($complaint->category) }} • {{ $complaint->created_at->format('d M Y H:i') }}
                                        </p>
                                    </div>
                                    @php
                                        $statusClass = 'status-pending';
                                        $statusText = 'Pending';
                                        if($complaint->status == 'approved') {
                                            $statusClass = 'status-approved';
                                            $statusText = 'Disetujui';
                                        } elseif($complaint->status == 'rejected') {
                                            $statusClass = 'status-rejected';
                                            $statusText = 'Ditolak';
                                        }
                                    @endphp
                                    <span class="request-status {{ $statusClass }}" style="margin-left:12px">{{ $statusText }}</span>
                                </div>
                                
                                @if($complaint->response)
                                    <div style="margin-top:12px;padding:12px;background:{{ $complaint->status == 'rejected' ? '#fee2e2' : '#d1fae5' }};border-left:3px solid {{ $complaint->status == 'rejected' ? '#ef4444' : '#10b981' }};border-radius:6px">
                                        <div style="font-size:12px;font-weight:600;color:{{ $complaint->status == 'rejected' ? '#991b1b' : '#065f46' }};margin-bottom:4px">
                                            {{ $complaint->status == 'rejected' ? '❌ Alasan Penolakan:' : '✅ Catatan Admin:' }}
                                        </div>
                                        <div style="font-size:13px;color:#374151">{{ $complaint->response }}</div>
                                        @if($complaint->responded_at)
                                            <div style="font-size:11px;color:#6b7280;margin-top:4px">
                                                {{ $complaint->responded_at->format('d M Y, H:i') }}
                                            </div>
                                        @endif
                                    </div>
                                @endif
                            </div>
                        @endforeach
                    </div>
                @else
                    <div style="text-align: center; padding: 20px; color: #6b7280;">
                        <div style="font-size: 48px; margin-bottom: 16px; opacity: 0.5;">📝</div>
                        <div>Belum ada pengajuan izin</div>
                        <small style="font-size: 12px; margin-top: 8px; display: block;">Ajukan izin pertama Anda di formulir di atas</small>
                    </div>
                @endif
            @else
                <div style="text-align: center; padding: 20px; color: #ff6b6b;">
                    <div style="font-size: 48px; margin-bottom: 16px;">⚠️</div>
                    <div>Data tidak tersedia - Variable $complaints tidak ada</div>
                </div>
            @endif
        </div>
    </div>

    <script src="{{ asset('components/popup.js') }}" onerror="console.error('❌ Failed to load popup.js')"></script>
    <script>
        // Check if popup.js loaded successfully
        console.log('🔍 Checking if popup.js loaded...');
        console.log('smartGoBack available:', typeof smartGoBack !== 'undefined');
        console.log('showErrorPopup available:', typeof showErrorPopup !== 'undefined');
        
        // Fallback functions if popup.js fails to load
        if (typeof smartGoBack === 'undefined') {
            console.log('⚠️ popup.js not loaded, creating fallback smartGoBack');
            window.smartGoBack = function(fallbackUrl) {
                console.log('📍 Fallback smartGoBack called with:', fallbackUrl);
                if (window.history.length > 1 && document.referrer && 
                    document.referrer !== window.location.href &&
                    !document.referrer.includes('login')) {
                    try {
                        console.log('📱 Using history.back()');
                        window.history.back();
                    } catch (error) {
                        console.log('🏠 History.back() failed, redirecting to:', fallbackUrl);
                        window.location.href = fallbackUrl;
                    }
                } else {
                    console.log('🏠 No valid history, redirecting to:', fallbackUrl);
                    window.location.href = fallbackUrl;
                }
            };
        }

        // Fallback popup functions
        if (typeof showErrorPopup === 'undefined') {
            function showErrorPopup(options) {
                alert(options.message || 'Terjadi kesalahan');
            }
        }

        if (typeof showSuccessPopup === 'undefined') {
            function showSuccessPopup(options) {
                alert(options.message || 'Berhasil!');
            }
        }

        if (typeof showInfoPopup === 'undefined') {
            function showInfoPopup(options) {
                alert(options.message || 'Informasi');
            }
        }

        let selectedLeaveType = null;

        function goBack() {
            console.log('🔙 goBack() function called');
            try {
                if (typeof smartGoBack === 'function') {
                    console.log('✅ Using smartGoBack function');
                    smartGoBack('{{ route("dashboard") }}');
                } else {
                    console.log('⚠️ smartGoBack not available, using fallback');
                    // Fallback navigation
                    if (window.history.length > 1 && document.referrer && 
                        document.referrer !== window.location.href &&
                        !document.referrer.includes('login')) {
                        console.log('📱 Going back in history');
                        window.history.back();
                    } else {
                        console.log('🏠 Redirecting to dashboard');
                        window.location.href = '{{ route("dashboard") }}';
                    }
                }
            } catch (error) {
                console.error('❌ Error in goBack():', error);
                // Emergency fallback
                window.location.href = '{{ route("dashboard") }}';
            }
        }

        // Test if page is loading
        console.log('JavaScript is loading...');
        
        // Ensure DOM is loaded before attaching events
        document.addEventListener('DOMContentLoaded', function() {
            console.log('✅ DOM loaded, setting up event listeners');
            
            // Handle leave type selection - PERBAIKAN DI SINI
            const leaveTypes = document.querySelectorAll('.leave-type');
            console.log('✅ Found leave types:', leaveTypes.length);
            
            // Test button clicking
            if (leaveTypes.length > 0) {
                console.log('✅ First leave type category:', leaveTypes[0].dataset.category); // PERUBAHAN: dataset.category
            }
            
            leaveTypes.forEach((type, index) => {
                console.log(`Setting up listener ${index + 1} for category:`, type.dataset.category); // PERUBAHAN
                type.addEventListener('click', function(e) {
                    console.log('🎯 Leave type clicked:', this.dataset.category); // PERUBAHAN
                    console.log('🎯 Event object:', e);
                    
                    // Remove selected class from all
                    leaveTypes.forEach(t => {
                        t.classList.remove('selected');
                        console.log('Removed selected from:', t.dataset.category); // PERUBAHAN
                    });
                    
                    // Add selected class to clicked item
                    this.classList.add('selected');
                    selectedLeaveType = this.dataset.category; // PERUBAHAN
                    console.log('🎯 Set selectedLeaveType to:', selectedLeaveType);
                    
                    // Update hidden input
                    const categoryInput = document.getElementById('categoryInput');
                    if (categoryInput) {
                        categoryInput.value = selectedLeaveType;
                        console.log('🎯 Updated categoryInput to:', categoryInput.value);
                    } else {
                        console.error('❌ categoryInput not found!');
                    }
                    
                    // Special handling for different leave types
                    try {
                        handleLeaveTypeChange(selectedLeaveType);
                        console.log('🎯 handleLeaveTypeChange completed');
                    } catch (error) {
                        console.error('❌ Error in handleLeaveTypeChange:', error);
                    }
                });
                
                // Test if the element is clickable
                type.style.outline = '1px solid transparent';
            });

            // Setup back button event listener as backup
            const backBtn = document.querySelector('.back-btn');
            if (backBtn) {
                console.log('✅ Setting up back button event listener');
                backBtn.addEventListener('click', function(e) {
                    console.log('🔙 Back button clicked via event listener');
                    // Don't prevent default - let onclick also work
                    goBack();
                });
            } else {
                console.error('❌ Back button not found!');
            }
            
            console.log('✅ Event listeners setup complete');
        });

        // Handle different leave types
        function handleLeaveTypeChange(leaveType) {
            const uploadSection = document.getElementById('uploadSection');
            const adminNotesSection = document.getElementById('adminNotesSection');
            const priorityInput = document.getElementById('priorityInput');
            const submitBtn = document.querySelector('.submit-btn');
            const uploadLabel = document.getElementById('uploadLabel');
            const uploadInfo = document.getElementById('uploadInfo');
            const uploadIcon = document.getElementById('uploadIcon');
            const uploadText = document.getElementById('uploadText');
            
            // Reset
            uploadSection.style.display = 'none';
            adminNotesSection.style.display = 'none';
            priorityInput.value = 'medium';
            submitBtn.textContent = 'Ajukan Izin';
            submitBtn.style.background = 'linear-gradient(135deg, #1ec7e6, #0ea5e9)';
            
            switch(leaveType) {
                case 'sakit':
                    uploadSection.style.display = 'block';
                    adminNotesSection.style.display = 'block';
                    uploadLabel.textContent = '📄 Upload Surat MC/Surat Dokter';
                    uploadIcon.textContent = '🏥';
                    uploadText.innerHTML = '<strong>Upload Surat MC/Surat Dokter</strong><br><small>PDF, JPG, PNG (max 5MB) - Wajib untuk verifikasi</small>';
                    uploadInfo.style.display = 'block';
                    uploadInfo.innerHTML = `
                        <div style="background: #fef3c7; border: 1px solid #f59e0b; border-radius: 8px; padding: 12px; margin-bottom: 12px;">
                            <strong style="color: #92400e;">📋 Wajib dilampirkan:</strong>
                            <ul style="margin: 8px 0 0 20px; color: #78716c; font-size: 13px;">
                                <li>Surat Keterangan Dokter (MC)</li>
                                <li>Resep obat (jika ada)</li>
                                <li>Surat rujukan (jika ada)</li>
                            </ul>
                        </div>
                    `;
                    if (typeof showInfoPopup === 'function') {
                        showInfoPopup({
                            title: '🏥 Izin Sakit - Perlu Surat MC',
                            message: 'Untuk izin sakit wajib melampirkan:\n\n📄 Surat Keterangan Dokter (MC)\n💊 Resep obat (jika ada)\n🏥 Surat rujukan (jika perlu)\n\nAdmin akan memverifikasi dokumen untuk pencatatan yang akurat.',
                            buttonText: 'Mengerti'
                        });
                    }
                    break;
                    
                case 'mendadak':
                    uploadSection.style.display = 'block';
                    priorityInput.value = 'high';
                    submitBtn.textContent = '⚡ Ajukan Segera';
                    submitBtn.style.background = 'linear-gradient(135deg, #f59e0b, #d97706)';
                    uploadLabel.textContent = '📎 Upload Bukti Pendukung';
                    uploadIcon.textContent = '⚡';
                    uploadText.innerHTML = '<strong>Upload Bukti Pendukung</strong><br><small>Foto, dokumen, atau bukti lainnya (max 5MB)</small>';
                    uploadInfo.style.display = 'block';
                    uploadInfo.innerHTML = `
                        <div style="background: #fee2e2; border: 1px solid #f87171; border-radius: 8px; padding: 12px; margin-bottom: 12px;">
                            <strong style="color: #dc2626;">⚡ Izin Mendadak:</strong>
                            <ul style="margin: 8px 0 0 20px; color: #7f1d1d; font-size: 13px;">
                                <li>Jelaskan kondisi darurat dengan detail</li>
                                <li>Upload bukti jika memungkinkan (foto, surat, dll)</li>
                                <li>Pengajuan akan diproses prioritas tinggi</li>
                            </ul>
                        </div>
                    `;
                    if (typeof showInfoPopup === 'function') {
                        showInfoPopup({
                            title: '⚡ Izin Mendadak - Prioritas Tinggi',
                            message: 'Untuk izin mendadak:\n\n📝 Berikan alasan yang sangat jelas\n📎 Upload bukti pendukung jika ada\n⚡ Pengajuan akan diprioritaskan\n📬 Notifikasi langsung ke admin/atasan\n\nAdmin akan segera memproses pengajuan ini.',
                            buttonText: 'Mengerti'
                        });
                    }
                    break;
                    
                case 'keluarga':
                    if (typeof showInfoPopup === 'function') {
                        showInfoPopup({
                            title: '👨‍👩‍👧‍👦 Urusan Keluarga',
                            message: 'Untuk urusan keluarga:\n• Jelaskan keperluan keluarga\n• Tentukan durasi yang diperlukan\n• Berikan pemberitahuan sejauh mungkin',
                            buttonText: 'Mengerti'
                        });
                    }
                    break;
                    
                case 'cuti':
                    if (typeof showInfoPopup === 'function') {
                        showInfoPopup({
                            title: '🏖️ Cuti Tahunan',
                            message: 'Anda menggunakan cuti tahunan.\n• Pastikan sisa cuti mencukupi\n• Berikan pemberitahuan minimal 3 hari kerja sebelum tanggal cuti\n• Koordinasikan dengan atasan dan rekan kerja',
                            buttonText: 'Mengerti'
                        });
                    }
                    break;
                    
                case 'pribadi':
                    if (typeof showInfoPopup === 'function') {
                        showInfoPopup({
                            title: '👤 Izin Pribadi',
                            message: 'Untuk keperluan pribadi:\n• Jelaskan keperluan dengan jelas\n• Tentukan durasi yang diperlukan\n• Sesuaikan dengan kebutuhan kerja tim',
                            buttonText: 'Mengerti'
                        });
                    }
                    break;
            }
        }

        // Handle file upload
        const attachmentInput = document.getElementById('attachment');
        if (attachmentInput) {
            attachmentInput.addEventListener('change', function(e) {
                const file = e.target.files[0];
                const preview = document.getElementById('filePreview');
                const placeholder = document.querySelector('.upload-placeholder');
                
                if (file) {
                    // Check file size (5MB limit)
                    if (file.size > 5 * 1024 * 1024) {
                        if (typeof showErrorPopup === 'function') {
                            showErrorPopup({
                                title: 'File Terlalu Besar',
                                message: 'Ukuran file maksimal 5MB. Silakan pilih file yang lebih kecil.',
                                buttonText: 'OK'
                            });
                        }
                        e.target.value = '';
                        return;
                    }
                    
                    if (placeholder) placeholder.style.display = 'none';
                    if (preview) {
                        preview.style.display = 'block';
                        preview.innerHTML = `
                            <div style="display: flex; align-items: center; justify-content: space-between;">
                                <div>
                                    <strong>📎 ${file.name}</strong><br>
                                    <small>${(file.size / 1024).toFixed(1)} KB</small>
                                </div>
                                <button type="button" onclick="removeFile()" style="background: #ef4444; color: white; border: none; padding: 4px 8px; border-radius: 4px; font-size: 12px;">✕</button>
                            </div>
                        `;
                    }
                }
            });
        }

        function removeFile() {
            document.getElementById('attachment').value = '';
            const preview = document.getElementById('filePreview');
            const placeholder = document.querySelector('.upload-placeholder');
            
            if (preview) preview.style.display = 'none';
            if (placeholder) placeholder.style.display = 'block';
        }

        // Handle form submission
        const leaveForm = document.getElementById('leaveForm');
        if (leaveForm) {
            leaveForm.addEventListener('submit', function(e) {
                console.log('Form submitted with selectedLeaveType:', selectedLeaveType);
                
                if (!selectedLeaveType) {
                    e.preventDefault();
                    console.log('No leave type selected, preventing submit');
                    if (typeof showErrorPopup === 'function') {
                        showErrorPopup({
                            title: 'Error',
                            message: 'Silakan pilih jenis izin terlebih dahulu',
                            buttonText: 'OK'
                        });
                    } else {
                        alert('Silakan pilih jenis izin terlebih dahulu');
                    }
                    return;
                }

                // Validasi wajib untuk izin sakit harus ada surat MC
                if (selectedLeaveType === 'sakit') {
                    const attachment = document.getElementById('attachment').files[0];
                    if (!attachment) {
                        e.preventDefault();
                        if (typeof showErrorPopup === 'function') {
                            showErrorPopup({
                                title: '🏥 Surat MC Wajib',
                                message: 'Untuk izin sakit, Anda wajib melampirkan Surat Keterangan Dokter (MC) atau dokumen medis lainnya untuk verifikasi admin.',
                                buttonText: 'OK'
                            });
                        }
                        return;
                    }
                }

                const startDate = document.getElementById('startDate').value;
                const endDate = document.getElementById('endDate').value;

                // Validate date range
                if (new Date(startDate) > new Date(endDate)) {
                    e.preventDefault();
                    if (typeof showErrorPopup === 'function') {
                        showErrorPopup({
                            title: 'Error',
                            message: 'Tanggal mulai tidak boleh lebih besar dari tanggal selesai',
                            buttonText: 'OK'
                        });
                    }
                    return;
                }

                console.log('Form data is valid, proceeding with submission...');
                console.log('Category:', selectedLeaveType);
                console.log('Title:', document.getElementById('title').value);
                console.log('Start Date:', startDate);
                console.log('End Date:', endDate);
            });
        }

        // Set minimum date to today and handle form interactions
        document.addEventListener('DOMContentLoaded', function() {
            const today = new Date().toISOString().split('T')[0];
            const startDate = document.getElementById('startDate');
            const endDate = document.getElementById('endDate');
            
            if (startDate) startDate.min = today;
            if (endDate) endDate.min = today;
            
            // Update end date minimum when start date changes
            if (startDate) {
                startDate.addEventListener('change', function() {
                    if (endDate) endDate.min = this.value;
                });
            }

            // Add click event to submit button for debugging
            const submitBtn = document.getElementById('submitBtn');
            if (submitBtn) {
                submitBtn.addEventListener('click', function(e) {
                    console.log('Submit button clicked!');
                    console.log('Current selectedLeaveType:', selectedLeaveType);
                });
            }

            // Auto-select leave type from URL parameter
            const urlParams = new URLSearchParams(window.location.search);
            const preSelectedType = urlParams.get('type');
            
            if (preSelectedType) {
                const targetLeaveType = document.querySelector(`[data-category="${preSelectedType}"]`);
                if (targetLeaveType) {
                    // Auto-click the specified leave type
                    setTimeout(() => {
                        targetLeaveType.click();
                        // Scroll to form
                        targetLeaveType.scrollIntoView({ behavior: 'smooth', block: 'center' });
                    }, 500);
                }
            }
        });

        // Show session messages
        @if(session('success'))
            if (typeof showSuccessPopup === 'function') {
                showSuccessPopup({
                    title: 'Pengajuan Berhasil!',
                    message: '{{ session('success') }}',
                    buttonText: 'OK'
                });
            }
        @endif

        @if(session('error'))
            if (typeof showErrorPopup === 'function') {
                showErrorPopup({
                    title: 'Error',
                    message: '{{ session('error') }}',
                    buttonText: 'OK'
                });
            }
        @endif
    </script>
</body>
</html>