@php
    use App\Enums\LinkStatus;

    $waitingGroup = \App\Models\Group::firstWhere('name', "{$campaign->name} - En attente");
    $paidGroup    = \App\Models\Group::firstWhere('name', "{$campaign->name} - Payés");

    $paidLinks      = $campaign->links->where('status', LinkStatus::Paid);
    $paidDonateurs  = $paidLinks->pluck('donateur_id')->unique();
    $campaignDonateurs = $campaign->links->pluck('donateur_id')->unique();

    $optOutLinks   = $campaign->links->where('no_relance', true);
    $toRelanceLinks = $campaign->links
        ->where('status', LinkStatus::Pending)
        ->where('no_relance', false);
@endphp

<div class="max-w-5xl mx-auto p-6 bg-white shadow rounded">
  <h2 class="text-2xl font-semibold mb-6">Détails Campagne : {{ $campaign->name }}</h2>

  @if($campaign->contact_email || $campaign->contact_phone)
    <p class="text-sm text-gray-600 mb-4">
      Contact :
      @if($campaign->contact_email)
        <a href="mailto:{{ $campaign->contact_email }}" class="underline">{{ $campaign->contact_email }}</a>
      @endif
      @if($campaign->contact_phone)
        @if($campaign->contact_email)&nbsp;|&nbsp;@endif
        <a href="tel:+{{ $campaign->contact_phone }}" class="underline">{{ $campaign->contact_phone }}</a>
      @endif
    </p>
  @endif

  @if($campaign->initiator_name || $campaign->initiator_position)
    <p class="text-sm text-gray-600 mb-4">
      Initiateur :
      @if($campaign->initiator_name)
        {{ $campaign->initiator_name }}
      @endif
      @if($campaign->initiator_position)
        @if($campaign->initiator_name)&nbsp;|&nbsp;@endif {{ $campaign->initiator_position }}
      @endif
    </p>
  @endif

  {{-- Statistiques --}}
  <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8">
    <div class="p-4 bg-blue-50 rounded">
      <h3 class="text-sm text-gray-500 uppercase">Liens générés</h3>
      <p class="text-3xl font-bold">{{ $campaign->links->count() }}</p>
    </div>
    <div class="p-4 bg-green-50 rounded">
      <h3 class="text-sm text-gray-500 uppercase">Donateurs payés</h3>
      <p class="text-3xl font-bold">{{ $paidDonateurs->count() }}</p>
    </div>
    <div class="p-4 bg-yellow-50 rounded">
      <h3 class="text-sm text-gray-500 uppercase">En attente</h3>
      <p class="text-3xl font-bold">{{ $campaign->links->where('status','pending')->count() }}</p>
    </div>
    <div class="p-4 bg-indigo-50 rounded">
      <h3 class="text-sm text-gray-500 uppercase">Total collecté</h3>
      <p class="text-3xl font-bold">
        {{ number_format($campaign->links->flatMap->payments->pluck('amount')->sum(), 0, ',', ' ') }} XOF
      </p>
    </div>
  </div>

  @php
      $progress = $campaignDonateurs->count() > 0
          ? round(($paidDonateurs->count() / $campaignDonateurs->count()) * 100, 1)
          : 0;
  @endphp

  <div class="mb-6 bg-gray-50 p-4 rounded flex flex-wrap gap-4 items-center">
    <div class="mb-8 w-full">
        <div class="w-full bg-gray-200 h-3 rounded">
            <div class="bg-green-500 h-3 rounded" style="width: {{ $progress }}%"></div>
        </div>
        <p class="text-xs text-gray-600 mt-1">{{ $progress }}% des donateurs ont payé</p>
    </div>

    {{-- Groupes associés et exports --}}
    <div class="flex flex-wrap gap-4 mb-6">
      @if($waitingGroup)
        <a href="{{ route('groups.export_members', $waitingGroup) }}"
           class="px-4 py-2 bg-yellow-600 text-white rounded hover:bg-yellow-700 whitespace-nowrap">
          Exporter « En attente » ({{ $waitingGroup->donateurs->count() }})
        </a>
        @if($toRelanceLinks->count())
          @php
              $uniqueRelanceCount = $toRelanceLinks
                  ->pluck('donateur_id')
                  ->unique()
                  ->count();

              $donateursToNotRelance = $optOutLinks
                ->pluck('donateur')
                ->unique('id');
          @endphp
          <form action="{{ route('campaigns.remind', $campaign) }}"
            method="POST"
            class="inline"
            onsubmit="return confirm('Confirmez-vous l\u2019envoi de la relance à {{ $uniqueRelanceCount }} donateur{{ $uniqueRelanceCount > 1 ? 's' : '' }} ?')">
            @csrf

            <button type="submit"
              class="px-4 py-2 bg-red-600 text-white rounded hover:bg-red-700">
              📣 Relancer les {{ $uniqueRelanceCount }} volontaires
            </button>
          </form>
        @endif
      @endif

      @if($paidGroup)
        <a href="{{ route('groups.export_members', $paidGroup) }}"
           class="px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700 whitespace-nowrap">
          Exporter « Payés » ({{ $paidGroup->donateurs->count() }})
        </a>
      @endif

      <a href="{{ route('reports.export', array_merge(request()->query(), ['type'=>'all'])) }}"
         class="px-4 py-2 bg-gray-600 text-white rounded hover:bg-gray-700 whitespace-nowrap">
        Exporter Tout
      </a>
    </div>
  </div>

  {{-- Listes repliables --}}
    @if($waitingGroup)
    <details class="mb-4 border rounded">
      <summary class="px-4 py-2 bg-yellow-100 cursor-pointer font-medium">
        Donateurs en attente ({{ $waitingGroup->donateurs->count() }})
      </summary>
      <div class="p-4">
        <select class="w-full border-gray-300 rounded shadow-sm p-2" size="8" readonly>
          @foreach($waitingGroup->donateurs as $don)
            <option value="{{ $don->id }}">
              {{ $don->nom }} {{ $don->prenom }}@if($don->email) ({{ $don->email }})@endif
            </option>
          @endforeach
        </select>
      </div>
    </details>
    @endif

    @if(isset($donateursToNotRelance) && $donateursToNotRelance)
    <details class="mb-4 border rounded">
      <summary class="px-4 py-2 bg-yellow-100 cursor-pointer font-medium">
        Donateurs ne voulant plus être relancé ({{ $donateursToNotRelance->count() }})
      </summary>
      <div class="p-4">
        <select class="w-full border-gray-300 rounded shadow-sm p-2" size="8" readonly>
          @foreach( $donateursToNotRelance->values() as $donateur)
            <option value="{{ $donateur->id }}">
              {{ $donateur->nom }} {{ $donateur->prenom }}@if($donateur->email) ({{ $donateur->email }})@endif
            </option>
          @endforeach
        </select>
      </div>
    </details>
    @endif

    @if($paidGroup)
    <details class="mb-4 border rounded">
      <summary class="px-4 py-2 bg-green-100 cursor-pointer font-medium">
        Donateurs ayant payés ({{ $paidGroup->donateurs->count() }})
      </summary>
      <div class="p-4">
        <select class="w-full border-gray-300 rounded shadow-sm p-2" size="8" readonly>
          @foreach($paidGroup->donateurs as $don)
            @php
                $amount = $don->payments()
                    ->whereHas('link', fn($q) => $q->where('campaign_id', $campaign->id))
                    ->sum('amount');
            @endphp
            <option value="{{ $don->id }}">
              {{ $don->nom }} {{ $don->prenom }}@if($don->email) ({{ $don->email }}) ({{ number_format($amount, 0, ',', ' ') }} XOF)@endif
            </option>
          @endforeach
        </select>
      </div>
    </details>
    @endif
  </div>

  <div class="text-right">
    <a href="{{ route('campaigns.index') }}"
       class="px-4 py-2 bg-gray-200 rounded hover:bg-gray-300">
      ← Retour aux campagnes
    </a>
  </div>
</div>
