@extends('layout.user')

@section('content')
@php
  $gs  = \App\Models\GeneralSetting::first();

  $p   = '#2563EB';
  $s   = '#1D4ED8';
  $a   = '#38BDF8';
  $bg  = '#F8FAFC';
  $ink = '#0F172A';

  $status = request('status');
  $search = request('search','');

  $fallbackAvatar = $gs && !empty($gs->logo) ? asset(ltrim($gs->logo,'/')) : asset('images/logo.png');
@endphp

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css"/>
<link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@400;500;600;700&display=swap" rel="stylesheet">

<style>
:root{
  --p: {{ $p }};
  --s: {{ $s }};
  --a: {{ $a }};
  --bg: {{ $bg }};
  --ink: {{ $ink }};
  --b: rgba(37,99,235,.80);
  --b2: rgba(37,99,235,.95);
}

body{
  background: var(--bg);
  font-family:'Hind Siliguri',sans-serif;
  color: var(--ink);
}
a{text-decoration:none!important}

.main-container{
  max-width:500px;
  margin:0 auto;
  padding:20px 15px 100px;
}

.header-card{
  background:linear-gradient(135deg,var(--p),var(--s));
  border-radius:24px;
  padding:35px 20px;
  color:#fff;
  text-align:center;
  position:relative;
  overflow:hidden;
  box-shadow:0 12px 30px -10px rgba(37,99,235,.5);
  margin-bottom:18px;
  border:2px solid #fff;
}
.header-card::after{
  content:'';
  position:absolute;
  bottom:-20px; left:-20px;
  width:100px; height:100px;
  background:rgba(255,255,255,.10);
  border-radius:50%;
}

.tab-group{
  display:flex;
  background:#E2E8F0;
  padding:6px;
  border-radius:18px;
  margin-bottom:14px;
  gap:6px;
  border:2px solid var(--b2);
}
.tab-btn{
  flex:1;
  padding:12px 5px;
  text-align:center;
  border-radius:14px;
  font-size:14px;
  font-weight:1000;
  color:#64748B;
  transition:.3s;
  border:2px solid transparent;
}
.tab-btn.active{
  background:#fff;
  color:var(--p);
  box-shadow:0 4px 15px rgba(37,99,235,.10);
  border:2px solid var(--b2);
}

