{# app/modules/core/templates/core/merchant/dashboard.html #}
{% extends "merchant/base.html" %}

{% block title %}Dashboard{% endblock %}

{% block content %}
<div x-data="merchantDashboard()">

    <!-- Welcome -->
    <div class="mb-8 mt-6">
        <h2 class="text-2xl font-bold text-gray-900 dark:text-gray-100">Welcome back<span x-show="merchantName">, <span x-text="merchantName"></span></span></h2>
        <p class="mt-1 text-gray-500 dark:text-gray-400">Here is an overview of your account.</p>
    </div>

    <!-- Quick Stats -->
    <div class="grid gap-6 mb-8 md:grid-cols-4">
        <!-- Active Subscriptions -->
        <div class="flex items-center p-6 bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700">
            <div class="p-3 mr-4 text-purple-600 dark:text-purple-400 bg-purple-100 dark:bg-purple-900/30 rounded-full">
                <span x-html="$icon('clipboard-list', 'w-6 h-6')"></span>
            </div>
            <div>
                <p class="text-sm font-medium text-gray-500 dark:text-gray-400">Active Subscriptions</p>
                <p class="text-2xl font-bold text-gray-900 dark:text-gray-100" x-text="stats.active_subscriptions">--</p>
            </div>
        </div>

        <!-- Total Stores -->
        <div class="flex items-center p-6 bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700">
            <div class="p-3 mr-4 text-green-600 dark:text-green-400 bg-green-100 dark:bg-green-900/30 rounded-full">
                <span x-html="$icon('shopping-bag', 'w-6 h-6')"></span>
            </div>
            <div>
                <p class="text-sm font-medium text-gray-500 dark:text-gray-400">Total Stores</p>
                <p class="text-2xl font-bold text-gray-900 dark:text-gray-100" x-text="stats.total_stores">--</p>
            </div>
        </div>

        <!-- Customers -->
        <div class="flex items-center p-6 bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700">
            <div class="p-3 mr-4 text-blue-600 dark:text-blue-400 bg-blue-100 dark:bg-blue-900/30 rounded-full">
                <span x-html="$icon('users', 'w-6 h-6')"></span>
            </div>
            <div>
                <p class="text-sm font-medium text-gray-500 dark:text-gray-400">Customers</p>
                <p class="text-2xl font-bold text-gray-900 dark:text-gray-100" x-text="stats.total_customers">--</p>
            </div>
        </div>

        <!-- Team Members -->
        <div class="flex items-center p-6 bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700">
            <div class="p-3 mr-4 text-orange-600 dark:text-orange-400 bg-orange-100 dark:bg-orange-900/30 rounded-full">
                <span x-html="$icon('user-group', 'w-6 h-6')"></span>
            </div>
            <div>
                <p class="text-sm font-medium text-gray-500 dark:text-gray-400">Team Members</p>
                <p class="text-2xl font-bold text-gray-900 dark:text-gray-100" x-text="stats.team_members">--</p>
            </div>
        </div>
    </div>

    <!-- Subscription Overview -->
    <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700">
        <div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
            <h3 class="text-lg font-semibold text-gray-900 dark:text-gray-100">Subscription Overview</h3>
        </div>
        <div class="p-6">
            <!-- Loading -->
            <div x-show="loading" class="text-center py-8 text-gray-500 dark:text-gray-400">
                <svg class="inline w-6 h-6 animate-spin mr-2" fill="none" viewBox="0 0 24 24">
                    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                    <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path>
                </svg>
                Loading...
            </div>

            <!-- Subscriptions list -->
            <div x-show="!loading && subscriptions.length > 0" class="space-y-4">
                <template x-for="sub in subscriptions" :key="sub.id">
                    <div class="flex items-center justify-between p-4 border border-gray-100 dark:border-gray-700 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors">
                        <div>
                            <p class="font-semibold text-gray-900 dark:text-gray-100" x-text="sub.platform_name || 'Subscription'"></p>
                            <p class="text-sm text-gray-500 dark:text-gray-400">
                                <span x-text="sub.tier" class="capitalize"></span> &middot;
                                Renews <span x-text="formatDate(sub.period_end)"></span>
                            </p>
                        </div>
                        <span class="px-3 py-1 text-xs font-semibold rounded-full"
                              :class="{
                                  'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400': sub.status === 'active',
                                  'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400': sub.status === 'trial',
                                  'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400': sub.status === 'past_due',
                                  'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400': sub.status === 'cancelled'
                              }"
                              x-text="sub.status.replace('_', ' ')"></span>
                    </div>
                </template>
            </div>

            <!-- Empty state -->
            <div x-show="!loading && subscriptions.length === 0" class="text-center py-8">
                <span x-html="$icon('clipboard-list', 'w-12 h-12 mx-auto mb-3 text-gray-300 dark:text-gray-600')"></span>
                <p class="text-gray-500 dark:text-gray-400">No active subscriptions.</p>
            </div>
        </div>
    </div>

</div>
{% endblock %}

{% block extra_scripts %}
<script>
function merchantDashboard() {
    return {
        loading: true,
        merchantName: '',
        stats: {
            active_subscriptions: '--',
            total_stores: '--',
            total_customers: '--',
            team_members: '--'
        },
        subscriptions: [],

        init() {
            // Get merchant name from parent component
            const token = localStorage.getItem('merchant_token');
            if (token) {
                try {
                    const payload = JSON.parse(atob(token.split('.')[1]));
                    this.merchantName = payload.merchant_name || '';
                } catch (e) {}
            }
            this.loadDashboard();
        },

        async loadDashboard() {
            try {
                const [statsData, subsData] = await Promise.all([
                    apiClient.get('/merchants/core/dashboard/stats'),
                    apiClient.get('/merchants/billing/subscriptions'),
                ]);

                // Stats from the aggregated endpoint
                this.stats.active_subscriptions = statsData.active_subscriptions ?? 0;
                this.stats.total_stores = statsData.total_stores ?? 0;
                this.stats.total_customers = statsData.total_customers ?? 0;
                this.stats.team_members = statsData.team_members ?? 0;

                // Subscriptions list for the overview table
                this.subscriptions = subsData.subscriptions || subsData.items || [];
            } catch (error) {
                console.error('Failed to load dashboard:', error);
            } finally {
                this.loading = false;
            }
        },

        formatDate(dateStr) {
            if (!dateStr) return '-';
            return new Date(dateStr).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' });
        }
    };
}
</script>
{% endblock %}
