@extends('layouts.admin')
@section('title', 'Tier Evaluation — ' . $user->full_name)
@section('page-title', 'Tier Evaluation')

@section('content')
<div x-data="{ overrideModal: false }" class="space-y-6 max-w-4xl">

    @if(session('success'))
    <div class="bg-green-900/20 border border-green-700/40 rounded-xl px-5 py-3 text-green-400 text-sm">{{ session('success') }}</div>
    @endif

    <div class="flex items-center gap-3">
        <a href="{{ route('admin.tiers.index') }}" class="text-white/30 hover:text-white transition-colors inline-flex items-center gap-1 text-xs">
            <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/></svg>
            Tier Management
        </a>
        <span class="text-white/20">/</span>
        <span class="text-white/50 text-xs">{{ $user->full_name }}</span>
    </div>

    <div class="flex items-start justify-between">
        <div>
            <h2 class="text-2xl font-semibold" style="font-family: 'Playfair Display', serif;">{{ $user->full_name }}</h2>
            <p class="text-white/40 text-sm mt-1">{{ $user->membership_number }} · Tier Evaluation</p>
        </div>
        <button @click="overrideModal = true"
                class="border border-[#D4B84A]/40 hover:border-[#D4B84A] text-[#D4B84A]/70 hover:text-[#D4B84A] text-xs tracking-wide uppercase px-5 py-2.5 rounded-full transition-colors">
            Manual Override
        </button>
    </div>

    {{-- Recommendation banner --}}
    @php
        $action = $result['action'];
        $bannerColor = match($action) {
            'upgrade'    => 'border-[#D4B84A]/40 bg-[#D4B84A]/5',
            'downgrade'  => 'border-orange-700/40 bg-orange-900/10',
            'deactivate' => 'border-red-700/40 bg-red-900/10',
            default      => 'border-[#1e1e1e] bg-[#111111]',
        };
        $bannerText = match($action) {
            'upgrade'    => '↑ Recommended: Upgrade to ' . $result['target_tier']?->name,
            'downgrade'  => '↓ Recommended: Downgrade to ' . $result['target_tier']?->name,
            'deactivate' => '⚠ Recommended: Mark membership inactive',
            default      => $result['at_risk'] ? '⚠ Member is at risk — monitor closely' : '✓ Tier is stable — no action required',
        };
        $bannerTextColor = match($action) {
            'upgrade'    => 'text-[#D4B84A]',
            'downgrade'  => 'text-orange-400',
            'deactivate' => 'text-red-400',
            default      => $result['at_risk'] ? 'text-orange-400' : 'text-white/60',
        };
    @endphp

    <div class="border {{ $bannerColor }} rounded-xl px-6 py-4 flex items-center justify-between">
        <div>
            <p class="font-semibold {{ $bannerTextColor }}">{{ $bannerText }}</p>
            @foreach($result['reasons'] as $reason)
            <p class="text-white/40 text-xs mt-1">{{ $reason }}</p>
            @endforeach
        </div>
        <div class="flex items-center gap-2 flex-shrink-0 ml-6">
            <span class="px-3 py-1 rounded-full text-xs border {{ $result['current_tier']?->slug === 'limitless' ? 'border-[#D4B84A]/50 text-[#D4B84A]' : ($result['current_tier']?->slug === 'indulged' ? 'border-blue-400/30 text-blue-300' : 'border-white/20 text-white/50') }}">
                {{ $result['current_tier']?->name ?? 'None' }}
            </span>
            @if($action !== 'maintain')
            <span class="{{ in_array($action,['upgrade']) ? 'text-[#D4B84A]' : 'text-orange-400' }}">→</span>
            <span class="px-3 py-1 rounded-full text-xs border {{ $result['target_tier']?->slug === 'limitless' ? 'border-[#D4B84A]/50 text-[#D4B84A]' : ($result['target_tier']?->slug === 'indulged' ? 'border-blue-400/30 text-blue-300' : 'border-white/20 text-white/50') }}">
                {{ $result['target_tier']?->name }}
            </span>
            @endif
        </div>
    </div>

    {{-- Stats grid --}}
    <div class="grid grid-cols-4 gap-4">
        @foreach([
            ['Visits (3 months)', $result['stats']['visits_3m']],
            ['Visits (1 month)',  $result['stats']['visits_1m']],
            ['Visits (12 months)', $result['stats']['visits_12m']],
            ['Points (quarter)', number_format($result['stats']['points_3m'])],
        ] as [$label, $value])
        <div class="bg-[#111111] border border-[#1e1e1e] rounded-xl p-5">
            <p class="text-white/40 text-xs tracking-widest uppercase mb-2">{{ $label }}</p>
            <p class="text-2xl font-semibold text-white">{{ $value }}</p>
        </div>
        @endforeach
    </div>

    {{-- Tier criteria comparison --}}
    <div class="bg-[#111111] border border-[#1e1e1e] rounded-xl">
        <div class="px-6 py-4 border-b border-[#1e1e1e]">
            <h3 class="text-sm font-medium">Criteria Check</h3>
        </div>
        <div class="divide-y divide-[#1e1e1e]">
            @foreach($tiers as $tier)
            @php
                $isCurrent = $result['current_tier']?->id === $tier->id;
                $meetsVisit3m = $result['stats']['visits_3m'] >= $tier->visits_per_period;
                $meetsPoints  = $result['stats']['points_3m'] >= $tier->points_threshold_3months;
            @endphp
            <div class="px-6 py-4">
                <div class="flex items-center justify-between mb-3">
                    <div class="flex items-center gap-3">
                        <span class="px-2.5 py-1 rounded-full text-xs border
                            {{ $tier->slug === 'limitless' ? 'border-[#D4B84A]/50 text-[#D4B84A]' : ($tier->slug === 'indulged' ? 'border-blue-400/30 text-blue-300' : 'border-white/20 text-white/50') }}">
                            {{ $tier->name }}
                        </span>
                        @if($isCurrent)
                        <span class="text-[10px] text-[#D4B84A] uppercase tracking-widest">Current</span>
                        @endif
                    </div>
                </div>
                <div class="grid grid-cols-3 gap-4 text-sm">
                    <div>
                        <p class="text-white/30 text-xs mb-1">Min spend/visit</p>
                        <p class="{{ $user->visits()->where('spend_amount','>=', $tier->min_spend_per_visit)->where('visit_date','>=', now()->subMonths(3)->toDateString())->exists() ? 'text-green-400' : 'text-red-400' }}">
                            ${{ number_format($tier->min_spend_per_visit, 0) }}
                        </p>
                    </div>
                    <div>
                        <p class="text-white/30 text-xs mb-1">Visits (3m)</p>
                        <p class="{{ $meetsVisit3m ? 'text-green-400' : 'text-red-400' }}">
                            {{ $result['stats']['visits_3m'] }} / {{ $tier->visits_per_period }} required
                        </p>
                    </div>
                    <div>
                        <p class="text-white/30 text-xs mb-1">Points threshold</p>
                        <p class="{{ $meetsPoints ? 'text-green-400' : 'text-orange-400' }}">
                            {{ number_format($result['stats']['points_3m']) }} / {{ number_format($tier->points_threshold_3months) }} needed
                        </p>
                    </div>
                </div>
            </div>
            @endforeach
        </div>
    </div>

    {{-- Recent visits --}}
    <div class="bg-[#111111] border border-[#1e1e1e] rounded-xl">
        <div class="px-6 py-4 border-b border-[#1e1e1e]">
            <h3 class="text-sm font-medium">Recent Visits (last 3 months)</h3>
        </div>
        <div class="divide-y divide-[#1e1e1e]">
            @forelse($user->visits()->where('visit_date','>=', now()->subMonths(3)->toDateString())->latest('visit_date')->get() as $visit)
            <div class="flex items-center justify-between px-6 py-3">
                <p class="text-white text-sm">{{ $visit->visit_date->format('d M Y') }}</p>
                <div class="flex items-center gap-6">
                    <p class="text-white/60 text-sm">${{ number_format($visit->spend_amount, 2) }}</p>
                    <p class="text-[#D4B84A] text-sm">+{{ $visit->points_awarded }} pts</p>
                    <p class="text-white/30 text-xs">by {{ $visit->recordedBy?->name }}</p>
                </div>
            </div>
            @empty
            <div class="px-6 py-6 text-center text-white/30 text-sm">No visits in the last 3 months.</div>
            @endforelse
        </div>
    </div>

    {{-- Manual Override Modal --}}
    <div x-show="overrideModal" x-cloak
         class="fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4"
         @keydown.escape.window="overrideModal = false">
        <div class="bg-[#111111] border border-[#2a2a2a] rounded-2xl p-8 w-full max-w-md" @click.stop>
            <h3 class="text-lg font-semibold mb-1" style="font-family: 'Playfair Display', serif;">Manual Tier Override</h3>
            <p class="text-white/40 text-sm mb-6">Bypass the system recommendation and set tier directly.</p>
            <form method="POST" action="{{ route('admin.tiers.override', $user) }}" class="space-y-4">
                @csrf
                <div>
                    <label class="block text-xs tracking-widest uppercase text-white/40 mb-2">Set Tier To</label>
                    <select name="tier_id" required
                            class="w-full bg-[#1a1a1a] border border-[#2a2a2a] focus:border-[#D4B84A] rounded-lg px-4 py-3 text-sm text-white outline-none transition-colors">
                        @foreach($tiers as $tier)
                        <option value="{{ $tier->id }}" {{ $result['current_tier']?->id === $tier->id ? 'selected' : '' }}>
                            {{ $tier->name }}
                        </option>
                        @endforeach
                    </select>
                </div>
                <div>
                    <label class="block text-xs tracking-widest uppercase text-white/40 mb-2">Reason *</label>
                    <textarea name="reason" rows="3" required
                              class="w-full bg-[#1a1a1a] border border-[#2a2a2a] focus:border-[#D4B84A] rounded-lg px-4 py-3 text-sm text-white outline-none transition-colors resize-none"
                              placeholder="Reason for manual override…"></textarea>
                </div>
                <div class="flex justify-end gap-3">
                    <button type="button" @click="overrideModal = false"
                            class="px-5 py-2.5 rounded-full border border-[#2a2a2a] text-white/50 text-sm hover:text-white transition-colors">
                        Cancel
                    </button>
                    <button type="submit"
                            class="px-5 py-2.5 rounded-full bg-[#D4B84A] hover:bg-[#E8D080] text-black font-semibold text-sm transition-colors">
                        Apply Override
                    </button>
                </div>
            </form>
        </div>
    </div>

</div>
@endsection