.search-wrap{
  display:flex;
  gap:10px;
  margin-bottom:16px;
}
.search{
  flex:1;
  border-radius:999px;
  padding:12px 18px;
  width:100%;
  background:#fff;
  border:2px solid var(--b2);
  font-weight:900;
  color:#0f172a;
}
.search::placeholder{ color:#94a3b8; font-weight:900; }
.search:focus{
  outline:none;
  box-shadow:0 0 0 3px rgba(37,99,235,.18);
}
.btn{
  border:none;
  cursor:pointer;
  background:linear-gradient(90deg,var(--p),var(--s));
  color:#fff;
  padding:12px 16px;
  border-radius:999px;
  font-weight:1000;
  font-size:.9rem;
  display:inline-flex;
  gap:8px;
  align-items:center;
  border:2px solid #fff;
}
.btn:active{ transform:scale(.99); }

.user-card{
  background:#fff;
  border-radius:22px;
  padding:20px;
  margin-bottom:16px;
  border:2px solid var(--b2);
  box-shadow:0 10px 25px -5px rgba(15,23,42,.04);
  transition:transform .2s ease;
}
.user-card:active{ transform:scale(.98); }

.user-top{
  display:flex;
  justify-content:space-between;
  align-items:center;
  margin-bottom:18px;
}
.user-info-meta{
  display:flex;
  align-items:center;
  gap:14px;
}
.user-avatar{
  width:52px;
  height:52px;
  border-radius:999px;
  overflow:hidden;
  background:#fff;
  border:2px solid var(--b2);
  display:grid;
  place-items:center;
  box-shadow:0 8px 16px rgba(37,99,235,.12);
  flex:0 0 auto;
}
.user-avatar img{
  width:100%;
  height:100%;
  object-fit:cover;
  display:block;
}
.user-avatar .ico{ color:var(--p); font-size:18px; }

.user-name{
  font-weight:1000;
  font-size:17px;
  color:#1E293B;
  margin:0;
  line-height:1.2;
}
.date-tag{
  font-size:12px;
  color:#94A3B8;
  display:flex;
  align-items:center;
  gap:4px;
  font-weight:900;
}

.badge-status{
  padding:6px 14px;
  border-radius:12px;
  font-size:11px;
  font-weight:1000;
  letter-spacing:.5px;
  border:2px solid transparent;
}
.badge-ok{ background:#DCFCE7; color:#166534; border-color:#16a34a55; }
.badge-no{ background:#FEE2E2; color:#991B1B; border-color:#ef444455; }

.data-box{
  background:#fff;
  border-radius:14px;
  padding:14px;
  display:flex;
  align-items:center;
  justify-content:space-between;
  margin-top:10px;
  border:2px solid var(--b);
}
.data-label{
  font-size:13px;
  color:#1d4ed8;
  display:flex;
  align-items:center;
  gap:10px;
  font-weight:1000;
}
.data-value{
  font-size:14px;
  font-weight:1000;
  color:#0f172a;
  display:flex;
  align-items:center;
  gap:8px;
}
.copy-btn{
  color:var(--p);
  background:#DBEAFE;
  width:30px;
  height:30px;
  display:grid;
  place-items:center;
  border-radius:10px;
  cursor:pointer;
  font-size:12px;
  transition:.2s;
  border:2px solid var(--b2);
}
.copy-btn:hover{ background:var(--p); color:#fff; }

.profile-btn{
  margin-top:12px;
  width:100%;
  background:linear-gradient(90deg,var(--p),var(--s));
  color:#fff;
  border:2px solid #fff;
  padding:11px 14px;
  border-radius:14px;
  font-weight:1000;
  cursor:pointer;
}
.profile-btn:active{ transform:scale(.99); }

.page-row{
  display:flex;
  justify-content:space-between;
  align-items:center;
  margin-top:22px;
  padding:0 6px;
}
.page-link{
  width:44px;
  height:44px;
  background:#fff;
  border-radius:14px;
  display:flex;
  align-items:center;
  justify-content:center;
  color:var(--p);
  box-shadow:0 4px 10px rgba(0,0,0,.05);
  border:2px solid var(--b2);
}
.page-mid{
  font-size:12px;
  font-weight:1000;
  color:#1d4ed8;
  letter-spacing:.12em;
  text-transform:uppercase;
}

#userProfileModal{
  display:none;
  position:fixed;
  inset:0;
  z-index:99999;
  background:rgba(15,23,42,.35);
  padding:14px;
  align-items:center;
  justify-content:center;
}
#userProfileModal .modal-card{
  background:#fff;
  width:100%;
  max-width:420px;
  border-radius:22px;
  box-shadow:0 25px 50px -12px rgba(0,0,0,.25);
  position:relative;
  border:2px solid var(--b2);
  max-height:72vh;
  overflow:hidden;
  display:flex;
  flex-direction:column;
}
#userProfileModal .modal-head{
  padding:12px 14px 10px;
  border-bottom:1px solid rgba(37,99,235,.15);
}
#userProfileModal .xbtn{
  position:absolute;
  top:10px;
  right:10px;
  width:34px;
  height:34px;
  border-radius:10px;
  border:2px solid var(--b2);
  background:#fff;
  color:#334155;
  font-size:18px;
  cursor:pointer;
}
#userProfileModal .title{
  font-weight:1000;
  font-size:18px;
  color:#0f172a;
  margin:0;
  text-align:center;
}
#userProfileModal .modal-body{
  padding:12px 14px 14px;
  overflow:auto;
  -webkit-overflow-scrolling:touch;
}
#userProfileModal .loading{
  display:none;
  font-weight:1000;
  color:#1d4ed8;
  padding:10px 0;
  text-align:center;
}
#userProfileModal .body{ display:none; }

#userProfileModal .box{
  background:#fff;
  border:2px solid var(--b);
  padding:14px 12px;
  border-radius:16px;
  margin-bottom:12px;
}

