@extends('layouts.user')

@section('title', __('user_dashboard.dashboard'))
@section('breadcrumb', __('user_dashboard.dashboard'))
@section('page_title', __('user_dashboard.dashboard'))

@section('content')
@php
  $m = fn($v) => number_format((float)$v, 2);
  $currentMonthLabel = now()->format('F Y');

  $statCards = [
    [
      'title' => __('user_dashboard.total_balance'),
      'value' => $m($totalBalance ?? 0),
      'valueClass' => ($totalBalance ?? 0) >= 0 ? 'text-emerald-600' : 'text-rose-600',
      'desc' => __('user_dashboard.total_balance_desc'),
      'theme' => 'emerald',
      'icon' => 'balance',
    ],
    [
      'title' => __('user_dashboard.total_expense'),
      'value' => $m($totalExpense ?? 0),
      'valueClass' => 'text-rose-600',
      'desc' => __('user_dashboard.current_month_expense_desc'),
      'theme' => 'rose',
      'icon' => 'expense',
      'tooltip' => __('user_dashboard.total_expense_tooltip'),
      'monthBadge' => $currentMonthLabel,
    ],
    [
      'title' => __('user_dashboard.receivable'),
      'value' => $m($totalReceivable ?? 0),
      'valueClass' => 'text-amber-600',
      'desc' => __('user_dashboard.receivable_desc'),
      'theme' => 'amber',
      'icon' => 'customer',
    ],
    [
      'title' => __('user_dashboard.payable'),
      'value' => $m($totalLiabilities ?? 0),
      'valueClass' => 'text-violet-700',
      'desc' => __('user_dashboard.payable_desc'),
      'theme' => 'violet',
      'icon' => 'supplier',
    ],
    [
      'title' => __('user_dashboard.today_income'),
      'value' => $m($todayIncome ?? 0),
      'valueClass' => 'text-emerald-600',
      'desc' => __('user_dashboard.today_income_desc'),
      'theme' => 'sky',
      'icon' => 'income',
    ],
    [
      'title' => __('user_dashboard.today_expense'),
      'value' => $m($todayExpense ?? 0),
      'valueClass' => 'text-rose-600',
      'desc' => __('user_dashboard.today_expense_desc'),
      'theme' => 'pink',
      'icon' => 'today_expense',
    ],
    [
      'title' => __('user_dashboard.loan_finance_cost'),
      'value' => $m($loanFinanceCost ?? 0),
      'valueClass' => 'text-green-600',
      'desc' => __('user_dashboard.current_month_loan_finance_cost_desc'),
      'theme' => 'green',
      'icon' => 'loan_finance',
      'tooltip' => __('user_dashboard.loan_finance_cost_tooltip'),
      'monthBadge' => $currentMonthLabel,
    ],
  ];

  function cardTheme($theme) {
      return match ($theme) {
          'emerald' => [
              'card' => 'border-emerald-200 bg-gradient-to-br from-emerald-50 via-white to-emerald-100/80',
              'orb1' => 'bg-emerald-200/50',
              'orb2' => 'bg-lime-200/40',
              'wave' => 'from-emerald-200/40 via-emerald-100/30 to-transparent',
              'line' => 'border-emerald-300/40',
              'iconBg' => 'bg-emerald-500/10 text-emerald-600',
          ],
          'rose' => [
              'card' => 'border-rose-200 bg-gradient-to-br from-rose-50 via-white to-pink-100/80',
              'orb1' => 'bg-rose-200/50',
              'orb2' => 'bg-pink-200/40',
              'wave' => 'from-rose-200/40 via-pink-100/30 to-transparent',
              'line' => 'border-rose-300/40',
              'iconBg' => 'bg-rose-500/10 text-rose-600',
          ],
          'amber' => [
              'card' => 'border-amber-200 bg-gradient-to-br from-amber-50 via-white to-orange-100/80',
              'orb1' => 'bg-amber-200/50',
              'orb2' => 'bg-orange-200/40',
              'wave' => 'from-amber-200/40 via-orange-100/30 to-transparent',
              'line' => 'border-amber-300/40',
              'iconBg' => 'bg-amber-500/10 text-amber-600',
          ],
          'violet' => [
              'card' => 'border-violet-200 bg-gradient-to-br from-violet-50 via-white to-purple-100/80',
              'orb1' => 'bg-violet-200/50',
              'orb2' => 'bg-purple-200/40',
              'wave' => 'from-violet-200/40 via-purple-100/30 to-transparent',
              'line' => 'border-violet-300/40',
              'iconBg' => 'bg-violet-500/10 text-violet-700',
          ],
          'sky' => [
              'card' => 'border-sky-200 bg-gradient-to-br from-sky-50 via-white to-cyan-100/80',
              'orb1' => 'bg-sky-200/50',
              'orb2' => 'bg-cyan-200/40',
              'wave' => 'from-sky-200/40 via-cyan-100/30 to-transparent',
              'line' => 'border-sky-300/40',
              'iconBg' => 'bg-sky-500/10 text-sky-600',
          ],
          'pink' => [
              'card' => 'border-pink-200 bg-gradient-to-br from-pink-50 via-white to-rose-100/80',
              'orb1' => 'bg-pink-200/50',
              'orb2' => 'bg-rose-200/40',
              'wave' => 'from-pink-200/40 via-rose-100/30 to-transparent',
              'line' => 'border-pink-300/40',
              'iconBg' => 'bg-pink-500/10 text-pink-600',
          ],
          'green' => [
              'card' => 'border-green-200 bg-gradient-to-br from-green-50 via-white to-emerald-100/80',
              'orb1' => 'bg-green-200/50',
              'orb2' => 'bg-emerald-200/40',
              'wave' => 'from-green-200/40 via-emerald-100/30 to-transparent',
              'line' => 'border-green-300/40',
              'iconBg' => 'bg-green-500/10 text-green-600',
          ],
          default => [
              'card' => 'border-slate-200 bg-white',
              'orb1' => 'bg-slate-200/50',
              'orb2' => 'bg-slate-100/40',
              'wave' => 'from-slate-200/40 via-slate-100/30 to-transparent',
              'line' => 'border-slate-300/40',
              'iconBg' => 'bg-slate-500/10 text-slate-600',
          ],
      };
  }
