@extends('layouts.admin')
@section('title', 'Dashboard')

@section('content')

{{-- ── Page header ── --}}
<div style="display:flex;align-items:flex-start;justify-content:space-between;margin-bottom:2rem">
  <div>
    <p style="font-size:.75rem;font-weight:500;color:var(--muted-foreground);
      text-transform:uppercase;letter-spacing:.08em;margin:0 0 .375rem">
      {{ now()->format('l, F j Y') }}
    </p>
    <h1 style="font-size:1.625rem;font-weight:700;color:var(--foreground);
      letter-spacing:-.03em;line-height:1.2;margin:0">Platform Overview</h1>
  </div>
  <div style="display:flex;gap:.5rem">
    <a href="{{ route('admin.licenses.create') }}" class="btn btn-primary btn-sm">
      <svg width="12" height="12" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M12 4v16m8-8H4"/>
      </svg>
      New License
    </a>
    <a href="{{ route('admin.orders.create') }}" class="btn btn-secondary btn-sm">New Order <svg width="13" height="13" fill="none" stroke="currentColor" viewBox="0 0 24 24" style="flex-shrink:0"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/></svg></a>
  </div>
</div>

@if($stats['critical_events'] > 0)
<div style="display:flex;align-items:center;gap:.625rem;padding:.625rem 1rem;margin-bottom:1.5rem;
  border-radius:var(--radius);background:#fef2f2;border:1px solid #fecaca">
  <svg width="13" height="13" fill="none" stroke="#dc2626" viewBox="0 0 24 24">
    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
      d="M12 9v2m0 4h.01M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"/>
  </svg>
  <span style="font-size:.8125rem;font-weight:500;color:#991b1b">
    {{ $stats['critical_events'] }} unresolved critical security event(s).
  </span>
  <a href="{{ route('admin.security.events') }}"
     style="margin-left:auto;font-size:.8rem;font-weight:600;color:#dc2626;text-decoration:none">Review →</a>
</div>
@endif

{{-- ── Stats: single row, separated by lines ── --}}
<div style="display:grid;grid-template-columns:repeat(5,1fr);gap:1px;
  background:var(--border);border:1px solid var(--border);border-radius:var(--radius);
  overflow:hidden;margin-bottom:2rem">
  @php $adminStats=[
    ['val'=>number_format($stats['active_licenses']),          'lbl'=>'Active Licenses', 'sub'=>'of '.number_format($stats['total_licenses']).' total'],
    ['val'=>number_format($stats['active_activations']),       'lbl'=>'Activations',     'sub'=>'live installs'],
    ['val'=>number_format($stats['expiring_soon']),            'lbl'=>'Expiring (30d)',  'sub'=>'need renewal'],
    ['val'=>number_format($stats['total_customers']),          'lbl'=>'Customers',       'sub'=>'registered'],
    ['val'=>$currencySymbol.number_format($stats['revenue_this_month'],0), 'lbl'=>'Revenue / Month', 'sub'=>$currencySymbol.number_format($stats['total_revenue'],0).' lifetime'],
  ]; @endphp

  @foreach($adminStats as $s)
  <div style="background:var(--card);padding:1.375rem 1.25rem">
    <div style="font-size:1.75rem;font-weight:700;color:var(--foreground);
      letter-spacing:-.04em;line-height:1;margin-bottom:.375rem">{{ $s['val'] }}</div>
    <div style="font-size:.8rem;font-weight:500;color:var(--foreground);margin-bottom:.125rem">{{ $s['lbl'] }}</div>
    <div style="font-size:.72rem;color:var(--muted-foreground)">{{ $s['sub'] }}</div>
  </div>
  @endforeach
</div>

