<?php $__env->startSection('content'); ?>

<style>
/* =========================
   ANIMATION & BASE
========================= */
.fade-section {
    opacity: 0;
    transform: translateY(20px);
    filter: blur(8px);
    transition: all 0.6s cubic-bezier(0.16, 1, 0.3, 1);
}
.fade-section.show {
    opacity: 1;
    transform: translateY(0);
    filter: blur(0);
}

/* =========================
   CARDS & CONTAINERS
========================= */
.modern-card {
    background: #ffffff;
    border: 1px solid rgba(226, 232, 240, 0.9);
    border-radius: 20px;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.02), 0 2px 4px -2px rgba(0, 0, 0, 0.02);
    transition: all 0.25s ease;
}

.modern-card:hover {
    box-shadow: 0 10px 25px -5px rgba(15, 23, 42, 0.05);
    border-color: rgba(203, 213, 225, 1);
}

/* =========================
   INPUT & DROPDOWN
========================= */
.input-modern {
    width: 100%;
    height: 48px;
    border-radius: 14px;
    border: 1px solid #e2e8f0;
    background: #f8fafc;
    padding: 0 16px;
    font-weight: 500;
    color: #0f172a;
    transition: all 0.2s ease;
    outline: none;
    font-size: 0.875rem;
}

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

.input-modern:disabled {
    background-color: #f1f5f9;
    color: #94a3b8;
    cursor: not-allowed;
}

.dropdown-list {
    position: absolute;
    z-index: 50;
    width: 100%;
    margin-top: 6px;
    background: #ffffff;
    border: 1px solid #e2e8f0;
    border-radius: 16px;
    overflow: hidden;
    box-shadow: 0 10px 25px -5px rgba(15, 23, 42, 0.1);
    max-height: 230px;
    overflow-y: auto;
}

.dropdown-list li {
    padding: 12px 16px;
    transition: background-color 0.15s ease;
    cursor: pointer;
    font-size: 0.875rem;
    color: #334155;
    font-weight: 500;
}

.dropdown-list li:hover {
    background: #eff6ff;
    color: #2563eb;
}

/* =========================
   BUTTON
========================= */
.btn-search {
    width: 100%;
    height: 48px;
    border-radius: 14px;
    background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%);
    color: #ffffff;
    font-weight: 700;
    font-size: 0.95rem;
    transition: all 0.25s ease;
    box-shadow: 0 4px 12px rgba(37, 99, 235, 0.25);
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
}

.btn-search:hover {
    transform: translateY(-1px);
    box-shadow: 0 8px 20px rgba(37, 99, 235, 0.35);
}

.btn-search:disabled {
    opacity: 0.7;
    cursor: not-allowed;
    transform: none;
    box-shadow: none;
}

/* =========================
   PRODUCT CARDS GRID
========================= */
#result {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 16px;
}

@media(max-width: 640px) {
    #result {
        grid-template-columns: repeat(2, minmax(0, 1fr));
        gap: 10px;
    }
}

.product-card {
    opacity: 0;
    transform: translateY(20px);
    filter: blur(8px);
    transition: all 0.5s cubic-bezier(0.16, 1, 0.3, 1);
}

.product-card.show {
    opacity: 1;
    transform: translateY(0);
    filter: blur(0);
}

.product-item {
    background: #ffffff;
    border: 1px solid #e2e8f0;
    border-radius: 18px;
    padding: 16px 12px;
    text-align: center;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.02);
    transition: all 0.25s ease;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-between;
    height: 100%;
}

.product-item:hover {
    transform: translateY(-3px);
    box-shadow: 0 10px 20px -5px rgba(15, 23, 42, 0.08);
    border-color: #cbd5e1;
}

.product-title {
    font-size: 0.8125rem;
    font-weight: 700;
    color: #0f172a;
    margin-top: 10px;
    line-height: 1.35;
    word-break: break-word;
}

.product-price {
    margin-top: 10px;
    display: inline-flex;
    align-items: baseline;
    justify-content: center;
    gap: 2px;
    color: #2563eb;
    font-weight: 800;
    font-size: 1rem;
}
</style>