#userProfileModal .phead{
  display:flex;
  flex-direction:column;
  align-items:center;
  justify-content:center;
  text-align:center;
  gap:10px;
}
#userProfileModal .pavatar{
  width:78px;
  height:78px;
  border-radius:999px;
  overflow:hidden;
  border:2px solid var(--b2);
  box-shadow:0 10px 22px rgba(37,99,235,.14);
  background:#fff;
}
#userProfileModal .pavatar img{
  width:100%;
  height:100%;
  object-fit:cover;
  display:block;
}
#userProfileModal .pname{
  font-weight:1000;
  color:#0f172a;
  font-size:18px;
  line-height:1.2;
}
#userProfileModal .pmeta{
  display:flex;
  flex-wrap:wrap;
  justify-content:center;
  gap:8px;
}
#userProfileModal .pill{
  padding:7px 10px;
  border-radius:999px;
  font-weight:1000;
  font-size:12px;
  background:#eff6ff;
  color:#1d4ed8;
  border:2px solid var(--b2);
  display:inline-flex;
  align-items:center;
  gap:6px;
}
#userProfileModal .pgrid{
  margin-top:12px;
  display:grid;
  grid-template-columns:1fr 1fr;
  gap:10px;
}
#userProfileModal .pitem{
  background:#fff;
  border:2px solid var(--b);
  border-radius:14px;
  padding:10px;
  text-align:center;
}
#userProfileModal .plbl{
  font-size:11px;
  font-weight:1000;
  color:#1d4ed8;
  opacity:.9;
  margin-bottom:6px;
}
#userProfileModal .pval{
  font-size:13px;
  font-weight:1000;
  color:#0f172a;
  word-break:break-all;
}

#userProfileModal .team-title{
  font-weight:1000;
  color:#0f172a;
  margin:12px 0 8px;
  text-align:center;
}
#userProfileModal .team{
  display:grid;
  grid-template-columns:repeat(2,1fr);
  gap:8px;
}
#userProfileModal .lv{
  background:#fff;
  border:2px solid var(--b2);
  border-radius:14px;
  padding:10px;
  font-weight:1000;
  color:#0f172a;
  display:flex;
  justify-content:space-between;
}
#userProfileModal .total{
  margin-top:12px;
  background:#2563EB;
  border:2px solid #fff;
  padding:10px;
  border-radius:16px;
  font-weight:1000;
  color:#fff;
  text-align:center;
}

.empty-card{
  background:#fff;
  border-radius:22px;
  padding:34px 18px;
  border:2px dashed var(--b2);
  text-align:center;
}

#toast{
  position:fixed;
  bottom:40px;
  left:50%;
  transform:translateX(-50%) translateY(100px);
  background:#1E293B;
  color:#fff;
  padding:14px 28px;
  border-radius:16px;
  font-weight:1000;
  transition:.4s cubic-bezier(.18,.89,.32,1.28);
  z-index:1000;
  box-shadow:0 15px 30px rgba(0,0,0,.30);
  border:2px solid #fff;
}
#toast.show{ transform:translateX(-50%) translateY(0); }
</style>

