<x-app-layout>
    <x-slot:heading>{{ $pond->name }} — Cycle #{{ $cycle->cycle_number }}</x-slot:heading>

    <div class="mb-4 flex items-center gap-2 text-sm text-gray-500">
        <a href="{{ route('ponds.index') }}" class="hover:text-gray-700">Ponds</a>
        <svg class="h-4 w-4 text-gray-300" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M8.25 4.5l7.5 7.5-7.5 7.5"/></svg>
        <a href="{{ route('ponds.show', $pond) }}" class="hover:text-gray-700">{{ $pond->name }}</a>
        <svg class="h-4 w-4 text-gray-300" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M8.25 4.5l7.5 7.5-7.5 7.5"/></svg>
        <span class="text-gray-900">Cycle #{{ $cycle->cycle_number }}</span>
        <x-status-badge :status="$cycle->status" size="xs" />
    </div>

    <!-- Top stats row -->
    <div class="grid grid-cols-2 gap-3 sm:grid-cols-4 mb-6">
        <x-stat-card label="Days in Cycle" :value="$cycle->days_elapsed" sub="{{ $cycle->start_date->format('d M Y') }}" colour="blue" />
        <x-stat-card label="Fish Stocked" :value="number_format($cycle->total_stocked)" sub="{{ $cycle->stockingRecords->pluck('species')->unique()->join(', ') }}" colour="green" />
        <x-stat-card label="Total Feed" :value="number_format($cycle->total_fed_kg, 1) . ' kg'" sub="across all sessions" colour="amber" />
        <x-stat-card label="Mortality" :value="number_format($cycle->total_mortality)"
            sub="{{ $cycle->total_stocked > 0 ? number_format($cycle->total_mortality / $cycle->total_stocked * 100, 1) . '% of stocked' : '' }}"
            colour="{{ $cycle->total_mortality > 0 ? 'red' : 'gray' }}" />
    </div>

    <div class="grid grid-cols-1 gap-6 lg:grid-cols-3">

        <!-- Main: sampling chart + details -->
        <div class="space-y-5 lg:col-span-2">

            <!-- FCR / Biomass -->
            @if($latestSampling)
            <div class="rounded-xl border border-gray-100 bg-white p-5 shadow-sm">
                <h3 class="font-semibold text-gray-900 mb-4">Growth Summary</h3>
                <div class="grid grid-cols-2 gap-4 sm:grid-cols-4">
                    <div>
                        <p class="text-xs text-gray-500">Avg Weight</p>
                        <p class="text-xl font-bold text-gray-900">{{ number_format($latestSampling->avg_weight_g) }}g</p>
                    </div>
                    <div>
                        <p class="text-xs text-gray-500">Est. Biomass</p>
                        <p class="text-xl font-bold text-gray-900">{{ number_format($latestSampling->estimated_biomass_kg, 1) }} kg</p>
                    </div>
                    <div>
                        <p class="text-xs text-gray-500">FCR</p>
                        <p class="text-xl font-bold @if($fcr && $fcr <= 1.8) text-green-600 @elseif($fcr) text-amber-600 @else text-gray-400 @endif">
                            {{ $fcr ?? '—' }}
                        </p>
                        <p class="text-xs text-gray-400">target &lt; 1.8</p>
                    </div>
                    <div>
                        <p class="text-xs text-gray-500">Days to Target</p>
                        <p class="text-xl font-bold text-gray-900">
                            @if($latestSampling->days_to_target === 0) Ready!
                            @elseif($latestSampling->days_to_target) {{ $latestSampling->days_to_target }} days
                            @else —
                            @endif
                        </p>
                    </div>
                </div>

                <!-- Sampling history table -->
                @if($cycle->samplingRecords->count() > 1)
                <div class="mt-5">
                    <div id="sampling-chart" class="h-48"></div>
                </div>
                @endif

                <a href="{{ route('sampling.index', ['cycle_id' => $cycle->id]) }}"
                   class="mt-4 block text-xs font-medium text-primary-600 hover:underline">All sampling records →</a>
            </div>
            @endif

            <!-- Feed by brand -->
            @if($feedByBrand->isNotEmpty())
            <div class="rounded-xl border border-gray-100 bg-white p-5 shadow-sm">
                <h3 class="font-semibold text-gray-900 mb-3">Feed Usage by Brand</h3>
                <div class="space-y-2">
                    @php $maxFeed = $feedByBrand->max('total_kg'); @endphp
                    @foreach($feedByBrand as $fb)
                    <div class="flex items-center gap-3">
                        <div class="min-w-0 flex-1">
                            <div class="flex justify-between text-sm mb-1">
                                <span class="font-medium text-gray-700 truncate">{{ $fb->feed_brand }} — {{ $fb->feed_type }}</span>
                                <span class="font-semibold text-gray-900 ml-2">{{ number_format($fb->total_kg, 1) }} kg</span>
                            </div>
                            <div class="h-2 w-full rounded-full bg-gray-100">
                                <div class="h-2 rounded-full bg-primary-500"
                                     style="width: {{ $maxFeed > 0 ? ($fb->total_kg / $maxFeed * 100) : 0 }}%"></div>
                            </div>
                        </div>
                    </div>
                    @endforeach
                </div>
            </div>
            @endif

            <!-- Treatments -->
            @if($cycle->treatmentLogs->isNotEmpty())
            <div class="rounded-xl border border-gray-100 bg-white overflow-hidden shadow-sm">
                <div class="px-5 py-4 border-b border-gray-50 flex items-center justify-between">
                    <h3 class="font-semibold text-gray-900">Treatments</h3>
                    <a href="{{ route('health.treatment.create', ['pond_id' => $pond->id]) }}"
                       class="text-xs font-medium text-primary-600 hover:underline">+ Add</a>
                </div>
                <table class="w-full text-sm">
                    <tbody class="divide-y divide-gray-50">
                        @foreach($cycle->treatmentLogs as $t)
                        <tr class="hover:bg-gray-50">
                            <td class="px-5 py-3">
                                <p class="font-medium text-gray-900">{{ $t->drug_chemical_name }}</p>
                                <p class="text-xs text-gray-400">{{ $t->treatment_date->format('d M Y') }} · {{ ucfirst($t->application_method) }}</p>
                            </td>
                            <td class="px-5 py-3 text-gray-600">{{ $t->dosage }}</td>
                            <td class="px-5 py-3">
                                @if($t->isWithdrawalActive())
                                    <x-status-badge status="danger" size="xs" />
                                    <p class="text-xs text-red-600 mt-0.5">Safe {{ $t->harvest_safe_after->format('d M') }}</p>
                                @elseif($t->outcome)
                                    <x-status-badge :status="$t->outcome === 'resolved' ? 'safe' : 'warning'" size="xs" />
                                @endif
                            </td>
                        </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
            @endif

        </div>

        <!-- Right: stocking + harvest + actions -->
        <div class="space-y-5">

            <!-- Stocking details -->
            <div class="rounded-xl border border-gray-100 bg-white p-5 shadow-sm">
                <h3 class="font-semibold text-gray-900 mb-3">Stocking</h3>
                <p class="text-xs text-gray-400 mb-3">{{ $cycle->start_date->format('d M Y') }}</p>
                @foreach($cycle->stockingRecords as $sr)
                <div class="rounded-lg bg-gray-50 p-3 mb-2 text-sm">
                    <p class="font-medium text-gray-900">{{ $sr->species }}
                        @if($sr->strain_variety) <span class="text-gray-400">({{ $sr->strain_variety }})</span> @endif
                    </p>
                    <div class="mt-1 grid grid-cols-2 gap-1 text-xs text-gray-500">
                        <span>{{ number_format($sr->quantity) }} fingerlings</span>
                        <span>{{ $sr->avg_weight_g }}g avg</span>
                        <span>₦{{ number_format($sr->cost_per_fingerling, 2) }}/fish</span>
                        <span>Total: ₦{{ number_format($sr->total_cost) }}</span>
                    </div>
                </div>
                @endforeach
            </div>

            <!-- Harvest summary (if closed) -->
            @if($cycle->harvestRecord)
            @php $harvest = $cycle->harvestRecord; @endphp
            <div class="rounded-xl border border-gray-100 bg-white p-5 shadow-sm">
                <h3 class="font-semibold text-gray-900 mb-3">Harvest</h3>
                <dl class="space-y-1.5 text-sm">
                    <div class="flex justify-between">
                        <dt class="text-gray-500">Date</dt>
                        <dd class="font-medium">{{ $harvest->harvest_date->format('d M Y') }}</dd>
                    </div>
                    <div class="flex justify-between">
                        <dt class="text-gray-500">Total Weight</dt>
                        <dd class="font-medium">{{ number_format($harvest->total_weight_kg, 1) }} kg</dd>
                    </div>
                    <div class="flex justify-between">
                        <dt class="text-gray-500">Fish Harvested</dt>
                        <dd class="font-medium">{{ number_format($harvest->total_fish_harvested) }}</dd>
                    </div>
                    <div class="flex justify-between">
                        <dt class="text-gray-500">Avg Weight</dt>
                        <dd class="font-medium">{{ number_format($harvest->avg_weight_g) }}g</dd>
                    </div>
                    @if($harvest->total_revenue > 0)
                    <div class="flex justify-between border-t border-gray-50 pt-2 mt-2">
                        <dt class="font-semibold text-gray-700">Total Revenue</dt>
                        <dd class="font-bold text-green-700">₦{{ number_format($harvest->total_revenue) }}</dd>
                    </div>
                    @endif
                </dl>
            </div>
            @endif

            <!-- Cycle actions -->
            @if($cycle->isOpen() && auth()->user()->hasRole(['admin','manager']))
            <div class="rounded-xl border border-gray-100 bg-white p-5 shadow-sm">
                <h3 class="font-semibold text-gray-900 mb-3">Actions</h3>
                <div class="space-y-2">
                    <a href="{{ route('harvest.create', ['pond_id' => $pond->id]) }}"
                       class="block w-full rounded-lg border border-gray-200 px-3 py-2 text-center text-sm font-medium text-gray-700 hover:bg-gray-50">
                        Record Harvest
                    </a>
                    <form method="POST" action="{{ route('cycles.close', [$pond, $cycle]) }}"
                          onsubmit="return confirm('Close this production cycle? This cannot be undone.')">
                        @csrf @method('PATCH')
                        <button type="submit" class="w-full rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm font-medium text-red-700 hover:bg-red-100">
                            Close Cycle
                        </button>
                    </form>
                </div>
            </div>
            @endif

        </div>
    </div>
</x-app-layout>

@if($cycle->samplingRecords->count() > 1)
@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/apexcharts@3/dist/apexcharts.min.js"></script>
<script>
const samplingData = @json($cycle->samplingRecords->map(fn($s) => ['x' => $s->sample_date->format('d M'), 'y' => (float)$s->avg_weight_g])->values());

new ApexCharts(document.querySelector('#sampling-chart'), {
    series: [{name: 'Avg Weight (g)', data: samplingData}],
    chart: {type: 'line', height: 190, toolbar: {show: false}, sparkline: {enabled: false}},
    stroke: {curve: 'smooth', width: 2},
    markers: {size: 4},
    colors: ['#16a34a'],
    xaxis: {type: 'category'},
    yaxis: {labels: {formatter: v => v + 'g'}},
    tooltip: {y: {formatter: v => v + 'g'}},
    grid: {borderColor: '#f3f4f6'},
}).render();
</script>
@endpush
@endif
