@extends('layout.user')

@section('content')
  @php
    $primary = '#0ea5e9';
    $dark = '#0f172a';
    $photo = $user->profile_photo ?? null;
    $photoUrl = null;
    if ($photo) {
      $photoUrl = str_contains($photo, '/') ? asset($photo) : asset('images/profile/' . $photo);
    }
    $noticeText = trim((string) ($rank->notice_text ?? ''));
    $needVerified = (int) ($rank->need_verified_members ?: 3);
    $includeLevel2 = (bool) ($rank->include_level2_verified ?? false);
    $includeLevel3 = (bool) ($rank->include_level3_verified ?? false);
    $needL2 = (int) ($rank->need_level2_members ?? 0);
    $needL3 = (int) ($rank->need_level3_members ?? 0);
    $cycleVerified = (int) ($cycleVerified ?? 0);
    $level1Total = (int) ($cycleLevel1Total ?? ($svcLevel1Total ?? ($counts['verified'] ?? 0)));
    $level2Total = (int) ($cycleLevel2Total ?? ($svcLevel2Total ?? ($counts['verified_level2'] ?? 0)));
    $level3Total = (int) ($cycleLevel3Total ?? ($svcLevel3Total ?? ($counts['verified_level3'] ?? 0)));
    $lvl1Need = $needVerified;
    $lvl2Need = $includeLevel2 ? $needL2 : 0;
    $lvl3Need = $includeLevel3 ? $needL3 : 0;
    $currentVerified = (int) ($verifiedNow ?? ($includeLevel2 ? $level1Total + $level2Total : $level1Total));
    $submitReady =
      $level1Total >= $lvl1Need
      && (!$includeLevel2 || $level2Total >= $lvl2Need)
      && (!$includeLevel3 || $level3Total >= $lvl3Need);
    $lvl1Percent = $lvl1Need > 0 ? min(1, $level1Total / $lvl1Need) * 100 : 100;
    $lvl2Percent = $lvl2Need > 0 ? min(1, $level2Total / $lvl2Need) * 100 : 100;
    $lvl3Percent = $lvl3Need > 0 ? min(1, $level3Total / $lvl3Need) * 100 : 100;
    $primaryPercent = $lvl1Percent;
    $primaryNeed = $lvl1Need ?: ($level1Total ?: 1);
    $primaryCurrent = $level1Total;
    $cycleStart = $cycleStartAt ?? $lastClaim?->claimed_at ?? $user->created_at;
    $canDownload = (int) ($claimCount ?? 0) > 0;
    $downloadRequested = request()->boolean('download');
    $leaderCount = max(1, (int) ($claimCount ?? 0));
    $bnDigits = ['0' => '০', '1' => '১', '2' => '২', '3' => '৩', '4' => '৪', '5' => '৫', '6' => '৬', '7' => '৭', '8' => '৮', '9' => '৯'];
    $leaderCountBn = strtr((string) $leaderCount, $bnDigits);
    $leaderOrdinal = match ($leaderCount) {
      1 => '১ম',
      2 => '২য়',
      3 => '৩য়',
      4 => '৪র্থ',
      5 => '৫ম',
      default => $leaderCountBn . 'তম',
    };
  @endphp

  <style>
    .page {
      max-width: 720px;
      margin: 0 auto;
      padding: 20px 12px 90px;
      text-align: center
    }

    .topbar {
      display: flex;
      justify-content: space-between;
      align-items: center;
      gap: 10px
    }

    .back {
      display: inline-flex;
      align-items: center;
      gap: 8px;
      padding: 10px 12px;
      border-radius: 12px;
      text-decoration: none;
      color: #0f172a;
      font-weight: 900;
      border: 1px solid #e2e8f0;
      background: #f8fafc
    }

    .hero {
      margin-top: 12px;
      background: linear-gradient(135deg, #0ea5e9, #2563eb);
      border-radius: 22px;
      padding: 22px 16px;
      box-shadow: 0 14px 32px rgba(14, 165, 233, .18);
      color: #fff;
      display: flex;
      flex-direction: column;
      gap: 10px;
      align-items: center;
      position: relative
    }

    .avatar {
      width: 96px;
      height: 96px;
      border-radius: 999px;
      background: radial-gradient(circle at 20% 20%, #e0f2fe, #bfdbfe);
      display: flex;
      align-items: center;
      justify-content: center;
      font-weight: 1000;
      font-size: 30px;
      color: #0ea5e9;
      border: 2px solid rgba(255, 255, 255, .4);
      overflow: hidden;
      background-size: cover;
      background-position: center;
    }

    .eyebrow {
      font-size: 18px;
      font-weight: 900;
      letter-spacing: .08em;
      margin-bottom: 20px;
      text-transform: uppercase;
      opacity: .9
    }

    .title {
      font-size: 22px;
      margin-top: 10px;
      font-weight: 1000;
      line-height: 1.1
    }

    .meta {
      font-size: 18px;
      font-weight: 800;
      opacity: .9
    }

    .hero-text {
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 4px
    }

    .pill-row {
      display: flex;
      gap: 10px;
      align-items: center;
      justify-content: center;
      flex-wrap: nowrap;
      width: 100%;
      max-width: 520px;
    }

    .pill {
      display: inline-flex;
      align-items: center;
      gap: 6px;
      padding: 10px 14px;
      min-height: 40px;
      flex: 1 1 0;
      border-radius: 12px;
      font-weight: 900;
      font-size: 12px;
      text-align: center;
      justify-content: center;
      background: #e0f2fe;
      color: #0ea5e9;
      margin-top: 4px;
      transition: background .2s ease, box-shadow .2s ease;
    }

    .pill:hover {
      box-shadow: 0 6px 14px rgba(59, 130, 246, .16);
    }

    .pill.reward {
      background: linear-gradient(135deg, #f59e0b, #f97316);
      color: #fff;
      border: 1px solid rgba(0, 0, 0, .05);
      box-shadow: 0 10px 24px rgba(249, 115, 22, .22);
      font-size: 13px;
    }

    .pill.reward .amount {
      font-size: 16px;
      font-weight: 1000;
      letter-spacing: -0.01em
    }

    .dl-btn {
      background: linear-gradient(135deg, #e0e7ff, #c7d2fe);
      border: 1.5px solid #bfdbfe;
      color: #1e3a8a;
      border-radius: 12px;
      padding: 10px 14px;
      min-height: 40px;
      font-weight: 900;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      gap: 8px;
      box-shadow: 0 8px 18px rgba(59, 130, 246, .12);
      text-decoration: none;
      transition: transform .15s ease, box-shadow .15s ease;
      flex: 1 1 0;
    }

    .dl-icon {
      width: 20px;
      height: 20px;
      display: block;
      line-height: 1;
      color: #0f172a
    }

    .dl-icon path {
      stroke: currentColor;
      stroke-width: 2;
      fill: none;
    }

    .dl-text {
      font-size: 12px;
      line-height: 1
    }

    .dl-btn:hover {
      transform: translateY(-1px);
      box-shadow: 0 10px 22px rgba(59, 130, 246, .18);
    }

    .dl-btn--disabled {
      opacity: .5;
      cursor: not-allowed;
      pointer-events: none;
      transform: none;
      box-shadow: none;
    }

    .cert-stage {
      position: fixed;
      left: -9999px;
      top: 0;
      opacity: 0;
      pointer-events: none;
    }

    .leader-cert {
      width: 1080px;
      height: 1080px;
      position: relative;
      background-position: center;
      background-size: cover;
      background-repeat: no-repeat;
      font-family: 'Noto Sans Bengali', sans-serif;
      color: #0f172a;
      --photo-x: 50.9%;
      --photo-y: 50.8%;
      --photo-size: 310px;
      --name-x: 50%;
      --name-y: 65%;
      --name-size: 34px;
      --name-color: #ffffff;
      --ordinal-inline-x: 55%;
      --ordinal-inline-y: 75.8%;
      --ordinal-inline-size: 28px;
    }

    .leader-cert-photo {
      position: absolute;
      left: var(--photo-x);
      top: var(--photo-y);
      width: var(--photo-size);
      height: var(--photo-size);
      transform: translate(-50%, -50%);
      border-radius: 50%;
      background: #ffffff;
      background-size: cover;
      background-position: center;
      display: flex;
      align-items: center;
      justify-content: center;
      font-weight: 900;
      font-size: 72px;
      color: #1e293b;
      border: 0;
      box-shadow: none;
    }

    .leader-cert-name {
      position: absolute;
      left: var(--name-x);
      top: var(--name-y);
      transform: translateX(-50%);
      font-size: var(--name-size);
      font-weight: 900;
      color: var(--name-color);
      text-align: center;
      width: 72%;
      line-height: 1.2;
      text-shadow: 0 2px 4px rgba(0, 0, 0, .25);
    }

    .leader-cert-ordinal-inline {
      position: absolute;
      left: var(--ordinal-inline-x);
      top: var(--ordinal-inline-y);
      transform: translate(-50%, -50%);
      font-size: var(--ordinal-inline-size);
      font-weight: 900;
      color: #0b102f;
      white-space: nowrap;
      text-align: center;
      min-width: 60px;
    }

    @media (max-width:640px) {
      .hero {
        margin-top: 18px;
        padding-top: 18px;
        gap: 6px;
      }

      .avatar {
        margin-top: 0;
      }

      .hero-text {
        margin-top: 4px;
        gap: 2px;
      }

      .pill-row {
        flex-wrap: wrap;
        justify-content: flex-start;
        max-width: 100%;
      }

      .dl-btn {
        position: absolute;
        right: 12px;
        top: 10px;
        width: 44px;
        height: 44px;
        min-height: 44px;
        padding: 0;
        border-radius: 50%;
        justify-content: center;
        gap: 0;
        background: #ffffff;
        border: 1.5px solid #cbd5e1;
        color: #0f172a;
        box-shadow: 0 10px 18px rgba(15, 23, 42, .18);
        backdrop-filter: blur(8px);
        z-index: 2;
      }

      .dl-text {
        display: none;
      }

      .dl-icon {
        width: 20px;
        height: 20px;
      }

      .pill {
        flex: 1 1 calc(50% - 10px);
      }
    }

    .card {
      background: #fff;
      border: 1.5px solid #e2e8f0;
      border-radius: 18px;
      padding: 18px;
      box-shadow: 0 12px 30px rgba(15, 23, 42, .06);
      margin-top: 18px;
      text-align: center;
      cursor: pointer
    }

    .card.standalone {
      cursor: default
    }

    .card-head {
      font-weight: 1000;
      color: #0f172a;
      font-size: 16px;
      margin-bottom: 12px
    }

    .score-wrap {
      display: flex;
      flex-direction: column;
      gap: 10px;
      margin-top: 12px
    }

    .score-bar {
      width: 100%;
      max-width: 520px;
      height: 24px;
      border-radius: 14px;
      border: 2px solid #e2e8f0;
      background: #f8fafc;
      position: relative;
      overflow: hidden;
      box-shadow: inset 0 0 0 2px #eff6ff;
      margin: 0 auto
    }

    .score-fill {
      position: absolute;
      top: 0;
      left: 0;
      height: 100%;
      transition: width .25s ease;
      box-shadow: 0 6px 14px rgba(14, 165, 233, .28)
    }

    .score-label {
      margin-top: 12px;
      font-weight: 900;
      color: #334155;
      font-size: 13px
    }

    .hint {
      margin-top: 8px;
      font-size: 12px;
      color: #475569
    }

    .ref-list {
      margin-top: 12px;
      display: none;
      text-align: left
    }

    .ref-item {
      border: 1px solid #e2e8f0;
      border-radius: 12px;
      padding: 10px 12px;
      margin-top: 8px;
      background: #f8fafc
    }

    .ref-name {
      font-weight: 900;
      color: #0f172a
    }

    .ref-meta {
      font-size: 12px;
      color: #475569;
      margin-top: 4px
    }

    .ref-level {
      display: inline-block;
      padding: 4px 8px;
      border-radius: 10px;
      font-size: 11px;
      font-weight: 900;
      background: #e0f2fe;
      color: #0ea5e9;
      margin-right: 8px
    }

    .claimBtn {
      margin-top: 12px;
      width: 100%;
      max-width: 240px;
      border: none;
      border-radius: 14px;
      padding: 12px 14px;
      font-weight: 1000;
      color: #fff;
      background: linear-gradient(135deg, #22c55e, #16a34a);
      box-shadow: 0 12px 28px rgba(34, 197, 94, .25);
      cursor: pointer;
    }

    .placeholder {
      margin-top: 12px;
      width: 100%;
      max-width: 240px;
      border: 2px dashed #e2e8f0;
      border-radius: 14px;
      padding: 12px 14px;
      font-weight: 900;
      color: #94a3b8;
      background: #f8fafc;
      text-align: center;
    }
    .notice-only{
      margin-top:16px;
      padding:18px 16px;
      border-radius:16px;
      background:#fff;
      border:2px solid #e2e8f0;
      box-shadow:0 10px 24px rgba(15,23,42,.06);
      text-align:center;
    }
    .notice-only-title{
      font-size:18px;
      font-weight:900;
      color:#0f172a;
      margin:0;
    }
    .notice-only-text{
      margin-top:8px;
      font-size:14px;
      line-height:1.5;
      color:#475569;
      font-weight:700;
    }
  </style>

  <div class="page">
    <div class="topbar">
      <a class="back" href="{{ route('leadership.progress') }}">← Leadership</a>
      <a class="back" style="background:#e0f2fe;border-color:#bae6fd" href="{{ route('leadership.history') }}">
        🕓 History
      </a>
    </div>

    @if($noticeText !== '')
      <div class="notice-only">
        <h3 class="notice-only-title">{{ $rank->display_title ?? 'আপডেট নোটিশ' }}</h3>
        <div class="notice-only-text">{{ $noticeText }}</div>
      </div>
    @else
    <div class="hero">

      <div class="hero-text">
        <div class="eyebrow">{{ strtoupper($rank->key) }}</div>
        <div class="avatar" @if($photoUrl) style="background-image:url('{{ $photoUrl }}')" @endif>
          @unless($photoUrl)
            <span>{{ strtoupper(substr($user->name, 0, 1)) }}</span>
          @endunless
        </div>
        <div class="title">{{ $user->name }}</div>
        <div class="meta">অর্জন: {{ (int) ($claimCount ?? 0) }}</div>
      </div>
      <div class="pill-row">

        @if($canDownload)
          <a class="dl-btn" href="{{ route('leadership.rank.show', $rank->key) }}?download=1">
            <svg class="dl-icon" viewBox="0 0 24 24" aria-hidden="true">
              <path d="M12 3v10m0 0l4-4m-4 4l-4-4M5 19h14" stroke-linecap="round" stroke-linejoin="round" />
            </svg>
            <span class="dl-text">Download</span>
          </a>
        @else
          <div class="dl-btn dl-btn--disabled" title="লিডারশিপ অর্জন করলে ডাউনলোড হবে">
            <svg class="dl-icon" viewBox="0 0 24 24" aria-hidden="true">
              <path d="M12 3v10m0 0l4-4m-4 4l-4-4M5 19h14" stroke-linecap="round" stroke-linejoin="round" />
            </svg>
            <span class="dl-text">Download</span>
          </div>
        @endif
        <div class="pill reward">Reward: <span class="amount">৳{{ number_format((float) $rank->reward_amount, 0) }}</span>
        </div>
      </div>
      <div style="font-size:12px;font-weight:800;opacity:.9">টার্গেট শুরু:
        {{ optional($cycleStart)->format('d M Y, h:i A') }}
      </div>
    </div>

    <div class="card" id="refScoreToggle">
      <div class="card-head">সরাসরি রেফার স্কোর</div>
      <div class="score-wrap">
        <div class="score-bar">
          <div class="score-fill"
            style="width: {{ $primaryPercent }}%; background:linear-gradient(90deg,#0ea5e9,#2563eb)"></div>
        </div>
      </div>
      <div class="score-label">{{ $primaryCurrent }} / {{ $primaryNeed }} ({{ number_format($primaryPercent, 1) }}%)</div>

      <div class="ref-list" id="refList">
        @forelse($verifiedRefs as $ref)
          <div class="ref-item">
            <div class="ref-name">
              <span class="ref-level">{{ $ref->level ?? 'L1' }}</span>
              {{ $ref->name ?? 'N/A' }}
            </div>
            <div class="ref-meta">
              রেফার কোড: {{ $ref->referral_code ?? 'N/A' }} • জয়েন: {{ $ref->created_at?->format('d M Y') }}
            </div>
          </div>
        @empty
          <div class="ref-item" style="text-align:center">কোনো ভেরিফাইড রেফার পাওয়া যায়নি।</div>
        @endforelse
      </div>
    </div>

    @if($includeLevel2)
      <div class="card standalone" style="margin-top:12px">
        <div class="card-head">আপনার দ্বিতীয় রেফারের স্কোর</div>
        <div class="score-wrap">
          <div class="score-bar">
            <div class="score-fill" style="width: {{ $lvl2Percent }}%; background:linear-gradient(90deg,#f97316,#fb923c)">
            </div>
          </div>
        </div>
        <div class="score-label">{{ $level2Total }} / {{ $lvl2Need ?: $level2Total }}
          ({{ number_format($lvl2Percent, 1) }}%)
        </div>
      </div>
    @endif

    @if($includeLevel3)
      <div class="card standalone" style="margin-top:12px">
        <div class="card-head">আপনার তৃতীয় রেফারের স্কোর</div>
        <div class="score-wrap">
          <div class="score-bar">
            <div class="score-fill" style="width: {{ $lvl3Percent }}%; background:linear-gradient(90deg,#a855f7,#c084fc)">
            </div>
          </div>
        </div>
        <div class="score-label">{{ $level3Total }} / {{ $lvl3Need ?: $level3Total }}
          ({{ number_format($lvl3Percent, 1) }}%)
        </div>
      </div>
    @endif

    <div style="margin-top:18px;display:flex;justify-content:center">
      @if($submitReady)
        <form method="POST" action="{{ route('leadership.claim', $rank->id) }}">
          @csrf
          <button type="submit" class="claimBtn">Submit</button>
        </form>
      @else
        @if($includeLevel2 || $includeLevel3)
          <div class="placeholder">সব লেভেল সম্পূর্ণ হলেই সাবমিট বাটন দেখা যাবে।</div>
        @else
          <div class="placeholder">{{ $lvl1Need }} জন সম্পূর্ণ হলেই সাবমিট বাটন দেখা যাবে।</div>
        @endif
      @endif
    </div>
  </div>

  @if($canDownload)
    <div class="cert-stage" aria-hidden="true">
      <div id="leadershipCertificate" class="leader-cert"
        style="background-image:url('{{ asset('leader_photos/student_leader_template.png') }}')">
        <div class="leader-cert-photo" @if($photoUrl) style="background-image:url('{{ $photoUrl }}')" @endif>
          @unless($photoUrl)
            <span>{{ strtoupper(substr($user->name, 0, 1)) }}</span>
          @endunless
        </div>
        <div class="leader-cert-name">{{ $user->name }}</div>
        <div class="leader-cert-ordinal-inline">{{ $leaderOrdinal }}</div>
      </div>
    </div>
  @endif

    @endif
  </div>

  @if($noticeText === '')
    <script>
      (function () {
        const toggle = document.getElementById('refScoreToggle');
        const list = document.getElementById('refList');
        if (toggle && list) {
          toggle.addEventListener('click', () => {
            list.style.display = list.style.display === 'block' ? 'none' : 'block';
          });
        }
      })();
    </script>

    @if($canDownload)
      <script src="https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js"></script>
      <script>
        (function () {
          const shouldAutoDownload = @json($downloadRequested);
          const cert = document.getElementById('leadershipCertificate');
          if (!cert || !window.html2canvas) return;

          const downloadCertificate = async () => {
            const canvas = await window.html2canvas(cert, {
              scale: 2,
              useCORS: true,
              backgroundColor: null,
            });
            const link = document.createElement('a');
            link.download = 'leadership-{{ $rank->key }}-{{ $user->id }}.png';
            link.href = canvas.toDataURL('image/png');
            link.click();
          };

          if (shouldAutoDownload) {
            window.addEventListener('load', () => {
              setTimeout(downloadCertificate, 300);
            });
          }
        })();
      </script>
    @endif
  @endif
@endsection