{{-- ── Main 2-col layout ── --}}
<div style="display:grid;grid-template-columns:1fr 22rem;gap:1.5rem;align-items:start">

  {{-- Left --}}
  <div style="display:flex;flex-direction:column;gap:1.75rem">

    {{-- API Chart --}}
    <section>
      <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:.875rem">
        <div>
          <h2 style="font-size:.875rem;font-weight:600;color:var(--foreground);margin:0 0 .125rem">
            API Validation Activity
          </h2>
          <p style="font-size:.75rem;color:var(--muted-foreground);margin:0">Last 14 days</p>
        </div>
        <div style="display:flex;align-items:center;gap:.875rem;font-size:.72rem;color:var(--muted-foreground)">
          <span style="display:flex;align-items:center;gap:.35rem">
            <span style="width:.5rem;height:.5rem;border-radius:1px;background:var(--foreground);display:inline-block"></span>
            Successful
          </span>
          <span style="display:flex;align-items:center;gap:.35rem">
            <span style="width:.5rem;height:.5rem;border-radius:1px;background:var(--muted-foreground);opacity:.4;display:inline-block"></span>
            Failed
          </span>
        </div>
      </div>

      <div style="border:1px solid var(--border);border-radius:var(--radius);
        background:var(--card);padding:1.25rem">
        @php $maxVal=max($validationChart->max('total')??1,1); @endphp
        @if($validationChart->sum('total')===0)
        <div style="height:80px;display:flex;flex-direction:column;align-items:center;
          justify-content:center;gap:.5rem;color:var(--muted-foreground)">
          <svg width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24" style="opacity:.3">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5"
              d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"/>
          </svg>
          <p style="font-size:.8rem;margin:0">No API activity yet.</p>
        </div>
        @else
        <div style="display:flex;align-items:flex-end;gap:3px;height:72px">
          @foreach($validationChart as $day)
          <div style="flex:1;display:flex;flex-direction:column;justify-content:flex-end;gap:1px"
               title="{{ \Carbon\Carbon::parse($day->date)->format('M j') }}: {{ $day->total }}">
            @if($day->success>0)
            <div style="width:100%;border-radius:1px 1px 0 0;background:var(--foreground);
              height:{{ max(2,round(($day->success/$maxVal)*66)) }}px;opacity:.75;transition:opacity .1s"
              onmouseover="this.style.opacity=1" onmouseout="this.style.opacity=.75"></div>
            @endif
            @if($day->failed>0)
            <div style="width:100%;border-radius:1px 1px 0 0;background:var(--muted-foreground);
              height:{{ max(2,round(($day->failed/$maxVal)*66)) }}px;opacity:.35"></div>
            @endif
          </div>
          @endforeach
        </div>
        <div style="display:flex;justify-content:space-between;margin-top:.5rem">
          @foreach($validationChart->filter(fn($d,$i)=>$i%3===0) as $day)
          <span style="font-size:.625rem;color:var(--muted-foreground)">
            {{ \Carbon\Carbon::parse($day->date)->format('M d') }}
          </span>
          @endforeach
        </div>
        @endif
      </div>
    </section>

    {{-- Recent Orders --}}
    <section>
      <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:.875rem">
        <h2 style="font-size:.875rem;font-weight:600;color:var(--foreground);margin:0">Recent Orders</h2>
        <a href="{{ route('admin.orders.index') }}"
           style="font-size:.8rem;color:var(--muted-foreground);text-decoration:none;transition:color .1s"
           onmouseover="this.style.color='var(--foreground)'" onmouseout="this.style.color='var(--muted-foreground)'">
          View all →
        </a>
      </div>

      <div style="border:1px solid var(--border);border-radius:var(--radius);overflow:hidden">
        <table style="width:100%;border-collapse:collapse">
          <thead>
            <tr style="border-bottom:1px solid var(--border);background:var(--muted)">
              <th style="padding:.625rem 1.25rem;font-size:.6875rem;font-weight:600;color:var(--muted-foreground);
                text-transform:uppercase;letter-spacing:.07em;text-align:left">Order</th>
              <th style="padding:.625rem 1.25rem;font-size:.6875rem;font-weight:600;color:var(--muted-foreground);
                text-transform:uppercase;letter-spacing:.07em;text-align:left">Customer</th>
              <th style="padding:.625rem 1.25rem;font-size:.6875rem;font-weight:600;color:var(--muted-foreground);
                text-transform:uppercase;letter-spacing:.07em;text-align:left">Status</th>
              <th style="padding:.625rem 1.25rem;font-size:.6875rem;font-weight:600;color:var(--muted-foreground);
                text-transform:uppercase;letter-spacing:.07em;text-align:right">Amount</th>
              <th style="padding:.625rem 1.25rem;font-size:.6875rem;font-weight:600;color:var(--muted-foreground);
                text-transform:uppercase;letter-spacing:.07em;text-align:left">Date</th>
              <th style="padding:.625rem 1.25rem"></th>
            </tr>
          </thead>
          <tbody>
            @forelse($recentOrders as $order)
            <tr style="background:var(--card);border-bottom:1px solid var(--border);transition:background .1s"
                onmouseover="this.style.background='var(--muted)'" onmouseout="this.style.background='var(--card)'">
              <td style="padding:.8rem 1.25rem;font-size:.8rem;font-weight:600;color:var(--foreground)">
                {{ $order->order_number }}
              </td>
              <td style="padding:.8rem 1.25rem">
                <div style="display:flex;align-items:center;gap:.5rem">
                  <div style="width:1.5rem;height:1.5rem;border-radius:50%;background:var(--muted);
                    border:1px solid var(--border);display:flex;align-items:center;justify-content:center;
                    font-size:.5625rem;font-weight:700;color:var(--foreground);flex-shrink:0">
                    {{ strtoupper(substr($order->user->name??'-',0,1)) }}
                  </div>
                  <span style="font-size:.8125rem;color:var(--foreground)">{{ $order->user->name??'-' }}</span>
                </div>
              </td>
              <td style="padding:.8rem 1.25rem">
                @php $ss=['paid'=>['#f0fdf4','#166534'],'pending'=>['#fefce8','#854d0e'],'refunded'=>['#eff6ff','#1e40af'],'failed'=>['#fef2f2','#991b1b'],'cancelled'=>['#f9fafb','#6b7280']][$order->status]??['#f9fafb','#6b7280']; @endphp
                <span style="padding:.2rem .55rem;border-radius:9999px;font-size:.7rem;font-weight:600;
                  background:{{ $ss[0] }};color:{{ $ss[1] }}">{{ ucfirst($order->status) }}</span>
              </td>
              <td style="padding:.8rem 1.25rem;text-align:right;font-size:.875rem;font-weight:700;color:var(--foreground)">
                {{ $currencySymbol }}{{ number_format($order->total,2) }}
              </td>
              <td style="padding:.8rem 1.25rem;font-size:.78rem;color:var(--muted-foreground);white-space:nowrap">
                {{ $order->created_at->format('M d, Y') }}
              </td>
              <td style="padding:.8rem 1.25rem">
                <a href="{{ route('admin.orders.show',$order) }}" class="btn btn-secondary btn-xs">View <svg width="13" height="13" fill="none" stroke="currentColor" viewBox="0 0 24 24" style="flex-shrink:0"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/></svg></a>
              </td>
            </tr>
            @empty
            <tr>
              <td colspan="6" style="padding:2.5rem;text-align:center;
                color:var(--muted-foreground);font-size:.875rem;background:var(--card)">No orders yet.</td>
            </tr>
            @endforelse
          </tbody>
        </table>
      </div>
    </section>

  </div>

  {{-- Right panel --}}
  <div style="display:flex;flex-direction:column;gap:1.25rem;position:sticky;top:calc(3.5rem + 1.5rem)">

    {{-- Today snapshot --}}
    <section>
      <h2 style="font-size:.875rem;font-weight:600;color:var(--foreground);margin:0 0 .875rem">Today</h2>
      <div style="border:1px solid var(--border);border-radius:var(--radius);background:var(--card);overflow:hidden">
        @foreach([
          ['Failed Validations', $stats['failed_validations'], $stats['failed_validations']>0?'#dc2626':'var(--foreground)'],
          ['New Orders',         $stats['orders_today'],       'var(--foreground)'],
          ['Security Alerts',    $stats['critical_events'],    $stats['critical_events']>0?'#dc2626':'var(--foreground)'],
        ] as [$lbl,$val,$c])
        <div style="display:flex;align-items:center;justify-content:space-between;
          padding:.75rem 1rem;border-bottom:1px solid var(--border)">
          <span style="font-size:.8125rem;color:var(--muted-foreground)">{{ $lbl }}</span>
          <span style="font-size:1rem;font-weight:700;color:{{ $c }}">{{ $val }}</span>
        </div>
        @endforeach
        <div style="padding:.875rem 1rem">
          <a href="{{ route('admin.licenses.create') }}" class="btn btn-primary btn-sm"
             style="width:100%;justify-content:center">
            <svg width="12" height="12" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M12 4v16m8-8H4"/>
            </svg>
            Create License
          </a>
        </div>
      </div>
    </section>

    {{-- Security Events --}}
    <section>
      <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:.875rem">
        <h2 style="font-size:.875rem;font-weight:600;color:var(--foreground);margin:0">Security Events</h2>
        <a href="{{ route('admin.security.events') }}"
           style="font-size:.8rem;color:var(--muted-foreground);text-decoration:none;transition:color .1s"
           onmouseover="this.style.color='var(--foreground)'" onmouseout="this.style.color='var(--muted-foreground)'">
          All →
        </a>
      </div>
      <div style="border:1px solid var(--border);border-radius:var(--radius);background:var(--card);overflow:hidden">
        @forelse($recentEvents as $event)
        @php $sevDot=['critical'=>'#ef4444','high'=>'#f97316','medium'=>'#f59e0b','low'=>'#9ca3af'][$event->severity]??'#9ca3af'; @endphp
        <div style="display:flex;align-items:flex-start;gap:.625rem;padding:.75rem 1rem;
          border-bottom:1px solid var(--border)">
          <span style="width:.4375rem;height:.4375rem;border-radius:50%;background:{{ $sevDot }};
            margin-top:.3125rem;flex-shrink:0"></span>
          <div style="flex:1;min-width:0">
            <div style="font-size:.8rem;font-weight:500;color:var(--foreground)">
              {{ ucwords(str_replace('_',' ',$event->event_type)) }}
            </div>
            <div style="font-size:.72rem;color:var(--muted-foreground);margin-top:1px">
              {{ $event->created_at->diffForHumans() }}
            </div>
          </div>
          <form method="POST" action="{{ route('admin.security.events.resolve',$event) }}" style="flex-shrink:0">
            @csrf
            <button class="btn btn-ghost btn-xs">Resolve</button>
          </form>
        </div>
        @empty
        <div style="padding:1.75rem;text-align:center;font-size:.8125rem;color:var(--muted-foreground)">
          No unresolved events.
        </div>
        @endforelse
      </div>
    </section>

    {{-- Latest Releases --}}
    <section>
      <h2 style="font-size:.875rem;font-weight:600;color:var(--foreground);margin:0 0 .875rem">Latest Releases</h2>
      <div style="border:1px solid var(--border);border-radius:var(--radius);background:var(--card);overflow:hidden">
        @php
          $rels=\App\Models\ProductVersion::with('product')->where('is_active',true)->latest('released_at')->take(5)->get();
          $rC=['#c0392b','#6c3483','#e91e63','#1565c0','#4527a0'];
          $tE=['plugin'=>'🔌','module'=>'🧩','software'=>'💻','theme'=>'🎨','api'=>'⚡','saas'=>'☁️'];
        @endphp
        @forelse($rels as $i=>$rel)
        @php $isLast=$loop->last; @endphp
        <a href="{{ route('admin.products.show', $rel->product) }}"
          style="display:flex;align-items:center;gap:.625rem;padding:.625rem 1rem;
            {{ !$isLast?'border-bottom:1px solid var(--border);':'' }}
            transition:background .1s;text-decoration:none"
          onmouseover="this.style.background='var(--muted)'" onmouseout="this.style.background=''">
          <div style="width:2rem;height:2rem;border-radius:.4rem;flex-shrink:0;
            background:{{ $rC[$i%count($rC)] }};display:flex;align-items:center;
            justify-content:center;font-size:.8125rem">
            {{ $tE[$rel->product->type??'-']??'-' }}
          </div>
          <div style="flex:1;min-width:0">
            <div style="font-size:.8rem;font-weight:500;color:var(--foreground);
              white-space:nowrap;overflow:hidden;text-overflow:ellipsis">{{ $rel->product->name }}</div>
            <div style="font-size:.7rem;color:var(--muted-foreground);margin-top:1px">
              v{{ $rel->version }} · {{ $rel->released_at?->diffForHumans()??'Recently' }}
            </div>
          </div>
          <svg width="11" height="11" fill="none" stroke="var(--muted-foreground)" viewBox="0 0 24 24" style="flex-shrink:0">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/>
          </svg>
        </a>
        @empty
        <div style="padding:1.5rem;text-align:center;font-size:.8rem;color:var(--muted-foreground)">No releases.</div>
        @endforelse
      </div>
    </section>

  </div>
</div>

@endsection