<div class="main-container">

  <div class="header-card">
    <h1 class="text-2xl font-bold">রেফারেল নেটওয়ার্ক</h1>
    <p class="text-blue-100/90 text-sm mt-1">আপনার টিমের প্রবৃদ্ধি পর্যবেক্ষণ করুন</p>
  </div>

  <div class="tab-group">
    <a href="{{ url()->current() }}{{ $search ? '?search='.$search : '' }}" class="tab-btn {{ is_null($status)?'active':'' }}">সকল</a>
    <a href="?status=active{{ $search ? '&search='.$search : '' }}" class="tab-btn {{ $status=='active'?'active':'' }}">ভেরিফাইড</a>
    <a href="?status=inactive{{ $search ? '&search='.$search : '' }}" class="tab-btn {{ $status=='inactive'?'active':'' }}">আনভেরিফাইড</a>
  </div>

  <form method="GET" class="search-wrap">
    <input type="text" name="search" value="{{ $search }}" class="search" placeholder="রেফার কোড বা মোবাইল লিখুন">
    @if($status)<input type="hidden" name="status" value="{{ $status }}">@endif
    <button type="submit" class="btn"><i class="fas fa-search"></i> খুঁজুন</button>
  </form>

  @forelse($referrals as $ref)
    @php
      $upline = \App\Models\User::where('referral_code',$ref->referred_by)->first();
      $avatar = null;
      if (!empty($ref->profile_photo)) {
        $avatar = str_starts_with($ref->profile_photo, 'http')
          ? $ref->profile_photo
          : asset(ltrim($ref->profile_photo, '/'));
      } else {
        $avatar = $fallbackAvatar;
      }
    @endphp

    <div class="user-card">
      <div class="user-top">
        <div class="user-info-meta">
          <div class="user-avatar">
            @if($avatar)
              <img src="{{ $avatar }}" alt="Profile">
            @else
              <span class="ico"><i class="fas fa-user"></i></span>
            @endif
          </div>
          <div>
            <h3 class="user-name">{{ $ref->name }}</h3>
            <span class="date-tag"><i class="far fa-calendar-check"></i> {{ $ref->created_at->format('d M, Y') }}</span>
          </div>
        </div>

        <div class="badge-status {{ $ref->is_active ? 'badge-ok' : 'badge-no' }}">
          {{ $ref->is_active ? 'ভেরিফাইড' : 'আনভেরিফাইড' }}
        </div>
      </div>

      <div class="data-box">
        <div class="data-label"><i class="fas fa-hashtag"></i> রেফার আইডি</div>
        <div class="data-value">
          <span id="r{{ $loop->index }}">{{ $ref->referral_code ?? $ref->refer_code }}</span>
          <div class="copy-btn" onclick="copyValue('r{{ $loop->index }}')"><i class="fas fa-copy"></i></div>
        </div>
      </div>

      <div class="data-box">
        <div class="data-label"><i class="fas fa-mobile-screen"></i> মোবাইল</div>
        <div class="data-value">
          <span id="m{{ $loop->index }}">{{ $ref->mobile ?? 'N/A' }}</span>
          <div class="copy-btn" onclick="copyValue('m{{ $loop->index }}')"><i class="fas fa-copy"></i></div>
        </div>
      </div>

      <div class="data-box">
        <div class="data-label"><i class="fas fa-sitemap"></i> আপলাইন</div>
        <div class="data-value">
          {{ $upline ? ($upline->mobile ?? 'N/A') : 'Direct Member' }}
        </div>
      </div>

      <button type="button" class="profile-btn" onclick="openUserProfile({{ $ref->id }})">প্রোফাইল দেখুন</button>
    </div>

  @empty
    <div class="empty-card">
      <i class="fas fa-user-group" style="font-size:48px;color:rgba(37,99,235,.22)"></i>
      <p style="margin-top:10px;color:#1d4ed8;font-weight:1000;">কোনো সদস্য পাওয়া যায়নি</p>
    </div>
  @endforelse

  @if($referrals->hasPages())
    <div class="page-row">
      @if($referrals->onFirstPage())
        <span style="opacity:0">Prev</span>
      @else
        <a href="{{ $referrals->previousPageUrl() }}" class="page-link"><i class="fas fa-chevron-left"></i></a>
      @endif

      <span class="page-mid">পেজ {{ $referrals->currentPage() }} / {{ $referrals->lastPage() }}</span>

      @if($referrals->hasMorePages())
        <a href="{{ $referrals->nextPageUrl() }}" class="page-link"><i class="fas fa-chevron-right"></i></a>
      @else
        <span style="opacity:0">Next</span>
      @endif
    </div>
  @endif
</div>

