{% extends "client_portal/base.html" %}
{% from "components/ui.html" import page_header %}

{% block title %}{{ _('Client Portal') }} - {{ client.name }}{% endblock %}

{% block content %}
{% set breadcrumbs = [
    {'text': _('Client Portal'), 'url': url_for('client_portal.dashboard')}
] %}

{{ page_header(
    icon_class='fas fa-building',
    title_text=_('Client Portal'),
    subtitle_text=_('Welcome, %(client_name)s', client_name=client.name),
    breadcrumbs=breadcrumbs
) }}

{# Customize dashboard button #}
<div class="mb-4 flex justify-end">
    <button type="button" id="dashboard-customize-btn" class="inline-flex items-center px-4 py-2 rounded-lg border border-border-light dark:border-border-dark bg-card-light dark:bg-card-dark text-text-light dark:text-text-dark hover:bg-background-light dark:hover:bg-background-dark transition-colors text-sm font-medium">
        <i class="fas fa-cog mr-2"></i>{{ _('Customize dashboard') }}
    </button>
</div>

{# Widget area: render only widgets in widget_ids, in widget_order; else default layout #}
{% set widget_ids_set = widget_ids | default([]) | list %}
{% set order = widget_order | default(widget_ids) | default([]) | list %}
{% if not order %}
    {% set order = ['stats', 'pending_actions', 'projects', 'invoices', 'time_entries'] %}
{% endif %}

<div id="dashboard-widgets">
{% if widget_ids_set %}
    {% for w in order %}
        {% if w in widget_ids_set %}
            {% if w == 'stats' %}
                {% include 'client_portal/widgets/stats.html' %}
            {% elif w == 'pending_actions' %}
                {% include 'client_portal/widgets/pending_actions.html' %}
            {% elif w == 'projects' %}
                {% include 'client_portal/widgets/projects.html' %}
            {% elif w == 'invoices' %}
                {% include 'client_portal/widgets/invoices.html' %}
            {% elif w == 'time_entries' %}
                {% include 'client_portal/widgets/time_entries.html' %}
            {% endif %}
        {% endif %}
    {% endfor %}
{% else %}
    {# Default: show all widgets in default order when no preferences saved #}
    {% include 'client_portal/widgets/stats.html' %}
    {% include 'client_portal/widgets/pending_actions.html' %}
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
        {% include 'client_portal/widgets/projects.html' %}
        {% include 'client_portal/widgets/invoices.html' %}
    </div>
    {% include 'client_portal/widgets/time_entries.html' %}
{% endif %}
</div>

{# Customize dashboard modal #}
<div id="dashboard-customize-modal" class="fixed inset-0 z-50 hidden overflow-y-auto" aria-labelledby="modal-title" role="dialog" aria-modal="true">
    <div class="flex items-center justify-center min-h-screen px-4 pt-4 pb-20 text-center sm:p-0">
        <div class="fixed inset-0 bg-gray-500/75 dark:bg-gray-900/75 transition-opacity" aria-hidden="true" id="dashboard-customize-backdrop"></div>
        <div class="relative inline-block align-bottom bg-card-light dark:bg-card-dark rounded-xl text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full border border-border-light dark:border-border-dark">
            <div class="px-6 py-4">
                <h3 class="text-lg font-bold text-text-light dark:text-text-dark" id="modal-title">{{ _('Customize dashboard') }}</h3>
                <p class="mt-1 text-sm text-text-muted-light dark:text-text-muted-dark">{{ _('Choose which widgets to show and their order.') }}</p>
                <div class="mt-4 space-y-3" id="dashboard-widget-checkboxes">
                    {% for w in ['stats', 'pending_actions', 'projects', 'invoices', 'time_entries'] %}
                    <label class="flex items-center space-x-3 cursor-pointer p-2 rounded-lg hover:bg-background-light dark:hover:bg-background-dark">
                        <input type="checkbox" class="dashboard-widget-cb rounded border-border-light dark:border-border-dark text-primary focus:ring-primary" value="{{ w }}" {% if w in widget_ids_set %}checked{% endif %}>
                        <span class="text-text-light dark:text-text-dark">
                            {% if w == 'stats' %}{{ _('Statistics cards') }}
                            {% elif w == 'pending_actions' %}{{ _('Pending actions') }}
                            {% elif w == 'projects' %}{{ _('Projects') }}
                            {% elif w == 'invoices' %}{{ _('Recent invoices') }}
                            {% elif w == 'time_entries' %}{{ _('Recent time entries') }}
                            {% else %}{{ w }}{% endif %}
                        </span>
                    </label>
                    {% endfor %}
                </div>
                <div id="dashboard-customize-error" class="mt-2 text-sm text-red-600 dark:text-red-400 hidden"></div>
            </div>
            <div class="px-6 py-4 bg-background-light dark:bg-background-dark flex flex-col-reverse sm:flex-row sm:justify-end gap-2">
                <button type="button" id="dashboard-customize-cancel" class="inline-flex justify-center px-4 py-2 rounded-lg border border-border-light dark:border-border-dark bg-card-light dark:bg-card-dark text-text-light dark:text-text-dark hover:bg-opacity-80 text-sm font-medium">
                    {{ _('Cancel') }}
                </button>
                <button type="button" id="dashboard-customize-save" class="inline-flex justify-center px-4 py-2 rounded-lg bg-primary text-white hover:opacity-90 text-sm font-medium">
                    {{ _('Save') }}
                </button>
            </div>
        </div>
    </div>
</div>

<script>
(function() {
    var modal = document.getElementById('dashboard-customize-modal');
    var backdrop = document.getElementById('dashboard-customize-backdrop');
    var btn = document.getElementById('dashboard-customize-btn');
    var cancelBtn = document.getElementById('dashboard-customize-cancel');
    var saveBtn = document.getElementById('dashboard-customize-save');
    var errorEl = document.getElementById('dashboard-customize-error');
    var prefsUrl = '{{ url_for("client_portal.dashboard_preferences_post") }}';

    function openModal() {
        modal.classList.remove('hidden');
        document.body.style.overflow = 'hidden';
    }
    function closeModal() {
        modal.classList.add('hidden');
        document.body.style.overflow = '';
        errorEl.classList.add('hidden');
    }

    if (btn) btn.addEventListener('click', openModal);
    if (cancelBtn) cancelBtn.addEventListener('click', closeModal);
    if (backdrop) backdrop.addEventListener('click', closeModal);

    if (saveBtn) {
        saveBtn.addEventListener('click', function() {
            var checkboxes = document.querySelectorAll('.dashboard-widget-cb:checked');
            var widgetIds = Array.from(checkboxes).map(function(cb) { return cb.value; });
            if (widgetIds.length === 0) {
                errorEl.textContent = '{{ _("Select at least one widget.") }}';
                errorEl.classList.remove('hidden');
                return;
            }
            errorEl.classList.add('hidden');
            saveBtn.disabled = true;
            saveBtn.setAttribute('aria-busy', 'true');
            var saveBtnOrigText = saveBtn.textContent;
            saveBtn.textContent = '{{ _("Saving...") }}';
            fetch(prefsUrl, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest' },
                body: JSON.stringify({ widget_ids: widgetIds, widget_order: widgetIds })
            }).then(function(r) {
                return r.json().then(function(data) {
                    if (!r.ok) throw new Error(data.error || 'Save failed');
                    closeModal();
                    window.location.reload();
                });
            }).catch(function(err) {
                errorEl.textContent = err.message || '{{ _("Failed to save.") }}';
                errorEl.classList.remove('hidden');
            }).finally(function() {
                saveBtn.disabled = false;
                saveBtn.removeAttribute('aria-busy');
                saveBtn.textContent = saveBtnOrigText;
            });
        });
    }
})();
</script>
{% endblock %}
