@php
    $salesGrowthHint = ($salesGrowth ?? 0) > 0
        ? '+'.number_format($salesGrowth, 1).'% vs LM'
        : (($salesGrowth ?? 0) < 0
            ? number_format($salesGrowth, 1).'% vs LM'
            : 'Flat vs LM');
@endphp

<div class="grid gap-2 grid-cols-2 md:grid-cols-4 xl:grid-cols-8">
    <x-ui.stat-card compact tone="primary" label="Today Sales" :value="'₹'.number_format($todaySales, 0)" :hint="$todayOrders.' orders'" icon="bi bi-cart-check" />
    <x-ui.stat-card compact tone="warning" label="Placed" :value="(string) ($pendingOrders ?? 0)" hint="Needs attention" icon="bi bi-clock-history" />
    <x-ui.stat-card compact tone="primary" label="Revenue MTD" :value="'₹'.number_format($monthSales, 0)" :hint="$salesGrowthHint" icon="bi bi-cash-coin" />
    <x-ui.stat-card compact tone="danger" label="Low Stock" :value="(string) ($lowStockProducts ?? 0)" hint="At this store" icon="bi bi-box-seam" />
    @isset($todayProfitData)
    <x-ui.stat-card
        compact
        tone="success"
        label="Today Profit"
        :value="'₹'.number_format($todayProfitData['total_profit'] ?? 0, 0)"
        :hint="(($todayProfitData['profit_margin_percent'] ?? 0) > 0)
            ? number_format($todayProfitData['profit_margin_percent'] ?? 0, 1).'% margin'
            : 'No data'"
        icon="bi bi-graph-up-arrow"
    />
    @endisset
    <x-ui.stat-card
        compact
        tone="success"
        label="Month Profit"
        :value="'₹'.number_format($monthProfitData['total_profit'] ?? 0, 0)"
        :hint="(($monthProfitData['profit_margin_percent'] ?? 0) > 0)
            ? number_format($monthProfitData['profit_margin_percent'] ?? 0, 1).'% margin'
            : 'Add costs'"
        icon="bi bi-trophy"
    />
    <x-ui.stat-card compact tone="info" label="POS today" :value="(string) ($todayPosOrders ?? 0)" hint="Walk-in" icon="bi bi-shop-window" />
    <x-ui.stat-card compact tone="muted" label="Incoming" :value="(string) ($incomingTransfers ?? 0)" hint="Transfers in" icon="bi bi-truck" />
</div>

<div class="grid gap-2 grid-cols-2 md:grid-cols-4">
    <x-ui.stat-card compact tone="muted" label="Total Revenue" :value="'₹'.number_format($totalRevenue, 0)" :hint="$totalOrders.' orders'" icon="bi bi-cash-stack" />
    <x-ui.stat-card compact tone="danger" label="Total COGS" :value="'₹'.number_format($totalProfitData['total_cogs'] ?? 0, 0)" hint="Cost of goods" icon="bi bi-box" />
    <x-ui.stat-card compact tone="success" label="Total Profit" :value="'₹'.number_format($totalProfitData['total_profit'] ?? 0, 0)" :hint="(($totalProfitData['profit_margin_percent'] ?? 0) > 0) ? number_format($totalProfitData['profit_margin_percent'], 1).'% margin' : '—'" icon="bi bi-graph-up-arrow" />
    <x-ui.stat-card compact tone="primary" label="Avg Order" :value="'₹'.number_format($avgOrderValue, 0)" hint="Per paid order" icon="bi bi-calculator" />
</div>

@if(($purchasePriceCoverage ?? 100) < 100)
@canany(['dashboard.view-kpis', 'dashboard.view-dashlets', 'reports.profit'])
<div class="dash-panel">
    <div class="dash-panel__body flex flex-wrap items-center justify-between gap-2 py-2">
        <p class="mb-0 text-xs text-[var(--color-text)]">
            <i class="bi bi-exclamation-triangle text-amber-600"></i>
            <strong>Purchase price coverage {{ $purchasePriceCoverage }}%</strong>
            — {{ $productsMissingPurchasePrice }} products missing costs
        </p>
        <a href="{{ route('admin.reports.missing-purchase-price') }}" class="tw-btn-primary text-[11px] px-2.5 py-1">
            Add prices
        </a>
    </div>
</div>
@endcanany
@endif