<div id="userProfileModal">
  <div class="modal-card">
    <button type="button" class="xbtn" onclick="closeUserProfile()">&times;</button>

    <div class="modal-head">
      <div class="title">ইউজার প্রোফাইল</div>
    </div>

    <div class="modal-body">
      <div id="upLoading" class="loading">লোড হচ্ছে...</div>

      <div id="upBody" class="body">
        <div class="box">
          <div class="phead">
            <div class="pavatar">
              <img id="upAvatar" src="{{ $fallbackAvatar }}" alt="Profile">
            </div>

            <div class="pname" id="upName"></div>

            <div class="pmeta">
              <span class="pill" id="upStatus"></span>
              <span class="pill" id="upDate"></span>
            </div>
          </div>

          <div class="pgrid">
            <div class="pitem">
              <div class="plbl">মোবাইল</div>
              <div class="pval" id="upMobile"></div>
            </div>
            <div class="pitem">
              <div class="plbl">রেফার কোড</div>
              <div class="pval" id="upRef"></div>
            </div>
            <div class="pitem">
              <div class="plbl">আপলাইন রেফার</div>
              <div class="pval" id="upUplineRef"></div>
            </div>
            <div class="pitem">
              <div class="plbl">আপলাইন মোবাইল</div>
              <div class="pval" id="upUplineMobile"></div>
            </div>
          </div>
        </div>

        <div class="team-title">টিম (লেভেল ১–{{ $maxNetworkLevel }})</div>
        <div id="upTeam" class="team"></div>

        <div class="total">মোট টিম: <span id="upTotalTeam"></span></div>
      </div>
    </div>
  </div>
</div>

<div id="toast">সফলভাবে কপি হয়েছে!</div>

<script>
function copyValue(id){
  const text = (document.getElementById(id)?.innerText || '').trim();
  if(!text) return;

  navigator.clipboard.writeText(text).then(() => {
    const toast = document.getElementById('toast');
    toast.classList.add('show');
    setTimeout(() => toast.classList.remove('show'), 2000);
  });
}

async function openUserProfile(userId){
  const modal = document.getElementById('userProfileModal');
  const loading = document.getElementById('upLoading');
  const body = document.getElementById('upBody');

  modal.style.display = 'flex';
  loading.style.display = 'block';
  body.style.display = 'none';
  loading.innerText = 'লোড হচ্ছে...';

  try{
    const res = await fetch("{{ url('/referrals/user') }}/" + userId + "/profile", {
      headers: { 'X-Requested-With': 'XMLHttpRequest' }
    });
    if(!res.ok) throw new Error('Failed');

    const data = await res.json();
    const fallback = @json($fallbackAvatar);

    let av = data.user && data.user.profile_photo ? (''+data.user.profile_photo) : '';
    if(av && !av.startsWith('http')){
      av = "{{ url('/') }}/" + av.replace(/^\/+/,'');
    }
    document.getElementById('upAvatar').src = av || fallback;

    document.getElementById('upName').innerText   = data.user.name || '';
    document.getElementById('upMobile').innerText = data.user.mobile || 'N/A';
    document.getElementById('upRef').innerText    = data.user.referral_code || 'N/A';

    document.getElementById('upUplineRef').innerText =
      (data.upline && data.upline.referral_code) ? data.upline.referral_code : 'N/A';

    document.getElementById('upUplineMobile').innerText =
      (data.upline && data.upline.mobile) ? data.upline.mobile : 'N/A';

    const st = data.user.is_banned ? 'ব্যানড' : (data.user.is_active ? 'ভেরিফাইড' : 'আনভেরিফাইড');
    document.getElementById('upStatus').innerHTML = `<i class="fas fa-circle-check"></i> ${st}`;

    const joined = data.user.created_at ? ('যোগদান: ' + data.user.created_at) : 'যোগদান: N/A';
    document.getElementById('upDate').innerHTML = `<i class="far fa-calendar"></i> ${joined}`;

    const teamWrap = document.getElementById('upTeam');
    teamWrap.innerHTML = '';
    (data.team.levels || []).forEach(lv => {
      const div = document.createElement('div');
      div.className = 'lv';
      div.innerHTML = `<span>লেভেল ${lv.level}</span><span>${lv.count}</span>`;
      teamWrap.appendChild(div);
    });

    document.getElementById('upTotalTeam').innerText =
      (data.team && data.team.total != null) ? data.team.total : 0;

    loading.style.display = 'none';
    body.style.display = 'block';
  }catch(e){
    loading.innerText = 'লোড করা যায়নি';
    loading.style.display = 'block';
    body.style.display = 'none';
  }
}

function closeUserProfile(){
  document.getElementById('userProfileModal').style.display = 'none';
}
</script>
@endsection
