<x-filament-panels::page>
    @php
        $report = $this->report;
        $format = fn (float $amount): string => 'PKR ' . number_format($amount, 2);
        $pct = fn (float $amount): string => ($report['total_revenue'] ?? 0) > 0
            ? number_format(($amount / $report['total_revenue']) * 100, 1) . '%'
            : '—';
        $netProfit = (float) ($report['net_profit'] ?? 0);
        $isProfit = $netProfit >= 0;
        $accent = $this->getPanelAccent();
        $margin = $this->getMarginPercent();
        $expenseRatio = $this->getExpenseRatioPercent();
        $brand = filament()->getBrandName();
        $panelId = filament()->getId();
    @endphp

    <style>
        .pl-report { --pl-accent: {{ $accent }}; }
        .pl-kpi {
            position: relative;
            overflow: hidden;
            border-radius: 1rem;
            border: 1px solid rgb(226 232 240);
            background: #fff;
            padding: 1.25rem 1.5rem;
            box-shadow: 0 1px 3px rgba(15, 23, 42, 0.06);
            transition: box-shadow .2s ease, transform .2s ease;
        }
        .dark .pl-kpi {
            border-color: rgb(51 65 85);
            background: rgb(15 23 42);
        }
        .pl-kpi:hover { box-shadow: 0 8px 24px rgba(15, 23, 42, 0.08); transform: translateY(-1px); }
        .pl-kpi::before {
            content: '';
            position: absolute;
            top: 0; left: 0; right: 0;
            height: 3px;
            background: var(--pl-kpi-accent, var(--pl-accent));
        }
        .pl-kpi-icon {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 2.5rem;
            height: 2.5rem;
            border-radius: 0.75rem;
            background: color-mix(in srgb, var(--pl-kpi-accent, var(--pl-accent)) 12%, transparent);
            color: var(--pl-kpi-accent, var(--pl-accent));
        }
        .pl-doc-header {
            background: linear-gradient(135deg, #0f172a 0%, #1e293b 60%, color-mix(in srgb, var(--pl-accent) 30%, #1e293b) 100%);
            border-radius: 1rem;
            padding: 1.75rem 2rem;
            color: #fff;
            box-shadow: 0 10px 40px rgba(15, 23, 42, 0.18);
        }
        .pl-statement { border-radius: 1rem; overflow: hidden; border: 1px solid rgb(226 232 240); background: #fff; box-shadow: 0 1px 3px rgba(15,23,42,.06); }
        .dark .pl-statement { border-color: rgb(51 65 85); background: rgb(15 23 42); }
        .pl-section-head {
            display: flex;
            align-items: center;
            gap: .75rem;
            padding: .875rem 1.5rem;
            background: rgb(248 250 252);
            border-bottom: 1px solid rgb(241 245 249);
            font-size: .75rem;
            font-weight: 700;
            letter-spacing: .06em;
            text-transform: uppercase;
            color: rgb(71 85 105);
        }
        .dark .pl-section-head { background: rgb(30 41 59); border-color: rgb(51 65 85); color: rgb(148 163 184); }
        .pl-row { display: grid; grid-template-columns: 1fr auto auto; gap: 1rem; padding: .7rem 1.5rem; border-bottom: 1px solid rgb(248 250 252); align-items: center; }
        .dark .pl-row { border-color: rgb(30 41 59); }
        .pl-row:hover { background: rgb(248 250 252 / .7); }
        .dark .pl-row:hover { background: rgb(30 41 59 / .5); }
        .pl-row-subtotal {
            display: grid;
            grid-template-columns: 1fr auto auto;
            gap: 1rem;
            padding: .85rem 1.5rem;
            background: rgb(241 245 249);
            font-weight: 700;
            border-top: 2px solid rgb(226 232 240);
        }
        .dark .pl-row-subtotal { background: rgb(30 41 59); border-color: rgb(51 65 85); }
        .pl-net-bar {
            border-radius: 1rem;
            padding: 1.5rem 2rem;
            background: linear-gradient(135deg, color-mix(in srgb, var(--pl-accent) 8%, #fff), #fff);
            border: 2px solid color-mix(in srgb, var(--pl-accent) 25%, transparent);
        }
        .dark .pl-net-bar {
            background: linear-gradient(135deg, color-mix(in srgb, var(--pl-accent) 12%, rgb(15 23 42)), rgb(15 23 42));
        }
        .pl-pct-col { width: 4.5rem; text-align: right; font-size: .75rem; color: rgb(148 163 184); font-variant-numeric: tabular-nums; }
        .pl-amt-col { min-width: 9rem; text-align: right; font-variant-numeric: tabular-nums; font-weight: 600; }
        .pl-margin-track { height: 6px; border-radius: 999px; background: rgb(226 232 240); overflow: hidden; }
        .dark .pl-margin-track { background: rgb(51 65 85); }
        .pl-margin-fill { height: 100%; border-radius: 999px; transition: width .6s ease; }
        @media print {
            .fi-sidebar, .fi-topbar, .pl-no-print { display: none !important; }
            .pl-doc-header { background: #1e293b !important; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
        }
    </style>

    <div class="pl-report space-y-6">
        {{-- Filters --}}
        <div class="pl-no-print">
            {{ $this->form }}
        </div>

        {{-- Document header --}}
        <div class="pl-doc-header">
            <div class="flex flex-col gap-4 md:flex-row md:items-start md:justify-between">
                <div>
                    <p class="text-xs font-semibold uppercase tracking-[0.2em] text-white/60">Financial Report</p>
                    <h1 class="mt-1 text-2xl font-bold tracking-tight md:text-3xl">Profit & Loss Statement</h1>
                    <p class="mt-2 text-sm text-white/70">{{ $brand }} · {{ str($panelId)->headline() }} Module</p>
                </div>
                <div class="text-left md:text-right">
                    <p class="text-xs font-medium uppercase tracking-wider text-white/50">Reporting Period</p>
                    <p class="mt-1 text-lg font-semibold">{{ $report['period_label'] ?? '—' }}</p>
                    <p class="mt-2 text-xs text-white/50">Generated {{ now()->format('M j, Y · g:i A') }}</p>
                </div>
            </div>
        </div>

        {{-- KPI cards --}}
        <div class="grid grid-cols-1 gap-4 sm:grid-cols-2 {{ ($report['total_direct_costs'] ?? 0) > 0 ? 'xl:grid-cols-5' : 'xl:grid-cols-4' }}">
            <div class="pl-kpi" style="--pl-kpi-accent: #10b981;">
                <div class="flex items-start justify-between gap-3">
                    <div>
                        <p class="text-xs font-semibold uppercase tracking-wider text-gray-500 dark:text-gray-400">Total Revenue</p>
                        <p class="mt-2 text-2xl font-bold tracking-tight text-emerald-600 dark:text-emerald-400">{{ $format($report['total_revenue'] ?? 0) }}</p>
                    </div>
                    <div class="pl-kpi-icon">
                        <x-heroicon-o-arrow-trending-up class="h-5 w-5" />
                    </div>
                </div>
            </div>

            @if (($report['total_direct_costs'] ?? 0) > 0)
                <div class="pl-kpi" style="--pl-kpi-accent: #ef4444;">
                    <div class="flex items-start justify-between gap-3">
                        <div>
                            <p class="text-xs font-semibold uppercase tracking-wider text-gray-500 dark:text-gray-400">Direct Costs</p>
                            <p class="mt-2 text-2xl font-bold tracking-tight text-red-600 dark:text-red-400">{{ $format($report['total_direct_costs']) }}</p>
                        </div>
                        <div class="pl-kpi-icon">
                            <x-heroicon-o-shopping-cart class="h-5 w-5" />
                        </div>
                    </div>
                </div>

                <div class="pl-kpi" style="--pl-kpi-accent: {{ $accent }};">
                    <div class="flex items-start justify-between gap-3">
                        <div>
                            <p class="text-xs font-semibold uppercase tracking-wider text-gray-500 dark:text-gray-400">Gross Profit</p>
                            <p class="mt-2 text-2xl font-bold tracking-tight {{ ($report['gross_profit'] ?? 0) >= 0 ? 'text-primary-600 dark:text-primary-400' : 'text-red-600 dark:text-red-400' }}">
                                {{ $format($report['gross_profit'] ?? 0) }}
                            </p>
                        </div>
                        <div class="pl-kpi-icon">
                            <x-heroicon-o-chart-bar class="h-5 w-5" />
                        </div>
                    </div>
                </div>
            @endif

            <div class="pl-kpi" style="--pl-kpi-accent: #f59e0b;">
                <div class="flex items-start justify-between gap-3">
                    <div>
                        <p class="text-xs font-semibold uppercase tracking-wider text-gray-500 dark:text-gray-400">Operating Expenses</p>
                        <p class="mt-2 text-2xl font-bold tracking-tight text-amber-600 dark:text-amber-400">{{ $format($report['total_operating_expenses'] ?? 0) }}</p>
                    </div>
                    <div class="pl-kpi-icon">
                        <x-heroicon-o-receipt-percent class="h-5 w-5" />
                    </div>
                </div>
            </div>

            <div class="pl-kpi" style="--pl-kpi-accent: {{ $isProfit ? '#10b981' : '#ef4444' }};">
                <div class="flex items-start justify-between gap-3">
                    <div class="flex-1">
                        <p class="text-xs font-semibold uppercase tracking-wider text-gray-500 dark:text-gray-400">Net {{ $isProfit ? 'Profit' : 'Loss' }}</p>
                        <p class="mt-2 text-2xl font-bold tracking-tight {{ $isProfit ? 'text-emerald-600 dark:text-emerald-400' : 'text-red-600 dark:text-red-400' }}">
                            {{ $format(abs($netProfit)) }}
                        </p>
                        <div class="mt-3">
                            <div class="flex items-center justify-between text-xs text-gray-500 dark:text-gray-400">
                                <span>Net margin</span>
                                <span class="font-semibold {{ $isProfit ? 'text-emerald-600' : 'text-red-600' }}">{{ $margin }}%</span>
                            </div>
                            <div class="pl-margin-track mt-1">
                                <div class="pl-margin-fill" style="width: {{ min(100, abs($margin)) }}%; background: {{ $isProfit ? '#10b981' : '#ef4444' }};"></div>
                            </div>
                        </div>
                    </div>
                    <div class="pl-kpi-icon">
                        @if ($isProfit)
                            <x-heroicon-o-check-badge class="h-5 w-5" />
                        @else
                            <x-heroicon-o-exclamation-triangle class="h-5 w-5" />
                        @endif
                    </div>
                </div>
            </div>
        </div>

        {{-- Expense ratio bar --}}
        @if (($report['total_revenue'] ?? 0) > 0)
            <div class="rounded-xl border border-gray-200 bg-white p-4 dark:border-gray-700 dark:bg-gray-900">
                <div class="flex items-center justify-between text-sm">
                    <span class="font-medium text-gray-600 dark:text-gray-400">Cost-to-Revenue Ratio</span>
                    <span class="font-bold text-gray-900 dark:text-white">{{ $expenseRatio }}%</span>
                </div>
                <div class="pl-margin-track mt-2 h-2">
                    <div class="pl-margin-fill h-2" style="width: {{ $expenseRatio }}%; background: linear-gradient(90deg, {{ $accent }}, #f59e0b);"></div>
                </div>
                <p class="mt-2 text-xs text-gray-400">Total costs as a percentage of revenue collected in this period</p>
            </div>
        @endif

        {{-- P&L Statement --}}
        <div class="pl-statement">
            <div class="flex items-center justify-between border-b border-gray-200 bg-white px-6 py-4 dark:border-gray-700 dark:bg-gray-900">
                <div>
                    <h2 class="text-base font-bold text-gray-900 dark:text-white">Detailed Statement</h2>
                    <p class="text-xs text-gray-500 dark:text-gray-400">All amounts in Pakistani Rupees (PKR)</p>
                </div>
                <div class="hidden text-right text-xs text-gray-400 sm:block">
                    <span class="font-medium">Line Item</span>
                    <span class="mx-3">·</span>
                    <span>% of Revenue</span>
                    <span class="mx-3">·</span>
                    <span>Amount</span>
                </div>
            </div>

            @foreach ($report['sections'] ?? [] as $sectionIndex => $section)
                @php
                    $sectionIcons = [
                        'Revenue' => 'arrow-trending-up',
                        'Revenue (Cash Collected)' => 'arrow-trending-up',
                        'Direct Project Costs' => 'wrench-screwdriver',
                        'Operating Expenses' => 'receipt-percent',
                        'Sales & Bookings' => 'home-modern',
                    ];
                    $icon = $sectionIcons[$section['title']] ?? 'document-text';
                    $sectionColors = [
                        'Revenue' => '#10b981',
                        'Revenue (Cash Collected)' => '#10b981',
                        'Direct Project Costs' => '#ef4444',
                        'Operating Expenses' => '#f59e0b',
                        'Sales & Bookings' => '#6366f1',
                    ];
                    $sectionColor = $sectionColors[$section['title']] ?? $accent;
                @endphp

                <div class="{{ $sectionIndex > 0 ? 'border-t border-gray-100 dark:border-gray-800' : '' }}">
                    <div class="pl-section-head">
                        <span class="flex h-7 w-7 items-center justify-center rounded-lg" style="background: color-mix(in srgb, {{ $sectionColor }} 15%, transparent); color: {{ $sectionColor }};">
                            @switch($icon)
                                @case('arrow-trending-up') <x-heroicon-o-arrow-trending-up class="h-4 w-4" /> @break
                                @case('wrench-screwdriver') <x-heroicon-o-wrench-screwdriver class="h-4 w-4" /> @break
                                @case('receipt-percent') <x-heroicon-o-receipt-percent class="h-4 w-4" /> @break
                                @case('home-modern') <x-heroicon-o-home-modern class="h-4 w-4" /> @break
                                @default <x-heroicon-o-document-text class="h-4 w-4" />
                            @endswitch
                        </span>
                        {{ $section['title'] }}
                    </div>

                    @if (empty($section['lines']))
                        <div class="px-6 py-5 text-sm italic text-gray-400">No entries recorded in this period</div>
                    @else
                        @foreach ($section['lines'] as $line)
                            <div class="pl-row text-sm">
                                <div class="text-gray-700 dark:text-gray-300">
                                    <span class="pl-2 border-l-2 border-gray-200 dark:border-gray-600">{{ $line['label'] }}</span>
                                    @if (! empty($line['note']))
                                        <p class="mt-0.5 pl-2.5 text-xs text-gray-400">{{ $line['note'] }}</p>
                                    @endif
                                </div>
                                <div class="pl-pct-col">{{ $pct($line['amount']) }}</div>
                                <div class="pl-amt-col text-gray-900 dark:text-white">{{ $format($line['amount']) }}</div>
                            </div>
                        @endforeach

                        <div class="pl-row-subtotal text-sm text-gray-900 dark:text-white">
                            <div>Subtotal — {{ $section['title'] }}</div>
                            <div class="pl-pct-col font-semibold">{{ $pct($section['subtotal']) }}</div>
                            <div class="pl-amt-col">{{ $format($section['subtotal']) }}</div>
                        </div>
                    @endif
                </div>
            @endforeach

            {{-- Net profit footer --}}
            <div class="pl-net-bar">
                <div class="space-y-2">
                    @if (($report['total_direct_costs'] ?? 0) > 0)
                        <div class="flex items-center justify-between text-sm">
                            <span class="font-medium text-gray-600 dark:text-gray-400">Gross Profit</span>
                            <span class="font-bold tabular-nums {{ ($report['gross_profit'] ?? 0) >= 0 ? 'text-primary-600 dark:text-primary-400' : 'text-red-600' }}">
                                {{ $format($report['gross_profit'] ?? 0) }}
                            </span>
                        </div>
                        <div class="border-t border-dashed border-gray-200 dark:border-gray-600"></div>
                    @endif
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-xs font-semibold uppercase tracking-wider text-gray-500 dark:text-gray-400">Bottom Line</p>
                            <p class="text-lg font-bold text-gray-900 dark:text-white">Net {{ $isProfit ? 'Profit' : 'Loss' }}</p>
                        </div>
                        <div class="text-right">
                            <p class="text-3xl font-bold tabular-nums {{ $isProfit ? 'text-emerald-600 dark:text-emerald-400' : 'text-red-600 dark:text-red-400' }}">
                                {{ $isProfit ? '' : '−' }}{{ $format(abs($netProfit)) }}
                            </p>
                            <p class="mt-1 text-sm font-medium {{ $isProfit ? 'text-emerald-600/70' : 'text-red-600/70' }}">{{ $margin }}% net margin</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        {{-- Supplementary --}}
        @if (! empty($report['supplementary']))
            <div class="rounded-xl border border-dashed border-gray-300 bg-gray-50 p-6 dark:border-gray-600 dark:bg-gray-900/50">
                <div class="mb-4 flex items-center gap-2">
                    <x-heroicon-o-information-circle class="h-5 w-5 text-gray-400" />
                    <h3 class="text-sm font-bold uppercase tracking-wider text-gray-500 dark:text-gray-400">Cash Flow Reference</h3>
                    <span class="rounded-full bg-gray-200 px-2 py-0.5 text-xs text-gray-600 dark:bg-gray-700 dark:text-gray-300">Not included in P&L totals</span>
                </div>
                <div class="space-y-2">
                    @foreach ($report['supplementary'] as $item)
                        <div class="flex items-center justify-between rounded-lg bg-white px-4 py-3 text-sm dark:bg-gray-800">
                            <div class="text-gray-700 dark:text-gray-300">
                                {{ $item['label'] }}
                                @if (! empty($item['note']))
                                    <span class="ml-1 text-xs text-gray-400">— {{ $item['note'] }}</span>
                                @endif
                            </div>
                            <span class="font-semibold tabular-nums text-gray-900 dark:text-white">{{ $format($item['amount']) }}</span>
                        </div>
                    @endforeach
                </div>
            </div>
        @endif

        {{-- Footer --}}
        <p class="text-center text-xs text-gray-400">
            This report is generated from live CRM data · {{ $brand }} · Confidential
        </p>
    </div>
</x-filament-panels::page>
