{% extends "base.html" %}
{% from "components/cards.html" import info_card %}
{% from "components/ui.html" import page_header, breadcrumb_nav, button, filter_badge %}

{% block content %}
{% set breadcrumbs = [
    {'text': _('Reports')}
] %}

{{ page_header(
    icon_class='fas fa-chart-bar',
    title_text=_('Reports'),
    subtitle_text=_('View comprehensive reports and analytics for your time tracking data'),
    breadcrumbs=breadcrumbs,
    actions_html=None
) }}

{% if current_user.is_authenticated and current_user.ui_show_donate and not is_license_activated %}
<p class="text-sm text-text-muted-light dark:text-text-muted-dark mb-4">
    {{ _('Enjoying TimeTracker?') }} {{ _('Support development or get a supporter license — the app stays free for everyone.') }}
    <button type="button" class="text-primary hover:underline font-medium js-open-support-modal">{{ _('Open support') }}</button>
</p>
{% endif %}

<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-6">
    {{ info_card(_("Total Hours"), "%.2f"|format(summary.total_hours), _("All time")) }}
    {{ info_card(_("Billable Hours"), "%.2f"|format(summary.billable_hours), _("All time")) }}
    {{ info_card(_("Active Projects"), summary.active_projects, _("Currently active")) }}
    {{ info_card(_("Active Users"), summary.total_users, _("Currently active")) }}
</div>

<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-6">
    <div class="bg-card-light dark:bg-card-dark p-6 rounded-xl border border-border-light dark:border-border-dark shadow-sm">
        <div class="flex items-center justify-between mb-2">
            <i class="fas fa-money-bill-wave text-green-600 text-xl"></i>
        </div>
        <div class="text-2xl font-semibold text-green-600">{{ currency|currency_symbol }}{{ "%.2f"|format(summary.total_payments) }}</div>
        <div class="text-xs text-text-muted-light dark:text-text-muted-dark">{{ _('Total Payments') }}</div>
        <div class="text-[11px] text-text-muted-light dark:text-text-muted-dark">{{ _('Last 30 days') }}</div>
    </div>
    <div class="bg-card-light dark:bg-card-dark p-6 rounded-xl border border-border-light dark:border-border-dark shadow-sm">
        <div class="flex items-center justify-between mb-2">
            <i class="fas fa-receipt text-blue-600 text-xl"></i>
        </div>
        <div class="text-2xl font-semibold text-blue-600">{{ summary.payment_count }}</div>
        <div class="text-xs text-text-muted-light dark:text-text-muted-dark">{{ _('Payments Received') }}</div>
        <div class="text-[11px] text-text-muted-light dark:text-text-muted-dark">{{ _('Last 30 days') }}</div>
    </div>
    <div class="bg-card-light dark:bg-card-dark p-6 rounded-xl border border-border-light dark:border-border-dark shadow-sm">
        <div class="flex items-center justify-between mb-2">
            <i class="fas fa-credit-card text-amber-600 text-xl"></i>
        </div>
        <div class="text-2xl font-semibold text-amber-600">{{ currency|currency_symbol }}{{ "%.2f"|format(summary.payment_fees) }}</div>
        <div class="text-xs text-text-muted-light dark:text-text-muted-dark">{{ _('Gateway Fees') }}</div>
        <div class="text-[11px] text-text-muted-light dark:text-text-muted-dark">{{ _('Last 30 days') }}</div>
    </div>
    <div class="bg-card-light dark:bg-card-dark p-6 rounded-xl border border-border-light dark:border-border-dark shadow-sm">
        <div class="flex items-center justify-between mb-2">
            <i class="fas fa-chart-line text-emerald-600 text-xl"></i>
        </div>
        <div class="text-2xl font-semibold text-emerald-600">{{ currency|currency_symbol }}{{ "%.2f"|format(summary.total_payments - summary.payment_fees) }}</div>
        <div class="text-xs text-text-muted-light dark:text-text-muted-dark">{{ _('Net Received') }}</div>
        <div class="text-[11px] text-text-muted-light dark:text-text-muted-dark">{{ _('After fees') }}</div>
    </div>
</div>

