@extends('layout.user')
@section('title','মোবাইল রিচার্জ')

@section('content')

@php
  $opLabel = [
    'gp' => 'গ্রামীণফোন',
    'robi' => 'রবি',
    'airtel' => 'এয়ারটেল',
    'banglalink' => 'বাংলালিংক',
    'teletalk' => 'টেলিটক',
    'skitto' => 'স্কিটো',
  ];

  $popup = session('recharge_popup');
  $voucher = (float) (auth()->user()->voucher_balance ?? 0);
  $tutorialLink = trim((string) ($currentProjectTutorialLink ?? ''));
  $tutorialType = trim((string) ($currentProjectTutorialPlayerType ?? ''));
  $tutorialSrc = trim((string) ($currentProjectTutorialPlayerSrc ?? ''));
  $tutorialTitle = trim((string) ($currentProjectTutorialTitle ?? '')) ?: 'প্রজেক্ট ভিডিও';
  $hasTutorialLink = $tutorialLink !== '' && $tutorialLink !== '#' && $tutorialType !== '' && $tutorialSrc !== '';

  $opImg = [
    'gp' => asset('assets/image/grameenphone.png'),
    'robi' => asset('assets/image/rabi.png'),
    'airtel' => asset('assets/image/airtel.png'),
    'banglalink' => asset('assets/image/banglalink.png'),
    'teletalk' => asset('assets/image/teletak.png'),
    'skitto' => asset('assets/image/skitto.png'),
  ];
@endphp

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css"/>