<div class="grid gap-2 lg:grid-cols-12">
    <div class="lg:col-span-8">
        <x-admin.chart-card compact title="Revenue & Profit Trend" canvas-id="businessChart">
            <div class="mt-2 flex flex-wrap gap-1.5">
                <button type="button" class="btn btn-outline-primary btn-sm active" onclick="switchChart('7')">7D</button>
                <button type="button" class="btn btn-outline-primary btn-sm" onclick="switchChart('30')">30D</button>
            </div>
        </x-admin.chart-card>
    </div>
    <div class="lg:col-span-4">
        <div class="dash-panel h-full">
            <div class="dash-panel__head">
                <h3 class="dash-panel__title">Quick Actions</h3>
            </div>
            <div class="dash-panel__body space-y-3">
                <div class="dash-actions">
                    @can('pos_access')
                        <a href="{{ route('admin.pos.index') }}" target="_blank" class="dash-action"><i class="bi bi-cash-stack"></i> Open POS</a>
                    @endcan
                    <a href="{{ route('admin.orders.index') }}?status=placed" class="dash-action"><i class="bi bi-receipt"></i> Manage orders</a>
                    @can('transfers.view')
                        <a href="{{ route('admin.transfers.index') }}" class="dash-action"><i class="bi bi-arrow-left-right"></i>Stock Transfers</a>
                    @endcan
                    @if(($lowStockProducts ?? 0) > 0)
                        <a href="{{ route('admin.products.restock') }}" class="dash-action"><i class="bi bi-exclamation-triangle"></i> Restock ({{ $lowStockProducts }})</a>
                    @endif
                </div>
                <div>
                    <p class="mb-1.5 text-[10px] font-semibold uppercase tracking-wide text-[var(--color-text-muted)]">Alerts</p>
                    @if(($pendingOrders ?? 0) > 0)
                        <div class="dash-alert dash-alert--warn"><i class="bi bi-clock"></i> {{ $pendingOrders }} pending orders</div>
                    @endif
                    @if(($incomingTransfers ?? 0) > 0)
                        <div class="dash-alert dash-alert--info"><i class="bi bi-truck"></i> {{ $incomingTransfers }} incoming transfers</div>
                    @endif
                    @if(($lowStockProducts ?? 0) > 0)
                        <div class="dash-alert dash-alert--danger"><i class="bi bi-box"></i> {{ $lowStockProducts }} low stock items</div>
                    @endif
                    @if(($pendingOrders ?? 0) < 1 && ($lowStockProducts ?? 0) < 1 && ($incomingTransfers ?? 0) < 1)
                        <p class="mb-0 text-[11px] text-[var(--color-text-muted)]">All clear</p>
                    @endif
                </div>
            </div>
        </div>
    </div>
</div>

@can('reports.salesman')
<div class="space-y-2">
    <div class="flex flex-col sm:flex-row sm:flex-wrap sm:items-end gap-2">
        <div class="btn-group btn-group-sm w-full sm:w-auto" role="group" id="salesmanPeriodGroup">
            <button type="button" class="btn btn-outline-primary" data-period="day">Day</button>
            <button type="button" class="btn btn-outline-primary active" data-period="week">Week</button>
            <button type="button" class="btn btn-outline-primary" data-period="month">Month</button>
            <button type="button" class="btn btn-outline-primary" data-period="year">Year</button>
            <button type="button" class="btn btn-outline-primary" data-period="custom">Custom</button>
        </div>
        <div id="salesmanCustomRange" class="d-none d-flex align-items-end gap-2 flex-wrap w-full sm:w-auto">
            <div class="flex-1 sm:flex-none">
                <label class="form-label small mb-0">Start</label>
                <input type="date" id="salesmanStartDate" class="form-control form-control-sm w-full" style="max-width: 160px;">
            </div>
            <div class="flex-1 sm:flex-none">
                <label class="form-label small mb-0">End</label>
                <input type="date" id="salesmanEndDate" class="form-control form-control-sm w-full" style="max-width: 160px;">
            </div>
            <button type="button" class="btn btn-sm btn-primary" id="salesmanApplyCustom">Apply</button>
        </div>
        <a href="{{ route('admin.reports.salesman') }}" class="btn btn-sm btn-outline-secondary w-full sm:w-auto text-center">Full report</a>
    </div>
    <x-admin.chart-card compact title="Salesman Performance (POS)" canvas-id="salesmanChart">
        <div id="salesmanChartEmpty" class="text-center py-4 text-muted d-none">
            <i class="bi bi-graph-up text-xl"></i>
            <p class="mb-0 mt-1 text-xs">No POS sales for this period.</p>
        </div>
    </x-admin.chart-card>
</div>
@endcan