<!-- Date Range Presets and Comparison View -->
<div class="bg-card-light dark:bg-card-dark p-6 rounded-xl border border-border-light dark:border-border-dark shadow-sm mb-6">
    <h2 class="text-lg font-semibold mb-4">{{ _('Date Range & Comparison') }}</h2>
    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
        <!-- Date Range Presets -->
        <div>
            <h3 class="text-sm font-medium text-text-muted-light dark:text-text-muted-dark mb-3">{{ _('Quick Date Ranges') }}</h3>
            <div class="flex flex-wrap gap-2">
                <button type="button" onclick="setDateRange('today')" class="date-preset-btn px-4 py-2 min-h-[44px] rounded-lg text-sm bg-background-light dark:bg-background-dark hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors">
                    <i class="fas fa-calendar-day mr-1"></i>{{ _('Today') }}
                </button>
                <button type="button" onclick="setDateRange('week')" class="date-preset-btn px-4 py-2 min-h-[44px] rounded-lg text-sm bg-background-light dark:bg-background-dark hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors">
                    <i class="fas fa-calendar-week mr-1"></i>{{ _('This Week') }}
                </button>
                <button type="button" onclick="setDateRange('month')" class="date-preset-btn px-4 py-2 min-h-[44px] rounded-lg text-sm bg-background-light dark:bg-background-dark hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors">
                    <i class="fas fa-calendar-alt mr-1"></i>{{ _('This Month') }}
                </button>
                <button type="button" onclick="setDateRange('year')" class="date-preset-btn px-4 py-2 min-h-[44px] rounded-lg text-sm bg-background-light dark:bg-background-dark hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors">
                    <i class="fas fa-calendar mr-1"></i>{{ _('This Year') }}
                </button>
            </div>
            <div class="mt-3">
                <label class="form-label">{{ _('Custom Range') }}</label>
                <div class="flex gap-2">
                    <input type="date" id="startDate" class="form-input user-date-input flex-1">
                    <input type="date" id="endDate" class="form-input user-date-input flex-1">
                    <button type="button" onclick="applyCustomDateRange()" class="btn btn-primary">
                        {{ _('Apply') }}
                    </button>
                </div>
            </div>
        </div>
        
        <!-- Comparison View -->
        <div>
            <h3 class="text-sm font-medium text-text-muted-light dark:text-text-muted-dark mb-3">{{ _('Comparison View') }}</h3>
            <div class="space-y-3">
                <a href="{{ url_for('reports.week_in_review') }}" class="block w-full px-4 py-3 rounded-lg text-left bg-background-light dark:bg-background-dark hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors no-underline">
                    <div class="flex items-center justify-between">
                        <div>
                            <div class="font-medium text-text-light dark:text-text-dark">{{ _('Week in Review') }}</div>
                            <div class="text-xs text-text-muted-light dark:text-text-muted-dark">{{ _('This week\'s hours, top projects, billable vs non-billable') }}</div>
                        </div>
                        <i class="fas fa-chevron-right text-text-muted-light dark:text-text-muted-dark"></i>
                    </div>
                </a>
                <button type="button" onclick="showComparisonView('month')" class="w-full px-4 py-3 rounded-lg text-left bg-background-light dark:bg-background-dark hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors">
                    <div class="flex items-center justify-between">
                        <div>
                            <div class="font-medium text-text-light dark:text-text-dark">{{ _('This Month vs Last Month') }}</div>
                            <div class="text-xs text-text-muted-light dark:text-text-muted-dark">{{ _('Compare current month with previous month') }}</div>
                        </div>
                        <i class="fas fa-chevron-right text-text-muted-light dark:text-text-muted-dark"></i>
                    </div>
                </button>
                <button type="button" onclick="showComparisonView('year')" class="w-full px-4 py-3 rounded-lg text-left bg-background-light dark:bg-background-dark hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors">
                    <div class="flex items-center justify-between">
                        <div>
                            <div class="font-medium text-text-light dark:text-text-dark">{{ _('This Year vs Last Year') }}</div>
                            <div class="text-xs text-text-muted-light dark:text-text-muted-dark">{{ _('Compare current year with previous year') }}</div>
                        </div>
                        <i class="fas fa-chevron-right text-text-muted-light dark:text-text-muted-dark"></i>
                    </div>
                </button>
            </div>
        </div>
    </div>
    
    <!-- Comparison Results (hidden by default) -->
    <div id="comparisonResults" class="hidden mt-6 p-4 bg-background-light dark:bg-background-dark rounded-lg">
        <h3 class="text-md font-semibold mb-4">{{ _('Comparison Results') }}</h3>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4" id="comparisonStats">
            <!-- Comparison stats will be loaded here -->
        </div>
    </div>
