<div>
    <div class="container mx-auto flex flex-col lg:flex-row gap-6">

        @if (settings('merchant_status') == \App\Models\Merchant::STATUS_ACTIVE)
            <div class="w-full lg:w-full flex-1">
                <!-- Stats -->
                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
                    @foreach ($stats as $stat)
                        <x-basics.stats-card :title="$stat['title']" :count="$stat['count']" :subtitle="$stat['subtitle']" :color="$stat['color']"
                            :icon="$stat['icon']" :link="$stat['link']" />
                    @endforeach
                </div>

                <!-- Charts -->
                <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8" x-data="pharmacyDashboard()" x-init="init()">

                    <x-basics.card title="Flux financier" subtitle="Ventes et dépenses des 7 derniers jours">
                        <div class="h-80">
                            <canvas id="weeklyFinancialChart"></canvas>
                        </div>
                    </x-basics.card>

                    <x-basics.card title="Méthodes de paiement" subtitle="Répartition des paiements reçus">
                        <div class="h-80">
                            <canvas id="paymentMethodsChart"></canvas>
                        </div>
                    </x-basics.card>
                </div>

                <!-- Recent Sales Table -->
                <div class="bg-white border border-gray-300 rounded overflow-hidden shadow-sm mb-8">
                    <div class="p-4 border-b">
                        <h4 class="font-semibold text-gray-800">Ventes récentes</h4>
                    </div>
                    <div class="overflow-x-auto">
                        @if ($recentSales->count() > 0)
                            <table class="min-w-full text-sm">
                                <thead class="bg-gray-100">
                                    <tr>
                                        <th class="p-3 text-left font-medium text-gray-700 w-10">#</th>
                                        <th class="p-3 text-left font-medium text-gray-700">Numéro de vente</th>
                                        <th class="p-3 text-left font-medium text-gray-700">Montant total</th>
                                        <th class="p-3 text-left font-medium text-gray-700">Méthode de paiement</th>
                                        <th class="p-3 text-left font-medium text-gray-700">Statut</th>
                                        <th class="p-3 text-left font-medium text-gray-700">Date de création</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach ($recentSales as $sale)
                                        <tr class="border-t hover:bg-gray-50">
                                            <td class="px-3 py-2 font-medium">{{ $loop->iteration }}.</td>
                                            <td class="px-3 py-2">
                                                <x-basics.link size="normal" href="{{ route('sales.show', $sale) }}">
                                                    {{ $sale->sale_number ?? 'N/A' }}
                                                </x-basics.link>
                                            </td>
                                            <td class="px-3 py-2 text-gray-900 font-medium">
                                                {{ number_format($sale->total_amount, 0, ',', ' ') }}
                                                {!! \App\Models\Setting::DEFAULT_CURRENCY !!}
                                            </td>
                                            <td class="px-3 py-2 text-gray-600">
                                                {!! $sale->getPaymentMethodBadge() !!}
                                            </td>
                                            <td class="px-3 py-2">
                                                {!! $sale->getStatusBadge() !!}
                                            </td>
                                            <td class="px-3 py-2 text-gray-600">
                                                {{ $sale->created_at->format('d/m/Y H:i') }}
                                            </td>
                                        </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        @else
                            <div class="text-center py-12">
                                <div class="text-gray-500">
                                    <i class="ph ph-receipt text-4xl mb-4"></i>
                                    <p class="text-lg font-medium">Aucune vente trouvée</p>
                                </div>
                            </div>
                        @endif
                    </div>

                    @if ($recentSales->count() > 0)
                        <div class="p-4 border-t bg-gray-50">
                            <div class="flex justify-between items-center">
                                <p class="text-sm text-gray-600">
                                    Affichage des {{ $recentSales->count() }} ventes les plus récentes
                                </p>
                                <x-basics.link href="{{ route('sales.index') }}" size="sm" variant="primary">
                                    <i class="ph ph-list mr-2"></i>
                                    Voir toutes les ventes
                                </x-basics.link>
                            </div>
                        </div>
                    @endif
                </div>

                <!-- Top Products Table -->
                <div class="bg-white border border-gray-300 rounded overflow-hidden shadow mb-8">
                    <div class="p-4 border-b">
                        <h4 class="font-semibold text-gray-800">Liste des produits</h4>
                    </div>
                    <div class="overflow-x-auto">
                        @if ($topProducts->count() > 0)
                            <table class="min-w-full text-sm">
                                <thead class="bg-gray-100">
                                    <tr>
                                        <th class="p-3 text-left font-medium text-gray-700 w-10">#</th>
                                        <th class="p-3 text-left font-medium text-gray-700">Produit</th>
                                        <th class="p-3 text-left font-medium text-gray-700">Catégorie</th>
                                        <th class="p-3 text-left font-medium text-gray-700">Prix de vente</th>
                                        <th class="p-3 text-left font-medium text-gray-700">Stock</th>
                                        <th class="p-3 text-left font-medium text-gray-700">Statut</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach ($topProducts as $product)
                                        <tr class="border-t hover:bg-gray-50">
                                            <td class="px-3 py-2">
                                                {{ $loop->iteration }}.
                                            </td>
                                            <td class="px-3 py-2">
                                                <x-basics.link size=""
                                                    href="{{ route('products.show', $product) }}">{{ $product->name ?? '—' }}</x-basics.link>
                                            </td>

                                            <td class="px-3 py-2 text-gray-600">
                                                {{ $product->category?->name ?? '—' }}
                                            </td>

                                            <td class="px-3 py-2 text-gray-600">
                                                {{ $product->selling_price ? number_format($product->selling_price, 2) . ' CDF' : '—' }}
                                            </td>

                                            <td class="px-3 py-2 text-gray-600">
                                                {!! $product->getStockQuantityBadge() !!}
                                            </td>

                                            <td class="px-3 py-2">
                                                {!! $product->getStatusBadge() !!}
                                            </td>

                                        </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        @else
                            <div class="text-center py-12">
                                <div class="text-gray-500">
                                    <i class="ph ph-package text-4xl mb-4"></i>
                                    <p class="text-lg font-medium">Aucun produit trouvé</p>
                                </div>
                            </div>
                        @endif
                    </div>

                    @if ($topProducts->count() > 0)
                        <div class="p-4 border-t bg-gray-50">
                            <div class="flex justify-between items-center">
                                <p class="text-sm text-gray-600">
                                    Affichage des {{ $topProducts->count() }} produits avec le plus de stock
                                </p>
                                <x-basics.link href="{{ route('products.index') }}" size="sm" variant="primary">
                                    <i class="ph ph-list mr-2"></i>
                                    Voir tous les produits
                                </x-basics.link>
                            </div>
                        </div>
                    @endif
                </div>

                <!-- Recent Prescriptions Table -->
                <livewire:dashboard.latest-prescription-table />
            </div>
        @endif


        @if (settings('merchant_status') == \App\Models\Merchant::STATUS_DRAFT)
            <div class="w-full flex-1">
                <div class="w-full rounded-xl border border-blue-200 bg-gradient-to-br from-blue-50 to-white p-6">
                    <div class="grid grid-cols-1 lg:grid-cols-2 items-stretch gap-6">
                        <!-- Left: Message & CTA -->
                        <div class="flex-1 flex flex-col justify-between h-full">
                            <div class="flex items-start gap-3">
                                <div class="flex-shrink-0">
                                    <span class="inline-flex h-10 w-10 items-center justify-center rounded-full bg-blue-100 text-blue-700">
                                        <i class="ph ph-info text-xl"></i>
                                    </span>
                                </div>
                                <div class="flex-1">
                                    <h3 class="text-base font-semibold text-blue-900">
                                        Établissement en attente d'activation
                                    </h3>
                                    <p class="mt-2 text-sm text-blue-800/90">
                                        Activez votre établissement pour débloquer toutes les fonctionnalités professionnelles
                                        de la plateforme.
                                    </p>
                                    <ul class="mt-4 text-sm text-blue-900 space-y-2">
                                        <li class="flex items-start gap-2"><i class="ph ph-check-circle text-blue-700 mt-0.5"></i> <span>Complétez les informations de votre établissement</span></li>
                                        <li class="flex items-start gap-2"><i class="ph ph-wifi-high text-blue-700 mt-0.5"></i> <span>Vérifiez votre connexion internet</span></li>
                                    </ul>

                                    @php
                                        $settingsData = settings();
                                        $hasInfo = ! empty($settingsData['merchant_name'] ?? null) && ! empty($settingsData['merchant_code'] ?? null);
                                        $hasSubscription = session('active_subscription_id') ? true : false;
                                        $stepsTotal = 3;
                                        $stepsDone = ($hasInfo ? 1 : 0) + ($hasSubscription ? 1 : 0);
                                        $progress = intval(($stepsDone / $stepsTotal) * 100);
                                    @endphp

                                    <div class="mt-5">
                                        <div class="flex items-center justify-between mb-2">
                                            <span class="text-xs font-medium text-blue-900">Progression de l'activation</span>
                                            <span class="text-xs text-blue-900/70">{{ $stepsDone }} / {{ $stepsTotal }}</span>
                                        </div>
                                        <div class="w-full h-2 rounded bg-blue-100 overflow-hidden">
                                            <div class="h-full bg-blue-600" style="width: {{ $progress }}%"></div>
                                        </div>
                                        <div class="mt-3 space-y-2 text-sm">
                                            <div class="flex items-center gap-2">
                                                <i class="ph {{ $hasInfo ? 'ph-check-circle text-emerald-600' : 'ph-circle text-gray-400' }}"></i>
                                                <span class="text-blue-900">Informations d'établissement</span>
                                                @if ($hasInfo)
                                                    <span class="ml-auto text-xs text-emerald-700 bg-emerald-100 px-2 py-0.5 rounded">OK</span>
                                                @else
                                                    <a href="{{ route('merchant.edit') }}" class="ml-auto text-xs text-blue-700 hover:underline">Compléter</a>
                                                @endif
                                            </div>
                                            <div class="flex items-center gap-2">
                                                <i class="ph {{ $hasSubscription ? 'ph-check-circle text-emerald-600' : 'ph-lock-simple text-gray-400' }}"></i>
                                                <span class="text-blue-900">Abonnement actif</span>
                                                @if ($hasSubscription)
                                                    <span class="ml-auto text-xs text-emerald-700 bg-emerald-100 px-2 py-0.5 rounded">Actif</span>
                                                @else
                                                    <a href="{{ url('subscriptions') }}" class="ml-auto text-xs text-blue-700 hover:underline">Activer</a>
                                                @endif
                                            </div>
                                            <div class="flex items-center gap-2">
                                                <i class="ph ph-wifi-high text-blue-600"></i>
                                                <span class="text-blue-900">Connexion internet</span>
                                                <span class="ml-auto text-xs text-blue-700 bg-blue-100 px-2 py-0.5 rounded">À vérifier</span>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="mt-5">
                                        <h4 class="text-xs font-semibold text-blue-900 uppercase tracking-wide">Pourquoi activer ?</h4>
                                        <ul class="mt-2 text-sm text-blue-900/90 space-y-1">
                                            <li class="flex items-start gap-2"><i class="ph ph-lightning text-amber-500 mt-0.5"></i> Accès complet aux modules métiers</li>
                                            <li class="flex items-start gap-2"><i class="ph ph-cloud-check text-blue-600 mt-0.5"></i> Sauvegarde & synchronisation sécurisées</li>
                                            <li class="flex items-start gap-2"><i class="ph ph-chart-line-up text-emerald-600 mt-0.5"></i> Rapports et analyses détaillés</li>
                                        </ul>
                                    </div>
                                </div>
                            </div>

                            <div class="mt-6">
                                <x-basics.button-link href="{{ route('merchant.edit') }}" class="w-full" variant="primary"
                                    icon='<i class="ph ph-play-circle"></i>'>
                                    Activer l'établissement
                                </x-basics.button-link>
                            </div>
                        </div>

                        <!-- Right: Locked features preview -->
                        <div class="flex-1 bg-white/60 backdrop-blur rounded-lg border border-blue-100 p-5 h-full">
                            <h4 class="text-sm font-semibold text-gray-800 mb-4">Fonctionnalités débloquées après activation</h4>
                            <div class="flex flex-col gap-3">
                                @php
                                    $features = [
                                        ['name' => 'Ventes', 'icon' => 'ph ph-shopping-cart', 'desc' => "Créer des ventes, remises, retours et reçus."],
                                        ['name' => 'Clients', 'icon' => 'ph ph-users', 'desc' => "Gérer la clientèle et l'historique des achats."],
                                        ['name' => 'Inventaire', 'icon' => 'ph ph-package', 'desc' => "Suivre les stocks, réceptions et ajustements."],
                                        ['name' => 'Prescriptions', 'icon' => 'ph ph-prescription', 'desc' => "Recevoir, traiter et archiver les ordonnances."],
                                        ['name' => 'Fournisseurs', 'icon' => 'ph ph-truck', 'desc' => "Gérer les fournisseurs et les bons de commande."],
                                        ['name' => 'Rapports', 'icon' => 'ph ph-chart-line-up', 'desc' => "Analyser les performances et indicateurs clés."],
                                    ];
                                @endphp

                                @foreach ($features as $f)
                                    <div class="relative rounded-md border border-gray-200 bg-white p-4 flex items-start gap-3">
                                        <span class="inline-flex h-9 w-9 items-center justify-center rounded-md bg-gray-100 text-gray-700 shrink-0">
                                            <i class="{{ $f['icon'] }} text-lg"></i>
                                        </span>
                                        <div class="flex-1">
                                            <div class="flex items-center justify-between">
                                                <p class="text-sm font-medium text-gray-800">{{ $f['name'] }}</p>
                                                <i class="ph ph-lock-simple text-gray-400"></i>
                                            </div>
                                            <p class="text-xs text-gray-500 mt-1">{{ $f['desc'] }}</p>
                                        </div>
                                    </div>
                                @endforeach
                            </div>

                            <p class="mt-4 text-xs text-gray-500">Astuce: activez votre établissement pour accéder immédiatement à ces modules.</p>
                        </div>
                    </div>
                </div>
            </div>
        @endif


        @if (settings('merchant_status') == \App\Models\Merchant::STATUS_SUSPENDED)
            <div class="w-full lg:w-full flex-1">
                <div class="bg-orange-50 border border-orange-200 rounded-lg p-6">
                    <div class="flex items-start">
                        <div class="flex-shrink-0">
                            <i class="ph ph-warning text-orange-600 text-xl"></i>
                        </div>
                        <div class="ml-3">
                            <h3 class="text-sm font-medium text-orange-800 mb-2">
                                Établissement suspendu
                            </h3>
                            <div class="text-sm text-orange-700 space-y-1">
                                <p>Votre établissement a été temporairement suspendu. Pour le réactiver
                                    :</p>
                                <ul class="list-disc list-inside mt-2 space-y-1">
                                    <li>Complétez les informations manquantes</li>
                                    <li>Vérifiez que votre connexion internet est active</li>
                                    <li>Contactez le support si nécessaire</li>
                                </ul>
                                <p class="mt-3 font-medium">La réactivation peut être effectuée à tout
                                    moment.</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        @endif

    </div>

    @push('scripts')
        @if ($isMerchantActive)
            <script src="{{ asset('plugins/chartjs/chart.min.js') }}"></script>
            <script>
                // Ensure Chart.js is available even when navigating with wire:navigate
                const chartJsUrl = "{{ asset('plugins/chartjs/chart.min.js') }}";

                function loadScriptOnce(url) {
                    return new Promise((resolve, reject) => {
                        if (document.querySelector(`script[src="${url}"]`)) {
                            // If already in DOM but Chart not ready yet, wait for load event once
                            if (window.Chart) {
                                return resolve();
                            }
                        }

                        if (window.__chartJsLoadingPromise) {
                            window.__chartJsLoadingPromise.then(resolve).catch(reject);
                            return;
                        }

                        const script = document.createElement('script');
                        script.src = url;
                        script.async = true;
                        window.__chartJsLoadingPromise = new Promise((res, rej) => {
                            script.onload = () => res();
                            script.onerror = (e) => rej(e);
                        });
                        document.head.appendChild(script);
                        window.__chartJsLoadingPromise.then(resolve).catch(reject);
                    });
                }

                async function ensureChartJs() {
                    if (typeof window.Chart === 'undefined') {
                        await loadScriptOnce(chartJsUrl);
                    }
                }

                function pharmacyDashboard() {
                    return {
                        async init() {
                            // Make sure Chart.js is loaded (wire:navigate may skip script execution)
                            try {
                                await ensureChartJs();
                            } catch (e) {
                                console.error('Failed to load Chart.js:', e);
                                return;
                            }
                            // Simple currency formatter for JavaScript
                            function formatCurrencyJS(amount) {
                                if (amount === null || amount === undefined) {
                                    return '0,00 CDF';
                                }
                                return new Intl.NumberFormat('fr-FR', {
                                    style: 'currency',
                                    currency: 'CDF',
                                    minimumFractionDigits: 2
                                }).format(amount);
                            }

                            try {
                                const weeklyFinancialCanvas = document.getElementById('weeklyFinancialChart');
                                if (!weeklyFinancialCanvas) throw new Error('weeklyFinancialChart canvas not found');
                                const weeklyFinancialCtx = weeklyFinancialCanvas.getContext('2d');
                                // Destroy existing instance if re-initializing after wire:navigate
                                if (window.Chart && typeof Chart.getChart === 'function') {
                                    const existingWeekly = Chart.getChart(weeklyFinancialCanvas);
                                    if (existingWeekly) existingWeekly.destroy();
                                }
                                console.log('Weekly financial chart canvas found:', weeklyFinancialCtx);
                                new Chart(weeklyFinancialCtx, {
                                    type: 'bar',
                                    data: {
                                        labels: @json($weeklyFinancialChart['labels']),
                                        datasets: [{
                                            label: 'Ventes',
                                            data: @json($weeklyFinancialChart['sales_data']),
                                            backgroundColor: 'rgba(16, 185, 129, 0.8)',
                                            borderColor: '#10B981',
                                            borderWidth: 2,
                                            borderRadius: 4,
                                            borderSkipped: false,
                                        }, {
                                            label: 'Dépenses',
                                            data: @json($weeklyFinancialChart['expenses_data']),
                                            backgroundColor: 'rgba(239, 68, 68, 0.8)',
                                            borderColor: '#EF4444',
                                            borderWidth: 2,
                                            borderRadius: 4,
                                            borderSkipped: false,
                                        }]
                                    },
                                    options: {
                                        responsive: true,
                                        maintainAspectRatio: false,
                                        plugins: {
                                            legend: {
                                                display: true,
                                                position: 'top',
                                                labels: {
                                                    usePointStyle: true,
                                                    padding: 20
                                                }
                                            },
                                            tooltip: {
                                                callbacks: {
                                                    label: function(context) {
                                                        return context.dataset.label + ': ' + formatCurrencyJS(context
                                                            .parsed.y);
                                                    }
                                                }
                                            }
                                        },
                                        scales: {
                                            y: {
                                                beginAtZero: true,
                                                ticks: {
                                                    callback: function(value) {
                                                        return formatCurrencyJS(value);
                                                    }
                                                }
                                            },
                                            x: {
                                                display: true,
                                                title: {
                                                    display: true,
                                                    text: 'Derniers 7 jours'
                                                }
                                            }
                                        }
                                    }
                                });
                            } catch (error) {
                                console.error('Error creating weekly financial chart:', error);
                            }

                            try {
                                const paymentMethodsCanvas = document.getElementById('paymentMethodsChart');
                                if (!paymentMethodsCanvas) throw new Error('paymentMethodsChart canvas not found');
                                const paymentMethodsCtx = paymentMethodsCanvas.getContext('2d');
                                // Destroy existing instance if re-initializing after wire:navigate
                                if (window.Chart && typeof Chart.getChart === 'function') {
                                    const existingPayment = Chart.getChart(paymentMethodsCanvas);
                                    if (existingPayment) existingPayment.destroy();
                                }
                                console.log('Payment methods chart canvas found:', paymentMethodsCtx);
                                new Chart(paymentMethodsCtx, {
                                    type: 'doughnut',
                                    data: {
                                        labels: @json($paymentMethodsChart['labels']),
                                        datasets: [{
                                            data: @json($paymentMethodsChart['data']),
                                            backgroundColor: [
                                                '#10B981', // Cash - Green
                                                '#F59E0B', // Debt - Orange  
                                                '#8B5CF6', // Mobile Money - Purple
                                                '#3B82F6', // Card - Blue
                                                '#EF4444', // Transfer - Red
                                                '#06B6D4', // Other - Cyan
                                            ],
                                            borderWidth: 2,
                                            borderColor: '#ffffff'
                                        }]
                                    },
                                    options: {
                                        responsive: true,
                                        maintainAspectRatio: false,
                                        plugins: {
                                            legend: {
                                                position: 'bottom',
                                                labels: {
                                                    fontSize: 12,
                                                    padding: 10,
                                                    usePointStyle: true
                                                }
                                            },
                                            tooltip: {
                                                callbacks: {
                                                    label: function(context) {
                                                        const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                                        const percentage = ((context.parsed / total) * 100).toFixed(1);
                                                        return context.label + ': ' + formatCurrencyJS(context.parsed) +
                                                            ' (' + percentage + '%)';
                                                    }
                                                }
                                            }
                                        }
                                    }
                                });
                            } catch (error) {
                                console.error('Error creating payment methods chart:', error);
                            }
                        }
                    }
                }
                document.addEventListener('alpine:init', () => {
                    Alpine.data('pharmacyDashboard', pharmacyDashboard);
                });

                // Alternative initialization if Alpine.js doesn't work
                document.addEventListener('DOMContentLoaded', () => {
                    setTimeout(() => {
                        if (typeof pharmacyDashboard !== 'undefined') {
                            try {
                                const dashboard = pharmacyDashboard();
                                if (dashboard && typeof dashboard.init === 'function') {
                                    dashboard.init();
                                }
                            } catch (e) {
                                console.error('Fallback init failed:', e);
                            }
                        }
                    }, 100);
                });

                // Re-initialize charts after Livewire wire:navigate navigations
                document.addEventListener('livewire:navigated', () => {
                    try {
                        if (typeof pharmacyDashboard !== 'undefined') {
                            const hasCharts = document.getElementById('weeklyFinancialChart') || document.getElementById('paymentMethodsChart');
                            if (hasCharts) {
                                const dashboard = pharmacyDashboard();
                                if (dashboard && typeof dashboard.init === 'function') {
                                    dashboard.init();
                                }
                            }
                        }
                    } catch (e) {
                        console.error('Re-initializing charts after navigation failed:', e);
                    }
                });
            </script>
        @endif
    @endpush
</div>
