@extends('app.shell')

@section('body')
  @php
    /** @var \Illuminate\Support\Collection<int, \App\Models\Group> $groups */
    /** @var \Illuminate\Support\Collection<int, \App\Models\Expense> $expenses */
    /** @var \Illuminate\Support\Collection<int, \App\Models\Activity> $activities */
    /** @var \Illuminate\Support\Collection<int, \App\Models\SharedList> $sharedLists */
    /** @var \Illuminate\Support\Collection<int, \App\Models\SharedPurchase> $sharedPurchases */
    /** @var \App\Models\Person|null $mePerson */
    /** @var float $overallBalance */

    $isPositive = ($overallBalance ?? 0) >= 0;
    $barWidth = min((abs((float) ($overallBalance ?? 0)) / 500) * 100, 100);

    $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);
    };
  @endphp

  <div class="min-h-screen safe-bottom animate-fade-in">
    <div class="app-page-wrap pt-14 md:pt-6 lg:pt-8 pb-6 md:pb-8 space-y-7">
      {{-- Header --}}
      <div class="flex items-center justify-between">
        <div>
          <p class="text-[13px] text-muted-foreground">{{ __('Hello') }}</p>
          <h1 class="text-[28px] font-bold text-foreground tracking-tight">{{ __('Dashboard') }}</h1>
        </div>
        <a
          href="{{ route('app.account') }}"
          class="w-11 h-11 rounded-full bg-secondary flex items-center justify-center text-xl active:scale-95 transition-transform"
          aria-label="{{ __('Account') }}"
        >
          {{ $mePerson?->avatar ?? '🙂' }}
        </a>
      </div>

      {{-- BalanceSummary --}}
      <div class="apple-card p-5 animate-fade-in">
        <p class="text-[13px] text-muted-foreground mb-1.5">
          {{ $isPositive ? __('You are owed overall') : __('You owe overall') }}
        </p>
        <p class="text-[34px] font-bold tracking-tight leading-none {{ $isPositive ? 'balance-positive' : 'balance-negative' }}">
          @php $fmtBal = $money(abs((float) ($overallBalance ?? 0)), $displayCurrency); @endphp
          {{ $fmtBal['primary'] }}
        </p>

        <div class="mt-4 h-[6px] rounded-full bg-secondary overflow-hidden">
          <div
            class="h-full rounded-full transition-all duration-700 ease-out {{ $isPositive ? 'bg-success' : 'bg-owe' }}"
            style="width: {{ $barWidth }}%;"
          ></div>
        </div>
        <div class="flex justify-between mt-1.5">
          <span class="text-[11px] text-muted-foreground">{{ __('Balanced') }}</span>
          <span class="text-[11px] font-medium {{ $isPositive ? 'balance-positive' : 'balance-negative' }}">
            {{ $isPositive ? '+' : '-' }}{{ $fmtBal['primary'] }}
          </span>
        </div>
      </div>

      {{-- Groups --}}
      <section>
        <div class="flex items-center justify-between mb-3 px-1">
          <p class="section-header">{{ __('Your groups') }}</p>
          <a href="{{ route('app.groups') }}" class="text-[13px] font-medium text-primary">{{ __('See all') }}</a>
        </div>

        @if ($groups->count() === 0)
          <a
            href="{{ route('app.create-group') }}"
            class="w-full rounded-2xl border-2 border-dashed border-border/60 bg-muted/20 px-5 py-6 text-center active:scale-[0.99] transition-transform block"
          >
            <div class="w-11 h-11 rounded-xl bg-primary/10 flex items-center justify-center mx-auto mb-3">
              <x-lucide-users class="w-5 h-5 text-primary" />
            </div>
            <p class="font-semibold text-[15px] text-foreground">{{ __('Create a group') }}</p>
            <p class="text-[13px] text-muted-foreground mt-1 leading-relaxed">{{ __('Start splitting expenses with friends.') }}</p>
          </a>
        @else
          <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-2.5">
            @foreach ($groups->take(4) as $g)
              <a
                href="{{ route('app.group.detail', ['id' => $g->id]) }}"
                class="apple-card flex flex-col px-3 py-3 gap-2 active:scale-[0.97] transition-transform snap-start"
              >
                <div class="flex items-center gap-2.5 min-w-0 w-full">
                  <div class="rounded-[14px] bg-primary-muted flex items-center justify-center shrink-0 w-9 h-9 text-lg">
                    {{ $g->emoji }}
                  </div>
                  <div class="flex-1 min-w-0">
                    <h3 class="font-semibold text-foreground leading-tight truncate text-[13px]">{{ $g->name }}</h3>
                    <p class="text-muted-foreground mt-0.5 text-[11px]">{{ $g->members->count() }} {{ __('members') }}</p>
                  </div>
                </div>
              </a>
            @endforeach
          </div>
        @endif
      </section>

      {{-- Shared Lists --}}
      <section>
        <div class="flex items-center justify-between mb-3 px-1">
          <p class="section-header">{{ __('Shared lists') }}</p>
          @if ($sharedLists->count() > 0)
            <a href="{{ route('app.shared-lists.intro') }}" class="text-[13px] font-medium text-primary">{{ __('See all') }}</a>
          @endif
        </div>

        @if ($sharedLists->count() === 0)
          <a
            href="{{ route('app.shared-lists.intro') }}"
            class="w-full rounded-2xl border-2 border-dashed border-border/60 bg-muted/20 px-5 py-6 text-center active:scale-[0.99] transition-transform block"
          >
            <div class="w-11 h-11 rounded-xl bg-primary/10 flex items-center justify-center mx-auto mb-3">
              <x-lucide-shopping-cart class="w-5 h-5 text-primary" />
            </div>
            <p class="font-semibold text-[15px] text-foreground">{{ __('Create a shared list') }}</p>
            <p class="text-[13px] text-muted-foreground mt-1 leading-relaxed">{{ __('Track items and split the checkout.') }}</p>
          </a>
        @else
          <div class="flex gap-2.5 overflow-x-auto pb-1 snap-x snap-mandatory -mx-1 px-1 scrollbar-hide">
            @foreach ($sharedLists as $list)
              @php
                $p = $listProgress($list);
                $spent = (float) $expenses->where('shared_list_id', $list->id)->sum('amount');
                $amt = $listMyBalance($list->id);
              @endphp
              <a
                href="{{ route('app.shared-lists.detail', ['id' => $list->id]) }}"
                class="apple-card shrink-0 w-[156px] px-3.5 py-3.5 text-left active:scale-[0.97] transition-transform snap-start flex flex-col gap-2.5 min-h-[116px]"
              >
                <div class="w-10 h-10 rounded-[12px] bg-primary-muted flex items-center justify-center text-xl">
                  {{ $list->emoji }}
                </div>
                <div class="min-w-0 flex-1">
                  <p class="font-semibold text-[14px] text-foreground leading-tight line-clamp-2">{{ $list->name }}</p>
                  <p class="text-[12px] text-muted-foreground mt-1 tabular-nums">
                    {{ $p['done'] }} / {{ $p['total'] }} {{ __('done') }}
                  </p>
                  @if ($spent > 0)
                    <p class="text-[11px] text-muted-foreground mt-0.5 tabular-nums">
                      @php $fmtSpent = $money($spent, $displayCurrency); @endphp
                      {{ __('Spent') }} {{ $fmtSpent['primary'] }}
                    </p>
                  @endif
                  @if (abs($amt) >= 0.01)
                    <p class="text-[11px] font-medium mt-0.5 tabular-nums {{ $amt >= 0 ? 'balance-positive' : 'balance-negative' }}">
                      @php $fmtAmt = $money(abs($amt), $displayCurrency); @endphp
                      {{ $amt >= 0 ? __('Owed') . ' ' : __('Owe') . ' ' }}{{ $fmtAmt['primary'] }}
                    </p>
                  @endif
                </div>
              </a>
            @endforeach

            <a
              href="{{ route('app.shared-lists.new') }}"
              class="shrink-0 w-[156px] rounded-2xl border-2 border-dashed border-border/60 bg-muted/10 flex flex-col items-center justify-center gap-2 min-h-[116px] active:scale-[0.97] transition-transform snap-start"
              aria-label="{{ __('New list') }}"
            >
              <div class="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center">
                <x-lucide-plus class="w-5 h-5 text-primary" />
              </div>
              <span class="text-[13px] font-medium text-foreground">{{ __('New') }}</span>
            </a>
          </div>
        @endif
      </section>

      {{-- Shared Purchases --}}
      <section>
        <div class="flex items-center justify-between mb-3 px-1">
          <p class="section-header">{{ __('Shared purchases') }}</p>
          @if ($sharedPurchases->count() > 0)
            <a href="{{ route('app.shared-purchases.intro') }}" class="text-[13px] font-medium text-primary">{{ __('See all') }}</a>
          @endif
        </div>

        @if ($sharedPurchases->count() === 0)
          <a
            href="{{ route('app.shared-purchases.intro') }}"
            class="w-full rounded-2xl border-2 border-dashed border-border/60 bg-muted/20 px-5 py-6 text-center active:scale-[0.99] transition-transform block"
          >
            <div class="w-11 h-11 rounded-xl bg-primary/10 flex items-center justify-center mx-auto mb-3">
              <x-lucide-package class="w-5 h-5 text-primary" />
            </div>
            <p class="font-semibold text-[15px] text-foreground">{{ __('Create a shared purchase') }}</p>
            <p class="text-[13px] text-muted-foreground mt-1 leading-relaxed">{{ __('Plan a bigger buy together.') }}</p>
          </a>
        @else
          <div class="flex gap-2.5 overflow-x-auto pb-1 snap-x snap-mandatory -mx-1 px-1 scrollbar-hide">
            @foreach ($sharedPurchases as $purchase)
              @php
                $status = $purchase->status ?? 'planning';
                $statusLabel = $status === 'bought' ? __('Bought') : ($status === 'decided' ? __('Decided') : __('Planning'));
                $statusColor = $status === 'bought'
                  ? 'bg-[hsl(var(--success)/0.12)] text-[hsl(var(--success))]'
                  : ($status === 'decided' ? 'bg-primary/10 text-primary' : 'bg-secondary text-muted-foreground');
              @endphp
              <a
                href="{{ route('app.shared-purchases.detail', ['id' => $purchase->id]) }}"
                class="apple-card shrink-0 w-[156px] px-3.5 py-3.5 text-left active:scale-[0.97] transition-transform snap-start flex flex-col gap-2.5 min-h-[116px]"
              >
                <div class="w-10 h-10 rounded-[12px] bg-primary-muted flex items-center justify-center text-xl">
                  {{ $purchase->emoji }}
                </div>
                <div class="min-w-0 flex-1">
                  <p class="font-semibold text-[14px] text-foreground leading-tight line-clamp-2">{{ $purchase->name }}</p>
                  <span class="inline-block mt-1.5 text-[11px] font-medium px-2 py-0.5 rounded-full {{ $statusColor }}">
                    {{ $statusLabel }}
                  </span>
                </div>
              </a>
            @endforeach

            <a
              href="{{ route('app.shared-purchases.new') }}"
              class="shrink-0 w-[156px] rounded-2xl border-2 border-dashed border-border/60 bg-muted/10 flex flex-col items-center justify-center gap-2 min-h-[116px] active:scale-[0.97] transition-transform snap-start"
              aria-label="{{ __('New purchase') }}"
            >
              <div class="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center">
                <x-lucide-plus class="w-5 h-5 text-primary" />
              </div>
              <span class="text-[13px] font-medium text-foreground">{{ __('New') }}</span>
            </a>
          </div>
        @endif
      </section>

      {{-- Recent Activity --}}
      @if ($activities->count() > 0)
        <section>
          <div class="flex items-center justify-between mb-2 px-1">
            <p class="section-header">{{ __('Recent activity') }}</p>
            <a href="{{ route('app.activity') }}" class="text-[13px] font-medium text-primary">{{ __('See all') }}</a>
          </div>
          <div class="apple-card px-4">
            @foreach ($activities->take(4) as $i => $a)
              <div>
                <div class="flex items-center gap-3 py-3">
                  <div class="w-10 h-10 rounded-full bg-secondary flex items-center justify-center text-lg shrink-0">
                    {{ $a->user?->avatar ?? '🙂' }}
                  </div>
                  <div class="flex-1 min-w-0">
                    <p class="text-[14px] text-foreground leading-snug">
                      <span class="font-semibold">
                        {{ ($mePerson && $a->user_person_id === $mePerson->id) ? __('You') : ($a->user?->name ?? __('Someone')) }}
                      </span>
                      <span class="text-muted-foreground">{{ $a->description }}</span>
                    </p>
                    <p class="text-[12px] text-muted-foreground mt-0.5">
                      @if ($a->list_name || $a->group_name)
                        <span>
                          {{ $a->list_name ?: $a->group_name }} ·
                        </span>
                      @endif
                      {{ optional($a->activity_at)->diffForHumans() }}
                    </p>
                  </div>
                  @if ($a->amount !== null)
                    <p class="text-[15px] font-semibold text-foreground shrink-0 tabular-nums">
                      @php $fmtAct = $money((float) $a->amount, $displayCurrency); @endphp
                      {{ $fmtAct['primary'] }}
                    </p>
                  @endif
                </div>
                @if ($i < 3)
                  <div class="subtle-divider ml-[52px]"></div>
                @endif
              </div>
            @endforeach
          </div>
        </section>
      @endif
    </div>
  </div>
@endsection