</div>

<!-- Export Format Selection -->
<div class="bg-card-light dark:bg-card-dark p-6 rounded-xl border border-border-light dark:border-border-dark shadow-sm mb-6">
    <h2 class="text-lg font-semibold mb-4">{{ _('Export Reports') }}</h2>
    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
        <div class="p-4 border border-border-light dark:border-border-dark rounded-lg">
            <h3 class="font-medium mb-2">{{ _('Export Format') }}</h3>
            <select id="exportFormat" class="form-input w-full mb-3">
                <option value="csv">CSV</option>
                <option value="excel">Excel</option>
            </select>
            <button type="button" onclick="exportReport()" class="btn btn-primary w-full">
                <i class="fas fa-download mr-2"></i>{{ _('Export Report') }}
            </button>
        </div>
        <div class="p-4 border border-border-light dark:border-border-dark rounded-lg">
            <h3 class="font-medium mb-2">{{ _('Scheduled Reports') }}</h3>
            <p class="text-sm text-text-muted-light dark:text-text-muted-dark mb-3">Set up automatic report generation</p>
            <button type="button" onclick="showScheduledReportsModal()" class="w-full bg-secondary text-white px-4 py-2 rounded-lg hover:bg-indigo-700 transition-colors">
                <i class="fas fa-clock mr-2"></i>{{ _('Manage Scheduled Reports') }}
            </button>
        </div>
        <div class="p-4 border border-border-light dark:border-border-dark rounded-lg">
            <h3 class="font-medium mb-2">{{ _('Quick Actions') }}</h3>
            <div class="space-y-2">
                <a href="{{ url_for('reports.export_form', format='csv') }}" class="btn btn-secondary block w-full text-center">
                    <i class="fas fa-file-csv mr-2"></i>{{ _('CSV Export') }}
                </a>
                <a href="{{ url_for('reports.export_form', format='excel') }}" class="block w-full bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700 transition-colors text-center">
                    <i class="fas fa-file-excel mr-2"></i>{{ _('Excel Export') }}
                </a>
            </div>
        </div>
    </div>
</div>

<div class="bg-card-light dark:bg-card-dark p-6 rounded-xl border border-border-light dark:border-border-dark shadow-sm mb-6">
    <h2 class="text-lg font-semibold mb-4">{{ _('Report Types') }}</h2>
    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
        <a href="{{ url_for('reports.project_report') }}" class="bg-primary text-white p-4 rounded-lg text-center hover:bg-primary/90 transition-colors">
            <i class="fas fa-project-diagram mr-2"></i>{{ _('Project Report') }}
        </a>
        <a href="{{ url_for('reports.user_report') }}" class="bg-primary text-white p-4 rounded-lg text-center hover:bg-primary/90 transition-colors">
            <i class="fas fa-users mr-2"></i>{{ _('User Report') }}
        </a>
        <a href="{{ url_for('reports.summary_report') }}" class="bg-primary text-white p-4 rounded-lg text-center hover:bg-primary/90 transition-colors">
            <i class="fas fa-chart-bar mr-2"></i>{{ _('Summary Report') }}
        </a>
        <a href="{{ url_for('reports.task_report') }}" class="bg-primary text-white p-4 rounded-lg text-center hover:bg-primary/90 transition-colors">
            <i class="fas fa-tasks mr-2"></i>{{ _('Task Report') }}
        </a>
        <a href="{{ url_for('reports.time_entries_report') }}" class="bg-primary text-white p-4 rounded-lg text-center hover:bg-primary/90 transition-colors">
            <i class="fas fa-list-alt mr-2"></i>{{ _('Time Entries Report') }}
        </a>
        <a href="{{ url_for('reports.unpaid_hours_report') }}" class="bg-primary text-white p-4 rounded-lg text-center hover:bg-primary/90 transition-colors">
            <i class="fas fa-money-bill-wave mr-2"></i>{{ _('Unpaid Hours Report') }}
        </a>
        <a href="{{ url_for('custom_reports.report_builder') }}" class="bg-secondary text-white p-4 rounded-lg text-center hover:bg-secondary/90 transition-colors">
            <i class="fas fa-magic mr-2"></i>{{ _('Report Builder') }}
        </a>
    </div>