<style>
  :root{
    --p:#2563EB;
    --p2:#1D4ED8;
    --ink:#0f172a;
    --muted:#64748b;
    --bg:#fdfdfd;
    --err:#dc2626;
  }

  body{background:var(--bg);}
  .page-wrap{padding:12px 12px 96px; max-width: 550px; margin: 0 auto;}

  .auth-card-main {
    background:#fff;
    border-radius:28px;
    padding:22px;
    border: 2px solid var(--p) !important;
    box-shadow: 0 15px 35px rgba(37, 99, 235, 0.12);
    margin-bottom: 20px;
  }

  .hero-premium {
    border-radius:28px;
    padding:20px;
    background: #fff;
    border: 2px solid var(--p) !important;
    box-shadow: 0 10px 25px rgba(37, 99, 235, 0.1);
    margin-bottom: 15px;
    text-align: center;
  }

  .title h2{font-size:22px; font-weight:1000; color:var(--ink); margin:0;}
  .title p{margin:5px 0 15px; font-size:12px; font-weight:900; color:var(--p); text-transform: uppercase; letter-spacing: 1px;}

  .balance-pill {
    display:inline-flex;
    align-items:center;
    gap:10px;
    background: linear-gradient(135deg, var(--p), var(--p2));
    color:#fff;
    font-size:14px;
    font-weight:1000;
    padding:12px 20px;
    border-radius:18px;
    box-shadow: 0 10px 20px rgba(37, 99, 235, 0.25);
  }

  label{display:block; font-size:13px; font-weight:1000; color:var(--ink); margin:0 0 10px 5px; text-transform: uppercase;}

  .input-group-premium { position: relative; margin-bottom: 8px; }
  .inpx-premium {
    width:100%;
    padding:14px 16px 14px 55px;
    border-radius:18px;
    border: 2px solid var(--p) !important;
    outline:none;
    font-size:18px;
    font-weight:900;
    transition: all 0.2s;
    background: #fff;
  }
  .inpx-premium.invalid{border-color:var(--err) !important;}
  .input-icon {
    position: absolute;
    left: 18px;
    top: 50%;
    transform: translateY(-50%);
    color: var(--p);
    font-size: 18px;
    z-index: 10;
  }
  .input-divider {
    position: absolute;
    left: 45px;
    top: 50%;
    transform: translateY(-50%);
    width: 2px;
    height: 25px;
    background-color: var(--p);
    opacity: 0.6;
  }
  .field-err{
    display:none;
    margin: 0 0 14px 6px;
    font-size:12px;
    font-weight:900;
    color:var(--err);
  }

  .grid3{display:grid; grid-template-columns:repeat(3,1fr); gap:15px; margin-bottom: 10px;}
  .op-item { text-align: center; cursor: pointer; }
  .opt-box {
    border-radius: 20px;
    padding: 15px;
    background: #fff;
    border: 2px solid var(--p) !important;
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 80px;
    transition: all 0.2s;
    margin-bottom: 8px;
    overflow: hidden;
  }
  .opt-box img {
    height: 40px;
    width: auto;
    object-fit: contain;
    filter: drop-shadow(0 2px 4px rgba(0,0,0,0.1));
    display: block;
    opacity: 1 !important;
  }

  .op-item.active .opt-box {
    background: var(--p2) !important;
    border-color: var(--p2) !important;
    box-shadow: 0 10px 18px rgba(29,78,216,.25);
    transform: translateY(-3px);
  }
  .op-item.active .opt-box img{
    filter: drop-shadow(0 4px 10px rgba(0,0,0,0.18));
  }
  .op-name {
    display: block;
    font-size: 12px;
    font-weight: 1000;
    color: var(--ink);
    transition: color 0.2s;
  }
  .op-item.active .op-name { color: var(--p2); }
  .op-err{ margin-top: 6px; }

  .grid2{display:grid; grid-template-columns:repeat(2,1fr); gap:12px; margin-bottom: 10px;}
  .type-opt {
    cursor:pointer;
    border-radius:18px;
    padding:12px;
    text-align:center;
    background:#fff;
    border: 2px solid var(--p) !important;
    font-weight: 1000;
    font-size: 14px;
    color: var(--p);
    transition: all 0.2s;
  }
  .type-opt.active {
    background: var(--p2);
    color: #fff;
    border-color: var(--p2) !important;
  }
  .type-err{ margin-top: 6px; }

  .btn-hold-premium {
    position:relative;
    width:100%;
    border:none;
    border-radius:22px;
    padding:20px;
    background:#94a3b8;
    color:#fff;
    font-size:16px;
    font-weight:1000;
    overflow:hidden;
    cursor:pointer;
    box-shadow: 0 10px 20px rgba(0,0,0,0.1);
    margin-top: 10px;
    user-select:none;
    -webkit-tap-highlight-color: transparent;
    touch-action: manipulation;
  }
  .btn-hold-premium:disabled{opacity:.85; cursor:not-allowed;}
  .hold-bar {
    position:absolute; left:0; top:0; height:100%; width:0%;
    background: linear-gradient(135deg, var(--p), var(--p2));
    z-index:0;
  }
  .btn-hold-premium span { position:relative; z-index:1; }

  .history-btn {
    display:flex; align-items:center; justify-content:center; gap:10px;
    width:100%; margin-top:15px; padding:15px;
    border-radius:18px; background:#fff;
    color:var(--p); font-weight:1000;
    border: 2px solid var(--p);
    text-decoration: none !important;
  }
  .history-actions{
    display:grid;
    grid-template-columns:repeat(2,minmax(0,1fr));
    gap:10px;
    margin-top:15px;
  }
  .history-actions .history-btn{margin-top:0;}
  .history-btn.disabled{opacity:.45;pointer-events:none;}

  @media (max-width:420px){
    .page-wrap{padding:10px 10px 96px;}
    .auth-card-main,.hero-premium{border-radius:22px;padding:16px;}
    .title h2{font-size:19px;}
    .balance-pill{font-size:12.5px;padding:10px 14px;}
    .history-actions{grid-template-columns:1fr;gap:8px;}
    .history-btn{
      justify-content:flex-start;
      text-align:left;
      padding:12px;
      font-size:13px;
      line-height:1.35;
    }
  }

  .sx-backdrop{position:fixed;inset:0;z-index:999999;background:rgba(0,0,0,.55);display:flex;align-items:center;justify-content:center;padding:14px 14px;}
  .sx-wrap{width:100%;max-width:360px}
  .sx-card{background:#fff;border-radius:18px;box-shadow:0 22px 48px rgba(0,0,0,.18);overflow:visible;}
  .sx-top{position:relative;padding:42px 16px 10px;text-align:center;}
  .sx-icon{position:absolute;top:-30px;left:50%;transform:translateX(-50%);width:64px;height:64px;border-radius:999px;background:#1d4ed8;color:#fff;display:grid;place-items:center;border:10px solid #fff;box-shadow:0 14px 28px rgba(29,78,216,.30);font-size:28px;}
  .sx-title{font-size:20px;font-weight:1000;color:#0f172a;line-height:1.25;}
  .sx-sub{font-size:12px;font-weight:900;color:#94a3b8;margin-top:6px}
  .sx-mobile{font-size:20px;font-weight:1000;color:#0f172a;margin-top:4px}
  .sx-body{padding:10px 16px 12px}
  .sx-grid{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-top:8px}
  .sx-box{border:2px solid rgba(59,130,246,.35);border-radius:14px;background:#fff;padding:12px 10px;text-align:center;min-height:78px;display:flex;flex-direction:column;justify-content:center;align-items:center;}
  .sx-lbl{font-size:12px;font-weight:900;color:#94a3b8;margin-bottom:6px}
  .sx-val{font-size:16px;font-weight:1000;color:#0f172a;word-break:break-all}
  .sx-footer{padding:0 16px 14px}
  .sx-ok{width:100%;border:none;background:#1d4ed8;color:#fff;font-weight:1000;font-size:18px;padding:14px 12px;border-radius:12px;box-shadow:0 14px 26px rgba(29,78,216,.22);cursor:pointer;}
</style>

<div class="page-wrap">
  <div class="hero-premium">
    <div class="title">
      <h2>📱 মোবাইল রিচার্জ</h2>
      <p>TASK EARNING Digital Service</p>
    </div>
    <div class="balance-pill">
      <i class="fa-solid fa-ticket"></i>
      ভাউচার ব্যালেন্স: ৳ {{ number_format($voucher, 2) }}
    </div>
  </div>

  @include('partials.mobile_action_cards', [
    'primaryVisible' => true,
    'primaryHref' => route('user.recharge.history'),
    'primaryLabel' => 'হিস্ট্রি',
    'primarySubtitle' => 'ট্রানজেকশন হিস্ট্রি',
    'videoLink' => $tutorialLink,
    'videoType' => $tutorialType,
    'videoSrc' => $tutorialSrc,
    'videoTitle' => $tutorialTitle,
    'videoLabel' => 'ভিডিও',
    'videoSubtitle' => 'এই প্রজেক্টের ভিডিও দেখতে এখানে ক্লিক করুন',
  ])

  <div class="auth-card-main">
    @if(session('error'))
      <div class="mb-3 rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm font-bold text-red-700">
        {{ session('error') }}
      </div>
    @endif
    @if($errors->any())
      <div class="mb-3 rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm font-bold text-red-700">
        {{ $errors->first() }}
      </div>
    @endif

    <form method="POST" action="{{ route('user.recharge.submit') }}" id="rechargeForm" novalidate>
      @csrf

      <label>মোবাইল নম্বর</label>
      <div class="input-group-premium">
        <i class="fas fa-phone-alt input-icon"></i>
        <div class="input-divider"></div>
        <input id="mobileInput" type="text" name="mobile" value="{{ old('mobile') }}" placeholder="01XXXXXXXXX" required maxlength="11"
          oninput="this.value=this.value.replace(/[^0-9]/g,'')" class="inpx-premium">
      </div>
      <div class="field-err" id="err_mobile"></div>

      <label>অপারেটর নির্বাচন করুন</label>
      <div class="grid3" id="opGrid">
        @foreach(['gp','robi','airtel','banglalink','teletalk','skitto'] as $op)
          <div class="op-item {{ old('operator')===$op ? 'active' : '' }}" data-value="{{ $op }}">
            <div class="opt-box">
              <img src="{{ $opImg[$op] ?? '' }}" alt="{{ $op }}" onerror="this.style.display='none'">
            </div>
            <span class="op-name">{{ $opLabel[$op] }}</span>
            <input type="radio" name="operator" value="{{ $op }}" class="hidden" required {{ old('operator')===$op ? 'checked' : '' }}>
          </div>
        @endforeach
      </div>
      <div class="field-err op-err" id="err_operator"></div>

      <label>কানেকশন টাইপ</label>
      <div class="grid2" id="typeGrid">
        <label class="type-opt {{ old('type')==='prepaid' ? 'active' : '' }}" data-value="prepaid">
          <input type="radio" name="type" value="prepaid" class="hidden" required {{ old('type')==='prepaid' ? 'checked' : '' }}>
          PREPAID
        </label>
        <label class="type-opt {{ old('type')==='postpaid' ? 'active' : '' }}" data-value="postpaid">
          <input type="radio" name="type" value="postpaid" class="hidden" required {{ old('type')==='postpaid' ? 'checked' : '' }}>
          POSTPAID
        </label>
      </div>
      <div class="field-err type-err" id="err_type"></div>

      <label>রিচার্জের পরিমাণ (৳)</label>
      <div class="input-group-premium">
        <i class="fas fa-money-bill-wave input-icon"></i>
        <div class="input-divider"></div>
        <input id="amountInput" type="number" name="amount" value="{{ old('amount') }}" min="20" required placeholder="২০ - ১০০০" class="inpx-premium">
      </div>
      <div class="field-err" id="err_amount"></div>

      <label>লগইন পাসওয়ার্ড</label>
      <div class="input-group-premium">
        <i class="fas fa-lock input-icon"></i>
        <div class="input-divider"></div>
        <input id="passwordInput" type="password" name="password" required minlength="6" autocomplete="current-password"
          placeholder="আপনার পাসওয়ার্ড দিন" class="inpx-premium">
      </div>
      <div class="field-err" id="err_password"></div>

      <button type="button" id="holdButton" class="btn-hold-premium">
        <div class="hold-bar" id="progressBar"></div>
        <span><i class="fa-solid fa-fingerprint"></i> রিচার্জ করতে চেপে ধরুন</span>
      </button>

    </form>
  </div>
</div>

@php
  if(!$popup && session('recharge_success')){
    $sx = session('recharge_success');
    $popup = [
      'title' => 'রিকোয়েস্ট গ্রহণ করা হয়েছে',
      'subtitle' => 'আপনার রিচার্জ রিকোয়েস্ট নেওয়া হয়েছে।',
      'mobile' => $sx['mobile'] ?? '',
      'amount' => $sx['amount'] ?? 0,
      'trx_id' => $sx['trx_id'] ?? '',
      'operator' => $sx['operator'] ?? '',
      'cashback' => $sx['cashback'] ?? ($sx['commission'] ?? 0),
    ];
  }
@endphp

@if($popup)
@php
  $sxMobile = (string)($popup['mobile'] ?? '');
  $sxAmt = (float)($popup['amount'] ?? 0);
  $sxCash = (float)($popup['cashback'] ?? ($popup['commission'] ?? 0));
  $sxTrx  = trim((string)($popup['trx_id'] ?? ''));
  $sxOp   = $opLabel[$popup['operator'] ?? ''] ?? ($popup['operator'] ?? '');
  $ttl    = (string)($popup['title'] ?? 'রিকোয়েস্ট গ্রহণ করা হয়েছে');
  $sub    = (string)($popup['subtitle'] ?? 'রিচার্জ রিকোয়েস্ট নেওয়া হয়েছে।');
@endphp

<div class="sx-backdrop" id="sxBackdrop" role="dialog" aria-modal="true">
  <div class="sx-wrap">
    <div class="sx-card">
      <div class="sx-top">
        <div class="sx-icon"><i class="fa-solid fa-check"></i></div>
        <div class="sx-title">{{ $ttl }}</div>
        <div class="sx-sub">{{ $sub }}</div>
        @if($sxMobile !== '')
          <div class="sx-mobile">{{ $sxMobile }}</div>
        @endif
      </div>

      <div class="sx-body">
        <div class="sx-grid">
          <div class="sx-box">
            <div class="sx-lbl">রিচার্জের পরিমাণ</div>
            <div class="sx-val">৳ {{ number_format($sxAmt,2) }}</div>
          </div>

          <div class="sx-box">
            <div class="sx-lbl">ক্যাশব্যাক</div>
            <div class="sx-val">৳ {{ number_format($sxCash,2) }}</div>
          </div>

          <div class="sx-box">
            <div class="sx-lbl">ট্রানজেকশন আইডি</div>
            <div class="sx-val">{{ $sxTrx ?: 'N/A' }}</div>
          </div>

          <div class="sx-box">
            <div class="sx-lbl">অপারেটর</div>
            <div class="sx-val">{{ $sxOp ?: 'N/A' }}</div>
          </div>
        </div>
      </div>

      <div class="sx-footer">
        <button type="button" class="sx-ok" onclick="closeRechargePopup()">ঠিক আছে</button>
      </div>
    </div>
  </div>
</div>
@endif

<script>
  const form = document.getElementById('rechargeForm');
  const holdButton = document.getElementById('holdButton');
  const progressBar = document.getElementById('progressBar');

  const mobileInput = document.getElementById('mobileInput');
  const amountInput = document.getElementById('amountInput');
  const passwordInput = document.getElementById('passwordInput');

  const errMobile = document.getElementById('err_mobile');
  const errAmount = document.getElementById('err_amount');
  const errOperator = document.getElementById('err_operator');
  const errType = document.getElementById('err_type');
  const errPassword = document.getElementById('err_password');

  function clearErr(){
    [errMobile, errAmount, errOperator, errType, errPassword].forEach(el => { el.style.display='none'; el.textContent=''; });
    [mobileInput, amountInput, passwordInput].forEach(inp => inp.classList.remove('invalid'));
  }

  function setErr(el, msg){
    el.textContent = msg || 'Please fill in this field';
    el.style.display = 'block';
  }

  function selectedValue(name){
    return form.querySelector(`input[name="${name}"]:checked`)?.value || '';
  }

  function setOperator(op){
    if(!op) return;
    const item = document.querySelector(`.op-item[data-value="${op}"]`);
    const radio = form.querySelector(`input[name="operator"][value="${op}"]`);
    if(!item || !radio) return;

    document.querySelectorAll('.op-item').forEach(i => i.classList.remove('active'));
    item.classList.add('active');
    radio.checked = true;
  }

  function setType(t){
    if(!t) return;
    const opt = document.querySelector(`.type-opt[data-value="${t}"]`);
    const radio = form.querySelector(`input[name="type"][value="${t}"]`);
    if(!opt || !radio) return;

    document.querySelectorAll('.type-opt').forEach(o => o.classList.remove('active'));
    opt.classList.add('active');
    radio.checked = true;
  }

  function detectOperatorByPrefix(msisdn){
    const s = String(msisdn || '').replace(/[^\d]/g,'');
    const p3 = s.slice(0,3);
    const p4 = s.slice(0,4);

    if(p4 === '0130') return 'skitto';

    const map3 = {
      '013':'gp',
      '017':'gp',
      '014':'banglalink',
      '019':'banglalink',
      '015':'teletalk',
      '018':'robi',
      '016':'airtel'
    };

    return map3[p3] || '';
  }

  function validateFields(){
    clearErr();
    let ok = true;

    const ms = mobileInput.value.trim();
    if(!ms){
      mobileInput.classList.add('invalid');
      setErr(errMobile, 'Please fill in this field');
      ok = false;
    }else if(!/^01[3-9][0-9]{8}$/.test(ms)){
      mobileInput.classList.add('invalid');
      setErr(errMobile, 'সঠিক মোবাইল নাম্বার দিন');
      ok = false;
    }

    const op = selectedValue('operator');
    if(!op){
      setErr(errOperator, 'Please fill in this field');
      ok = false;
    }

    const tp = selectedValue('type');
    if(!tp){
      setErr(errType, 'Please fill in this field');
      ok = false;
    }

    const amt = amountInput.value.trim();
    if(!amt){
      amountInput.classList.add('invalid');
      setErr(errAmount, 'Please fill in this field');
      ok = false;
    }else if(parseFloat(amt) < 20){
      amountInput.classList.add('invalid');
      setErr(errAmount, 'সর্বনিম্ন ২০৳ দিন');
      ok = false;
    }

    const pass = passwordInput.value.trim();
    if(!pass){
      passwordInput.classList.add('invalid');
      setErr(errPassword, 'পাসওয়ার্ড দিন');
      ok = false;
    }else if(pass.length < 6){
      passwordInput.classList.add('invalid');
      setErr(errPassword, 'পাসওয়ার্ড কমপক্ষে ৬ অক্ষর হতে হবে');
      ok = false;
    }

    return ok;
  }

  document.querySelectorAll('.op-item').forEach(item => {
    item.addEventListener('click', () => {
      setOperator(item.getAttribute('data-value'));
      clearErr();
    });
  });

  document.querySelectorAll('.type-opt').forEach(opt => {
    opt.addEventListener('click', () => {
      setType(opt.getAttribute('data-value'));
      clearErr();
    });
  });

  mobileInput.addEventListener('input', function(){
    const op = detectOperatorByPrefix(mobileInput.value);
    if(op){
      setOperator(op);
      if(!selectedValue('type')) setType('prepaid');
    }else{
      if(!selectedValue('type')) setType('prepaid');
    }
    clearErr();
  });

  form.addEventListener('input', function(){
    clearErr();
  });

  let holdTimer = null;
  let isHolding = false;
  let isSubmitting = false;
  const HOLD_MS = 2000;

  function startHold(e){
    e?.preventDefault?.();
    if(isHolding || isSubmitting) return;

    if(!validateFields()){
      const firstErr = document.querySelector('.field-err[style*="block"]');
      if(firstErr) firstErr.scrollIntoView({behavior:'smooth', block:'center'});
      return;
    }

    isHolding = true;
    progressBar.style.transition = 'none';
    progressBar.style.width = '0%';
    progressBar.offsetHeight;

    progressBar.style.transition = `width ${HOLD_MS}ms linear`;
    progressBar.style.width = '100%';

    holdTimer = setTimeout(() => {
      if(isHolding && !isSubmitting){
        isSubmitting = true;
        holdButton.disabled = true;
        form.submit();
      }
    }, HOLD_MS);
  }

  function endHold(){
    if(!isHolding || isSubmitting) return;
    isHolding = false;
    clearTimeout(holdTimer);
    progressBar.style.transition = 'width 220ms ease-out';
    progressBar.style.width = '0%';
  }

  holdButton.addEventListener('mousedown', startHold);
  holdButton.addEventListener('touchstart', startHold, {passive:false});
  ['mouseup','mouseleave','touchend','touchcancel'].forEach(evt => holdButton.addEventListener(evt, endHold));

  form.addEventListener('submit', function(e){
    if(isSubmitting) {
      e.preventDefault();
      return;
    }
    isSubmitting = true;
    holdButton.disabled = true;
  });

  function closeRechargePopup(){
    const b = document.getElementById('sxBackdrop');
    if(b) b.remove();
  }
  window.closeRechargePopup = closeRechargePopup;

  document.getElementById('sxBackdrop')?.addEventListener('click', function(e){
    if(e.target === this) closeRechargePopup();
  });

  document.addEventListener('keydown', function(e){
    if(e.key === 'Escape') closeRechargePopup();
  }, {once:true});

  if(!selectedValue('type')) setType('prepaid');
</script>

@endsection
