@extends('layouts.app')
@section('title', "Dashboard — God's Treat")

@push('styles')
<style>
  .dash-wrap{padding:110px 5% 60px;max-width:1200px;margin:0 auto;}
  .dash-header{margin-bottom:36px;}
  .dash-greeting{font-family:'Bebas Neue',sans-serif;font-size:2.5rem;}
  .dash-sub{color:var(--muted);margin-top:4px;}
  .dash-grid{display:grid;grid-template-columns:280px 1fr;gap:32px;}
  /* Sidebar */
  .dash-sidebar{position:sticky;top:100px;height:fit-content;}
  .dash-profile-card{background:var(--card);border:1px solid var(--border);border-radius:var(--radius);padding:28px;margin-bottom:20px;}
  .dash-avatar{width:72px;height:72px;border-radius:50%;background:linear-gradient(135deg,var(--orange),var(--gold));display:flex;align-items:center;justify-content:center;font-size:1.8rem;font-weight:800;margin-bottom:14px;color:#0a0a14;}
  .dash-name{font-weight:700;font-size:1.1rem;margin-bottom:4px;}
  .dash-email{color:var(--muted);font-size:.82rem;}
  .dash-nav{position:static !important;display:block !important;top:auto !important;left:auto !important;width:auto !important;background:none !important;box-shadow:none !important;z-index:auto !important;}
  .dash-nav a{display:block;padding:12px 16px;border-radius:10px;color:var(--muted);text-decoration:none;font-size:.9rem;font-weight:500;transition:all .2s;margin-bottom:4px;}
  .dash-nav a:hover,.dash-nav a.active{background:rgba(255,107,26,.12);color:var(--orange);}
  /* Stats */
  .dash-stats{display:grid;grid-template-columns:repeat(3,1fr);gap:16px;margin-bottom:28px;}
  .stat-card{background:var(--card);border:1px solid var(--border);border-radius:16px;padding:20px;}
  .stat-card-num{font-family:'Bebas Neue',sans-serif;font-size:2rem;color:var(--orange);}
  .stat-card-lbl{color:var(--muted);font-size:.78rem;margin-top:2px;}
  /* Orders */
  .order-card{background:var(--card);border:1px solid var(--border);border-radius:16px;padding:22px;margin-bottom:16px;}
  .order-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:16px;flex-wrap:wrap;gap:10px;}
  .order-num{font-family:'Bebas Neue',sans-serif;font-size:1.3rem;color:var(--orange);}
  .order-status{display:inline-block;padding:4px 14px;border-radius:50px;font-size:.75rem;font-weight:700;}
  .status-placed{background:rgba(255,107,26,.15);color:var(--orange);}
  .status-shipped{background:rgba(6,214,160,.15);color:#06d6a0;}
  .status-delivered{background:rgba(6,214,160,.15);color:#06d6a0;}
  .status-cancelled{background:rgba(247,37,133,.15);color:var(--pink);}
  .order-meta{color:var(--muted);font-size:.8rem;margin-bottom:14px;}
  .order-items{display:flex;gap:10px;flex-wrap:wrap;margin-bottom:14px;}
  .order-item-thumb{width:56px;height:56px;background:rgba(255,107,26,.06);border-radius:10px;display:flex;align-items:center;justify-content:center;overflow:hidden;}
  .order-item-thumb img{max-width:80%;max-height:80%;object-fit:contain;}
  .order-total{font-weight:700;font-size:1.05rem;}
  /* Tabs */
  .dash-tab-btns{display:flex;gap:8px;margin-bottom:24px;}
  .tab-btn{padding:8px 20px;border:1px solid var(--border2);border-radius:50px;background:none;color:var(--muted);cursor:pointer;font-size:.85rem;transition:all .2s;}
  .tab-btn.active{background:var(--orange);border-color:var(--orange);color:#0a0a14;font-weight:700;}
  /* Form */
  .setting-card{background:var(--card);border:1px solid var(--border);border-radius:var(--radius);padding:28px;margin-bottom:24px;}
  .setting-title{font-family:'Bebas Neue',sans-serif;font-size:1.3rem;margin-bottom:20px;}
  .form-group{margin-bottom:16px;}
  .form-label{font-size:.78rem;font-weight:700;letter-spacing:.1em;text-transform:uppercase;color:var(--muted);margin-bottom:6px;display:block;}
  .form-input{width:100%;background:var(--card2);border:1px solid var(--border2);color:var(--white);padding:12px 16px;border-radius:10px;font-size:.9rem;transition:border-color .2s;box-sizing:border-box;}
  .form-input:focus{outline:none;border-color:var(--orange);}
  .alert-success{background:rgba(6,214,160,.1);border:1px solid rgba(6,214,160,.3);color:#06d6a0;padding:12px 16px;border-radius:10px;margin-bottom:20px;font-size:.875rem;}
  @media(max-width:768px){.dash-grid{grid-template-columns:1fr}.dash-sidebar{position:static}.dash-stats{grid-template-columns:1fr 1fr}}
</style>
@endpush

@section('content')
<div class="dash-wrap">
  <div class="dash-header">
    <h1 class="dash-greeting">HEY, <span class="gradient-text">{{ strtoupper(explode(' ', $user->name)[0]) }}!</span> 👋</h1>
    <p class="dash-sub">Welcome to your God's Treat dashboard</p>
  </div>

  <div class="dash-grid">
    <!-- Sidebar -->
    <aside class="dash-sidebar">
      <div class="dash-profile-card">
        <div class="dash-avatar">{{ strtoupper(substr($user->name, 0, 1)) }}</div>
        <div class="dash-name">{{ $user->name }}</div>
        <div class="dash-email">{{ $user->email }}</div>
      </div>
      <nav class="dash-nav">
        @if(auth()->user()->is_admin)
        <a href="{{ route('admin.dashboard') }}" style="background:rgba(255,107,26,.15);color:var(--orange);font-weight:700;border:1px solid rgba(255,107,26,.25);margin-bottom:8px">⚙️ Admin Panel</a>
        @endif
        <a href="#orders" class="active" onclick="showTab('orders', this)">📦 My Orders</a>
        <a href="#referral" onclick="showTab('referral', this)">🔗 Referral</a>
        <a href="#profile" onclick="showTab('profile', this)">👤 Profile</a>
        <a href="#security" onclick="showTab('security', this)">🔒 Password</a>
        <a href="{{ route('products') }}">🛒 Shop Again</a>
        <form method="POST" action="{{ route('logout') }}" style="margin-top:8px">
          @csrf
          <button type="submit" style="width:100%;background:none;border:none;text-align:left;padding:12px 16px;border-radius:10px;color:var(--pink);cursor:pointer;font-size:.9rem;font-weight:500">🚪 Logout</button>
        </form>
      </nav>
    </aside>

    <!-- Main -->
    <main>
      @if(session('success'))
        <div class="alert-success">✅ {{ session('success') }}</div>
      @endif

      <!-- Stats -->
      <div class="dash-stats">
        <div class="stat-card">
          <div class="stat-card-num">{{ $orders->count() }}</div>
          <div class="stat-card-lbl">Total Orders</div>
        </div>
        <div class="stat-card">
          <div class="stat-card-num">₹{{ number_format($orders->sum('total')) }}</div>
          <div class="stat-card-lbl">Total Spent</div>
        </div>
        <div class="stat-card">
          <div class="stat-card-num">{{ $orders->where('status', 'delivered')->count() }}</div>
          <div class="stat-card-lbl">Delivered</div>
        </div>
      </div>

      <!-- Orders Tab -->
      <div id="tab-orders">
        <div class="dash-tab-btns">
          <button class="tab-btn active">All Orders</button>
        </div>

        @forelse($orders as $order)
        <div class="order-card reveal">
          <div class="order-header">
            <div>
              <div class="order-num">{{ $order->order_number }}</div>
              <div class="order-meta">{{ $order->created_at->format('d M Y') }} · {{ ucfirst($order->payment_method) }}</div>
            </div>
            <span class="order-status status-{{ $order->status }}">{{ $order->status_label }}</span>
          </div>

          <div class="order-items">
            @foreach($order->items as $item)
            <div class="order-item-thumb" title="{{ $item->name }}">
              <img src="{{ asset('images/' . $item->image) }}" alt="{{ $item->name }}"
                onerror="this.src='data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 width=%22100%22 height=%22100%22><rect width=%22100%22 height=%22100%22 fill=%22%23ff6b1a11%22/><text x=%2250%22 y=%2258%22 text-anchor=%22middle%22 fill=%22%23ff6b1a55%22 font-size=%2240%22>🌾</text></svg>'"/>
            </div>
            @endforeach
          </div>

          <div style="display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap">
            <div class="order-total">₹{{ number_format($order->total) }}</div>
            <div style="display:flex;gap:16px;align-items:center">
              <a href="{{ route('invoice.download', $order->order_number) }}" style="color:var(--muted);text-decoration:none;font-size:.85rem;font-weight:600">📄 Invoice</a>
              <a href="{{ route('order.success', $order->order_number) }}" style="color:var(--orange);text-decoration:none;font-size:.85rem;font-weight:600">View Details →</a>
            </div>
          </div>
        </div>
        @empty
        <div style="text-align:center;padding:60px 20px;background:var(--card);border:1px solid var(--border);border-radius:var(--radius)">
          <div style="font-size:3rem;margin-bottom:16px">📦</div>
          <h3 style="font-family:'Bebas Neue',sans-serif;font-size:1.8rem;margin-bottom:8px">NO ORDERS YET</h3>
          <p style="color:var(--muted);margin-bottom:20px">Start your makhana journey today!</p>
          <a href="{{ route('products') }}" class="btn-primary">Shop Now →</a>
        </div>
        @endforelse
      </div>

      <!-- Referral Tab -->
      <div id="tab-referral" style="display:none">
        <div class="setting-card">
          <div class="setting-title">YOUR REFERRAL LINK</div>
          <p style="color:var(--muted);font-size:.88rem;margin-bottom:20px">
            Share your unique referral link. When a friend signs up using your link and places their first order, you both get rewarded!
          </p>

          @php $refLink = route('register') . '?ref=' . ($user->referral_code ?? 'N/A') @endphp

          <div class="form-group">
            <label class="form-label">Your Referral Link</label>
            <div style="display:flex;gap:10px">
              <input type="text" id="refLinkInput" class="form-input" value="{{ $refLink }}" readonly style="font-size:.82rem"/>
              <button onclick="copyRef()" class="btn-primary" style="padding:12px 20px;white-space:nowrap">Copy</button>
            </div>
          </div>

          <div style="display:flex;gap:10px;margin-top:10px">
            <a href="https://wa.me/?text={{ urlencode('Join God\'s Treat — India\'s freshest makhana! Use my referral link: ' . $refLink) }}"
               target="_blank" class="btn-primary" style="padding:10px 18px;font-size:.82rem;background:rgba(37,211,102,.15);color:#25d366;border:1px solid rgba(37,211,102,.3)">
              WhatsApp Share
            </a>
            <button onclick="copyRef()" class="btn-primary" style="padding:10px 18px;font-size:.82rem">Copy Link</button>
          </div>

          <div style="margin-top:28px;display:grid;grid-template-columns:1fr 1fr;gap:14px">
            <div style="background:var(--card2);border:1px solid var(--border);border-radius:12px;padding:16px;text-align:center">
              <div style="font-family:'Bebas Neue',sans-serif;font-size:2rem;color:var(--orange)">{{ $user->referrals()->count() }}</div>
              <div style="color:var(--muted);font-size:.78rem;margin-top:2px">Friends Referred</div>
            </div>
            <div style="background:var(--card2);border:1px solid var(--border);border-radius:12px;padding:16px;text-align:center">
              <div style="font-family:'Bebas Neue',sans-serif;font-size:2rem;color:var(--green)">₹{{ $user->referrals()->where('status','credited')->sum('reward_amount') }}</div>
              <div style="color:var(--muted);font-size:.78rem;margin-top:2px">Rewards Earned</div>
            </div>
          </div>

          <div style="margin-top:20px;padding:14px;background:rgba(255,197,71,.06);border:1px solid rgba(255,197,71,.15);border-radius:10px;font-size:.82rem;color:var(--muted)">
            <strong style="color:var(--gold)">How it works:</strong> Share your link → Friend signs up → Friend places first order → You both get ₹50 off on your next order.
          </div>
        </div>
      </div>

      <!-- Profile Tab -->
      <div id="tab-profile" style="display:none">
        <div class="setting-card">
          <div class="setting-title">PROFILE INFO</div>
          <form method="POST" action="{{ route('dashboard.profile') }}">
            @csrf
            <div class="form-group">
              <label class="form-label">Full Name</label>
              <input type="text" name="name" class="form-input" value="{{ $user->name }}" required/>
            </div>
            <div class="form-group">
              <label class="form-label">Email (read-only)</label>
              <input type="email" class="form-input" value="{{ $user->email }}" disabled style="opacity:.5"/>
            </div>
            <div class="form-group">
              <label class="form-label">Phone</label>
              <input type="tel" name="phone" class="form-input" value="{{ $user->phone }}" placeholder="+91 98765 43210"/>
            </div>
            <button type="submit" class="btn-primary" style="padding:13px 32px">Save Changes</button>
          </form>
        </div>
      </div>

      <!-- Security Tab -->
      <div id="tab-security" style="display:none">
        <div class="setting-card">
          <div class="setting-title">CHANGE PASSWORD</div>
          <form method="POST" action="{{ route('dashboard.password') }}">
            @csrf
            <div class="form-group">
              <label class="form-label">Current Password</label>
              <input type="password" name="current_password" class="form-input {{ $errors->has('current_password') ? 'border-pink' : '' }}" required/>
              @error('current_password')<div style="color:var(--pink);font-size:.78rem;margin-top:4px">{{ $message }}</div>@enderror
            </div>
            <div class="form-group">
              <label class="form-label">New Password</label>
              <input type="password" name="password" class="form-input {{ $errors->has('password') ? 'border-pink' : '' }}" required/>
              @error('password')<div style="color:var(--pink);font-size:.78rem;margin-top:4px">{{ $message }}</div>@enderror
            </div>
            <div class="form-group">
              <label class="form-label">Confirm New Password</label>
              <input type="password" name="password_confirmation" class="form-input" required/>
            </div>
            <button type="submit" class="btn-primary" style="padding:13px 32px">Update Password</button>
          </form>
        </div>
      </div>
    </main>
  </div>
</div>
@endsection

@push('scripts')
<script>
function showTab(tab, el) {
  document.querySelectorAll('[id^=tab-]').forEach(t => t.style.display = 'none');
  document.getElementById('tab-' + tab).style.display = 'block';
  document.querySelectorAll('.dash-nav a').forEach(a => a.classList.remove('active'));
  el.classList.add('active');
  return false;
}
function copyRef() {
  const inp = document.getElementById('refLinkInput');
  if (inp) { inp.select(); navigator.clipboard.writeText(inp.value).then(() => showToast('Referral link copied!')); }
}
</script>
@endpush
