@extends('app.shell')

@section('body')
  @php
    /** @var \App\Models\SharedList $list */
  @endphp

  <div class="min-h-screen safe-bottom animate-in-up">
    <div class="app-page-wrap pt-6 md:pt-6 lg:pt-8 pb-6 md:pb-8 space-y-5">
      <x-page-header title="{{ $list->emoji }} {{ $list->name }}" back />

      <section class="space-y-3">
        <div class="flex items-center justify-between px-1">
          <div>
            <p class="section-header mb-1">{{ __('Who’s in it') }}</p>
          </div>
          <a
            href="{{ route('app.shared-lists.members', ['id' => $list->id]) }}"
            class="inline-flex items-center justify-center w-10 h-10 rounded-2xl apple-card text-[18px] font-semibold text-foreground active:scale-[0.98] transition-transform"
            aria-label="{{ __('Add someone') }}"
            title="{{ __('Add someone') }}"
          >
            +
          </a>
        </div>
        <div class="flex gap-4 overflow-x-auto pb-1 px-1">
          @foreach ($list->members as $m)
            <div class="flex flex-col items-center gap-1.5 min-w-[52px]">
              <div class="w-12 h-12 rounded-full bg-secondary flex items-center justify-center text-xl">
                {{ $m->avatar }}
              </div>
              <span class="text-[12px] font-medium text-foreground">{{ $m->name }}</span>
            </div>
          @endforeach
        </div>
      </section>

      <section>
        <div class="flex items-center justify-between mb-3 px-1">
          <p class="section-header">{{ __('List') }}</p>
        </div>
        <div class="apple-card divide-y divide-border/60 overflow-hidden">
          @if ($list->items->count() === 0)
            <p class="px-4 py-8 text-center text-[14px] text-muted-foreground">
              {{ __('No items yet.') }}
            </p>
          @else
            @foreach ($list->items as $item)
              <div class="px-4 py-3.5">
                <div class="flex items-start gap-3">
                  <form method="POST" action="{{ route('app.shared-lists.items.toggle', ['id' => $list->id, 'itemId' => $item->id]) }}" class="pt-0.5">
                    @csrf
                    <button type="submit" class="active:scale-[0.98] transition-transform">
                      <input type="checkbox" {{ $item->done ? 'checked' : '' }} class="w-5 h-5 rounded-md border-border accent-primary pointer-events-none" />
                    </button>
                  </form>

                  <div class="flex-1 min-w-0">
                    <div class="flex items-start justify-between gap-3">
                      <p class="text-[15px] truncate {{ $item->done ? 'line-through text-muted-foreground' : 'text-foreground' }}" data-item-text>
                        {{ $item->item_text }}
                      </p>
                    </div>
                  </div>

                  <div class="flex items-center gap-2 shrink-0 pt-0.5">
                    <button
                      type="button"
                      class="w-9 h-9 rounded-2xl apple-card flex items-center justify-center text-foreground active:scale-[0.98] transition-transform"
                      aria-label="{{ __('Edit item') }}"
                      title="{{ __('Edit') }}"
                      data-edit-btn
                    >
                      <x-lucide-pencil class="w-4 h-4" />
                    </button>

                    <form method="POST" action="{{ route('app.shared-lists.items.delete', ['id' => $list->id, 'itemId' => $item->id]) }}">
                      @csrf
                      <button
                        type="submit"
                        class="w-9 h-9 rounded-2xl apple-card flex items-center justify-center text-destructive active:scale-[0.98] transition-transform"
                        aria-label="{{ __('Remove item') }}"
                        title="{{ __('Remove') }}"
                      >
                        <x-lucide-trash-2 class="w-4 h-4" />
                      </button>
                    </form>
                  </div>
                </div>

                <div class="mt-3 hidden" data-edit-row>
                  <form method="POST" action="{{ route('app.shared-lists.items.update', ['id' => $list->id, 'itemId' => $item->id]) }}" class="flex items-center gap-2">
                    @csrf
                    <input
                      type="text"
                      name="text"
                      value="{{ $item->item_text }}"
                      class="flex-1 min-w-0 apple-card-inset px-4 py-3 text-[15px] text-foreground placeholder:text-muted-foreground/50 outline-none focus:ring-2 focus:ring-primary/15 rounded-2xl"
                      required
                    />

                    <button
                      type="submit"
                      class="w-9 h-9 rounded-2xl bg-primary text-primary-foreground flex items-center justify-center active:scale-[0.98] transition-transform"
                      aria-label="{{ __('Save') }}"
                      title="{{ __('Save') }}"
                    >
                      <x-lucide-check class="w-4 h-4" />
                    </button>

                    <button
                      type="button"
                      class="w-9 h-9 rounded-2xl apple-card flex items-center justify-center text-foreground active:scale-[0.98] transition-transform"
                      aria-label="{{ __('Cancel') }}"
                      title="{{ __('Cancel') }}"
                      data-cancel-btn
                    >
                      <x-lucide-x class="w-4 h-4" />
                    </button>
                  </form>
                </div>
              </div>
            @endforeach
          @endif
        </div>
      </section>

      <div class="flex gap-2">
        <form method="POST" action="{{ route('app.shared-lists.items.add', ['id' => $list->id]) }}" class="w-full space-y-2" id="add-item-form">
          @csrf
          <div class="flex gap-2">
            <input
              type="text"
              name="text"
              placeholder="{{ __('Add an item') }}"
              id="addItemInput"
              class="flex-1 apple-card-inset px-5 py-4 text-[16px] text-foreground placeholder:text-muted-foreground/50 outline-none focus:ring-2 focus:ring-primary/15 rounded-2xl"
              required
            />
            <button
              type="submit"
              class="shrink-0 w-12 h-12 rounded-2xl bg-primary text-primary-foreground flex items-center justify-center active:scale-[0.98] transition-transform"
              aria-label="{{ __('Add item') }}"
              title="{{ __('Add item') }}"
            >
              <x-lucide-plus class="w-5 h-5" />
            </button>
          </div>
        </form>
      </div>

      <section class="space-y-3">
        <p class="section-header mb-1 px-1">{{ __('Receipt') }}</p>

        @php
          /** @var \App\Models\Expense|null $latestCheckout */
          $checkout = $latestCheckout ?? null;
          $paidBy = $checkout?->paidBy;
          $locale = app()->getLocale();
          $displayCurrency = request()->user()?->profile?->currency ?: ($checkout?->currency ?: 'USD');
          $members = $list->members->values();
          $n = max(1, $members->count());
          $amount = $checkout ? (float) $checkout->amount : null;
          $cents = $amount !== null ? (int) round($amount * 100) : 0;
          $base = $n > 0 ? intdiv($cents, $n) : 0;
          $rem = $n > 0 ? ($cents - ($base * $n)) : 0;
        @endphp

        <div class="rounded-[26px] bg-[#fbfbfb] border border-border/60 overflow-hidden shadow-[0_14px_40px_rgba(0,0,0,0.08)]">
          {{-- Perforated top edge (cut-outs) --}}
          <div class="relative h-4 bg-[#fbfbfb]">
            <div class="absolute inset-x-0 bottom-0 translate-y-1/2 flex justify-between px-4 pointer-events-none">
              @for ($i = 0; $i < 12; $i++)
                <div class="w-6 h-6 rounded-full bg-background border border-border/60"></div>
              @endfor
            </div>
          </div>

          <div class="px-6 pt-6 pb-4 text-center">
            <p class="text-[11px] tracking-[0.22em] text-muted-foreground">RECEIPT</p>
            <p class="mt-2 text-[18px] font-semibold text-foreground">{{ $list->emoji }} {{ $list->name }}</p>
            <p class="mt-1 text-[12px] text-muted-foreground">
              @if ($checkout)
                {{ \Illuminate\Support\Carbon::parse($checkout->expense_date)->format('m-d-Y') }}
              @else
                —
              @endif
            </p>
          </div>

          <div class="px-6 pb-6 space-y-4 font-mono">
            @if (! $checkout)
              <form method="POST" action="{{ route('app.shared-lists.checkout', ['id' => $list->id]) }}" class="space-y-4" enctype="multipart/form-data">
                @csrf
                <div>
                  <p class="text-[11px] text-muted-foreground mb-2">{{ __('WHO PAID') }}</p>
                  <select
                    name="paid_by_person_id"
                    class="w-full bg-white/70 border border-border/60 px-4 py-3 rounded-2xl text-[14px] text-foreground outline-none focus:ring-2 focus:ring-primary/15"
                    required
                  >
                    @foreach ($list->members as $m)
                      <option value="{{ $m->id }}">{{ $m->avatar }} {{ $m->name }}</option>
                    @endforeach
                  </select>
                </div>

                <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
                  <div>
                    <p class="text-[11px] text-muted-foreground mb-2">{{ __('AMOUNT') }}</p>
                    <input
                      type="number"
                      step="0.01"
                      inputmode="decimal"
                      name="amount"
                      placeholder="{{ __('0.00') }}"
                      class="w-full bg-white/70 border border-border/60 px-4 py-3 rounded-2xl text-[16px] font-semibold text-foreground outline-none focus:ring-2 focus:ring-primary/15 tabular-nums"
                      required
                    />
                  </div>
                  <div>
                    <p class="text-[11px] text-muted-foreground mb-2">{{ __('DESCRIPTION') }}</p>
                    <input
                      type="text"
                      name="description"
                      placeholder="{{ __('Groceries') }}"
                      class="w-full bg-white/70 border border-border/60 px-4 py-3 rounded-2xl text-[14px] text-foreground outline-none focus:ring-2 focus:ring-primary/15"
                    />
                  </div>
                </div>

                <div>
                  <p class="text-[11px] text-muted-foreground mb-2">{{ __('ATTACH RECEIPT') }}</p>
                  <input
                    type="file"
                    name="receipt"
                    accept=".jpg,.jpeg,.png,.webp,.pdf"
                    class="w-full bg-white/70 border border-border/60 px-4 py-3 rounded-2xl text-[13px] text-foreground file:mr-3 file:rounded-xl file:border-0 file:bg-secondary file:px-3 file:py-2 file:text-[12px] file:font-semibold file:text-foreground"
                  />
                  @if ($list->receipt_path)
                    <a
                      href="{{ asset('storage/' . $list->receipt_path) }}"
                      target="_blank"
                      rel="noreferrer"
                      class="inline-block mt-2 text-[13px] font-semibold text-primary"
                    >
                      {{ __('View current receipt') }}
                    </a>
                  @endif
                </div>

                <button
                  type="submit"
                  class="w-full py-3.5 rounded-2xl bg-primary text-primary-foreground text-[15px] font-semibold active:scale-[0.98] transition-transform"
                >
                  {{ __('CHECKOUT') }}
                </button>
              </form>
            @else
              <div class="text-[12px] text-foreground/90">
                <div class="flex items-center justify-between">
                  <span class="text-muted-foreground">{{ __('PAID BY') }}</span>
                  <span class="font-semibold">{{ $paidBy?->avatar }} {{ $paidBy?->name ?? '—' }}</span>
                </div>
              </div>

              <div class="border-t border-dashed border-border/60"></div>

              <div class="text-[11px] tracking-[0.20em] text-muted-foreground">{{ __('SPLIT EQUALLY') }}</div>

              <div class="space-y-2 text-[13px]">
                @foreach ($members as $i => $m)
                  @php
                    $share = ($base + ($i < $rem ? 1 : 0)) / 100;
                    $isPayer = $checkout->paid_by_person_id === $m->id;
                  @endphp

                  <div class="flex items-center justify-between gap-3">
                    <div class="min-w-0">
                      <div class="flex items-center gap-2 min-w-0">
                        <span class="shrink-0">{{ $m->avatar }}</span>
                        <span class="truncate text-foreground">{{ $m->name }}</span>
                        @if ($isPayer)
                          <span class="shrink-0 text-[11px] text-muted-foreground">{{ __('(payer)') }}</span>
                        @endif
                      </div>
                    </div>

                    <div class="flex items-center gap-2 shrink-0">
                      @php
                        $fmtShare = \App\Support\Money::formatConvertedWithOriginal((float) $share, $checkout->currency ?: 'USD', $displayCurrency, $locale);
                      @endphp
                      <span class="tabular-nums font-semibold text-foreground">{{ $fmtShare['primary'] }}</span>
                      @if (! $isPayer && $share > 0)
                        <form method="POST" action="{{ route('app.shared-lists.settle.store', ['id' => $list->id]) }}">
                          @csrf
                          <input type="hidden" name="from_person_id" value="{{ $m->id }}" />
                          <input type="hidden" name="to_person_id" value="{{ $checkout->paid_by_person_id }}" />
                          <input type="hidden" name="amount" value="{{ number_format($share, 2, '.', '') }}" />
                          <button
                            type="submit"
                            class="w-9 h-9 rounded-2xl bg-primary text-primary-foreground flex items-center justify-center active:scale-[0.98] transition-transform"
                            aria-label="{{ __('Settle') }}"
                            title="{{ __('Settle') }}"
                          >
                            <x-lucide-check class="w-4 h-4" />
                          </button>
                        </form>
                      @endif
                    </div>
                  </div>
                @endforeach
              </div>

              <div class="border-t border-dashed border-border/60"></div>

              <div class="flex items-center justify-between text-[14px] font-semibold text-foreground">
                <span>{{ __('TOTAL') }}</span>
                @php
                  $fmtTotal = \App\Support\Money::formatConvertedWithOriginal((float) $checkout->amount, $checkout->currency ?: 'USD', $displayCurrency, $locale);
                @endphp
                <span class="tabular-nums">{{ $fmtTotal['primary'] }}</span>
              </div>
              @if ($fmtTotal['secondary'])
                <p class="text-[12px] text-muted-foreground tabular-nums -mt-2">
                  {{ $fmtTotal['secondary'] }}
                </p>
              @endif

              <div class="grid grid-cols-1 sm:grid-cols-2 gap-2 pt-1 font-sans">
                <form method="POST" action="{{ route('app.shared-lists.receipt.settleAll', ['id' => $list->id]) }}">
                  @csrf
                  <button
                    type="submit"
                    class="w-full py-3.5 rounded-2xl bg-primary text-primary-foreground text-[15px] font-semibold active:scale-[0.98] transition-transform"
                  >
                    {{ __('Settle all to payer') }}
                  </button>
                </form>

                <a
                  href="{{ route('app.shared-lists.settle', ['id' => $list->id]) }}"
                  class="block text-center w-full py-3.5 rounded-2xl border border-border/70 bg-white text-[15px] font-semibold text-foreground active:scale-[0.98] transition-transform"
                >
                  {{ __('Open settle view') }}
                </a>
              </div>

              @if ($list->receipt_path)
                <a
                  href="{{ asset('storage/' . $list->receipt_path) }}"
                  target="_blank"
                  rel="noreferrer"
                  class="inline-flex items-center gap-2 text-[13px] font-semibold text-primary"
                >
                  <x-lucide-paperclip class="w-4 h-4" />
                  {{ __('View attached receipt') }}
                </a>
              @endif
            @endif
          </div>

          <div class="h-4 bg-background"></div>
          {{-- Perforated bottom edge (cut-outs) --}}
          <div class="relative h-4 bg-[#fbfbfb]">
            <div class="absolute inset-x-0 top-0 -translate-y-1/2 flex justify-between px-4 pointer-events-none">
              @for ($i = 0; $i < 12; $i++)
                <div class="w-6 h-6 rounded-full bg-background border border-border/60"></div>
              @endfor
            </div>
          </div>
        </div>
      </section>

      <section class="space-y-3">
        <p class="section-header mb-1 px-1">{{ __('Notes') }}</p>
        <div class="apple-card p-5">
          <form method="POST" action="{{ route('app.shared-lists.notes.update', ['id' => $list->id]) }}" class="space-y-4">
            @csrf
            <textarea
              name="notes"
              rows="4"
              placeholder="{{ __('Add notes…') }}"
              class="w-full min-h-[120px] apple-card-inset px-4 py-3.5 rounded-2xl text-[15px] text-foreground placeholder:text-muted-foreground/50 outline-none focus:ring-2 focus:ring-primary/15 resize-none"
            >{{ old('notes', $list->notes) }}</textarea>
            <x-primary-button variant="sheet">{{ __('Save notes') }}</x-primary-button>
          </form>
        </div>
      </section>
    </div>
  </div>

  <script>
    (function () {
      document.querySelectorAll('[data-edit-btn]').forEach((btn) => {
        const row = btn.closest('div.px-4.py-3\\.5');
        if (!row) return;
        const editRow = row.querySelector('[data-edit-row]');
        const cancelBtn = row.querySelector('[data-cancel-btn]');
        const input = row.querySelector('input[name="text"]');
        const labelText = row.querySelector('[data-item-text]');

        const open = () => {
          if (!editRow) return;
          editRow.classList.remove('hidden');
          input?.focus();
          input?.select();
        };
        const close = () => {
          if (!editRow) return;
          editRow.classList.add('hidden');
          if (input && labelText) input.value = (labelText.textContent || '').trim();
        };

        btn.addEventListener('click', open);
        cancelBtn?.addEventListener('click', close);
      });
    })();
  </script>

  {{-- Replaced by contextual bottom action bar on this screen --}}
@endsection

@section('bottom_nav')
  <x-bottom-nav
    mode="context"
    aria-label="{{ __('Shared list actions') }}"
    primary-label="Add item"
    primary-onclick="(function(){ const el=document.getElementById('addItemInput'); if(el){ el.scrollIntoView({behavior:'smooth', block:'center'}); el.focus(); el.select(); } })()"
  />
@endsection