@endphp

<div class="w-full px-1 sm:px-2 lg:px-3 space-y-6">
  @if(session('warning'))
    <div class="rounded-2xl border border-amber-100 bg-amber-50 px-4 py-3 text-amber-800 shadow-sm">
      ⚠ {{ session('warning') }}
    </div>
  @endif

  <div class="flex items-center justify-end">
    <div class="inline-flex items-center rounded-full border border-slate-200 bg-white px-3 py-1.5 text-xs font-semibold text-slate-600 shadow-sm">
      {{ __('user_dashboard.running_month') }}: {{ $currentMonthLabel }}
    </div>
  </div>

  {{-- Main Summary Cards --}}
  <div class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
    @foreach(array_slice($statCards, 0, 4) as $card)
      @php($theme = cardTheme($card['theme']))
      <div class="group relative overflow-hidden rounded-3xl border p-5 shadow-sm transition duration-300 hover:-translate-y-0.5 hover:shadow-lg {{ $theme['card'] }}">
        <div class="absolute inset-0 pointer-events-none">
          <div class="absolute -right-8 -top-8 h-28 w-28 rounded-full blur-2xl {{ $theme['orb1'] }}"></div>
          <div class="absolute right-10 bottom-0 h-20 w-20 rounded-full blur-2xl {{ $theme['orb2'] }}"></div>
          <div class="absolute inset-x-0 bottom-0 h-16 bg-gradient-to-r {{ $theme['wave'] }}"></div>
          <div class="absolute -bottom-8 left-1/2 h-24 w-[140%] -translate-x-1/2 rounded-[100%] border {{ $theme['line'] }}"></div>
          <div class="absolute -bottom-10 left-1/2 h-24 w-[120%] -translate-x-1/2 rounded-[100%] border {{ $theme['line'] }}"></div>
        </div>

        <div class="relative z-10 flex items-start justify-between gap-4">
          <div class="min-w-0">
            <div class="flex flex-wrap items-center gap-2">
              <p class="text-sm text-slate-500">{{ $card['title'] }}</p>

              @if(!empty($card['monthBadge']))
                <span class="rounded-full border border-white/60 bg-white/70 px-2 py-0.5 text-[10px] font-semibold text-slate-600 backdrop-blur">
                  {{ $card['monthBadge'] }}
                </span>
              @endif

              @if(!empty($card['tooltip']))
                <div class="relative group/info">
                  <button type="button" class="inline-flex h-5 w-5 items-center justify-center rounded-full border border-slate-300 bg-white/80 text-[11px] font-bold text-slate-500">
                    i
                  </button>
                  <div class="pointer-events-none absolute left-0 top-7 z-30 w-56 rounded-xl border border-slate-200 bg-slate-900 px-3 py-2 text-xs text-white opacity-0 shadow-lg transition group-hover/info:opacity-100">
                    {{ $card['tooltip'] }}
                  </div>
                </div>
              @endif
            </div>

            <h2 class="mt-1 text-2xl font-extrabold {{ $card['valueClass'] }}">
              {{ $card['value'] }}
            </h2>
            <p class="mt-1 text-xs text-slate-500">{{ $card['desc'] }}</p>
          </div>

          <div class="shrink-0 rounded-2xl p-3 backdrop-blur-sm {{ $theme['iconBg'] }}">
            @if($card['icon'] === 'balance')
              <svg class="h-8 w-8" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8">
                <path d="M12 3v18M5 8h14M7 8c0 2-1.5 4-3 4s-3-2-3-4h6Zm16 0c0 2-1.5 4-3 4s-3-2-3-4h6ZM8 21h8"/>
              </svg>
            @elseif($card['icon'] === 'expense')
              <svg class="h-8 w-8" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8">
                <rect x="3" y="6" width="18" height="12" rx="2"/>
                <path d="M3 10h18M7 14h3"/>
              </svg>
            @elseif($card['icon'] === 'customer')
              <svg class="h-8 w-8" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8">
                <path d="M17 21v-2a4 4 0 0 0-4-4H7a4 4 0 0 0-4 4v2"/>
                <circle cx="10" cy="7" r="4"/>
                <path d="M21 21v-2a4 4 0 0 0-3-3.87"/>
                <path d="M16 3.13a4 4 0 0 1 0 7.75"/>
              </svg>
            @elseif($card['icon'] === 'supplier')
              <svg class="h-8 w-8" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8">
                <path d="M3 7l9-4 9 4-9 4-9-4Z"/>
                <path d="M3 7v10l9 4 9-4V7"/>
                <path d="M12 11v10"/>
              </svg>
            @endif
          </div>
        </div>
      </div>
    @endforeach
  </div>

  {{-- Today + Loan Finance --}}
  <div class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
    @foreach(array_slice($statCards, 4, 3) as $card)
      @php($theme = cardTheme($card['theme']))
      <div class="group relative overflow-hidden rounded-3xl border p-5 shadow-sm transition duration-300 hover:-translate-y-0.5 hover:shadow-lg {{ $theme['card'] }}">
        <div class="absolute inset-0 pointer-events-none">
          <div class="absolute -right-8 top-2 h-24 w-24 rounded-full blur-2xl {{ $theme['orb1'] }}"></div>
          <div class="absolute left-10 bottom-0 h-20 w-20 rounded-full blur-2xl {{ $theme['orb2'] }}"></div>
          <div class="absolute inset-x-0 bottom-0 h-16 bg-gradient-to-r {{ $theme['wave'] }}"></div>
          <div class="absolute -bottom-8 left-1/2 h-24 w-[140%] -translate-x-1/2 rounded-[100%] border {{ $theme['line'] }}"></div>
          <div class="absolute -bottom-10 left-1/2 h-24 w-[120%] -translate-x-1/2 rounded-[100%] border {{ $theme['line'] }}"></div>
        </div>

        <div class="relative z-10 flex items-start justify-between gap-4">
          <div class="min-w-0">
            <div class="flex flex-wrap items-center gap-2">
              <p class="text-sm text-slate-500">{{ $card['title'] }}</p>

              @if(!empty($card['monthBadge']))
                <span class="rounded-full border border-white/60 bg-white/70 px-2 py-0.5 text-[10px] font-semibold text-slate-600 backdrop-blur">
                  {{ $card['monthBadge'] }}
                </span>
              @endif

              @if(!empty($card['tooltip']))
                <div class="relative group/info">
                  <button type="button" class="inline-flex h-5 w-5 items-center justify-center rounded-full border border-slate-300 bg-white/80 text-[11px] font-bold text-slate-500">
                    i
                  </button>
                  <div class="pointer-events-none absolute left-0 top-7 z-30 w-60 rounded-xl border border-slate-200 bg-slate-900 px-3 py-2 text-xs text-white opacity-0 shadow-lg transition group-hover/info:opacity-100">
                    {{ $card['tooltip'] }}
                  </div>
                </div>
              @endif
            </div>

            <h2 class="mt-1 text-xl font-extrabold {{ $card['valueClass'] }}">
              {{ $card['value'] }}
            </h2>
            <p class="mt-1 text-xs text-slate-500">{{ $card['desc'] }}</p>
          </div>

          <div class="shrink-0 rounded-2xl p-3 backdrop-blur-sm {{ $theme['iconBg'] }}">
            @if($card['icon'] === 'income')
              <svg class="h-8 w-8" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8">
                <rect x="3" y="5" width="18" height="14" rx="2"/>
                <path d="M3 10h18"/>
                <path d="M12 13c-1.1 0-2 .67-2 1.5S10.9 16 12 16s2 .67 2 1.5S13.1 19 12 19"/>
                <path d="M12 12v8"/>
              </svg>
            @elseif($card['icon'] === 'today_expense')
              <svg class="h-8 w-8" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8">
                <path d="M7 3v3M17 3v3M4 8h16"/>
                <rect x="4" y="5" width="16" height="16" rx="2"/>
                <path d="M9 14h6M9 18h3"/>
              </svg>
            @elseif($card['icon'] === 'loan_finance')
              <svg class="h-8 w-8" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8">
                <path d="M12 2v20"/>
                <path d="M17 5H9.5a3.5 3.5 0 0 0 0 7H14.5a3.5 3.5 0 0 1 0 7H6"/>
              </svg>
            @endif
          </div>
        </div>
      </div>
    @endforeach
  </div>

  {{-- Charts --}}
  <div class="grid grid-cols-1 gap-6 lg:grid-cols-2">
    <div class="rounded-3xl border bg-white p-6 shadow-sm">
      <div class="mb-3 flex items-center justify-between">
        <h3 class="font-extrabold">{{ __('user_dashboard.monthly_expense') }}</h3>
        <span class="text-xs text-slate-500">{{ __('user_dashboard.year') }}: {{ now()->year }}</span>
      </div>
      <canvas id="expenseChart" height="140"></canvas>
    </div>

    <div class="relative overflow-hidden rounded-3xl border bg-white p-6 shadow-sm">
      <div class="absolute inset-x-0 bottom-0 h-24 bg-gradient-to-r from-violet-100/40 via-amber-100/40 to-pink-100/40 pointer-events-none"></div>
      <div class="absolute -bottom-8 left-1/2 h-24 w-[140%] -translate-x-1/2 rounded-[100%] border border-amber-200/50 pointer-events-none"></div>
      <div class="absolute -bottom-12 left-1/2 h-24 w-[120%] -translate-x-1/2 rounded-[100%] border border-pink-200/40 pointer-events-none"></div>

      <div class="relative z-10">
        <div class="mb-3 flex items-center justify-between">
          <h3 class="font-extrabold">{{ __('user_dashboard.account_distribution') }}</h3>
          <span class="text-xs text-slate-500">{{ __('user_dashboard.all_active_accounts') }}</span>
        </div>
        <canvas id="accountChart" height="140"></canvas>
      </div>
    </div>
  </div>

  {{-- Accounts Table --}}
  <div class="rounded-3xl border bg-white p-6 shadow-sm">
    <div class="mb-3 flex items-center justify-between">
      <h3 class="font-extrabold">{{ __('user_dashboard.accounts') }}</h3>
      <span class="text-xs text-slate-500">{{ __('user_dashboard.computed_opening_ledger') }}</span>
    </div>

    <div class="overflow-x-auto">
      <table class="min-w-full text-sm">
        <thead>
          <tr class="border-b text-left text-slate-500">
            <th class="py-2">{{ __('user_dashboard.name') }}</th>
            <th>{{ __('user_dashboard.type') }}</th>
            <th>{{ __('user_dashboard.opening') }}</th>
            <th class="text-right">{{ __('user_dashboard.balance') }}</th>
          </tr>
        </thead>
        <tbody>
          @forelse($accounts as $a)
            <tr class="border-b last:border-0">
              <td class="py-3 font-semibold">{{ $a->name }}</td>
              <td>
                <span class="rounded-full border bg-slate-50 px-2 py-1 text-xs">
                  {{ strtoupper($a->type) }}
                </span>
              </td>
              <td>{{ $m($a->opening_balance) }}</td>
              <td class="text-right font-extrabold {{ $a->balance >= 0 ? 'text-emerald-600' : 'text-rose-600' }}">
                {{ $m($a->balance) }}
              </td>
            </tr>
          @empty
            <tr>
              <td colspan="4" class="py-6 text-center text-slate-500">{{ __('user_dashboard.no_accounts_found') }}</td>
            </tr>
          @endforelse
        </tbody>
      </table>
    </div>
  </div>

