@extends('app.shell')

@section('body')
  @php
    /** @var \Illuminate\Support\Collection<int, \App\Models\SharedList> $sharedLists */
    /** @var \Illuminate\Support\Collection<int, \App\Models\Expense> $expenses */
    /** @var \App\Models\Person|null $mePerson */

    $locale = app()->getLocale();
    $displayCurrency = request()->user()?->profile?->currency ?: 'USD';

    $money = function (float $n, string $originalCurrency = 'USD') use ($displayCurrency, $locale): array {
      return \App\Support\Money::formatConvertedWithOriginal($n, $originalCurrency, $displayCurrency, $locale);
    };

    $listProgress = function (\App\Models\SharedList $list): array {
      $total = $list->items->count();
      $done = $list->items->where('done', true)->count();
      return ['done' => $done, 'total' => $total];
    };

    $listMyBalance = function (string $listId) use ($expenses, $mePerson): float {
      if (! $mePerson) return 0.0;
      $relevant = $expenses->where('shared_list_id', $listId);
      $paid = (float) $relevant->where('paid_by_person_id', $mePerson->id)->sum('amount');
      $share = 0.0;
      foreach ($relevant as $exp) {
        $split = is_array($exp->split_among) ? $exp->split_among : [];
        foreach ($split as $row) {
          $uid = (string) (data_get($row, 'user.id') ?? data_get($row, 'userId') ?? '');
          if ($uid !== $mePerson->id) continue;
          $share += (float) (data_get($row, 'amount') ?? 0);
        }
      }
      return round($paid - $share, 2);
    };

    $openLists = 0;
    $settledLists = 0;
    $openItems = 0;
    foreach ($sharedLists as $list) {
      $progress = $listProgress($list);
      $openItems += max(0, $progress['total'] - $progress['done']);
      if ($progress['total'] === 0 || $progress['done'] < $progress['total']) {
        $openLists++;
      }
      if (abs($listMyBalance($list->id)) < 0.01) {
        $settledLists++;
      }
    }
  @endphp

  <div class="min-h-screen safe-bottom animate-fade-in">
    <div class="app-page-wrap pt-6 md:pt-6 lg:pt-8 pb-10 md:pb-10 space-y-6" data-collection-root>
      <x-page-header title="{{ __('Shared lists') }}" back>
        <x-slot:right>
          <a
            href="{{ route('app.shared-lists.new') }}"
            class="tap-target w-9 h-9 rounded-full bg-primary text-primary-foreground flex items-center justify-center shadow-sm active:scale-95 transition-transform"
            aria-label="{{ __('Create shared list') }}"
          >
            <x-lucide-plus class="w-5 h-5" />
          </a>
        </x-slot:right>
      </x-page-header>

      <div class="apple-card p-5 space-y-4">
        <div class="flex items-start justify-between gap-4">
          <div class="min-w-0">
            <p class="text-[13px] text-muted-foreground">{{ __('Share items, track checkout, and see who still needs to settle.') }}</p>
            <p class="mt-1 text-[21px] font-semibold text-foreground">
              {{ trans_choice(':count list|:count lists', $sharedLists->count(), ['count' => $sharedLists->count()]) }}
            </p>
          </div>
          <div class="w-12 h-12 rounded-[18px] bg-primary/10 text-[24px] flex items-center justify-center shrink-0">
            🛒
          </div>
        </div>

        <div class="grid grid-cols-3 gap-2.5">
          <div class="rounded-2xl bg-secondary/70 px-3 py-3">
            <p class="text-[11px] uppercase tracking-wide text-muted-foreground">{{ __('Open') }}</p>
            <p class="mt-1 text-[18px] font-semibold text-foreground">{{ $openLists }}</p>
          </div>
          <div class="rounded-2xl bg-secondary/70 px-3 py-3">
            <p class="text-[11px] uppercase tracking-wide text-muted-foreground">{{ __('Items left') }}</p>
            <p class="mt-1 text-[18px] font-semibold text-foreground">{{ $openItems }}</p>
          </div>
          <div class="rounded-2xl bg-secondary/70 px-3 py-3">
            <p class="text-[11px] uppercase tracking-wide text-muted-foreground">{{ __('Settled') }}</p>
            <p class="mt-1 text-[18px] font-semibold text-foreground">{{ $settledLists }}</p>
          </div>
        </div>
      </div>

      <div class="space-y-3" @class(['hidden' => $sharedLists->count() === 0])>
        <div class="relative">
          <x-lucide-search class="absolute left-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground/60" />
          <input
            type="text"
            placeholder="{{ __('Search lists, members, or items') }}"
            class="w-full rounded-xl bg-secondary/80 border-0 py-3 pl-10 pr-4 text-[15px] text-foreground placeholder:text-muted-foreground/50 focus:outline-none focus:ring-2 focus:ring-primary/30"
            data-collection-search
          />
        </div>

        <div class="flex gap-2 overflow-x-auto pb-1">
          <button type="button" class="shrink-0 rounded-full px-3.5 py-2 text-[13px] font-medium bg-primary text-primary-foreground shadow-sm" data-collection-chip="all" data-active="true">
            {{ __('All') }}
          </button>
          <button type="button" class="shrink-0 rounded-full px-3.5 py-2 text-[13px] font-medium bg-secondary/80 text-foreground" data-collection-chip="open" data-active="false">
            {{ __('Open') }}
          </button>
          <button type="button" class="shrink-0 rounded-full px-3.5 py-2 text-[13px] font-medium bg-secondary/80 text-foreground" data-collection-chip="checked-out" data-active="false">
            {{ __('Checked out') }}
          </button>
          <button type="button" class="shrink-0 rounded-full px-3.5 py-2 text-[13px] font-medium bg-secondary/80 text-foreground" data-collection-chip="settled" data-active="false">
            {{ __('Settled') }}
          </button>
        </div>
      </div>

      <div class="space-y-3">
        @foreach ($sharedLists as $list)
          @php
            $progress = $listProgress($list);
            $spent = (float) $expenses->where('shared_list_id', $list->id)->sum('amount');
            $amount = $listMyBalance($list->id);
            $pendingItems = max(0, $progress['total'] - $progress['done']);
            $isOpen = $progress['total'] === 0 || $pendingItems > 0;
            $isSettled = abs($amount) < 0.01;
            $fmtSpent = $money($spent);
            $fmtAmount = $money(abs($amount));
            $searchText = collect([
              $list->name,
              $list->members->pluck('name')->join(' '),
              $list->items->pluck('item_text')->join(' '),
            ])->filter()->join(' ');
          @endphp

          <a
            href="{{ route('app.shared-lists.detail', ['id' => $list->id]) }}"
            class="apple-card px-4 py-4 active:scale-[0.98] transition-transform block"
            data-collection-item
            data-collection-filters="{{ implode(' ', array_filter(['all', $isOpen ? 'open' : null, $spent > 0 ? 'checked-out' : null, $isSettled ? 'settled' : null])) }}"
            data-collection-text="{{ strtolower($searchText) }}"
          >
            <div class="flex items-start gap-3">
              <div class="w-12 h-12 rounded-[16px] bg-primary-muted flex items-center justify-center text-xl shrink-0">
                {{ $list->emoji }}
              </div>

              <div class="min-w-0 flex-1 space-y-4">
                <div class="flex items-start justify-between gap-3">
                  <div class="min-w-0">
                    <p class="font-semibold text-[16px] text-foreground leading-tight truncate">{{ $list->name }}</p>
                    <p class="text-[13px] text-muted-foreground mt-1">
                      {{ $list->members->count() }} {{ __('members') }} · {{ $progress['total'] }} {{ __('items') }}
                    </p>
                  </div>

                  <div class="flex gap-1.5 shrink-0">
                    @if ($isOpen)
                      <span class="rounded-full bg-amber-100 text-amber-700 px-2.5 py-1 text-[11px] font-medium">
                        {{ $pendingItems }} {{ __('left') }}
                      </span>
                    @endif
                    @if (! $isOpen && $progress['total'] > 0)
                      <span class="rounded-full bg-[hsl(var(--success)/0.12)] text-[hsl(var(--success))] px-2.5 py-1 text-[11px] font-medium">
                        {{ __('Done') }}
                      </span>
                    @endif
                  </div>
                </div>

                <div>
                  @php
                    $progressPct = $progress['total'] > 0 ? min(100, max(0, (int) round(($progress['done'] / $progress['total']) * 100))) : 0;
                  @endphp
                  <div class="h-2 rounded-full bg-secondary overflow-hidden">
                    <div class="h-full rounded-full bg-primary transition-all duration-500" style="width: {{ $progressPct }}%;"></div>
                  </div>
                  <p class="mt-1.5 text-[12px] text-muted-foreground">
                    {{ $progress['done'] }} / {{ $progress['total'] }} {{ __('items done') }}
                  </p>
                </div>

                <div class="flex items-end justify-between gap-3">
                  <div>
                    @if ($spent > 0)
                      <p class="text-[12px] text-muted-foreground">{{ __('Spent') }}</p>
                      <p class="text-[15px] font-semibold text-foreground tabular-nums">{{ $fmtSpent['primary'] }}</p>
                    @else
                      <p class="text-[12px] text-muted-foreground">{{ __('No checkout yet') }}</p>
                    @endif
                  </div>

                  <div class="text-right">
                    @if ($isSettled)
                      <p class="text-[12px] font-medium text-muted-foreground">{{ __('Settled') }}</p>
                    @else
                      <p class="text-[12px] text-muted-foreground">{{ $amount > 0 ? __('You’re owed') : __('You owe') }}</p>
                      <p class="text-[15px] font-semibold tabular-nums {{ $amount > 0 ? 'balance-positive' : 'balance-negative' }}">{{ $fmtAmount['primary'] }}</p>
                    @endif
                  </div>
                </div>
              </div>
            </div>
          </a>
        @endforeach
      </div>

      <a
        href="{{ route('app.shared-lists.new') }}"
        class="apple-card border-2 border-dashed border-border/60 px-4 py-4 flex items-center gap-3 active:scale-[0.98] transition-transform"
        @class(['hidden' => $sharedLists->count() === 0])
      >
        <div class="w-11 h-11 rounded-2xl bg-primary/10 flex items-center justify-center shrink-0">
          <x-lucide-plus class="w-5 h-5 text-primary" />
        </div>
        <div>
          <p class="text-[15px] font-semibold text-foreground">{{ __('Create another shared list') }}</p>
          <p class="text-[13px] text-muted-foreground">{{ __('Start a new checklist for the next run.') }}</p>
        </div>
      </a>

      <div class="hidden text-center py-12 space-y-3" data-collection-no-results>
        <div class="w-14 h-14 rounded-2xl bg-secondary/80 text-[26px] flex items-center justify-center mx-auto">🔎</div>
        <div>
          <p class="text-[17px] font-semibold text-foreground">{{ __('No shared lists match that search') }}</p>
          <p class="text-[14px] text-muted-foreground mt-1">{{ __('Try another name, member, item, or filter.') }}</p>
        </div>
      </div>

      <div class="space-y-8" data-collection-empty @class(['hidden' => $sharedLists->count() > 0])>
        <div class="text-center space-y-4">
          <div class="w-[72px] h-[72px] rounded-[20px] bg-primary-muted flex items-center justify-center text-[36px] mx-auto">
            🛒
          </div>
          <p class="text-[15px] text-muted-foreground leading-relaxed px-2">
            {{ __('Create a shared checklist, add items, and split checkout costs.') }}
          </p>
        </div>

        <ul class="space-y-3 px-1">
          @foreach ([
            'Add items as you go',
            'Record a checkout and split it',
            'Settle up with suggested payments',
          ] as $line)
            <li class="flex gap-3 items-start">
              <span class="mt-0.5 w-6 h-6 rounded-full bg-primary/15 flex items-center justify-center shrink-0">
                <x-lucide-check class="w-3.5 h-3.5 text-primary" />
              </span>
              <span class="text-[15px] text-foreground leading-snug pt-0.5">{{ __($line) }}</span>
            </li>
          @endforeach
        </ul>

        <a
          href="{{ route('app.shared-lists.new') }}"
          class="w-full py-4 rounded-2xl bg-primary text-primary-foreground text-[17px] font-semibold active:scale-[0.98] transition-transform text-center block"
        >
          {{ __('Create a shared list') }}
        </a>
      </div>
    </div>
  </div>
@endsection