</div>

<div class="bg-card-light dark:bg-card-dark p-6 rounded-xl border border-border-light dark:border-border-dark shadow-sm mb-6">
    <h2 class="text-lg font-semibold mb-4">{{ _('Report Management') }}</h2>
    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
        <a href="{{ url_for('custom_reports.list_saved_views') }}" class="bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-gray-200 p-4 rounded-lg text-center hover:bg-gray-300 dark:hover:bg-gray-600 transition-colors">
            <i class="fas fa-save mr-2"></i>{{ _('Saved Report Views') }}
            <p class="text-sm mt-2 text-gray-600 dark:text-gray-400">{{ _('View and manage your saved report configurations') }}</p>
        </a>
        <a href="{{ url_for('scheduled_reports.list_scheduled') }}" class="bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-gray-200 p-4 rounded-lg text-center hover:bg-gray-300 dark:hover:bg-gray-600 transition-colors">
            <i class="fas fa-clock mr-2"></i>{{ _('Scheduled Reports') }}
            <p class="text-sm mt-2 text-gray-600 dark:text-gray-400">{{ _('Manage automated report delivery via email') }}</p>
        </a>
    </div>
</div>

<div class="bg-card-light dark:bg-card-dark p-6 rounded-xl border border-border-light dark:border-border-dark shadow-sm">
    <h2 class="text-lg font-semibold mb-4">{{ _('Recent Entries') }}</h2>
    <table class="w-full text-left responsive-cards">
        <thead>
            <tr>
                <th class="p-2">{{ _('Project') }}</th>
                <th class="p-2">{{ _('Duration') }}</th>
                <th class="p-2">{{ _('Date') }}</th>
            </tr>
        </thead>
        <tbody>
            {% for entry in recent_entries %}
            <tr class="border-b border-border-light dark:border-border-dark">
                <td class="p-2" data-label="{{ _('Project') }}">{{ entry.project.name }}</td>
                <td class="p-2" data-label="{{ _('Duration') }}">{{ entry.duration }}</td>
                <td class="p-2" data-label="{{ _('Date') }}">{{ entry.start_time|user_date }}</td>
            </tr>
            {% else %}
            <tr>
                <td colspan="3" class="p-8">
                    <div class="flex flex-col items-center justify-center text-center py-4">
                        <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-gray-100 dark:bg-gray-800 mb-3">
                            <i class="fas fa-inbox text-2xl text-text-muted-light dark:text-text-muted-dark"></i>
                        </div>
                        <p class="text-text-muted-light dark:text-text-muted-dark font-medium mb-1">{{ _('No recent entries.') }}</p>
                        <p class="text-sm text-text-muted-light dark:text-text-muted-dark mb-3">{{ _('Start tracking time to see entries here.') }}</p>
                        <a href="{{ url_for('timer.manual_entry') }}" class="btn btn-primary">
                            <i class="fas fa-play"></i>{{ _('Log Time') }}
                        </a>
                    </div>
                </td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
</div>

