@extends('layouts.app')

@section('content')

<style>

/* =========================
   PAGE
========================= */
.page-bg{
  min-height:100vh;
  background:
  radial-gradient(circle at top right,#dbeafe 0,#f8fafc 35%);
}

/* =========================
   FADE
========================= */
.fade-section{
  opacity:0;
  transform:translateY(20px);
  filter:blur(8px);
  transition:all .7s ease;
}

.fade-section.show{
  opacity:1;
  transform:none;
  filter:none;
}

/* =========================
   CARD
========================= */
.modern-card{
  background:rgba(255,255,255,.92);
  backdrop-filter:blur(12px);
  border:1px solid rgba(255,255,255,.7);
  border-radius:28px;
  box-shadow:
  0 10px 40px rgba(15,23,42,.06);
  transition:.25s ease;
}

.modern-card:hover{
  transform:translateY(-2px);
  box-shadow:
  0 20px 50px rgba(15,23,42,.08);
}

/* =========================
   HERO
========================= */
.hero-box{
  position:relative;
  overflow:hidden;
  border-radius:30px;
  padding:38px;
  background:
  linear-gradient(
    135deg,
    #2563eb 0%,
    #4f46e5 100%
  );
}

.hero-box::before{
  content:'';
  position:absolute;
  width:320px;
  height:320px;
  background:rgba(255,255,255,.08);
  border-radius:999px;
  top:-140px;
  right:-120px;
}

/* =========================
   INPUT
========================= */
.input-modern{
  width:100%;
  height:58px;
  border-radius:18px;
  border:1px solid #e5e7eb;
  background:#fff;
  padding:0 18px;
  transition:.2s ease;
  outline:none;
  font-size:.95rem;
}

.input-modern:focus{
  border-color:#2563eb;
  box-shadow:0 0 0 4px rgba(37,99,235,.10);
}

/* =========================
   DROPDOWN
========================= */
.autocomplete-list{
  position:absolute;
  z-index:50;
  width:100%;
  margin-top:8px;
  background:#fff;
  border:1px solid #e5e7eb;
  border-radius:18px;
  overflow:hidden;
  box-shadow:
  0 15px 40px rgba(15,23,42,.08);
  max-height:260px;
  overflow-y:auto;
}

.autocomplete-item{
  padding:14px 16px;
  transition:.15s ease;
  cursor:pointer;
  display:flex;
  align-items:center;
  justify-content:space-between;
}

.autocomplete-item:hover{
  background:#eff6ff;
}

/* =========================
   BUTTON
========================= */
.btn-buy{
  width:100%;
  height:58px;
  border-radius:18px;
  background:
  linear-gradient(
    135deg,
    #2563eb,
    #4f46e5
  );

  color:#fff;
  font-weight:700;

  transition:.25s ease;

  box-shadow:
  0 12px 30px rgba(37,99,235,.22);
}

.btn-buy:hover{
  transform:translateY(-1px);
  box-shadow:
  0 18px 40px rgba(37,99,235,.28);
}

/* =========================
   PRICE BOX
========================= */
.price-box{
  background:#eff6ff;
  border:1px solid #bfdbfe;
  border-radius:20px;
  padding:16px 18px;
}

/* =========================
   INFO TOGGLE
========================= */
#infoContent{
  display:none;
}

#infoContent.show{
  display:block;
  animation:fadeDown .25s ease;
}

@keyframes fadeDown{
  from{
    opacity:0;
    transform:translateY(-10px);
  }

  to{
    opacity:1;
    transform:translateY(0);
  }
}

/* =========================
   MOBILE
========================= */
@media(max-width:768px){

  .hero-box{
    padding:28px;
    border-radius:24px;
  }

  .modern-card{
    border-radius:24px;
  }

}

</style>