</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<script>
document.addEventListener("DOMContentLoaded", function () {
  const expenseCanvas = document.getElementById('expenseChart');
  if (expenseCanvas) {
    new Chart(expenseCanvas, {
      type: 'bar',
      data: {
        labels: ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],
        datasets: [{
          label: @json(__('user_dashboard.monthly_expense')),
          data: @json($chartData ?? []),
          backgroundColor: [
            'rgba(96, 165, 250, 0.55)',
            'rgba(96, 165, 250, 0.55)',
            'rgba(96, 165, 250, 0.75)',
            'rgba(96, 165, 250, 0.55)',
            'rgba(96, 165, 250, 0.55)',
            'rgba(96, 165, 250, 0.55)',
            'rgba(96, 165, 250, 0.55)',
            'rgba(96, 165, 250, 0.55)',
            'rgba(96, 165, 250, 0.55)',
            'rgba(96, 165, 250, 0.55)',
            'rgba(96, 165, 250, 0.55)',
            'rgba(96, 165, 250, 0.55)'
          ],
          borderColor: 'rgba(59, 130, 246, 0.9)',
          borderWidth: 1,
          borderRadius: 10
        }]
      },
      options: {
        responsive: true,
        plugins: {
          legend: { display: false }
        },
        scales: {
          y: { beginAtZero: true }
        }
      }
    });
  }

  const accountCanvas = document.getElementById('accountChart');
  if (accountCanvas) {
    new Chart(accountCanvas, {
      type: 'pie',
      data: {
        labels: @json($accountLabels ?? []),
        datasets: [{
          data: @json($accountBalances ?? []),
          backgroundColor: [
            'rgba(59, 130, 246, 0.85)',
            'rgba(244, 114, 182, 0.85)',
            'rgba(251, 146, 60, 0.85)',
            'rgba(168, 85, 247, 0.85)',
            'rgba(16, 185, 129, 0.85)',
            'rgba(234, 179, 8, 0.85)'
          ],
          borderColor: '#ffffff',
          borderWidth: 2
        }]
      },
      options: {
        responsive: true
      }
    });
  }
});
</script>
@endsection