<!-- Scheduled Reports Modal -->
<div id="scheduledReportsModal" class="hidden fixed inset-0 z-50 flex items-center justify-center bg-black/50">
    <div class="bg-card-light dark:bg-card-dark rounded-lg shadow-xl max-w-2xl w-full mx-4 max-h-[90vh] overflow-y-auto">
        <div class="p-6">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-lg font-semibold">{{ _('Scheduled Reports') }}</h3>
                <button type="button" onclick="hideScheduledReportsModal()" class="text-text-muted-light dark:text-text-muted-dark hover:text-text-light dark:hover:text-text-dark">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div id="scheduledReportsList" class="space-y-3">
                <!-- Scheduled reports will be loaded here -->
                <p class="text-text-muted-light dark:text-text-muted-dark text-center py-4">{{ _('No scheduled reports yet.') }}</p>
            </div>
            <div class="mt-6 pt-4 border-t border-border-light dark:border-border-dark">
                <button type="button" onclick="showAddScheduledReportForm()" class="btn btn-primary w-full">
                    <i class="fas fa-plus mr-2"></i>{{ _('Add Scheduled Report') }}
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts_extra %}
<script>
// Date range presets
function setDateRange(preset) {
    const today = new Date();
    let startDate, endDate;
    
    switch(preset) {
        case 'today':
            startDate = endDate = today;
            break;
        case 'week':
            const dayOfWeek = today.getDay();
            const diff = today.getDate() - dayOfWeek + (dayOfWeek === 0 ? -6 : 1);
            startDate = new Date(today);
            startDate.setDate(diff);
            endDate = new Date(today);
            break;
        case 'month':
            startDate = new Date(today.getFullYear(), today.getMonth(), 1);
            endDate = new Date(today);
            break;
        case 'year':
            startDate = new Date(today.getFullYear(), 0, 1);
            endDate = new Date(today);
            break;
    }
    
    document.getElementById('startDate').value = startDate.toISOString().split('T')[0];
    document.getElementById('endDate').value = endDate.toISOString().split('T')[0];
    
    // Apply to current report
    applyCustomDateRange();
}

function applyCustomDateRange() {
    const startDate = document.getElementById('startDate').value;
    const endDate = document.getElementById('endDate').value;
    
    if (startDate && endDate) {
        // Redirect to project report with date range
        window.location.href = `{{ url_for('reports.project_report') }}?start_date=${startDate}&end_date=${endDate}`;
    }
}

// Comparison view
function showComparisonView(period) {
    fetch(`/reports/comparison?period=${period}`)
        .then(response => response.json())
        .then(data => {
            const resultsDiv = document.getElementById('comparisonResults');
            const statsDiv = document.getElementById('comparisonStats');
            
            statsDiv.innerHTML = `
                <div class="text-center">
                    <div class="text-2xl font-bold text-primary">${data.current.hours.toFixed(1)}</div>
                    <div class="text-sm text-text-muted-light dark:text-text-muted-dark">Current Period Hours</div>
                </div>
                <div class="text-center">
                    <div class="text-2xl font-bold ${data.change >= 0 ? 'text-green-600' : 'text-red-600'}">
                        ${data.change >= 0 ? '+' : ''}${data.change.toFixed(1)}%
                    </div>
                    <div class="text-sm text-text-muted-light dark:text-text-muted-dark">Change</div>
                </div>
                <div class="text-center">
                    <div class="text-2xl font-bold text-text-light dark:text-text-dark">${data.previous.hours.toFixed(1)}</div>
                    <div class="text-sm text-text-muted-light dark:text-text-muted-dark">Previous Period Hours</div>
                </div>
            `;
            
            resultsDiv.classList.remove('hidden');
        })
        .catch(error => {
            console.error('Error loading comparison:', error);
            alert('Failed to load comparison data');
        });
}

// Export report
function exportReport() {
    const format = document.getElementById('exportFormat').value;
    const startDate = document.getElementById('startDate').value;
    const endDate = document.getElementById('endDate').value;

    if (!startDate || !endDate) {
        alert('{{ _("Please set a date range") }}');
        return;
    }

    let url = '';
    if (format === 'csv') {
        url = `{{ url_for('reports.export_csv') }}`;
    } else if (format === 'excel') {
        url = `{{ url_for('reports.export_excel') }}`;
    }

    url += `?start_date=${startDate}&end_date=${endDate}`;
    window.location.href = url;
}

// Scheduled reports
function showScheduledReportsModal() {
    document.getElementById('scheduledReportsModal').classList.remove('hidden');
    loadScheduledReports();
}

function hideScheduledReportsModal() {
    document.getElementById('scheduledReportsModal').classList.add('hidden');
}