<div class="page-bg p-4 md:p-8 space-y-6">

  <!-- HERO -->
  <section class="fade-section">

    <div class="hero-box">

      <div class="relative z-10">

        <h1 class="text-3xl md:text-4xl font-bold text-white tracking-tight">
          Beli Nomor Virtual
        </h1>

        <p class="text-blue-100 mt-3 max-w-2xl leading-relaxed text-sm md:text-base">
          Pilih negara, operator, dan layanan OTP yang kamu butuhkan.
        </p>

      </div>

    </div>

  </section>

  <!-- INFO -->
  <section class="fade-section">

    <button
      onclick="toggleInfo()"
      class="w-full modern-card p-5 flex items-center justify-between"
    >

      <div class="flex items-center gap-4">

        <div class="w-12 h-12 rounded-2xl flex items-center justify-center bg-blue-50">

                    <svg width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <defs>
    <path id="info-a" d="M10.5134277,0.293457031 C12.3116048,6.98051974 11.4737956,10.510549 8,10.8835449 C1.8918457,10.8835449 -0.0366210938,14.6247559 0.773681641,16.5002441 C1.58398438,18.3757324 4.12866211,19.8500977 6.21289062,20.2067871 C8.29711914,20.5634766 11.6750488,20.5915527 15.8925781,16.5002441 C20.1101074,12.4089355 17.1142578,5.80639648 15.8925781,4.07495117 C15.078125,2.9206543 13.2850749,1.66015625 10.5134277,0.293457031 Z"/>
    <path id="info-c" d="M11,22 C4.92486775,22 0,17.0751322 0,11 C0,4.92486775 4.92486775,0 11,0 C17.0751322,0 22,4.92486775 22,11 C22,17.0751322 17.0751322,22 11,22 Z M11,20.24 C16.1031111,20.24 20.24,16.1031111 20.24,11 C20.24,5.89688891 16.1031111,1.76 11,1.76 C5.89688891,1.76 1.76,5.89688891 1.76,11 C1.76,16.1031111 5.89688891,20.24 11,20.24 Z M10,10 C10,9.44771525 10.4477153,9 11,9 C11.5522847,9 12,9.44771525 12,10 L12,15 C12,15.5522847 11.5522847,16 11,16 C10.4477153,16 10,15.5522847 10,15 L10,10 Z M11,8 C10.4477153,8 10,7.55228475 10,7 C10,6.44771525 10.4477153,6 11,6 C11.5522847,6 12,6.44771525 12,7 C12,7.55228475 11.5522847,8 11,8 Z"/>
  </defs>
  <g fill="none" fill-rule="evenodd" transform="translate(1 1)">
    <g transform="translate(3 1)">
      <mask id="info-b" fill="#ffffff">
        <use xlink:href="#info-a"/>
      </mask>
      <use fill="#D8D8D8" xlink:href="#info-a"/>
      <g fill="#FFA0A0" mask="url(#info-b)">
        <rect width="24" height="24" transform="translate(-4 -2)"/>
      </g>
    </g>
    <mask id="info-d" fill="#ffffff">
      <use xlink:href="#info-c"/>
    </mask>
    <use fill="#000000" fill-rule="nonzero" xlink:href="#info-c"/>
    <g fill="#7600FF" mask="url(#info-d)">
      <rect width="24" height="24" transform="translate(-1 -1)"/>
    </g>
  </g>
</svg>


        </div>

        <div class="text-left">

          <h2 class="font-semibold text-gray-800">
            Langkah Pembelian
          </h2>

          <p class="text-sm text-gray-500">
            Klik untuk melihat panduan pembelian
          </p>

        </div>

      </div>

      <svg
        id="infoArrow"
        xmlns="http://www.w3.org/2000/svg"
        width="22"
        height="22"
        fill="none"
        viewBox="0 0 24 24"
        class="transition duration-300"
      >
        <path stroke="#64748b" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m6 9 6 6 6-6"/>
      </svg>

    </button>

    <!-- CONTENT -->
    <div id="infoContent">

      <div class="modern-card mt-4 p-6">

        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">

          <div class="bg-blue-50 border border-blue-100 rounded-2xl p-4">
            <span class="text-blue-600 font-semibold">1.</span>
            <p class="text-sm text-gray-700 mt-2">
              Pastikan saldo akun mencukupi sebelum membeli nomor.
            </p>
          </div>
          <div class="bg-blue-50 border border-blue-100 rounded-2xl p-4">
            <span class="text-blue-600 font-semibold">2.</span>
            <p class="text-sm text-gray-700 mt-2">
              Harga dapat berubah sewaktu waktu tanpa pemberitahuan.
            </p>
          </div>

          <div class="bg-blue-50 border border-blue-100 rounded-2xl p-4">
            <span class="text-blue-600 font-semibold">3.</span>
            <p class="text-sm text-gray-700 mt-2">
              Pilih negara, operator, dan layanan sesuai kebutuhan OTP.
            </p>
          </div>

          <div class="bg-blue-50 border border-blue-100 rounded-2xl p-4">
            <span class="text-blue-600 font-semibold">4.</span>
            <p class="text-sm text-gray-700 mt-2">
              Pesanan otomatis failed dan saldo kembali jika OTP tidak masuk dalam 10 menit.
            </p>
          </div>

        </div>

      </div>

    </div>

  </section>

  <!-- FORM -->
  <div class="flex justify-center">

    <section class="fade-section modern-card w-full max-w-2xl p-6 md:p-7">

      <div class="space-y-5">

        <!-- HEADER -->
        <div class="flex items-center gap-4 mb-2">

          <div class="w-14 h-14 rounded-2xl bg-gradient-to-br from-blue-500 to-indigo-600 flex items-center justify-center shadow-lg shadow-blue-200">

           <svg width="30" height="30" version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" 
	 viewBox="0 0 392.533 392.533" xml:space="preserve">