<main class="space-y-6 font-['Inter',sans-serif]">

    <!-- SEARCH FORM SECTION -->
    <section class="fade-section">
        <div class="modern-card max-w-4xl mx-auto p-5 sm:p-7">

            <!-- HEADER -->
            <div class="flex items-center gap-3.5 pb-5 mb-6 border-b border-slate-100">
                <div class="w-12 h-12 rounded-2xl bg-blue-50 text-blue-600 border border-blue-100 flex items-center justify-center shrink-0">
                    <span class="material-symbols-outlined text-[24px]">category_search</span>
                </div>
                <div>
                    <h2 class="text-base sm:text-lg font-bold text-slate-900">Cari Harga & Layanan</h2>
                    <p class="text-xs text-slate-500 mt-0.5">Pilih negara dan jenis aplikasi untuk cek ketersediaan harga real-time</p>
                </div>
            </div>

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

                <!-- NEGARA -->
                <div class="relative">
                    <label class="block text-xs font-bold text-slate-700 mb-2 uppercase tracking-wider">
                        1. Pilih Negara
                    </label>
                    <input
                        id="countryInput"
                        class="input-modern"
                        placeholder="Ketik negara..."
                        autocomplete="off"
                    >
                    <ul id="countryList" class="dropdown-list hidden"></ul>
                </div>

                <!-- LAYANAN -->
                <div class="relative">
                    <label class="block text-xs font-bold text-slate-700 mb-2 uppercase tracking-wider">
                        2. Pilih Layanan
                    </label>
                    <input
                        id="serviceInput"
                        class="input-modern"
                        placeholder="Pilih negara terlebih dahulu..."
                        autocomplete="off"
                        disabled
                    >
                    <ul id="serviceList" class="dropdown-list hidden"></ul>
                </div>

            </div>

            <!-- BUTTON ACTION -->
            <div class="mt-6">
                <button id="cekBtn" class="btn-search" disabled>
                    <span class="material-symbols-outlined text-[20px]">search</span>
                    <span id="btnText">Cari</span>
                </button>
            </div>

        </div>
    </section>

    <!-- RESULT SECTION -->
    <section class="fade-section max-w-4xl mx-auto px-1 sm:px-0">
        <div id="result"></div>
    </section>

    <!-- FOOTER INCLUSION -->
    <?php echo $__env->make('components.footer', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>

</main>

<script>
function autoSelect(input, list, data, callback) {
    const q = input.value.toLowerCase().trim();
    const exact = data.find(x => (x.name || '').toLowerCase() === q);
    if (exact) {
        callback(exact);
        list.classList.add('hidden');
    }
}

const countryInput = document.getElementById('countryInput');
const serviceInput = document.getElementById('serviceInput');
const countryList  = document.getElementById('countryList');
const serviceList  = document.getElementById('serviceList');
const resultBox    = document.getElementById('result');
const cekBtn       = document.getElementById('cekBtn');

let countries = [];
let services = [];
let selectedCountry = null;
let selectedService = null;

// INITIAL STATE
countryInput.disabled = true;
serviceInput.disabled = true;

// ================= LOAD COUNTRIES =================
(async () => {
    try {
        countryInput.placeholder = 'Memuat daftar negara...';

        const res = await fetch('/ajax/smscode/countries');
        const json = await res.json();

        countries = json.data || [];

        countryInput.disabled = false;
        countryInput.placeholder = 'Ketik nama negara (misal: Indonesia)...';

    } catch (e) {
        console.error(e);
        countryInput.placeholder = 'Gagal memuat daftar negara';
    }
})();

// ================= RENDER LIST =================
function renderList(input, list, data, callback) {
    const q = input.value.toLowerCase();
    list.innerHTML = '';

    const filtered = data.filter(x =>
        (x.name || '').toLowerCase().includes(q)
    );

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

    filtered.forEach(item => {
        const li = document.createElement('li');
        li.textContent = item.name;

        li.onclick = () => {
            callback(item);
            list.classList.add('hidden');
        };

        list.appendChild(li);
    });

    list.classList.remove('hidden');
}

// ================= COUNTRY =================
countryInput.addEventListener('input', () => {
    renderList(countryInput, countryList, countries, selectCountry);
    autoSelect(countryInput, countryList, countries, selectCountry);
});

async function selectCountry(c) {
    selectedCountry = c.id;
    countryInput.value = c.name;

    serviceInput.value = '';
    serviceInput.disabled = true;

    selectedService = null;
    cekBtn.disabled = true;

    resultBox.innerHTML = '';

    try {
        serviceInput.placeholder = 'Memuat daftar layanan...';
        serviceInput.classList.add('animate-pulse');

        const res = await fetch(`/ajax/smscode/services/${c.id}`);
        const json = await res.json();

        services = json.data || [];

        serviceInput.disabled = false;
        serviceInput.placeholder = 'Ketik nama layanan/aplikasi...';

    } catch (e) {
        console.error(e);
        serviceInput.placeholder = 'Gagal memuat layanan';
    } finally {
        serviceInput.classList.remove('animate-pulse');
    }
}

// ================= SERVICE =================
serviceInput.addEventListener('input', () => {
    renderList(serviceInput, serviceList, services, selectService);
    autoSelect(serviceInput, serviceList, services, selectService);
});

function selectService(s) {
    selectedService = s;
    serviceInput.value = s.name;

    cekBtn.disabled = false;
}

// ================= CEK HARGA =================
cekBtn.addEventListener('click', async () => {
    if (!selectedCountry || !selectedService) return;

    // 1. Tampilkan animasi loading SVG pada tombol & nonaktifkan klik
    cekBtn.disabled = true;
    cekBtn.innerHTML = `
        <svg class="animate-spin h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
        </svg>
        <span>Memproses...</span>
    `;

    resultBox.innerHTML = `
    <div class="col-span-full flex items-center justify-center py-12">
      <div class="flex flex-col items-center gap-3">
        <div class="w-8 h-8 border-3 border-blue-600 border-t-transparent rounded-full animate-spin"></div>
        <p class="text-xs font-bold text-slate-600 tracking-wide">
          Memuat harga produk server...
        </p>
      </div>
    </div>
    `;

    try {
        const res = await fetch(`/ajax/smscode/products?country=${selectedCountry}&service=${selectedService.id}`);
        const json = await res.json();

        if (!json.data?.length) {
            resultBox.innerHTML = `
            <div class="col-span-full">
              <div class="modern-card p-8 text-center">
                <div class="w-12 h-12 rounded-2xl bg-slate-100 text-slate-400 flex items-center justify-center mx-auto mb-2.5">
                  <span class="material-symbols-outlined text-[26px]">inventory_2</span>
                </div>
                <h3 class="font-bold text-slate-800 text-sm">
                  Produk Tidak Ditemukan
                </h3>
                <p class="text-xs text-slate-500 mt-1">
                  Saat ini tidak ada server yang tersedia untuk layanan tersebut.
                </p>
              </div>
            </div>
            `;
            return;
        }

        resultBox.innerHTML = '';

        json.data.forEach((p, i) => {
            const el = document.createElement('div');
            el.className = 'product-card';
            el.style.transitionDelay = `${i * 50}ms`;

            const cleanName = p.name
                .replace(/\(\$[^)]*\)/g, '')
                .replace(/\s+/g, ' ')
                .trim();

            el.innerHTML = `
            <div class="product-item">
              <div class="w-10 h-10 rounded-xl bg-blue-50 text-blue-600 border border-blue-100 flex items-center justify-center shrink-0">
                <span class="material-symbols-outlined text-[20px]">dns</span>
              </div>

              <div class="product-title">
                (Server ${i + 1})<br>
                <span class="font-semibold text-slate-600">${cleanName}</span>
              </div>

              <div class="product-price">
                <span class="text-[11px] font-medium text-slate-500">Rp</span>
                <span>${p.harga.toLocaleString('id-ID')}</span>
              </div>
            </div>
            `;

            resultBox.appendChild(el);
        });

        setTimeout(() => {
            document.querySelectorAll('.product-card').forEach(el => el.classList.add('show'));
        }, 50);

    } catch (e) {
        console.error(e);

        resultBox.innerHTML = `
        <div class="col-span-full">
          <div class="modern-card p-8 text-center border-rose-200 bg-rose-50/30">
            <div class="w-12 h-12 rounded-2xl bg-rose-100 text-rose-600 flex items-center justify-center mx-auto mb-2.5">
              <span class="material-symbols-outlined text-[26px]">error</span>
            </div>
            <h3 class="font-bold text-rose-600 text-sm">
              Gagal Memuat Data
            </h3>
            <p class="text-xs text-slate-500 mt-1">
              Terjadi kesalahan jaringan saat mengambil daftar harga layanan.
            </p>
          </div>
        </div>
        `;
    } finally {
        // 2. Kembalikan keadaan tombol ke asal setelah proses pencarian selesai
        cekBtn.disabled = false;
        cekBtn.innerHTML = `
            <span class="material-symbols-outlined text-[20px]">search</span>
            <span>Cari</span>
        `;
    }
});

// ================= CLICK OUTSIDE =================
document.addEventListener('click', e => {
    [countryList, serviceList].forEach(list => {
        if (!list.contains(e.target) && !list.previousElementSibling.contains(e.target)) {
            list.classList.add('hidden');
        }
    });
});

// ================= FADE =================
document.addEventListener("DOMContentLoaded", () => {
  setTimeout(() => {
    document.querySelectorAll('.fade-section').forEach(el => el.classList.add('show'));
  }, 100);
});
</script>

<?php $__env->stopSection(); ?>
<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /home/nusaotp/public_html/resources/views/daftar-harga/indexv2.blade.php ENDPATH**/ ?>