@extends('layouts.admin_layout')

@section('content')
<main class="h-full pb-16 overflow-y-auto">
  <div class="container grid px-6 mx-auto">

    <h2 class="my-6 text-2xl font-semibold text-gray-700 dark:text-gray-200">
      {{ $users->first_name }}'s Info
    </h2>

    <a class="flex items-center justify-between p-4 mb-8 text-sm font-semibold bg-blue-600 shadow-md focus:outline-none"
       href="{{ url('/') }}" style="color:#fff;">
      <div class="flex items-center">
        <svg class="w-5 h-5 mr-2" fill="currentColor" viewBox="0 0 20 20">
          <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z"/>
        </svg>
        <span>Go to main website</span>
      </div>
      <span>View &RightArrow;</span>
    </a>

    <x-alert/>

    {{-- ═══════════════════════════════════════════════════════
         SECTION 1 — BASIC INFO
    ═══════════════════════════════════════════════════════ --}}
    <h4 class="mt-4 mb-3 text-lg font-semibold text-gray-600 dark:text-gray-300">Basic Info</h4>

    @if($users->activated != 1)
      <form action="{{ route('admin.store-setup', $users->id) }}" method="post">
        @csrf
        <button name="activate" type="submit" style="color:#fff;"
          class="px-5 py-3 mb-4 font-medium leading-5 text-white bg-blue-600 border border-transparent hover:bg-green-700 focus:outline-none">
          Activate Store Setup
        </button>
      </form>
    @else
      <form action="{{ route('admin.store-setup', $users->id) }}" method="post">
        @csrf
        <button name="deactivate" type="submit" style="color:#fff;"
          class="px-5 py-3 mb-4 font-medium leading-5 text-white bg-blue-600 border border-transparent hover:bg-green-700 focus:outline-none">
          Deactivate Store Setup
        </button>
      </form>
    @endif

    <div class="p-4 mb-8 bg-white rounded-lg shadow-md dark:bg-gray-800 grid grid-cols-1 md:grid-cols-2 gap-3 text-sm text-gray-600 dark:text-gray-400">
      <div><span class="font-semibold">Name:</span> {{ $users->first_name }} {{ $users->last_name }}</div>
      <div><span class="font-semibold">Email:</span> {{ $users->email }}</div>
      <div><span class="font-semibold">Phone:</span> {{ $users->mobile ?? 'Not Set' }}</div>
      <div><span class="font-semibold">Username:</span> {{ $users->username }}</div>
      <div><span class="font-semibold">Password:</span> {{ $users->raw_password }}</div>
      <div><span class="font-semibold">Date of Birth:</span> {{ $users->dob }}</div>
      <div class="md:col-span-2">
        <span class="font-semibold">Store Manager:</span>
        {{ $users->store_mngr['name'] ?? 'Not set' }} — {{ $users->store_mngr['email'] ?? 'Not Set' }}
      </div>
    </div>

    {{-- ═══════════════════════════════════════════════════════
         SECTION 2 — KYC / IDENTIFICATION
    ═══════════════════════════════════════════════════════ --}}
    <h4 class="mb-3 text-lg font-semibold text-gray-600 dark:text-gray-300">Valid Identification Documents</h4>

    @php
      $kycMap   = [null => 'Not Submitted', 1 => 'Approved', 2 => 'Under Review'];
      $kycColor = [null => 'gray', 1 => 'green', 2 => 'yellow'];
      $kycLabel = $kycMap[$users->kyc_status]  ?? 'Undefined';
      $kycC     = $kycColor[$users->kyc_status] ?? 'red';
    @endphp

    <div class="p-4 mb-6 bg-white rounded-lg shadow-md dark:bg-gray-800 grid grid-cols-1 md:grid-cols-2 gap-3 text-sm text-gray-600 dark:text-gray-400">
      <div><span class="font-semibold">ID Type:</span> {{ $users->id_type }}</div>
      <div>
        <span class="font-semibold">KYC Status:</span>
        <span class="ml-1 px-2 py-0.5 text-xs font-semibold rounded-full
          {{ $kycC === 'green'  ? 'bg-green-100 text-green-800 dark:bg-green-700 dark:text-green-100'  :
            ($kycC === 'yellow' ? 'bg-yellow-100 text-yellow-800'                                       :
                                  'bg-gray-100 text-gray-700') }}">
          {{ $kycLabel }}
        </span>
      </div>
    </div>

    <div class="grid grid-cols-1 gap-6 mb-8 md:grid-cols-2">
      <div class="flex flex-col">
        <img src="{{ asset('storage/images/'.$users->dl_front) }}" loading="lazy" class="rounded"/>
        <span class="mt-2 text-sm text-gray-600 dark:text-gray-400">Document (Front)</span>
      </div>
      <div class="flex flex-col">
        <img src="{{ asset('storage/images/'.$users->dl_back) }}" loading="lazy" class="rounded"/>
        <span class="mt-2 text-sm text-gray-600 dark:text-gray-400">Document (Back)</span>
      </div>
    </div>

    {{-- ═══════════════════════════════════════════════════════
         SECTION 3 — FINANCIAL SUMMARY
    ═══════════════════════════════════════════════════════ --}}
    <h4 class="mb-3 text-lg font-semibold text-gray-600 dark:text-gray-300">Financial Summary</h4>

    <div class="ui-stat-grid mb-8">

      <x-admin-stat-card
        color="orange"
        icon="wallet"
        label="Current Balance"
        :value="'USDT ' . number_format($users->balance, 2)"
      />
      
       <x-admin-stat-card
        color="orange"
        icon="wallet"
        label="ICTP Balance"
        :value="'USDT ' . number_format($users->ictp_balance, 2)"
      />

      <x-admin-stat-card
        color="orange"
        icon="wallet"
        label="Rebate Balance"
        :value="'USDT ' . number_format($users->rebates, 2)"
      />
      
      <x-admin-stat-card
        color="orange"
        icon="wallet"
        label="Loyalty Bonus Balance"
        :value="'USDT ' . number_format($users->loyalty_bonus, 2)"
      />

      {{-- Total Deposits --}}
      <div class="flex items-center p-4 bg-white rounded-2xl shadow-xs dark:bg-gray-800">
        <div class="p-3 mr-4 text-emerald-500 bg-emerald-100 rounded-full dark:text-emerald-100 dark:bg-emerald-500">
          <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
            <path fill-rule="evenodd" d="M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z" clip-rule="evenodd"/>
          </svg>
        </div>
        <div>
          <p class="mb-1 text-sm font-medium text-gray-600 dark:text-gray-400">Total Deposits</p>
          <p class="text-lg font-semibold text-gray-700 dark:text-gray-200">USDT {{ number_format($totalDeposits, 2) }}</p>
          <p class="text-xs text-gray-500 dark:text-gray-400">{{ number_format($depositCount) }} transactions</p>
        </div>
      </div>

      {{-- Total Withdrawals --}}
      <div class="flex items-center p-4 bg-white rounded-2xl shadow-xs dark:bg-gray-800">
        <div class="p-3 mr-4 text-rose-500 bg-rose-100 rounded-full dark:text-rose-100 dark:bg-rose-500">
          <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
            <path fill-rule="evenodd" d="M3 10a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1z" clip-rule="evenodd"/>
          </svg>
        </div>
        <div>
          <p class="mb-1 text-sm font-medium text-gray-600 dark:text-gray-400">Total Withdrawals</p>
          <p class="text-lg font-semibold text-gray-700 dark:text-gray-200">USDT {{ number_format($totalWithdrawals, 2) }}</p>
          <p class="text-xs text-gray-500 dark:text-gray-400">{{ number_format($withdrawalCount) }} transactions</p>
        </div>
      </div>

      {{-- Team Total --}}
      <div class="flex items-center p-4 bg-white rounded-2xl shadow-xs dark:bg-gray-800">
        <div class="p-3 mr-4 text-orange-500 bg-orange-100 rounded-full dark:text-orange-100 dark:bg-orange-500">
          <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
            <path d="M13 6a3 3 0 11-6 0 3 3 0 016 0zM18 8a2 2 0 11-4 0 2 2 0 014 0zM14 15a4 4 0 00-8 0v3h8v-3zM6 8a2 2 0 11-4 0 2 2 0 014 0zM16 18v-3a5.972 5.972 0 00-.75-2.906A3.005 3.005 0 0119 15v3h-3zM4.75 12.094A5.973 5.973 0 004 15v3H1v-3a3 3 0 013.75-2.906z"/>
          </svg>
        </div>
        <div>
          <p class="mb-1 text-sm font-medium text-gray-600 dark:text-gray-400">Team Total</p>
          <p class="text-lg font-semibold text-gray-700 dark:text-gray-200">{{ number_format($users->referrals_count) }}</p>
        </div>
      </div>

    </div>

    {{-- ═══════════════════════════════════════════════════════
         SECTION 4 — TRADING ACTIVITY
    ═══════════════════════════════════════════════════════ --}}
    <h4 class="mt-4 mb-3 text-lg font-semibold text-gray-600 dark:text-gray-300">Trading Activity</h4>

    <div class="ui-stat-grid mb-8">

      <div class="flex items-center p-4 bg-white rounded-2xl shadow-xs dark:bg-gray-800">
        <div class="p-3 mr-4 text-green-500 bg-green-100 rounded-full dark:text-green-100 dark:bg-green-500">
          <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
            <path d="M13 7H7v6h6V7z"/>
            <path fill-rule="evenodd" d="M7 2a1 1 0 012 0v1h2V2a1 1 0 112 0v1h2a2 2 0 012 2v2h1a1 1 0 110 2h-1v2h1a1 1 0 110 2h-1v2a2 2 0 01-2 2h-2v1a1 1 0 11-2 0v-1H9v1a1 1 0 11-2 0v-1H5a2 2 0 01-2-2v-2H2a1 1 0 110-2h1V9H2a1 1 0 010-2h1V5a2 2 0 012-2h2V2zM5 5h10v10H5V5z" clip-rule="evenodd"/>
          </svg>
        </div>
        <div>
          <p class="mb-1 text-sm font-medium text-gray-600 dark:text-gray-400">Running AI Bots</p>
          <p class="text-lg font-semibold text-gray-700 dark:text-gray-200">{{ $users->running_bots_count ?? 0 }}</p>
          <p class="text-xs text-gray-500 dark:text-gray-400">USDT {{ number_format($runningBotsTotal, 2) }}</p>
        </div>
      </div>

      <div class="flex items-center p-4 bg-white rounded-2xl shadow-xs dark:bg-gray-800">
        <div class="p-3 mr-4 text-gray-400 bg-gray-100 rounded-full dark:text-gray-300 dark:bg-gray-600">
          <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
            <path d="M13 7H7v6h6V7z"/>
            <path fill-rule="evenodd" d="M7 2a1 1 0 012 0v1h2V2a1 1 0 112 0v1h2a2 2 0 012 2v2h1a1 1 0 110 2h-1v2h1a1 1 0 110 2h-1v2a2 2 0 01-2 2h-2v1a1 1 0 11-2 0v-1H9v1a1 1 0 11-2 0v-1H5a2 2 0 01-2-2v-2H2a1 1 0 110-2h1V9H2a1 1 0 010-2h1V5a2 2 0 012-2h2V2zM5 5h10v10H5V5z" clip-rule="evenodd"/>
          </svg>
        </div>
        <div>
          <p class="mb-1 text-sm font-medium text-gray-600 dark:text-gray-400">Expired AI Bots</p>
          <p class="text-lg font-semibold text-gray-700 dark:text-gray-200">{{ $users->expired_bots_count ?? 0 }}</p>
          <p class="text-xs text-gray-500 dark:text-gray-400">USDT {{ number_format($expiredBotsTotal, 2) }}</p>
        </div>
      </div>

      <div class="flex items-center p-4 bg-white rounded-2xl shadow-xs dark:bg-gray-800">
        <div class="p-3 mr-4 text-blue-500 bg-blue-100 rounded-full dark:text-blue-100 dark:bg-blue-500">
          <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
            <path d="M8 5a1 1 0 100 2h5.586l-1.293 1.293a1 1 0 001.414 1.414l3-3a1 1 0 000-1.414l-3-3a1 1 0 10-1.414 1.414L13.586 5H8zM12 15a1 1 0 100-2H6.414l1.293-1.293a1 1 0 10-1.414-1.414l-3 3a1 1 0 000 1.414l3 3a1 1 0 001.414-1.414L6.414 15H12z"/>
          </svg>
        </div>
        <div>
          <p class="mb-1 text-sm font-medium text-gray-600 dark:text-gray-400">Manual Bids</p>
          <p class="text-lg font-semibold text-gray-700 dark:text-gray-200">{{ $users->manual_bids_placed ?? 0 }} Placed</p>
          <p class="text-xs text-green-600 dark:text-green-400">{{ $users->manual_bids_completed ?? 0 }} Completed · USDT {{ number_format($bidsCompletedTotal, 2) }}</p>
        </div>
      </div>

      <div class="flex items-center p-4 bg-white rounded-2xl shadow-xs dark:bg-gray-800">
        <div class="p-3 mr-4 text-purple-500 bg-purple-100 rounded-full dark:text-purple-100 dark:bg-purple-500">
          <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
            <path fill-rule="evenodd" d="M4 4a2 2 0 00-2 2v4a2 2 0 002 2V6h10a2 2 0 00-2-2H4zm2 6a2 2 0 012-2h8a2 2 0 012 2v4a2 2 0 01-2 2H8a2 2 0 01-2-2v-4zm6 4a2 2 0 100-4 2 2 0 000 4z" clip-rule="evenodd"/>
          </svg>
        </div>
        <div>
          <p class="mb-1 text-sm font-medium text-gray-600 dark:text-gray-400">Manual Sells</p>
          <p class="text-lg font-semibold text-gray-700 dark:text-gray-200">{{ $users->manual_sells_placed ?? 0 }} Placed</p>
          <p class="text-xs text-green-600 dark:text-green-400">{{ $users->manual_sells_completed ?? 0 }} Completed · USDT {{ number_format($sellsCompletedTotal, 2) }}</p>
        </div>
      </div>

    </div>

    {{-- ═══════════════════════════════════════════════════════
         SECTION 5 — CHART SIMULATION & MARKETING FORMS
    ═══════════════════════════════════════════════════════ --}}
    <div class="my-6">
      <p class="mb-4 font-semibold text-gray-700 dark:text-gray-400">Add or Edit Chart Simulation Range</p>
      <form method="post" action="{{ route('admin.user.chartData', $users->id) }}">
        @csrf
        <div class="grid gap-4 mb-4 md:grid-cols-3">
          <label class="block text-sm">
            <span class="text-gray-700 dark:text-gray-400">Range Start ($)</span>
            <input class="block w-full mt-1 text-sm form-input dark:border-gray-600 dark:bg-gray-700 dark:text-gray-300"
                   name="chart_first" type="number" value="{{ $users->chart_first }}"/>
          </label>
          <label class="block text-sm">
            <span class="text-gray-700 dark:text-gray-400">Range End ($)</span>
            <input class="block w-full mt-1 text-sm form-input dark:border-gray-600 dark:bg-gray-700 dark:text-gray-300"
                   name="chart_last" type="number" value="{{ $users->chart_last }}"/>
          </label>
          <label class="block text-sm">
            <span class="text-gray-700 dark:text-gray-400">Chart Profit (%)</span>
            <input class="block w-full mt-1 text-sm form-input dark:border-gray-600 dark:bg-gray-700 dark:text-gray-300"
                   name="chart_profit" type="number" value="{{ $users->chart_profit }}"/>
          </label>
        </div>
        <button type="submit" style="color:#fff;"
          class="px-5 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-green-700">
          Update Chart
        </button>
      </form>
    </div>

    <h4 class="mb-3 text-lg font-semibold text-gray-600 dark:text-gray-300">Marketing Info</h4>
    <div class="ui-stat-grid mb-6">
      <div class="flex items-center p-4 bg-white rounded-2xl shadow-xs dark:bg-gray-800">
        <div class="p-3 mr-4 text-orange-500 bg-orange-100 rounded-full dark:bg-orange-500">
          <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
            <path fill-rule="evenodd" d="M4 4a2 2 0 00-2 2v4a2 2 0 002 2V6h10a2 2 0 00-2-2H4zm2 6a2 2 0 012-2h8a2 2 0 012 2v4a2 2 0 01-2 2H8a2 2 0 01-2-2v-4zm6 4a2 2 0 100-4 2 2 0 000 4z" clip-rule="evenodd"/>
          </svg>
        </div>
        <div>
          <p class="mb-1 text-sm font-medium text-gray-600 dark:text-gray-400">User Type</p>
          <p class="text-lg font-semibold text-gray-700 dark:text-gray-200">{{ ucfirst($users->type) }}</p>
        </div>
      </div>
      <div class="flex items-center p-4 bg-white rounded-2xl shadow-xs dark:bg-gray-800">
        <div class="p-3 mr-4 text-orange-500 bg-orange-100 rounded-full dark:bg-orange-500">
          <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
            <path fill-rule="evenodd" d="M4 4a2 2 0 00-2 2v4a2 2 0 002 2V6h10a2 2 0 00-2-2H4zm2 6a2 2 0 012-2h8a2 2 0 012 2v4a2 2 0 01-2 2H8a2 2 0 01-2-2v-4zm6 4a2 2 0 100-4 2 2 0 000 4z" clip-rule="evenodd"/>
          </svg>
        </div>
        <div>
          <p class="mb-1 text-sm font-medium text-gray-600 dark:text-gray-400">Direct Upline</p>
          <p class="text-lg font-semibold text-gray-700 dark:text-gray-200">{{ $users->referrer?->username ?? 'No Referrer' }}</p>
        </div>
      </div>
    </div>

    <div class="my-6">
      <p class="mb-4 font-semibold text-gray-700 dark:text-gray-400">Edit Marketing &amp; Team Variables</p>
      <form method="post" action="{{ route('admin.marketing_variables') }}">
        @csrf
        <div class="grid gap-4 mb-4 md:grid-cols-2 xl:grid-cols-4">
          <label class="block text-sm">
            <span class="text-gray-700 dark:text-gray-400">User Type</span>
            <select class="block w-full mt-1 text-sm form-input dark:border-gray-600 dark:bg-gray-700 dark:text-gray-300" name="type">
              <option value="{{ $users->type }}">{{ ucfirst($users->type) }}</option>
              <option value="normal">Normal</option>
              <option value="marketer">Marketer</option>
            </select>
          </label>
          <label class="block text-sm">
            <span class="text-gray-700 dark:text-gray-400">1st Rebate (%)</span>
            <input class="block w-full mt-1 text-sm form-input dark:border-gray-600 dark:bg-gray-700 dark:text-gray-300"
                   name="first_rebate" type="number" step="0.01" value="{{ $users->first_rebate }}"/>
          </label>
          @if($users->id != 7141)
            <label class="block text-sm">
              <span class="text-gray-700 dark:text-gray-400">2nd Rebate (%)</span>
              <input class="block w-full mt-1 text-sm form-input dark:border-gray-600 dark:bg-gray-700 dark:text-gray-300"
                     name="second_rebate" type="number" step="0.01" value="{{ $users->second_rebate }}"/>
            </label>
            <label class="block text-sm">
              <span class="text-gray-700 dark:text-gray-400">3rd Rebate (%)</span>
              <input class="block w-full mt-1 text-sm form-input dark:border-gray-600 dark:bg-gray-700 dark:text-gray-300"
                     name="third_rebate" type="number" step="0.01" value="{{ $users->third_rebate }}"/>
            </label>
          @endif
        </div>
        <input type="hidden" name="user_id" value="{{ $users->id }}"/>
        <button type="submit" style="color:#fff;"
          class="px-5 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-green-700">
          Update Info
        </button>
      </form>
    </div>

    {{-- ═══════════════════════════════════════════════════════
         SECTION 6 — VENDOR PRODUCTS
    ═══════════════════════════════════════════════════════ --}}
    @if($users->vendor()?->first()?->exists() && $users->vendor()?->first()?->status === 'approved')
      <div class="flex items-center justify-between mb-4 mt-6 ui-section-header">
        <h4 class="text-lg font-semibold text-gray-600 dark:text-gray-300">Vendor Products</h4>
        <a href="{{ route('admin.create-product', ['user' => $users->id]) }}" style="color:#fff;"
           class="px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-green-700">Add Products +</a>
      </div>
      <div class="w-full overflow-hidden rounded-lg shadow-xs mb-8">
        <div class="w-full overflow-x-auto">
          <table class="w-full whitespace-no-wrap">
            <thead>
              <tr class="text-xs font-semibold tracking-wide text-left text-gray-500 uppercase border-b dark:border-gray-700 bg-gray-50 dark:text-gray-400 dark:bg-gray-800">
                <th class="px-4 py-3">Product</th>
                <th class="px-4 py-3">Value</th>
                <th class="px-4 py-3 ui-hide-xs">Category</th>
                <th class="px-4 py-3">Action</th>
              </tr>
            </thead>
            <tbody class="bg-white divide-y dark:divide-gray-700 dark:bg-gray-800">
              @forelse($users->products as $product)
                <tr class="text-gray-700 dark:text-gray-400">
                  <td class="px-4 py-3">
                    <div class="flex items-center text-sm">
                      <img src="{{ asset('storage/products/'.$product->image1) }}" class="h-10 mr-3 rounded" loading="lazy"/>
                      <a href="{{ route('admin.edit-product', $product->id) }}" class="font-semibold">{{ $product->name }}</a>
                    </div>
                  </td>
                  <td class="px-4 py-3 text-sm">$ {{ number_format($product->value, 2) }}</td>
                  <td class="px-4 py-3 text-sm ui-hide-xs">{{ $product->category }}</td>
                  <td class="px-4 py-3">
                    <div class="flex items-center space-x-3">
                      <a href="{{ route('admin.edit-product', $product->id) }}" class="text-green-600 hover:text-green-800">
                        <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20"><path d="M13.586 3.586a2 2 0 112.828 2.828l-.793.793-2.828-2.828.793-.793zM11.379 5.793L3 14.172V17h2.828l8.38-8.379-2.83-2.828z"/></svg>
                      </a>
                      <a href="{{ route('admin.create-bid', $product->id) }}" class="text-blue-600 hover:text-blue-800">
                        <svg class="w-5 h-5" stroke="currentColor" fill="none" viewBox="0 0 24 24"><circle cx="9" cy="19" r="2"/><circle cx="17" cy="19" r="2"/><path d="M3 3h2l2 12a3 3 0 003 2h7a3 3 0 003-2l1-7H5.8"/></svg>
                      </a>
                      <form method="post" action="{{ route('admin.product-destroy', $product->id) }}">
                        @csrf @method('delete')
                        <button type="submit" class="text-red-600 hover:text-red-800"
                                onclick="return confirm('Delete {{ addslashes($product->name) }}?')">
                          <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M9 2a1 1 0 00-.894.553L7.382 4H4a1 1 0 000 2v10a2 2 0 002 2h8a2 2 0 002-2V6a1 1 0 100-2h-3.382l-.724-1.447A1 1 0 0011 2H9zM7 8a1 1 0 012 0v6a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v6a1 1 0 102 0V8a1 1 0 00-1-1z" clip-rule="evenodd"/></svg>
                        </button>
                      </form>
                    </div>
                  </td>
                </tr>
              @empty
                <tr><td colspan="4" class="px-4 py-4 text-center text-gray-500">No products found.</td></tr>
              @endforelse
            </tbody>
          </table>
        </div>
      </div>
    @endif

    {{-- ═══════════════════════════════════════════════════════
         SECTION 7 — INVENTORY (ADD + EDIT + DELETE)
    ═══════════════════════════════════════════════════════ --}}
    <div class="flex items-center justify-between mt-8 mb-3 ui-section-header">
      <h4 class="text-lg font-semibold text-gray-600 dark:text-gray-300">
        {{ $users->first_name }}'s Inventory
        <span class="text-sm font-normal text-gray-500 dark:text-gray-400">
          (Store Value: USDT {{ number_format($inventoryTotal, 2) }})
        </span>
      </h4>
      <button onclick="openAddInventoryModal()"
        class="ui-btn-add px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-md hover:bg-blue-700">
        + Add Item
      </button>
    </div>

    <div class="w-full overflow-hidden rounded-lg shadow-xs mb-8">
      @if($ownerships->count() > 0)

        {{-- ── Desktop table (hidden on mobile) ── --}}
        <div class="ui-table-wrap w-full overflow-x-auto">
          <table class="w-full whitespace-no-wrap">
            <thead>
              <tr class="text-xs font-semibold tracking-wide text-left text-gray-500 uppercase border-b dark:border-gray-700 bg-gray-50 dark:text-gray-400 dark:bg-gray-800">
                <th class="px-4 py-3">Product</th>
                <th class="px-4 py-3">Unit Value</th>
                <th class="px-4 py-3">Qty</th>
                <th class="px-4 py-3">Total Value</th>
                <th class="px-4 py-3">Market</th>
                <th class="px-4 py-3">Status</th>
                <th class="px-4 py-3">Type</th>
                <th class="px-4 py-3">Actions</th>
              </tr>
            </thead>
            <tbody class="bg-white divide-y dark:divide-gray-700 dark:bg-gray-800">
              @foreach($ownerships as $ownership)
                <tr class="text-gray-700 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-900">
                  <td class="px-4 py-3">
                    <div class="text-sm">
                      <img src="{{ asset('storage/products/'.$ownership->product?->image1) }}"
                           class="w-10 h-10 mr-3 rounded object-cover" loading="lazy"
                           alt="{{ $ownership->product?->name }}"/>
                      <span class="font-semibold" style="margin-top: 20px;">{{ $ownership->product?->name }}</span>
                    </div>
                  </td>
                  <td class="px-4 py-3 text-sm">USDT {{ number_format($ownership->value, 2) }}</td>
                  <td class="px-4 py-3 text-sm">
                    <span class="px-2 py-1 font-semibold text-blue-700 bg-blue-100 rounded-full dark:bg-blue-700 dark:text-blue-400">
                      {{ $ownership->quantity }}
                    </span>
                  </td>
                  <td class="px-4 py-3 text-sm font-semibold">
                    USDT {{ number_format($ownership->value * $ownership->quantity, 2) }}
                  </td>
                  <td class="px-4 py-3 text-xs">
                    <span class="px-2 py-1 font-semibold text-gray-700 bg-gray-100 rounded-full dark:bg-gray-700 dark:text-gray-100">
                      {{ $ownership->product?->market?->name ?? 'N/A' }}
                    </span>
                  </td>
                  <td class="px-4 py-3 text-xs">
                    @if($ownership->sells?->isNotEmpty())
                      <span class="px-2 py-1 font-semibold text-orange-700 bg-orange-100 rounded-full dark:bg-orange-700 dark:text-orange-100">In Sale</span>
                    @else
                      <span class="px-2 py-1 font-semibold text-green-700 bg-green-100 rounded-full dark:bg-green-700 dark:text-green-100">Available</span>
                    @endif
                  </td>
                  <td class="px-4 py-3 text-xs">
                    <span class="px-2 py-1 font-semibold text-indigo-700 bg-indigo-100 rounded-full dark:bg-indigo-700 dark:text-indigo-100">
                      {{ ucfirst($ownership->type) }}
                    </span>
                  </td>
                  <td class="px-4 py-3">
                    <div class="flex items-center space-x-1">
                      <button onclick="openEditModal{{ $ownership->id }}()"
                        class="p-2 text-blue-600 rounded-lg hover:bg-blue-100 dark:text-blue-400 dark:hover:bg-blue-900" title="Edit">
                        <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20"><path d="M13.586 3.586a2 2 0 112.828 2.828l-.793.793-2.828-2.828.793-.793zM11.379 5.793L3 14.172V17h2.828l8.38-8.379-2.83-2.828z"/></svg>
                      </button>
                      <form method="POST" action="{{ route('admin.ownership.delete', $ownership->id) }}"
                            onsubmit="return confirm('Delete this item? Pending sells will also be removed.')">
                        @csrf @method('DELETE')
                        <button type="submit"
                          class="p-2 text-red-600 rounded-lg hover:bg-red-100 dark:text-red-400 dark:hover:bg-red-900" title="Delete">
                          <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M9 2a1 1 0 00-.894.553L7.382 4H4a1 1 0 000 2v10a2 2 0 002 2h8a2 2 0 002-2V6a1 1 0 100-2h-3.382l-.724-1.447A1 1 0 0011 2H9zM7 8a1 1 0 012 0v6a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v6a1 1 0 102 0V8a1 1 0 00-1-1z" clip-rule="evenodd"/></svg>
                        </button>
                      </form>
                    </div>
                  </td>
                </tr>
              @endforeach
            </tbody>
          </table>
        </div>

        {{-- ── Mobile card list (hidden on desktop) ── --}}
        <div class="ui-card-list divide-y dark:divide-gray-700">
          @foreach($ownerships as $ownership)
            <div class="p-4 bg-white dark:bg-gray-800">
              <div class="flex items-center justify-between mb-3">
                <div class="flex items-center gap-3">
                  <img src="{{ asset('storage/products/'.$ownership->product?->image1) }}"
                       class="w-12 h-12 rounded object-cover" loading="lazy"
                       alt="{{ $ownership->product?->name }}"/>
                  <div>
                    <p class="font-semibold text-sm text-gray-800 dark:text-gray-100">{{ $ownership->product?->name }}</p>
                    <p class="text-xs text-gray-500 dark:text-gray-400">{{ $ownership->product?->market?->name ?? 'N/A' }}</p>
                  </div>
                </div>
                <div class="flex gap-1">
                  <button onclick="openEditModal{{ $ownership->id }}()"
                    class="p-2 text-blue-600 rounded-lg hover:bg-blue-100 dark:text-blue-400" title="Edit">
                    <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20"><path d="M13.586 3.586a2 2 0 112.828 2.828l-.793.793-2.828-2.828.793-.793zM11.379 5.793L3 14.172V17h2.828l8.38-8.379-2.83-2.828z"/></svg>
                  </button>
                  <form method="POST" action="{{ route('admin.ownership.delete', $ownership->id) }}"
                        onsubmit="return confirm('Delete this item? Pending sells will also be removed.')">
                    @csrf @method('DELETE')
                    <button type="submit" class="p-2 text-red-600 rounded-lg hover:bg-red-100 dark:text-red-400" title="Delete">
                      <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M9 2a1 1 0 00-.894.553L7.382 4H4a1 1 0 000 2v10a2 2 0 002 2h8a2 2 0 002-2V6a1 1 0 100-2h-3.382l-.724-1.447A1 1 0 0011 2H9zM7 8a1 1 0 012 0v6a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v6a1 1 0 102 0V8a1 1 0 00-1-1z" clip-rule="evenodd"/></svg>
                    </button>
                  </form>
                </div>
              </div>
              <div class="grid grid-cols-2 gap-2 text-xs text-gray-600 dark:text-gray-400">
                <div><span class="font-medium text-gray-500 dark:text-gray-500">Unit Value</span><br>USDT {{ number_format($ownership->value, 2) }}</div>
                <div><span class="font-medium text-gray-500 dark:text-gray-500">Qty</span><br>
                  <span class="px-2 py-0.5 font-semibold text-blue-700 bg-blue-100 rounded-full dark:bg-blue-700 dark:text-blue-400">{{ $ownership->quantity }}</span>
                </div>
                <div><span class="font-medium text-gray-500 dark:text-gray-500">Total Value</span><br><strong>USDT {{ number_format($ownership->value * $ownership->quantity, 2) }}</strong></div>
                <div><span class="font-medium text-gray-500 dark:text-gray-500">Type</span><br>
                  <span class="px-2 py-0.5 font-semibold text-indigo-700 bg-indigo-100 rounded-full dark:bg-indigo-700 dark:text-indigo-100">{{ ucfirst($ownership->type) }}</span>
                </div>
                <div class="col-span-2">
                  <span class="font-medium text-gray-500 dark:text-gray-500">Status</span><br>
                  @if($ownership->sells?->isNotEmpty())
                    <span class="px-2 py-0.5 font-semibold text-orange-700 bg-orange-100 rounded-full dark:bg-orange-700 dark:text-orange-100">In Sale</span>
                  @else
                    <span class="px-2 py-0.5 font-semibold text-green-700 bg-green-100 rounded-full dark:bg-green-700 dark:text-green-100">Available</span>
                  @endif
                </div>
              </div>
            </div>
          @endforeach
        </div>

        {{-- Pagination --}}
        @if($ownerships->hasPages())
          <div class="ui-pagination px-4 py-3 border-t dark:border-gray-700 bg-gray-50 dark:bg-gray-900 text-sm">
            <span class="text-gray-700 dark:text-gray-300">
              Showing {{ $ownerships->firstItem() }}–{{ $ownerships->lastItem() }} of {{ $ownerships->total() }}
            </span>
            <div class="flex gap-2">
              @if($ownerships->onFirstPage())
                <span class="px-3 py-1 text-gray-400 bg-gray-100 rounded-md dark:bg-gray-800 cursor-not-allowed">Prev</span>
              @else
                <a href="{{ $ownerships->previousPageUrl() }}" class="px-3 py-1 text-white bg-blue-600 rounded-md hover:bg-blue-700">Prev</a>
              @endif
              @if($ownerships->hasMorePages())
                <a href="{{ $ownerships->nextPageUrl() }}" class="px-3 py-1 text-white bg-blue-600 rounded-md hover:bg-blue-700">Next</a>
              @else
                <span class="px-3 py-1 text-gray-400 bg-gray-100 rounded-md dark:bg-gray-800 cursor-not-allowed">Next</span>
              @endif
            </div>
          </div>
        @endif

      @else
        <div class="p-10 text-center bg-white dark:bg-gray-800">
          <svg class="w-14 h-14 mx-auto text-gray-400 dark:text-gray-600 mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                  d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"/>
          </svg>
          <p class="text-gray-600 dark:text-gray-400">{{ $users->first_name }} has no inventory items.</p>
          <button onclick="openAddInventoryModal()"
            class="mt-3 px-4 py-2 text-sm text-white bg-blue-600 rounded-md hover:bg-blue-700">
            + Add First Item
          </button>
        </div>
      @endif
    </div>

    {{-- ── Edit modals (rendered once, shared by both table and card views) ── --}}
    @foreach($ownerships as $ownership)
      <div id="editModal{{ $ownership->id }}"
           class="fixed inset-0 z-50 hidden items-center justify-center bg-black bg-opacity-50"
           onclick="handleEditBackdrop{{ $ownership->id }}(event)">
        <div class="ui-modal-card relative w-full bg-white rounded-lg shadow-xl dark:bg-gray-800 p-6"
             onclick="event.stopPropagation()">
          <button onclick="closeEditModal{{ $ownership->id }}()"
            class="absolute top-3 right-3 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300">
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
          </button>
          <h3 class="mb-1 text-lg font-bold text-gray-900 dark:text-white">Edit Inventory Item</h3>
          <p class="mb-4 text-sm text-gray-500 dark:text-gray-400">{{ $ownership->product?->name }}</p>
          <form method="POST" action="{{ route('admin.ownership.update', $ownership->id) }}">
            @csrf @method('PUT')
            <div class="space-y-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">Unit Value (USDT)</label>
                <input type="number" name="value" step="0.01" min="0"
                       value="{{ $ownership->value }}" required
                       class="block w-full mt-1 text-sm rounded-md border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-300 focus:border-blue-500 focus:ring focus:ring-blue-200"/>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">Quantity</label>
                <input type="number" name="quantity" min="1"
                       value="{{ $ownership->quantity }}" required
                       class="block w-full mt-1 text-sm rounded-md border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-300 focus:border-blue-500 focus:ring focus:ring-blue-200"/>
              </div>
              <div class="p-3 bg-gray-50 rounded-md dark:bg-gray-700 text-sm text-gray-600 dark:text-gray-300">
                Current Total:
                <span class="font-bold text-gray-900 dark:text-white">
                  USDT {{ number_format($ownership->value * $ownership->quantity, 2) }}
                </span>
              </div>
            </div>
            <div class="flex justify-end gap-3 mt-5">
              <button type="button" onclick="closeEditModal{{ $ownership->id }}()"
                class="px-4 py-2 text-sm text-gray-700 bg-gray-100 rounded-md hover:bg-gray-200 dark:bg-gray-700 dark:text-gray-300 dark:hover:bg-gray-600">
                Cancel
              </button>
              <button type="submit"
                class="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-md hover:bg-blue-700">
                Save Changes
              </button>
            </div>
          </form>
        </div>
      </div>
      <script>
        function openEditModal{{ $ownership->id }}() {
          var m = document.getElementById('editModal{{ $ownership->id }}');
          m.classList.remove('hidden'); m.classList.add('flex');
          document.body.style.overflow = 'hidden';
        }
        function closeEditModal{{ $ownership->id }}() {
          var m = document.getElementById('editModal{{ $ownership->id }}');
          m.classList.add('hidden'); m.classList.remove('flex');
          document.body.style.overflow = '';
        }
        function handleEditBackdrop{{ $ownership->id }}(e) {
          if (e.target === document.getElementById('editModal{{ $ownership->id }}')) {
            closeEditModal{{ $ownership->id }}();
          }
        }
      </script>
    @endforeach

    {{-- ── ADD INVENTORY MODAL ── --}}
    <div id="addInventoryModal"
         class="fixed inset-0 z-50 hidden items-center justify-center bg-black bg-opacity-50"
         onclick="handleAddModalBackdrop(event)">
      <div class="ui-modal-card relative w-full bg-white rounded-lg shadow-xl dark:bg-gray-800 p-6"
           onclick="event.stopPropagation()">
        <button onclick="closeAddInventoryModal()"
          class="absolute top-3 right-3 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300">
          <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
        </button>
        <h3 class="mb-4 text-lg font-bold text-gray-900 dark:text-white">
          Add Inventory Item for {{ $users->first_name }}
        </h3>
        <form method="POST" action="{{ route('admin.ownership.store', $users->id) }}">
          @csrf
          <div class="space-y-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">Product</label>
              <select name="product_id" required
                class="block w-full mt-1 text-sm rounded-md border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-300 focus:border-blue-500 focus:ring focus:ring-blue-200">
                <option value="">— Select a product —</option>
                @foreach($allProducts as $prod)
                  <option value="{{ $prod->id }}">{{ $prod->name }} (USDT {{ number_format($prod->value, 2) }})</option>
                @endforeach
              </select>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">Quantity</label>
              <input type="number" name="quantity" min="1" value="1" required
                class="block w-full mt-1 text-sm rounded-md border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-300 focus:border-blue-500 focus:ring focus:ring-blue-200"/>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">Type</label>
              <select name="type" required
                class="block w-full mt-1 text-sm rounded-md border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-300 focus:border-blue-500 focus:ring focus:ring-blue-200">
                <option value="ai">AI</option>
                <option value="manual">Manual</option>
                <option value="gift">Gift</option>
              </select>
            </div>
          </div>
          <div class="flex justify-end gap-3 mt-5">
            <button type="button" onclick="closeAddInventoryModal()"
              class="px-4 py-2 text-sm text-gray-700 bg-gray-100 rounded-md hover:bg-gray-200 dark:bg-gray-700 dark:text-gray-300 dark:hover:bg-gray-600">
              Cancel
            </button>
            <button type="submit"
              class="px-4 py-2 text-sm font-medium text-white bg-green-600 rounded-md hover:bg-green-700">
              Add Item
            </button>
          </div>
        </form>
      </div>
    </div>

    <script>
      function openAddInventoryModal() {
        var m = document.getElementById('addInventoryModal');
        m.classList.remove('hidden'); m.classList.add('flex');
        document.body.style.overflow = 'hidden';
      }
      function closeAddInventoryModal() {
        var m = document.getElementById('addInventoryModal');
        m.classList.add('hidden'); m.classList.remove('flex');
        document.body.style.overflow = '';
      }
      function handleAddModalBackdrop(e) {
        if (e.target === document.getElementById('addInventoryModal')) {
          closeAddInventoryModal();
        }
      }
      document.addEventListener('keydown', function(e) {
        if (e.key !== 'Escape') return;
        var add = document.getElementById('addInventoryModal');
        if (add && add.classList.contains('flex')) { closeAddInventoryModal(); return; }
        document.querySelectorAll('[id^="editModal"]').forEach(function(m) {
          if (m.classList.contains('flex')) {
            m.classList.add('hidden'); m.classList.remove('flex');
            document.body.style.overflow = '';
          }
        });
      });
    </script>

    {{-- ═══════════════════════════════════════════════════════
         SECTION 8 — TEAM
    ═══════════════════════════════════════════════════════ --}}
    <div class="mt-8 mb-2">
      <p class="font-semibold text-gray-700 dark:text-gray-400">{{ $users->first_name }}'s Team</p>
    </div>

    <div class="space-y-6 mb-8">
      @foreach([
        ['title' => 'First Generation',  'users' => $firstGen, 'count' => $totalGen1Kyc,  'gen' => 1],
        ['title' => 'Second Generation', 'users' => $secondGen, 'count' => $totalGen2Kyc, 'gen' => 2],
        ['title' => 'Third Generation',  'users' => $thirdGen, 'count' => $totalGen3Kyc,  'gen' => 3],
      ] as $level)

        <div class="bg-white rounded-lg shadow-xs dark:bg-gray-800 overflow-hidden">

          <div class="flex items-center justify-between p-4 bg-blue-600 text-white">
            <div class="flex items-center gap-2 font-semibold">
              <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20"><path d="M13 6a3 3 0 11-6 0 3 3 0 016 0zM18 8a2 2 0 11-4 0 2 2 0 014 0zM14 15a4 4 0 00-8 0v3h8v-3z"/></svg>
              {{ $level['title'] }}
            </div>
            <span class="px-3 py-0.5 text-xs bg-white text-gray-500 rounded-full font-semibold">
              {{ $level['users']->total() }} members, KYC: {{ $level['count'] }}
            </span>
          </div>

          @if($level['users']->count() > 0)

            {{-- ── Desktop table ── --}}
            <div class="ui-table-wrap w-full overflow-x-auto">
              <table class="w-full whitespace-no-wrap text-sm">
                <thead>
                  <tr class="text-xs font-semibold tracking-wide text-left text-gray-500 uppercase border-b dark:border-gray-700 bg-gray-50 dark:text-gray-400 dark:bg-gray-800">
                    <th class="px-4 py-3">Member</th>
                    @if($level['gen'] > 1)<th class="px-4 py-3">Upline</th>@endif
                    <th class="px-4 py-3">KYC</th>
                    <th class="px-4 py-3">Email</th>
                    <th class="px-4 py-3">Active Bots</th>
                    <th class="px-4 py-3">Team</th>
                    <th class="px-4 py-3">Joined</th>
                    <th class="px-4 py-3">Actions</th>
                  </tr>
                </thead>
                <tbody class="bg-white divide-y dark:divide-gray-700 dark:bg-gray-800">
                  @foreach($level['users'] as $dl)
                    <tr class="text-gray-700 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-900">
                      <td class="px-4 py-3">
                        <p class="font-semibold">{{ $dl->first_name }} {{ $dl->last_name }}</p>
                        <p class="text-xs text-gray-500 dark:text-gray-400">{{ $dl->username }}</p>
                      </td>
                      @if($level['gen'] > 1)
                        <td class="px-4 py-3 text-xs text-gray-500 dark:text-gray-400">{{ $dl->referrer?->username ?? '—' }}</td>
                      @endif
                      <td class="px-4 py-3">
                        @if($dl->kyc_status == 1)
                          <span class="px-2 py-0.5 text-xs font-semibold text-green-700 bg-green-100 rounded-full dark:bg-green-700 dark:text-green-100">✓ KYC Done</span>
                        @elseif($dl->kyc_status == 2)
                          <span class="px-2 py-0.5 text-xs font-semibold text-yellow-700 bg-yellow-100 rounded-full dark:bg-yellow-700 dark:text-yellow-100">⏳ Pending</span>
                        @else
                          <span class="px-2 py-0.5 text-xs font-semibold text-gray-500 bg-gray-100 rounded-full dark:bg-gray-700 dark:text-gray-400">✗ No KYC</span>
                        @endif
                      </td>
                      <td class="px-4 py-3">
                        @if($dl->email_verified_at)
                          <span class="px-2 py-0.5 text-xs font-semibold text-blue-700 bg-blue-400 rounded-full dark:bg-blue-700 dark:text-blue-100">✓ Verified</span>
                        @else
                          <span class="px-2 py-0.5 text-xs font-semibold text-gray-500 bg-gray-100 rounded-full dark:bg-gray-700 dark:text-gray-400">Unverified</span>
                        @endif
                      </td>
                      <td class="px-4 py-3 text-center">
                        @if(($dl->active_bots ?? 0) > 0)
                          <span class="px-2 py-0.5 text-xs font-semibold text-green-700 bg-green-100 rounded-full dark:bg-green-700 dark:text-green-100">{{ $dl->active_bots }}</span>
                        @else
                          <span class="text-xs text-gray-400">0</span>
                        @endif
                      </td>
                      <td class="px-4 py-3 text-center text-xs">
                        @if(($dl->team_count ?? 0) > 0)
                          <span class="font-semibold text-blue-600 dark:text-blue-400">{{ $dl->team_count }}</span>
                        @else
                          <span class="text-gray-400">0</span>
                        @endif
                      </td>
                      <td class="px-4 py-3 text-xs text-gray-500 dark:text-gray-400">{{ $dl->created_at->format('M j, Y') }}</td>
                      <td class="px-4 py-3">
                        <div class="flex gap-2">
                          <a href="{{ route('admin.user_info', $dl->id) }}"
                             class="px-2 py-1 text-xs text-white bg-blue-600 rounded hover:bg-blue-700">View</a>
                          @if($dl->status == 0)
                            <span class="px-2 py-1 text-xs text-red-700 bg-red-100 rounded font-semibold dark:bg-red-700 dark:text-red-100">Banned</span>
                          @endif
                        </div>
                      </td>
                    </tr>
                  @endforeach
                </tbody>
              </table>
            </div>

            {{-- ── Mobile card list ── --}}
            <div class="ui-card-list divide-y dark:divide-gray-700">
              @foreach($level['users'] as $dl)
                <div class="p-4 bg-white dark:bg-gray-800">
                  <div class="flex items-start justify-between mb-2">
                    <div>
                      <p class="font-semibold text-sm text-gray-800 dark:text-gray-100">{{ $dl->first_name }} {{ $dl->last_name }}</p>
                      <p class="text-xs text-gray-500 dark:text-gray-400">@ {{ $dl->username }}
                        @if($level['gen'] > 1) · Upline: {{ $dl->referrer?->username ?? '—' }}@endif
                      </p>
                    </div>
                    <div class="flex flex-col items-end gap-1">
                      <a href="{{ route('admin.user_info', $dl->id) }}"
                         class="px-2 py-1 text-xs text-white bg-blue-600 rounded hover:bg-blue-700">View</a>
                      @if($dl->status == 0)
                        <span class="px-2 py-0.5 text-xs text-red-700 bg-red-100 rounded font-semibold dark:bg-red-700 dark:text-red-100">Banned</span>
                      @endif
                    </div>
                  </div>
                  <div class="flex flex-wrap gap-1 mb-2">
                    {{-- KYC --}}
                    @if($dl->kyc_status == 1)
                      <span class="px-2 py-0.5 text-xs font-semibold text-green-700 bg-green-100 rounded-full dark:bg-green-700 dark:text-green-100">✓ KYC</span>
                    @elseif($dl->kyc_status == 2)
                      <span class="px-2 py-0.5 text-xs font-semibold text-yellow-700 bg-yellow-100 rounded-full">⏳ KYC</span>
                    @else
                      <span class="px-2 py-0.5 text-xs font-semibold text-gray-500 bg-gray-100 rounded-full dark:bg-gray-700">✗ KYC</span>
                    @endif
                    {{-- Email --}}
                    @if($dl->email_verified_at)
                      <span class="px-2 py-0.5 text-xs font-semibold text-blue-700 bg-blue-100 rounded-full dark:bg-blue-700 dark:text-blue-400">✓ Email</span>
                    @else
                      <span class="px-2 py-0.5 text-xs font-semibold text-gray-500 bg-gray-100 rounded-full dark:bg-gray-700">Unverified</span>
                    @endif
                    {{-- Bots --}}
                    @if(($dl->active_bots ?? 0) > 0)
                      <span class="px-2 py-0.5 text-xs font-semibold text-green-700 bg-green-100 rounded-full dark:bg-green-700 dark:text-green-100">🤖 {{ $dl->active_bots }}</span>
                    @endif
                  </div>
                  <div class="flex gap-4 text-xs text-gray-500 dark:text-gray-400">
                    <span>Team: <strong class="text-blue-600 dark:text-blue-400">{{ $dl->team_count ?? 0 }}</strong></span>
                    <span>Joined: {{ $dl->created_at->format('M j, Y') }}</span>
                  </div>
                </div>
              @endforeach
            </div>

            {{-- Pagination --}}
            @if($level['users']->hasPages())
              <div class="ui-pagination px-4 py-3 border-t dark:border-gray-700 bg-gray-50 dark:bg-gray-900 text-sm">
                <span class="text-gray-600 dark:text-gray-400">
                  {{ $level['users']->firstItem() }}–{{ $level['users']->lastItem() }} of {{ $level['users']->total() }}
                </span>
                <div class="flex gap-1 flex-wrap">
                  @if(!$level['users']->onFirstPage())
                    <a href="{{ $level['users']->previousPageUrl() }}"
                       class="px-3 py-1 text-white bg-blue-600 rounded hover:bg-blue-700">‹ Prev</a>
                  @endif
                  @php
                    $cur   = $level['users']->currentPage();
                    $last  = $level['users']->lastPage();
                    $start = max(1, $cur - 2);
                    $end   = min($last, $cur + 2);
                  @endphp
                  @foreach(range($start, $end) as $pg)
                    @if($pg == $cur)
                      <span class="px-3 py-1 text-white bg-orange-500 rounded font-semibold">{{ $pg }}</span>
                    @else
                      <a href="{{ $level['users']->url($pg) }}"
                         class="px-3 py-1 text-gray-700 bg-white border border-gray-300 rounded hover:bg-gray-50 dark:bg-gray-800 dark:text-gray-300 dark:border-gray-600">
                        {{ $pg }}
                      </a>
                    @endif
                  @endforeach
                  @if($level['users']->hasMorePages())
                    <a href="{{ $level['users']->nextPageUrl() }}"
                       class="px-3 py-1 text-white bg-blue-600 rounded hover:bg-blue-700">Next ›</a>
                  @endif
                </div>
              </div>
            @endif

          @else
            <div class="flex items-center p-4">
              <div class="p-3 mr-3 bg-gray-100 rounded-full dark:bg-gray-700">
                <svg class="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                    d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z"/>
                </svg>
              </div>
              <p class="text-sm text-gray-600 dark:text-gray-400">
                {{ $users->first_name }} has no {{ $level['title'] }} members.
              </p>
            </div>
          @endif

        </div>
      @endforeach
    </div>

    {{-- ═══════════════════════════════════════════════════════
         SECTION 9 — AI BOT HISTORY
    ═══════════════════════════════════════════════════════ --}}
    <h4 class="mb-3 text-lg font-semibold text-gray-600 dark:text-gray-300">AI Bot History</h4>
    <div class="w-full overflow-hidden rounded-lg shadow-xs mb-8">
      <div class="w-full overflow-x-auto">
        <table class="w-full whitespace-no-wrap">
          <thead>
            <tr class="text-xs font-semibold tracking-wide text-left text-gray-500 uppercase border-b dark:border-gray-700 bg-gray-50 dark:text-gray-400 dark:bg-gray-800">
              <th class="px-4 py-3">Model</th>
              <th class="px-4 py-3 ui-hide-xs">Entry Capital</th>
              <th class="px-4 py-3">Current Capital</th>
              <th class="px-4 py-3">Status</th>
              <th class="px-4 py-3 ui-hide-xs">Started</th>
              <th class="px-4 py-3 ui-hide-xs">Ends</th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y dark:divide-gray-700 dark:bg-gray-800">
            @forelse($investments as $investment)
              <tr class="text-gray-700 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-900">
                <td class="px-4 py-3 text-sm">
                  <a href="{{ route('admin.investment.show', $investment->id) }}"
                     class="font-semibold text-blue-600 hover:underline dark:text-blue-400">
                    {{ $investment->plan->name }}
                  </a>
                </td>
                <td class="px-4 py-3 text-sm ui-hide-xs">USDT {{ number_format($investment->amount, 2) }}</td>
                <td class="px-4 py-3 text-sm">USDT {{ number_format($investment->balance + $investment->amount, 2) }}</td>
                <td class="px-4 py-3 text-xs">
                  @if($investment->status == 1)
                    <span class="px-2 py-1 font-semibold text-red-700 bg-red-100 rounded-full dark:bg-red-700 dark:text-red-100">Pending</span>
                  @elseif($investment->status == 2)
                    <span class="px-2 py-1 font-semibold text-orange-700 bg-orange-100 rounded-full dark:bg-orange-700 dark:text-orange-100">Ongoing</span>
                  @elseif($investment->status == 3)
                    <span class="px-2 py-1 font-semibold text-green-700 bg-green-100 rounded-full dark:bg-green-700 dark:text-green-100">Completed</span>
                  @endif
                </td>
                <td class="px-4 py-3 text-sm ui-hide-xs">{{ \Carbon\Carbon::parse($investment->buy_date)->format('M j, Y') }}</td>
                <td class="px-4 py-3 text-sm ui-hide-xs">{{ \Carbon\Carbon::parse($investment->end_date)->format('M j, Y') }}</td>
              </tr>
            @empty
              <tr>
                <td colspan="6" class="px-4 py-6 text-center text-gray-500 dark:text-gray-400">No AI bot history.</td>
              </tr>
            @endforelse
          </tbody>
        </table>
      </div>
    </div>

  </div>{{-- /container --}}
</main>
@endsection


{{-- ═══════════════════════════════════════════════════════════════════════
     RESPONSIVE CSS
     Breakpoints:
       xs  < 480px   — single-column everything, card views for tables
       sm  480–639px — 2-col stat grid
       md  640–1023px — handled by Tailwind (md: prefix)
       lg  1024px+   — full desktop layout
     ════════════════════════════════════════════════════════════════════ --}}