<div class="grid gap-2 lg:grid-cols-2">
    <div class="dash-panel">
        <div class="dash-panel__head">
            <h3 class="dash-panel__title">Top profitable · 30 days</h3>
            <a href="{{ route('admin.reports.profit') }}" class="text-[10px] font-medium text-[var(--color-primary)] no-underline">Report</a>
        </div>
        <div class="dash-panel__body p-0">
            @if(isset($topProfitableProducts['most_profitable']) && $topProfitableProducts['most_profitable']->count() > 0)
                <div class="overflow-x-auto">
                    <table class="dash-table">
                        <thead>
                            <tr>
                                <th>Product</th>
                                <th>Sold</th>
                                <th>Profit</th>
                                <th>Margin</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($topProfitableProducts['most_profitable'] as $item)
                                <tr>
                                    <td>
                                        <div class="font-medium text-[var(--color-text)]">{{ \Illuminate\Support\Str::limit($item['product_name'] ?? 'Unknown', 28) }}</div>
                                        <div class="text-[10px] text-[var(--color-text-muted)]">{{ $item['sku'] ?? 'N/A' }}</div>
                                    </td>
                                    <td><span class="dash-chip">{{ $item['units_sold'] ?? 0 }}</span></td>
                                    <td class="font-semibold text-emerald-700">₹{{ number_format($item['gross_profit'] ?? 0, 0) }}</td>
                                    <td><span class="dash-chip dash-chip--ok">{{ number_format($item['margin_percent'] ?? 0, 1) }}%</span></td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
            @else
                <p class="mb-0 px-3 py-4 text-center text-xs text-[var(--color-text-muted)]">No profit data yet</p>
            @endif
        </div>
    </div>

    <div class="dash-panel">
        <div class="dash-panel__head">
            <h3 class="dash-panel__title">Top selling · 30 days</h3>
        </div>
        <div class="dash-panel__body p-0">
            @if(isset($topProducts) && $topProducts->count() > 0)
                <div class="overflow-x-auto">
                    <table class="dash-table">
                        <thead>
                            <tr>
                                <th>Product</th>
                                <th>Sold</th>
                                <th>Revenue</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($topProducts as $item)
                                <tr>
                                    <td>{{ \Illuminate\Support\Str::limit($item->product->name ?? 'N/A', 30) }}</td>
                                    <td class="font-semibold">{{ $item->total_sold }}</td>
                                    <td>₹{{ number_format($item->total_revenue, 0) }}</td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
            @else
                <p class="mb-0 px-3 py-4 text-center text-xs text-[var(--color-text-muted)]">No sales data available</p>
            @endif
        </div>
    </div>
</div>

@push('scripts')
<script src="{{ asset('js/vendor/chart.umd.min.js') }}"></script>
<script>
let businessChart = null;
const businessCtx = document.getElementById('businessChart');
const revenueData7 = @json($revenueData ?? []);
const revenueData30 = @json($monthlyRevenueData ?? []);
const profitTrendData = @json($profitTrendData ?? []);

function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
}