<path style="fill:#FFFFFF;" d="M87.24,21.786c-6.012,0-10.925,4.848-10.925,10.925v327.111c0,6.012,4.848,10.925,10.925,10.925
	h218.052c6.012,0,10.925-4.848,10.925-10.925V73.503l-51.717-51.717C264.501,21.786,87.24,21.786,87.24,21.786z"/>
<path style="fill:#56ACE0;" d="M255.515,43.572H98.166v31.612h64c6.012,0,10.925,4.848,10.925,10.925
	c0,6.012-4.848,10.925-10.925,10.925h-64v21.786h31.224c6.012,0,10.925,4.848,10.925,10.925c0,6.012-4.848,10.925-10.925,10.925
	H98.166v208.356h196.267V82.683L255.515,43.572z"/>
<rect x="131.782" y="194.133" style="fill:#FFC10D;" width="128.97" height="128.97"/>
<g>
	<path style="fill:#194F82;" d="M334.836,61.285L276.719,3.168C274.715,1.164,271.935,0,268.962,0H87.24
		C69.204,0,54.529,14.675,54.529,32.711v327.111c0,18.036,14.675,32.711,32.711,32.711h218.052
		c18.036,0,32.711-14.675,32.711-32.711V68.978C338.004,66.069,336.84,63.289,334.836,61.285z M316.218,359.822
		c0,6.012-4.849,10.925-10.925,10.925H87.24c-6.012,0-10.925-4.848-10.925-10.925V32.711c0-6.012,4.848-10.925,10.925-10.925
		h177.261l51.717,51.717V359.822L316.218,359.822z"/>
	<path style="fill:#194F82;" d="M109.996,183.208v150.82c0,6.012,4.848,10.925,10.925,10.925h150.82
		c6.012,0,10.925-4.849,10.925-10.925v-150.82c0-6.012-4.848-10.925-10.925-10.925H120.857
		C114.844,172.283,109.996,177.196,109.996,183.208z M207.224,194.133h53.657v53.657h-53.657V194.133z M207.224,269.511h53.657
		v53.657h-53.657V269.511z M131.782,194.133h53.657v20.881h-53.657C131.782,215.014,131.782,194.133,131.782,194.133z
		 M131.782,236.735h53.657v43.766h-53.657C131.782,280.501,131.782,236.735,131.782,236.735z M131.782,302.287h53.657v20.881
		h-53.657C131.782,323.168,131.782,302.287,131.782,302.287z"/>
