@extends('pdf.base')

@section('content')
<style>
    /* ========== BASE STYLES ========== */
    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }

    @page {
        size: A4;
        margin: 12mm 15mm 15mm 15mm;
    }

    body {
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Helvetica', 'Arial', sans-serif;
        font-size: 10px;
        line-height: 1.4;
        color: #1F2937;
        background: #fff;
    }

    /* ========== CLIENT HEADER ========== */
    .client-header {
        display: table;
        width: 100%;
        margin-bottom: 12px;
    }

    .client-left {
        display: table-cell;
        vertical-align: middle;
        width: 55%;
    }

    .client-info-wrapper {
        display: table;
    }

    .client-avatar-cell {
        display: table-cell;
        vertical-align: middle;
        width: 55px;
    }

    .client-avatar {
        width: 45px;
        height: 45px;
        border-radius: 50%;
        object-fit: cover;
        border: 2px solid #7C3AED;
    }

    .client-avatar-placeholder {
        width: 45px;
        height: 45px;
        border-radius: 50%;
        background: linear-gradient(135deg, #7C3AED, #5B21B6);
        text-align: center;
        line-height: 45px;
        font-size: 18px;
        font-weight: 700;
        color: #fff;
    }

    .client-name-cell {
        display: table-cell;
        vertical-align: middle;
        padding-left: 12px;
    }

    .client-name {
        font-size: 24px;
        font-weight: 700;
        color: #1F2937;
        margin-bottom: 2px;
    }

    .client-label {
        font-size: 12px;
        color: #6B7280;
    }

    .client-right {
        display: table-cell;
        vertical-align: middle;
        text-align: right;
        width: 45%;
    }

    .logo-container img {
        max-width: 120px;
        max-height: 45px;
        object-fit: contain;
    }

    .current-date {
        font-size: 11px;
        color: #6B7280;
        margin-top: 4px;
    }

    .header-separator {
        width: 100%;
        height: 2px;
        background: linear-gradient(90deg, #7C3AED, #10B981);
        margin-bottom: 18px;
    }

    /* ========== INFO GRID ========== */
    .info-grid {
        display: table;
        width: 100%;
        margin-bottom: 18px;
        table-layout: fixed;
    }

    .info-col {
        display: table-cell;
        vertical-align: top;
        width: 50%;
    }

    .info-col:first-child {
        padding-right: 8px;
    }

    .info-col:last-child {
        padding-left: 8px;
    }

    .info-box {
        border-radius: 10px;
        padding: 14px;
    }

    .info-personal {
        background: #F5F3FF;
        border: 1px solid #E9D5FF;
    }

    .info-macros {
        background: #ECFDF5;
        border: 1.5px solid #6EE7B7;
    }

    .info-title {
        font-size: 12px;
        font-weight: 700;
        text-transform: uppercase;
        color: #1F2937;
        margin-bottom: 10px;
        letter-spacing: 0.5px;
    }

    .info-row {
        margin-bottom: 6px;
        display: table;
        width: 100%;
    }

    .info-row:last-child {
        margin-bottom: 0;
    }

    .info-label {
        display: table-cell;
        font-size: 10px;
        color: #6B7280;
    }

    .info-value {
        display: table-cell;
        font-size: 10px;
        font-weight: 600;
        color: #1F2937;
        text-align: right;
    }

    /* ========== DIET PLAN HEADER ========== */
    .plan-header-section {
        margin-bottom: 12px;
    }

    .plan-title-row {
        display: table;
        width: 100%;
        margin-bottom: 8px;
    }

    .plan-title-cell {
        display: table-cell;
        vertical-align: middle;
    }

    .plan-name {
        font-size: 20px;
        font-weight: 700;
        color: #1F2937;
    }

    .plan-days {
        font-size: 13px;
        color: #6B7280;
        font-weight: 400;
        margin-left: 6px;
    }

    .plan-badges {
        text-align: right;
        margin-bottom: 10px;
    }

    .macro-badge {
        display: inline-block;
        padding: 6px 12px;
        border-radius: 10px;
        font-size: 8px;
        font-weight: 600;
        text-transform: uppercase;
        margin-left: 5px;
        text-align: center;
        min-width: 85px;
        border: none;
    }

    .badge-protein {
        color: #fff;
        background: linear-gradient(135deg, #10B981, #059669);
    }

    .badge-carbs {
        color: #fff;
        background: linear-gradient(135deg, #3B82F6, #2563EB);
    }

    .badge-fat {
        color: #fff;
        background: linear-gradient(135deg, #F97316, #EA580C);
    }

    .badge-calories {
        color: #fff;
        background: linear-gradient(135deg, #7C3AED, #6D28D9);
    }

    .badge-label {
        display: block;
        font-size: 7px;
        margin-bottom: 2px;
        opacity: 0.9;
    }

    .badge-value {
        display: block;
        font-size: 12px;
        font-weight: 700;
    }

    /* ========== MEAL GRID ========== */
    .meals-grid {
        display: table;
        width: 100%;
        margin-bottom: 15px;
        table-layout: fixed;
        border-spacing: 6px 0;
    }

    .meal-column {
        display: table-cell;
        vertical-align: top;
        border: 1px solid #E5E7EB;
        border-radius: 8px;
        padding: 0;
        overflow: hidden;
    }

    .meal-header {
        font-size: 11px;
        font-weight: 700;
        text-transform: uppercase;
        color: #1F2937;
        padding: 8px 10px;
        background: #F3F4F6;
        letter-spacing: 0.5px;
        border-left: 3px solid #10B981;
    }

    .meal-kcal-badge {
        display: inline-block;
        background: #E5E7EB;
        color: #6B7280;
        padding: 2px 6px;
        border-radius: 3px;
        font-size: 8px;
        margin-left: 5px;
        font-weight: 600;
    }

    .meal-body {
        padding: 8px;
    }

    .food-card {
        padding: 8px;
        margin-bottom: 8px;
        border-bottom: 1px solid #F3F4F6;
    }

    .food-card:last-child {
        border-bottom: none;
        margin-bottom: 0;
    }

    .food-name {
        font-size: 11px;
        font-weight: 700;
        color: #1F2937;
        margin-bottom: 3px;
        line-height: 1.3;
    }

    .food-quantity {
        font-size: 11px;
        font-weight: 700;
        color: #374151;
        margin-bottom: 5px;
    }

    .food-macros {
        font-size: 9px;
        line-height: 1.5;
    }

    .macro-p {
        color: #10B981;
        font-weight: 600;
    }

    .macro-c {
        color: #3B82F6;
        font-weight: 600;
    }

    .macro-g {
        color: #F97316;
        font-weight: 600;
    }

    .meal-totals {
        padding: 6px 8px;
        background: #F9FAFB;
        border-top: 1px solid #E5E7EB;
        font-size: 9px;
        font-weight: 600;
    }

    /* ========== HYDRATION SECTION ========== */
    .hydration-section {
        background: #F9FAFB;
        border: 1px solid #E5E7EB;
        border-radius: 10px;
        padding: 14px;
        margin-bottom: 12px;
    }

    .section-title {
        font-size: 11px;
        font-weight: 700;
        text-transform: uppercase;
        color: #1F2937;
        margin-bottom: 8px;
        letter-spacing: 0.5px;
    }

    .section-text {
        font-size: 11px;
        color: #4B5563;
        line-height: 1.6;
    }

    /* ========== NOTES SECTION ========== */
    .notes-section {
        background: #FEF3C7;
        border: 1.5px solid #FDE68A;
        border-radius: 10px;
        padding: 14px;
        margin-bottom: 18px;
    }

    .notes-section .section-title {
        color: #92400E;
    }

    .notes-section .section-text {
        color: #78350F;
        font-size: 12px;
        line-height: 1.7;
    }

    /* ========== DISCLAIMER ========== */
    .disclaimer {
        font-size: 8px;
        color: #9CA3AF;
        text-align: center;
        margin-bottom: 12px;
        padding: 8px;
        background: #F9FAFB;
        border-radius: 6px;
    }

    /* ========== FOOTER ========== */
    .pdf-footer {
        text-align: center;
        font-size: 9px;
        font-style: italic;
        color: #6B7280;
        padding-top: 12px;
        border-top: 1px solid #E5E7EB;
    }

    /* Page break */
    .page-break {
        page-break-after: always;
    }
</style>

@php
    // ===== CLIENT AVATAR =====
    // Priority: portalUser->avatar_url (User accessor) > client->avatar field
    $clientAvatarUrl = null;
    if ($client->portalUser) {
        $clientAvatarUrl = $client->portalUser->avatar_url;
    }
    if (!$clientAvatarUrl && ($client->avatar ?? null)) {
        $clientAvatarUrl = str_starts_with($client->avatar, 'http')
            ? $client->avatar
            : asset('storage/' . $client->avatar);
    }

    // ===== DATE =====
    $currentDate = now()->locale('es')->isoFormat('dddd, D [de] MMMM [de] YYYY');

    // ===== CLIENT DATA =====
    $age = '-';
    if ($client->age) {
        $age = $client->age . ' años';
    } elseif ($client->date_of_birth ?? null) {
        try {
            $age = \Carbon\Carbon::parse($client->date_of_birth)->age . ' años';
        } catch (\Exception $e) {
            $age = '-';
        }
    }
    
    $gender = match($client->gender ?? '') {
        'male' => 'Masculino',
        'female' => 'Femenino',
        default => '-',
    };

    $activityLabels = [
        'sedentary' => 'Sedentario',
        'light' => 'Ligera',
        'moderate' => 'Moderada', 
        'active' => 'Activa',
        'very_active' => 'Muy Activa',
    ];

    // ===== MEAL TYPE LABELS (both English and Spanish keys) =====
    $allMealLabels = [
        'breakfast' => 'DESAYUNO',
        'pre_workout' => 'PRE-ENTRENO',
        'post_workout' => 'POST-ENTRENO',
        'lunch' => 'ALMUERZO',
        'snack' => 'MERIENDA',
        'dinner' => 'CENA',
        'mid_morning_snack' => 'MEDIA MAÑANA',
        'mid_afternoon_snack' => 'MEDIA TARDE',
        'intra_workout' => 'INTRA-ENTRENO',
        'desayuno' => 'DESAYUNO',
        'almuerzo' => 'ALMUERZO',
        'merienda' => 'MERIENDA',
        'merienda_media_manana' => 'MEDIA MAÑANA',
        'merienda_media_tarde' => 'MEDIA TARDE',
        'cena' => 'CENA',
        'comida_1' => 'COMIDA 1',
        'comida_2' => 'COMIDA 2',
        'comida_3' => 'COMIDA 3',
        'comida_4' => 'COMIDA 4',
        'comida_5' => 'COMIDA 5',
        'comida_6' => 'COMIDA 6',
        'comida_7' => 'COMIDA 7',
        'comida_8' => 'COMIDA 8',
        'meal_1' => 'COMIDA 1',
        'meal_2' => 'COMIDA 2',
        'meal_3' => 'COMIDA 3',
    ];

    // ===== TOTALS FROM ALL PLANS =====
    $totalP = 0; $totalC = 0; $totalF = 0; $totalCals = 0;
    foreach ($dietPlans ?? [] as $plan) {
        foreach ($plan->items ?? $plan->mealItems ?? [] as $item) {
            $totalP += $item->proteins ?? 0;
            $totalC += $item->carbs ?? 0;
            $totalF += $item->fats ?? 0;
            $totalCals += $item->calories ?? 0;
        }
    }

    // ===== DAY LABELS =====
    $dayLabels = [
        'monday' => 'LUN', 'tuesday' => 'MAR', 'wednesday' => 'MIE',
        'thursday' => 'JUE', 'friday' => 'VIE', 'saturday' => 'SAB', 'sunday' => 'DOM',
    ];
@endphp

<!-- ========== CLIENT HEADER ========== -->
<div class="client-header">
    <div class="client-left">
        <div class="client-info-wrapper">
            <div class="client-avatar-cell">
                @if($clientAvatarUrl)
                    <img src="{{ $clientAvatarUrl }}" class="client-avatar" alt="{{ $client->name }}" onerror="this.style.display='none';this.nextElementSibling.style.display='block';">
                    <div class="client-avatar-placeholder" style="display:none;">{{ strtoupper(substr($client->name ?? 'C', 0, 1)) }}</div>
                @else
                    <div class="client-avatar-placeholder">{{ strtoupper(substr($client->name ?? 'C', 0, 1)) }}</div>
                @endif
            </div>
            <div class="client-name-cell">
                <div class="client-name">{{ $client->name ?? 'Cliente' }}</div>
                <div class="client-label">Cliente</div>
            </div>
        </div>
    </div>
    <div class="client-right">
        <div class="logo-container">
            @if(($settings['show_logo'] ?? true) && ($settings['logo'] ?? null))
                @php
                    $logoPath = str_starts_with($settings['logo'], 'http')
                        ? $settings['logo']
                        : asset('storage/' . $settings['logo']);
                @endphp
                <img src="{{ $logoPath }}" alt="Logo" onerror="this.style.display='none'">
            @endif
        </div>
        <div class="current-date">{{ $currentDate }}</div>
    </div>
</div>

<div class="header-separator"></div>

<!-- ========== INFO GRID ========== -->
<div class="info-grid">
    <div class="info-col">
        <div class="info-box info-personal">
            <div class="info-title">Información Personal</div>
            <div class="info-row">
                <span class="info-label">Peso</span>
                <span class="info-value">{{ number_format($client->weight ?? 0, 2) }} kg</span>
            </div>
            <div class="info-row">
                <span class="info-label">Altura</span>
                <span class="info-value">{{ number_format($client->height ?? 0, 2) }} cm</span>
            </div>
            <div class="info-row">
                <span class="info-label">Edad</span>
                <span class="info-value">{{ $age }}</span>
            </div>
            <div class="info-row">
                <span class="info-label">Sexo</span>
                <span class="info-value">{{ $gender }}</span>
            </div>
            <div class="info-row">
                <span class="info-label">Nivel Actividad</span>
                <span class="info-value">{{ $activityLabels[$client->activity_level] ?? '-' }}</span>
            </div>
        </div>
    </div>
    <div class="info-col">
        <div class="info-box info-macros">
            <div class="info-title">Resumen de Macros</div>
            <div class="info-row">
                <span class="info-label">Proteínas Totales</span>
                <span class="info-value">{{ number_format($totalP, 1) }}g</span>
            </div>
            <div class="info-row">
                <span class="info-label">Carbohidratos Totales</span>
                <span class="info-value">{{ number_format($totalC, 1) }}g</span>
            </div>
            <div class="info-row">
                <span class="info-label">Grasas Totales</span>
                <span class="info-value">{{ number_format($totalF, 1) }}g</span>
            </div>
            @if($client->bmr ?? null)
            <div class="info-row">
                <span class="info-label">BMR (Metabolismo Basal)</span>
                <span class="info-value">{{ number_format($client->bmr, 2) }} kcal</span>
            </div>
            @endif
            @if($client->tdee ?? null)
            <div class="info-row">
                <span class="info-label">TDEE (Gasto Diario)</span>
                <span class="info-value">{{ number_format($client->tdee, 2) }} kcal</span>
            </div>
            @endif
        </div>
    </div>
</div>

<!-- ========== DIET PLANS ========== -->
@foreach($dietPlans ?? [] as $index => $dietPlan)
    @php
        // Get items from the relation (items = mealItems)
        $planItems = $dietPlan->items ?? $dietPlan->mealItems ?? collect();
        
        // Calculate plan totals directly from pre-calculated values
        $planP = $planItems->sum('proteins');
        $planC = $planItems->sum('carbs');
        $planF = $planItems->sum('fats');
        $planCals = $planItems->sum('calories');

        // Group by meal_type - use ALL items, no filtering
        $grouped = $planItems->groupBy('meal_type');
        
        // Get meal types in order as they appear
        $mealTypes = $grouped->keys()->toArray();
    @endphp

    <!-- Plan Header -->
    <div class="plan-header-section">
        <div class="plan-title-row">
            <div class="plan-title-cell">
                <span class="plan-name">{{ $dietPlan->name ?? 'Plan ' . ($index + 1) }}</span>
                @if(($dietPlan->days ?? null) && is_array($dietPlan->days) && count($dietPlan->days))
                    <span class="plan-days">({{ implode(', ', array_map(fn($d) => $dayLabels[$d] ?? strtoupper(substr($d, 0, 3)), $dietPlan->days)) }})</span>
                @endif
            </div>
        </div>
        <div class="plan-badges">
            <span class="macro-badge badge-protein">
                <span class="badge-label">PROTEÍNAS</span>
                <span class="badge-value">{{ number_format($planP, 1) }}g</span>
            </span>
            <span class="macro-badge badge-carbs">
                <span class="badge-label">CARBOHIDRATOS</span>
                <span class="badge-value">{{ number_format($planC, 1) }}g</span>
            </span>
            <span class="macro-badge badge-fat">
                <span class="badge-label">GRASAS</span>
                <span class="badge-value">{{ number_format($planF, 1) }}g</span>
            </span>
            <span class="macro-badge badge-calories">
                <span class="badge-label">CALORÍAS</span>
                <span class="badge-value">{{ number_format(round($planCals)) }}</span>
            </span>
        </div>
    </div>

    <!-- Meals Grid - Show ALL meal types dynamically -->
    @php
        // Split meal types into rows of 4 columns
        $mealChunks = array_chunk($mealTypes, 4);
    @endphp

    @foreach($mealChunks as $chunk)
        <div class="meals-grid">
            @foreach($chunk as $mealType)
                @php
                    $items = $grouped[$mealType];
                    $mealCals = $items->sum('calories');
                @endphp
                <div class="meal-column">
                    <div class="meal-header">
                        {{ $allMealLabels[$mealType] ?? strtoupper(str_replace('_', ' ', $mealType)) }}
                        <span class="meal-kcal-badge">{{ number_format(round($mealCals)) }} kcal</span>
                    </div>
                    <div class="meal-body">
                        @foreach($items as $item)
                            <div class="food-card">
                                <div class="food-name">{{ $item->food->name ?? 'Alimento' }}</div>
                                <div class="food-quantity">{{ rtrim(rtrim(number_format($item->quantity, 2), '0'), '.') }} {{ $item->unit ?? 'g' }}</div>
                                <div class="food-macros">
                                    <span class="macro-p">P: {{ number_format($item->proteins ?? 0, 1) }}g</span>
                                    <span class="macro-c"> C: {{ number_format($item->carbs ?? 0, 1) }}g</span>
                                    <span class="macro-g"> G: {{ number_format($item->fats ?? 0, 1) }}g</span>
                                </div>
                            </div>
                        @endforeach
                    </div>
                    <div class="meal-totals">
                        <span class="macro-p">P: {{ number_format($items->sum('proteins'), 1) }}g</span>
                        <span class="macro-c"> C: {{ number_format($items->sum('carbs'), 1) }}g</span>
                        <span class="macro-g"> G: {{ number_format($items->sum('fats'), 1) }}g</span>
                    </div>
                </div>
            @endforeach

            {{-- Fill empty columns if fewer than 4 --}}
            @for($i = count($chunk); $i < 4; $i++)
                <div class="meal-column" style="border: none;"></div>
            @endfor
        </div>
    @endforeach

    @if($index < count($dietPlans) - 1)
        <div class="page-break"></div>
    @endif
@endforeach

<!-- Empty state -->
@if(empty($dietPlans) || count($dietPlans) === 0)
    <div style="text-align: center; padding: 40px; color: #9ca3af;">
        <p style="font-size: 14px;">No hay planes de dieta configurados.</p>
    </div>
@endif

<!-- ========== HYDRATION ========== -->
<div class="hydration-section">
    <div class="section-title">💧 Recomendaciones de Hidratación</div>
    <div class="section-text">
        {{ $mealPlan->description ?? 'Se recomienda consumir mínimo 2-3 litros de agua al día. Aumentar la ingesta en días de entrenamiento intenso. Evitar bebidas azucaradas y limitar el consumo de alcohol.' }}
    </div>
</div>

<!-- ========== NOTES ========== -->
@if(trim(strip_tags($mealPlan->notes ?? '')) !== '')
<div class="notes-section">
    <div class="section-title">📝 Notas del Coach</div>
    <div class="section-text">{{ trim(strip_tags($mealPlan->notes)) }}</div>
</div>
@endif

<!-- ========== DISCLAIMER ========== -->
<div class="disclaimer">
    ⚠️ Este plan nutricional es personalizado. No compartir ni seguir sin supervisión profesional.
    Los resultados pueden variar según cada individuo.
</div>

<!-- ========== FOOTER ========== -->
<div class="pdf-footer">
    © {{ now()->year }} {{ $settings['site_name'] ?? $settings['header'] ?? 'CoachPro' }}. Todos los derechos reservados.
</div>

@endsection