function loadScheduledReports() {
    const listContainer = document.getElementById('scheduledReportsList');
    listContainer.innerHTML = '<p class="text-text-muted-light dark:text-text-muted-dark text-center py-4">Loading...</p>';
    
    fetch('/api/reports/scheduled')
        .then(response => response.json())
        .then(data => {
            if (data.schedules && data.schedules.length > 0) {
                listContainer.innerHTML = data.schedules.map(schedule => {
                    const nextRun = schedule.next_run_at ? new Date(schedule.next_run_at).toLocaleString() : 'Not scheduled';
                    const lastRun = schedule.last_run_at ? new Date(schedule.last_run_at).toLocaleString() : 'Never';
                    const statusBadge = schedule.active 
                        ? '<span class="px-2 py-1 bg-green-100 dark:bg-green-900 text-green-800 dark:text-green-200 rounded text-xs">Active</span>'
                        : '<span class="px-2 py-1 bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-300 rounded text-xs">Inactive</span>';
                    
                    return `
                        <div class="p-4 border border-border-light dark:border-border-dark rounded-lg">
                            <div class="flex justify-between items-start mb-2">
                                <div class="flex-1">
                                    <h4 class="font-semibold">${escapeHtml(schedule.saved_view_name || 'Unknown Report')}</h4>
                                    <p class="text-sm text-text-muted-light dark:text-text-muted-dark">
                                        <i class="fas fa-clock mr-1"></i>${schedule.cadence}
                                        <span class="mx-2">•</span>
                                        <i class="fas fa-envelope mr-1"></i>${schedule.recipients.split(',').length} recipient(s)
                                    </p>
                                </div>
                                ${statusBadge}
                            </div>
                            <div class="text-xs text-text-muted-light dark:text-text-muted-dark mt-2">
                                <div><strong>Next run:</strong> ${nextRun}</div>
                                <div><strong>Last run:</strong> ${lastRun}</div>
                            </div>
                            <div class="flex gap-2 mt-3">
                                <button onclick="toggleSchedule(${schedule.id}, ${!schedule.active})" class="text-sm px-3 py-1 rounded bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600">
                                    ${schedule.active ? 'Deactivate' : 'Activate'}
                                </button>
                                <button onclick="deleteSchedule(${schedule.id})" class="text-sm px-3 py-1 rounded bg-red-600 text-white hover:bg-red-700">
                                    Delete
                                </button>
                            </div>
                        </div>
                    `;
                }).join('');
            } else {
                listContainer.innerHTML = '<p class="text-text-muted-light dark:text-text-muted-dark text-center py-4">{{ _('No scheduled reports yet.') }}</p>';
            }
        })
        .catch(error => {
            console.error('Error loading scheduled reports:', error);
            listContainer.innerHTML = '<p class="text-red-600 dark:text-red-400 text-center py-4">Failed to load scheduled reports.</p>';
        });
}