</g>
</svg>

          </div>

          <div>

            <h2 class="text-2xl font-bold text-gray-800">
              Beli Nomor
            </h2>

            <p class="text-sm text-gray-500 mt-1">
              Pilih negara, operator, dan layanan
            </p>

          </div>

        </div>

        <form method="POST" action="{{ route('order.store') }}" id="orderForm" class="space-y-5">
          @csrf

          <!-- SERVER -->
          <div>

            <label class="block text-sm font-semibold text-gray-700 mb-2">
              Server
            </label>

            <select
              id="serverSelect"
              class="input-modern"
            >
              <option value="1" {{ $server==1?'selected':'' }}>
                Cepat
              </option>

              <!--<option value="2" {{ $server==2?'selected':'' }}>-->
              <!--  Server 2-->
              <!--</option>-->
            </select>

            <input type="hidden" name="server" id="server" value="{{ $server }}">

          </div>

          <!-- NEGARA -->
          <div class="relative">

            <label class="block text-sm font-semibold text-gray-700 mb-2">
              Negara
            </label>

            <input
              type="text"
              id="negaraInput"
              class="input-modern"
              placeholder="Ketik nama negara..."
              autocomplete="off"
            >

            <ul id="negaraList" class="autocomplete-list hidden"></ul>

          </div>

          <!-- OPERATOR -->
          <div class="relative">

            <label class="block text-sm font-semibold text-gray-700 mb-2">
              Operator
            </label>

            <input
              type="text"
              id="operatorInput"
              disabled
              class="input-modern disabled:bg-gray-50 disabled:text-gray-400"
              placeholder="Ketik nama operator..."
              autocomplete="off"
            >

            <ul id="operatorList" class="autocomplete-list hidden"></ul>

            <p id="operatorLoading" class="hidden text-sm text-blue-500 mt-2 animate-pulse">
              Memuat daftar operator...
            </p>

          </div>

          <!-- LAYANAN -->
          <div class="relative">

            <label class="block text-sm font-semibold text-gray-700 mb-2">
              Layanan
            </label>

            <input
              type="text"
              id="layananInput"
              disabled
              class="input-modern disabled:bg-gray-50 disabled:text-gray-400"
              placeholder="Ketik nama layanan..."
              autocomplete="off"
            >

            <ul id="layananList" class="autocomplete-list hidden"></ul>

            <p id="layananLoading" class="hidden text-sm text-blue-500 mt-2 animate-pulse">
              Memuat daftar layanan...
            </p>

          </div>

          <!-- PRICE -->
          <div class="price-box flex items-center justify-between">

            <div>
              <p class="text-sm font-medium text-blue-700">
                Harga
              </p>
            </div>

            <span id="hargaLabel" class="text-2xl font-bold text-blue-600">
              Rp 0
            </span>

          </div>

          <input type="hidden" name="negara" id="negara">
          <input type="hidden" name="operator" id="operator">
          <input type="hidden" name="layanan" id="layanan">
          <input type="hidden" name="harga" id="hargaInput" value="0">
          <input type="hidden" name="layanan_nama" id="layananNamaInput" value="">

          <!-- SUBMIT -->
          <button type="submit" class="btn-buy flex items-center justify-center gap-3">

            <span>
              Beli
            </span>

          </button>

        </form>

      </div>

    </section>

  </div>

</div>

@include('components.footer')

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

@if(session('error'))
<script>
Swal.fire({
    icon: 'error',
    title: 'Gagal',
    html: `<b>{{ session('error') }}</b>`,
    background: '#fff',
    color: '#111',
    confirmButtonText: 'OK',
    confirmButtonColor: '#dc2626',
    timer: 4000,
    timerProgressBar: true
});
</script>
@endif

@if(session('success'))
<script>
Swal.fire({
    icon: 'success',
    title: 'Berhasil',
    text: "{{ session('success') }}",
    confirmButtonColor: '#2563eb'
});
</script>
@endif

<script>

/* ================= INFO ================= */

function toggleInfo() {

  const content = document.getElementById('infoContent');
  const arrow = document.getElementById('infoArrow');

  content.classList.toggle('show');
  arrow.classList.toggle('rotate-180');

}

/* ================= INIT ================= */

const negaraInput = document.getElementById('negaraInput');
const operatorInput = document.getElementById('operatorInput');
const layananInput = document.getElementById('layananInput');

const negaraList = document.getElementById('negaraList');
const operatorList = document.getElementById('operatorList');
const layananList = document.getElementById('layananList');

const hargaLabel = document.getElementById('hargaLabel');
const hargaInput = document.getElementById('hargaInput');
const layananNamaInput = document.getElementById('layananNamaInput');

const negaraHidden = document.getElementById('negara');
const operatorHidden = document.getElementById('operator');
const layananHidden = document.getElementById('layanan');

const serverSelect = document.getElementById('serverSelect');
const serverHidden = document.getElementById('server');

let countries = @json($countries);
if (!Array.isArray(countries)) countries = Object.values(countries);

/* ================= SERVER ================= */

serverSelect.addEventListener('change', () => {
  serverHidden.value = serverSelect.value;
});

function getServerValue() {
  return serverSelect?.value || serverHidden?.value || 1;
}

/* ================= AUTOCOMPLETE ================= */

function showSuggestions(input, list, items, keyName, displayName) {

  const query = input.value.trim().toLowerCase();

  list.innerHTML = '';

  const arr = Array.isArray(items)
    ? items
    : Object.values(items);

  const filtered = arr.filter(i =>
    (i[displayName] || '').toLowerCase().includes(query)
  );

  if (filtered.length === 0 || !query) {
    list.classList.add('hidden');
    return;
  }

  filtered.forEach(i => {

    const li = document.createElement('li');

    li.innerHTML = `
      <div class="autocomplete-item">
        <span>${i[displayName]}</span>
        <span class="text-xs text-gray-400"></span>
      </div>
    `;

    li.onclick = () => {

      input.value = i[displayName];
      list.classList.add('hidden');

      if (input === negaraInput) selectNegara(i[keyName]);
      if (input === operatorInput) selectOperator(i[keyName]);
      if (input === layananInput) selectLayanan(i[keyName]);

    };

    list.appendChild(li);

  });

  list.classList.remove('hidden');

}