function createBusinessChart(days) {
    if (!businessCtx || typeof Chart === 'undefined') return;
    try {
        if (businessChart) businessChart.destroy();
        const rev7 = Array.isArray(revenueData7) ? revenueData7 : [];
        const rev30 = Array.isArray(revenueData30) ? revenueData30 : [];
        const profitArr = Array.isArray(profitTrendData) ? profitTrendData : [];
        const revenueData = days === '7' ? rev7 : rev30;
        const profitData = days === '7' ? (profitArr.length ? profitArr.slice(-7) : []) : profitArr;
        if (revenueData.length === 0 && profitData.length === 0) return;

        const allDates = new Set();
        revenueData.forEach(d => allDates.add(d.date));
        profitData.forEach(d => allDates.add(d.date));
        const sortedDates = Array.from(allDates).sort();
        const revenueMap = new Map(revenueData.map(d => [d.date, d]));
        const profitMap = new Map(profitData.map(d => [d.date, d]));
        const labels = sortedDates.map(date => formatDate(date));
        const revenueValues = sortedDates.map(date => parseFloat((revenueMap.get(date) || {}).revenue || 0));
        const profitValues = sortedDates.map(date => parseFloat((profitMap.get(date) || {}).profit || 0));
        const cogsValues = sortedDates.map(date => parseFloat((profitMap.get(date) || {}).cogs || 0));

        businessChart = new Chart(businessCtx, {
            type: 'line',
            data: {
                labels,
                datasets: [
                    { label: 'Revenue (₹)', data: revenueValues, borderColor: 'rgb(59, 130, 246)', backgroundColor: 'rgba(59, 130, 246, 0.1)', tension: 0.4, fill: false },
                    { label: 'Profit (₹)', data: profitValues, borderColor: 'rgb(16, 185, 129)', backgroundColor: 'rgba(16, 185, 129, 0.1)', tension: 0.4, fill: false },
                    { label: 'COGS (₹)', data: cogsValues, borderColor: 'rgb(239, 68, 68)', backgroundColor: 'rgba(239, 68, 68, 0.1)', tension: 0.4, fill: false }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: { legend: { display: true, position: 'top', labels: { boxWidth: 10, font: { size: 10 } } } },
                scales: {
                    y: { beginAtZero: true, ticks: { callback: (v) => '₹' + Number(v).toLocaleString('en-IN') } },
                    x: { grid: { display: false } }
                }
            }
        });
    } catch (e) { console.error(e); }
}

function switchChart(days) {
    document.querySelectorAll('.btn-group button, .btn-outline-primary.btn-sm').forEach(btn => btn.classList.remove('active'));
    if (typeof event !== 'undefined' && event?.target) event.target.classList.add('active');
    createBusinessChart(days);
}

const salesmanChartUrl = @json(route('admin.dashboard.salesman-chart-data'));
const dashboardLocationId = @json($locationId ?? 'all');
let salesmanChartInstance = null;

function renderSalesmanChart(res) {
    const canvas = document.getElementById('salesmanChart');
    const emptyEl = document.getElementById('salesmanChartEmpty');
    if (!canvas) return;
    if (!res || !res.datasets || res.datasets.length === 0) {
        if (emptyEl) emptyEl.classList.remove('d-none');
        return;
    }
    if (emptyEl) emptyEl.classList.add('d-none');
    if (salesmanChartInstance) salesmanChartInstance.destroy();
    salesmanChartInstance = new Chart(canvas, {
        type: 'line',
        data: {
            labels: res.labels || [],
            datasets: (res.datasets || []).map(d => ({
                label: d.staff_name,
                data: d.data || [],
                borderColor: d.borderColor || 'rgb(59, 130, 246)',
                backgroundColor: d.backgroundColor || 'rgba(59, 130, 246, 0.1)',
                tension: 0.35,
                fill: false
            }))
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: { legend: { display: true, position: 'top', labels: { boxWidth: 10, font: { size: 10 } } } },
            scales: {
                y: { beginAtZero: true, ticks: { callback: (v) => '₹' + Number(v).toLocaleString('en-IN') } },
                x: { grid: { display: false } }
            }
        }
    });
}

function loadSalesmanChart(period, startDate, endDate) {
    const params = new URLSearchParams({ period: period || 'week' });
    if (startDate) params.set('start_date', startDate);
    if (endDate) params.set('end_date', endDate);
    if (dashboardLocationId !== null && dashboardLocationId !== undefined) {
        params.set('location_id', dashboardLocationId);
    }
    fetch(salesmanChartUrl + '?' + params.toString(), {
        headers: { 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json' }
    })
        .then(r => r.json())
        .then(renderSalesmanChart)
        .catch(() => renderSalesmanChart(null));
}

document.addEventListener('DOMContentLoaded', function () {
    if (businessCtx) createBusinessChart('7');
    const group = document.getElementById('salesmanPeriodGroup');
    if (!group) return;
    const customRange = document.getElementById('salesmanCustomRange');
    const startInput = document.getElementById('salesmanStartDate');
    const endInput = document.getElementById('salesmanEndDate');
    const applyBtn = document.getElementById('salesmanApplyCustom');
    const today = new Date();
    const weekAgo = new Date(today);
    weekAgo.setDate(weekAgo.getDate() - 6);
    if (startInput) startInput.value = weekAgo.toISOString().slice(0, 10);
    if (endInput) endInput.value = today.toISOString().slice(0, 10);
    group.querySelectorAll('[data-period]').forEach(btn => {
        btn.addEventListener('click', function () {
            const period = this.getAttribute('data-period');
            group.querySelectorAll('[data-period]').forEach(b => b.classList.remove('active'));
            this.classList.add('active');
            if (period === 'custom') {
                if (customRange) customRange.classList.remove('d-none');
                if (startInput && endInput) loadSalesmanChart('custom', startInput.value, endInput.value);
            } else {
                if (customRange) customRange.classList.add('d-none');
                loadSalesmanChart(period);
            }
        });
    });
    if (applyBtn && startInput && endInput) {
        applyBtn.addEventListener('click', () => loadSalesmanChart('custom', startInput.value, endInput.value));
    }
    loadSalesmanChart('week');
});
</script>
@endpush