function showAddScheduledReportForm() {
    // Load saved views first
    fetch('/api/reports/saved-views')
        .then(response => response.json())
        .then(data => {
            const savedViews = data.saved_views || [];
            if (savedViews.length === 0) {
                alert('{{ _("You need to create a saved report view first. Please create one from the reports page.") }}');
                return;
            }
            
            // Create form modal
            const formModal = document.createElement('div');
            formModal.id = 'addScheduledReportForm';
            formModal.className = 'fixed inset-0 z-50 flex items-center justify-center bg-black/50';
            formModal.innerHTML = `
                <div class="bg-card-light dark:bg-card-dark rounded-lg shadow-xl max-w-md w-full mx-4">
                    <div class="p-6">
                        <div class="flex justify-between items-center mb-4">
                            <h3 class="text-lg font-semibold">{{ _('Schedule Report') }}</h3>
                            <button type="button" onclick="closeAddScheduledReportForm()" class="text-text-muted-light dark:text-text-muted-dark hover:text-text-light dark:hover:text-text-dark">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                        <form id="newScheduledReportForm" onsubmit="createScheduledReport(event)">
                            <div class="mb-4">
                                <label class="block text-sm font-medium mb-2">{{ _('Report View') }}</label>
                                <select id="savedViewId" name="saved_view_id" class="form-input w-full" required>
                                    <option value="">{{ _('Select a report view...') }}</option>
                                    ${savedViews.map(sv => `<option value="${sv.id}">${escapeHtml(sv.name)}</option>`).join('')}
                                </select>
                            </div>
                            <div class="mb-4">
                                <label class="block text-sm font-medium mb-2">{{ _('Recipients') }}</label>
                                <input type="email" id="recipients" name="recipients" class="form-input w-full" 
                                       placeholder="email1@example.com, email2@example.com" required>
                                <p class="text-xs text-text-muted-light dark:text-text-muted-dark mt-1">{{ _('Comma-separated email addresses') }}</p>
                            </div>
                            <div class="mb-4">
                                <label class="block text-sm font-medium mb-2">{{ _('Frequency') }}</label>
                                <select id="cadence" name="cadence" class="form-input w-full" required>
                                    <option value="daily">{{ _('Daily') }}</option>
                                    <option value="weekly">{{ _('Weekly') }}</option>
                                    <option value="monthly">{{ _('Monthly') }}</option>
                                </select>
                            </div>
                            <div class="flex gap-2">
                                <button type="button" onclick="closeAddScheduledReportForm()" class="btn btn-secondary flex-1">
                                    {{ _('Cancel') }}
                                </button>
                                <button type="submit" class="btn btn-primary flex-1">
                                    {{ _('Create Schedule') }}
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            `;
            document.body.appendChild(formModal);
        })
        .catch(error => {
            console.error('Error loading saved views:', error);
            alert('{{ _("Failed to load report views") }}');
        });
}

function closeAddScheduledReportForm() {
    const formModal = document.getElementById('addScheduledReportForm');
    if (formModal) formModal.remove();
}

function createScheduledReport(event) {
    event.preventDefault();
    const form = event.target;
    const formData = {
        saved_view_id: parseInt(document.getElementById('savedViewId').value),
        recipients: document.getElementById('recipients').value.trim(),
        cadence: document.getElementById('cadence').value,
    };
    
    const submitBtn = form.querySelector('button[type="submit"]');
    const originalText = submitBtn.innerHTML;
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>{{ _("Creating...") }}';
    
    fetch('/api/reports/scheduled', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': '{{ csrf_token() }}'
        },
        body: JSON.stringify(formData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            closeAddScheduledReportForm();
            loadScheduledReports();
            if (window.showToast) {
                window.showToast('{{ _("Scheduled report created successfully") }}', 'success');
            }
        } else {
            alert(data.error || '{{ _("Failed to create scheduled report") }}');
            submitBtn.disabled = false;
            submitBtn.innerHTML = originalText;
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('{{ _("Failed to create scheduled report") }}');
        submitBtn.disabled = false;
        submitBtn.innerHTML = originalText;
    });
}

function toggleSchedule(scheduleId, newActive) {
    fetch(`/api/reports/scheduled/${scheduleId}/toggle`, {
        method: 'POST',
        headers: {
            'X-CSRFToken': '{{ csrf_token() }}'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            loadScheduledReports();
        } else {
            alert(data.error || '{{ _("Failed to update schedule") }}');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('{{ _("Failed to update schedule") }}');
    });
}

function deleteSchedule(scheduleId) {
    if (!confirm('{{ _("Are you sure you want to delete this scheduled report?") }}')) {
        return;
    }
    
    fetch(`/api/reports/scheduled/${scheduleId}`, {
        method: 'DELETE',
        headers: {
            'X-CSRFToken': '{{ csrf_token() }}'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            loadScheduledReports();
            if (window.showToast) {
                window.showToast('{{ _("Scheduled report deleted successfully") }}', 'success');
            }
        } else {
            alert(data.error || '{{ _("Failed to delete scheduled report") }}');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('{{ _("Failed to delete scheduled report") }}');
    });
}

function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// Initialize date inputs
document.addEventListener('DOMContentLoaded', function() {
    const today = new Date();
    const weekStart = new Date(today);
    weekStart.setDate(today.getDate() - today.getDay());
    
    document.getElementById('startDate').value = weekStart.toISOString().split('T')[0];
    document.getElementById('endDate').value = today.toISOString().split('T')[0];
});
</script>
{% endblock %}