function tryAutoSelect(input, list, items, keyName, displayName, onSelect) {

  const query = input.value.trim().toLowerCase();

  if (!query) return;

  const arr = Array.isArray(items)
    ? items
    : Object.values(items);

  const exact = arr.filter(i =>
    (i[displayName] || '').toLowerCase() === query
  );

  if (exact.length === 1) {

    const item = exact[0];

    input.value = item[displayName];
    list.classList.add('hidden');

    onSelect(item[keyName]);

  }

}

/* ================= NEGARA ================= */

negaraInput.addEventListener('input', () => {

  showSuggestions(
    negaraInput,
    negaraList,
    countries,
    'id_negara',
    'nama_negara'
  );

  tryAutoSelect(
    negaraInput,
    negaraList,
    countries,
    'id_negara',
    'nama_negara',
    selectNegara
  );

});

async function selectNegara(idNegara) {

  negaraHidden.value = idNegara;

  operatorInput.value = '';
  operatorInput.disabled = true;

  layananInput.value = '';
  layananInput.disabled = true;

  document.getElementById('operatorLoading').classList.remove('hidden');

  try {

    const res = await fetch(`/ajax/operators/${idNegara}?server=${getServerValue()}`);
    const data = await res.json();

    const arr = data.data ? data.data[idNegara] : [];

    window.operatorData = (arr || []).map(op => ({
      id: op,
      name: op
    }));

    operatorInput.disabled = false;

  } catch (e) {

    console.error(e);

  } finally {

    document.getElementById('operatorLoading').classList.add('hidden');

  }

}

/* ================= OPERATOR ================= */

operatorInput.addEventListener('input', () => {

  showSuggestions(
    operatorInput,
    operatorList,
    window.operatorData || [],
    'id',
    'name'
  );

  tryAutoSelect(
    operatorInput,
    operatorList,
    window.operatorData || [],
    'id',
    'name',
    selectOperator
  );

});

async function selectOperator(opName) {

  operatorHidden.value = opName;

  layananInput.value = '';
  layananInput.disabled = true;

  document.getElementById('layananLoading').classList.remove('hidden');

  try {

    const res = await fetch(`/ajax/services/${negaraHidden.value}?server=${getServerValue()}`);
    const data = await res.json();

    const map =
      data[negaraHidden.value] ||
      data?.data?.[negaraHidden.value] ||
      Object.values(data)[0] ||
      {};

    window.layananData = Object.entries(map).map(([kode, item]) => ({
      id: kode,
      name: item.layanan || kode,
      harga: item.harga || 0,
      stok: item.stok ?? 0
    }));

    layananInput.disabled = false;

  } catch (e) {

    console.error(e);

  } finally {

    document.getElementById('layananLoading').classList.add('hidden');

  }

}

/* ================= LAYANAN ================= */

layananInput.addEventListener('input', () => {

  showSuggestions(
    layananInput,
    layananList,
    window.layananData || [],
    'id',
    'name'
  );

  tryAutoSelect(
    layananInput,
    layananList,
    window.layananData || [],
    'id',
    'name',
    selectLayanan
  );

});

function selectLayanan(id) {

  const data = (window.layananData || []).find(l => l.id === id);

  if (!data) return;

  layananHidden.value = id;
  layananNamaInput.value = data.name;
  hargaInput.value = data.harga;

  hargaLabel.textContent =
    'Rp ' + new Intl.NumberFormat('id-ID').format(data.harga);

}

/* ================= CLICK OUTSIDE ================= */

document.addEventListener('click', e => {

  [negaraList, operatorList, layananList].forEach(list => {

    if (
      !list.contains(e.target) &&
      !list.previousElementSibling.contains(e.target)
    ) {
      list.classList.add('hidden');
    }

  });

});

/* ================= FADE ================= */

document.addEventListener("DOMContentLoaded", () => {

  const els = document.querySelectorAll('.fade-section');

  els.forEach((el, i) => {

    setTimeout(() => {
      el.classList.add('show');
    }, i * 120);

  });

});

</script>

@endsection