<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>{{ config('app.name', 'Nusa OTP') }}</title>

    <link rel="icon" type="image/png" href="{{ asset('public/assets/icon-nusaotp.ico') }}">
    <link rel="apple-touch-icon" href="{{ asset('public/assets/icon-nusaotp.ico') }}">

    <meta property="og:title" content="{{ config('app.name', 'Nusa OTP') }}">
    <meta property="og:description" content="Nusa OTP Adalah Platform Layanan Nomor Virtual Dengan OTP Otomatis Tercepat Dan Termurah Di Indonesia. Beli Nomor Virtual Sekarang, Instan, Terpercaya, Dan Aktif 24 Jam.">
    <meta property="og:image" content="{{ asset('public/assets/og-nusaotp.webp') }}">
    <meta property="og:type" content="website">
    <meta property="og:url" content="https://nusa-otp.com">

    <meta name="twitter:card" content="summary_large_image">
    <meta name="twitter:title" content="{{ config('app.name', 'Nusa OTP') }}">
    <meta name="twitter:description" content="Nusa OTP Adalah Platform Layanan Nomor Virtual Dengan OTP Otomatis Tercepat Dan Termurah Di Indonesia. Beli Nomor Virtual Sekarang, Instan, Terpercaya, Dan Aktif 24 Jam.">
    <meta name="twitter:image" content="{{ asset('public/assets/og-nusaotp.webp') }}">
    <meta name="keywords" content="Nusa OTP, nomor virtual murah, Nusa OTP nokos, Nokos, beli nomor virtual, OTP murah, Nokos Indonesia, OTP Wa, nomor virtual, nomor WhatsApp, nomor Telegram, nomor Gmail, nomor registrasi, layanan verifikasi akun, platform nomor virtual, nomor online, nomor SMS verifikasi, nokos wa, nokos indonesia, nomor kosong, nomor virtual murah, otp murah, nokos wa murah, nokos wa, nomor kosong murah, nomor murah, beli nomor kosong, jasa nomor kosong murah, jasa nomor kosong, jasa otp murah, beli nomor kosong wa, nomor kosong">
    
    <link rel="stylesheet" href="{{ asset('public/build/assets/XxX/app.css') }}">
    <link rel="stylesheet" href="{{ asset('public/build/assets/app-BJyaNEiF.css') }}">
    <script src="{{ asset('build/assets/app-DFwq5eDd.js') }}" defer></script>

    <!-- Tailwind CDN & Material Symbols -->
    <script src="https://cdn.tailwindcss.com?plugins=forms,container-queries"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Material+Symbols+Outlined:wght,FILL@100..700,0..1&display=swap" rel="stylesheet"/>

    <script src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js" defer></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <script>
        document.addEventListener('contextmenu', e => e.preventDefault());
        document.onkeydown = e => {
          if (e.keyCode === 123) return false; // F12
          if (e.ctrlKey && e.shiftKey && ['I','J','C'].includes(e.key.toUpperCase())) return false; // Ctrl+Shift+I/J/C
          if (e.ctrlKey && e.key.toUpperCase() === 'U') return false; // Ctrl+U
        };
    </script>

    <style>
        body {
            font-family: 'Inter', sans-serif;
            background-color: #F8FAFC;
        }
        
        /* Custom Scrollbar */
        ::-webkit-scrollbar {
            width: 6px;
            height: 6px;
        }
        ::-webkit-scrollbar-track {
            background: #f1f5f9;
        }
        ::-webkit-scrollbar-thumb {
            background: #cbd5e1;
            border-radius: 4px;
        }
        ::-webkit-scrollbar-thumb:hover {
            background: #94a3b8;
        }

        /* Animations */
        @keyframes slideDown {
          from { transform: translate(-50%, -80px); opacity: 0; }
          to { transform: translate(-50%, 20px); opacity: 1; }
        }
        @keyframes fadeOutUp {
          from { opacity: 1; transform: translate(-50%, 20px); }
          to { opacity: 0; transform: translate(-50%, -20px); }
        }

        .otp-toast-top, .broadcast-toast-top {
          position: fixed;
          top: 0;
          left: 50%;
          transform: translate(-50%, -80px);
          text-align: center;
          font-weight: 500;
          border-radius: 12px;
          box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 8px 10px -6px rgba(0, 0, 0, 0.1);
          z-index: 9999;
          padding: 0.75rem 1.25rem;
          font-size: 0.875rem;
          animation: slideDown 0.4s cubic-bezier(0.16, 1, 0.3, 1) forwards;
          width: fit-content;
          max-width: 90%;
        }

        .otp-toast-top {
          background: #10b981;
          color: white;
        }

        .broadcast-toast-top {
          background: #091426;
          border: 1px solid #1e293b;
          color: white;
        }

        .otp-toast-top.fade-out, .broadcast-toast-top.fade-out {
          animation: fadeOutUp 0.5s forwards;
        }

        /* Purchase Toast Animation */
        #purchaseToast {
          transition: all 0.4s cubic-bezier(0.16, 1, 0.3, 1);
          transform: translateY(100px);
          opacity: 0;
        }

        #purchaseToast.toast-show {
          transform: translateY(0);
          opacity: 1;
        }
    </style>
</head>

<body x-data="{ openProfile: false, openWidget: false }" class="text-slate-800 antialiased selection:bg-blue-500 selection:text-white">

<div class="flex min-h-screen">

    <!-- Include Sidebar Layout -->
    @include('components.sidebar')

    <!-- Main Wrapper -->
    <div class="flex flex-col flex-1 transition-all duration-300 md:pl-64">

        <!-- Top Header / App Bar -->
        <header class="bg-white/80 backdrop-blur-md sticky top-0 z-40 border-b border-slate-200/80 shadow-sm">
            <div class="px-4 sm:px-6 lg:px-8 flex justify-between items-center h-16">
                
                <!-- Left Header Space / Mobile Toggle Spacer -->
                <div class="flex items-center gap-3">

                </div>

                <!-- Right Action Icons (Inbox Broadcast & Notifications) -->
                <div class="flex items-center gap-3 relative" x-data="{ openProfile: false, openBroadcast: false }" @click.outside="openProfile = false; openBroadcast = false">

                    <!-- Inbox Container -->
                    <div class="flex items-center gap-2">
                      <!-- Badge Unread counter -->
                      <div id="inboxBadge" class="hidden relative">
                        <span class="flex h-3 w-3 absolute -top-1 -right-1">
                          <span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-rose-400 opacity-75"></span>
                          <span class="relative inline-flex rounded-full h-3 w-3 bg-rose-500"></span>
                        </span>
                        <span id="inboxBadgeText" class="hidden">0</span>
                      </div>

                      <!-- Button Inbox -->
                      <button id="inboxButton"
                              onclick="window.showAllBroadcasts && window.showAllBroadcasts()"
                              class="p-2 rounded-xl text-slate-600 hover:text-blue-600 hover:bg-slate-100 transition-all duration-200 focus:outline-none flex items-center justify-center border border-slate-200/60 shadow-sm"
                              title="Pesan Masuk">
                        <span class="material-symbols-outlined text-[22px]">mail</span>
                      </button>
                    </div>

                </div>

            </div>
        </header>

        <!-- Main Content Section -->
        <main class="flex-1 p-4 sm:p-6 lg:p-8 bg-[#F8FAFC]">
            @yield('content')
        </main>

    </div>
</div>
<!-- Floating Toast Purchase Notification -->
<div id="purchaseToast" 
     class="hidden fixed bottom-4 left-4 sm:bottom-6 sm:left-6 z-50 bg-white/95 rounded-xl sm:rounded-2xl shadow-xl sm:shadow-2xl border border-slate-200/90 p-3 sm:p-4 w-[calc(100vw-2rem)] max-w-[280px] sm:w-80 sm:max-w-none flex items-start gap-2.5 sm:gap-3.5 backdrop-blur-md">
  
  <!-- Icon Box -->
  <div class="flex-shrink-0 w-8 h-8 sm:w-10 sm:h-10 rounded-lg sm:rounded-xl bg-emerald-50 text-emerald-600 border border-emerald-100 flex items-center justify-center">
    <span class="material-symbols-outlined text-[18px] sm:text-[22px]">check_circle</span>
  </div>
  
  <!-- Text Content -->
  <div class="flex-1 min-w-0">
    <div class="font-bold text-slate-900 text-xs sm:text-sm tracking-tight">Pembelian Berhasil!</div>
    <div class="text-[11px] sm:text-xs text-slate-600 leading-snug sm:leading-relaxed mt-0.5 sm:mt-1" id="toastText">
      Layanan: <span class="font-medium text-slate-800">-</span><br>
      Nomor: <span class="font-mono text-slate-800">-</span><br>
      Harga: <span class="text-emerald-600 font-semibold">Rp 0</span><br>
      Tanggal: <span class="text-slate-500">-</span>
    </div>
  </div>

</div>
<script>
// Global Queue Variables
let isShowing = false;
let orderQueue = [];

function showPurchaseToast({ layanan, nomor, harga, tanggal, status }) {
  const toast = document.getElementById("purchaseToast");
  const text = document.getElementById("toastText");
  if (!toast || !text) return;

  let color = "#10b981"; // SUCCESS
  if (status === "PENDING") color = "#f59e0b";
  if (status === "FAILED") color = "#ef4444";

  let nomorTersensor = nomor && nomor.length > 4 ? nomor.slice(0, -4) + "****" : (nomor || '-');

  text.innerHTML = `
    Layanan: <span class="font-medium text-slate-800">${layanan || '-'}</span><br>
    Nomor: <span class="font-mono text-slate-800">${nomorTersensor}</span><br>
    Harga: <span class="font-semibold" style="color:${color}">Rp ${Number(harga || 0).toLocaleString('id-ID')}</span><br>
    Tanggal: <span class="text-slate-500">${tanggal || '-'}</span>
  `;

  isShowing = true;
  toast.classList.remove("hidden");

  setTimeout(() => {
    toast.classList.add("toast-show");
  }, 50);

  setTimeout(() => {
    toast.classList.remove("toast-show");

    setTimeout(() => {
      toast.classList.add("hidden");
      isShowing = false; // Reset agar item queue berikutnya bisa diputar
    }, 400);
  }, 3500);
}

function showBroadcastPopup() {
  const sound = new Audio("{{ asset('public/sound/notifikasi-inbox.mp3') }}");
  sound.volume = 0.7;
  sound.play().catch(() => {});

  const old = document.querySelector('.broadcast-toast-top');
  if (old) old.remove();

  const toast = document.createElement('div');
  toast.className = 'broadcast-toast-top flex items-center gap-2';

  toast.innerHTML = `
    <span class="material-symbols-outlined text-[20px] text-blue-400">mark_email_unread</span>
    <span class="font-medium text-sm">Pesan Baru Masuk di Inbox!</span>
  `;

  document.body.appendChild(toast);

  setTimeout(() => toast.classList.add('fade-out'), 6000);
  setTimeout(() => toast.remove(), 6600);
}

// Badge Counter Logic
let unreadInboxCount = Number(localStorage.getItem('unreadInboxCount') || 0);
const inboxBadge = document.getElementById('inboxBadge');
const inboxBadgeText = document.getElementById('inboxBadgeText');
const inboxButton = document.getElementById('inboxButton');

function updateInboxBadge() {
  if (!inboxBadge) return;
  if (unreadInboxCount > 0) {
    inboxBadge.classList.remove('hidden');
  } else {
    inboxBadge.classList.add('hidden');
  }
}

function incrementInboxCount() {
  unreadInboxCount++;
  localStorage.setItem('unreadInboxCount', unreadInboxCount);
  updateInboxBadge();
}

if (inboxButton) {
  inboxButton.addEventListener('click', () => {
    unreadInboxCount = 0;
    localStorage.setItem('unreadInboxCount', 0);
    updateInboxBadge();
  });
}

setTimeout(() => {
  const oldPopup = window.showBroadcastPopup;
  window.showBroadcastPopup = function (...args) {
    incrementInboxCount();
    if (typeof oldPopup === 'function') oldPopup.apply(this, args);
  };
}, 1000);

window.showAllBroadcasts = showAllBroadcasts;
updateInboxBadge();
window.updateInboxBadge = updateInboxBadge;
window.incrementInboxCount = incrementInboxCount;

document.addEventListener("DOMContentLoaded", () => {
  setTimeout(updateInboxBadge, 300);
});

// Fetch & Display Broadcast Messages
async function showAllBroadcasts() {
  try {
    const res = await fetch(`{{ route('broadcast.list') }}`);
    const data = await res.json();

    if (!Array.isArray(data) || data.length === 0) {
      return Swal.fire({
        title: 'Kosong',
        text: 'Belum ada pesan masuk.',
        icon: 'info',
        confirmButtonText: 'Tutup',
        confirmButtonColor: '#091426',
        background: '#ffffff',
        width: window.innerWidth < 768 ? '85%' : '380px',
        customClass: {
          popup: 'rounded-2xl shadow-xl border border-slate-100 text-sm',
          confirmButton: 'px-5 py-2 text-sm font-medium rounded-xl'
        }
      });
    }

    const listHtml = data
      .map(b => {
        const safeMessage = (b.message || '')
          .replace(
            /(https?:\/\/[^\s<]+)/g,
            '<a href="$1" target="_blank" class="text-blue-600 font-medium hover:underline break-all">$1</a>'
          );

        return `
          <div class="border-b border-slate-100 py-3 last:border-0 text-left">
            <div class="font-semibold text-slate-900 text-sm">${b.title}</div>
            <div class="text-slate-600 text-xs leading-relaxed mt-1">${safeMessage}</div>
            <div class="text-[10px] text-slate-400 mt-1.5 font-medium">${b.time}</div>
          </div>`;
      })
      .join('');

    Swal.fire({
      title: '',
      html: `
        <div class="flex items-center justify-center gap-2 text-slate-900 font-bold text-base mb-3 border-b border-slate-100 pb-3">
          <span class="material-symbols-outlined text-blue-600 text-[22px]">inbox</span>
          <span>Pemberitahuan & Memo</span>
        </div>
        <div class="max-h-[50vh] overflow-y-auto px-1 space-y-1">${listHtml}</div>
      `,
      background: '#ffffff',
      width: window.innerWidth < 768 ? '90%' : '440px',
      confirmButtonText: 'Tutup',
      confirmButtonColor: '#091426',
      showCloseButton: true,
      customClass: {
        popup: 'rounded-2xl shadow-2xl border border-slate-100 text-sm',
        confirmButton: 'px-5 py-2 text-sm font-medium rounded-xl'
      }
    });

  } catch (err) {
    console.error('Gagal ambil daftar broadcast:', err);
    Swal.fire('Error', 'Tidak bisa memuat broadcast.', 'error');
  }
}
</script>

@auth
<script>
document.addEventListener("DOMContentLoaded", async () => {
  const shownKey = "info_popup_shown_{{ auth()->id() }}";
  if (sessionStorage.getItem(shownKey)) return;

  try {
    const res = await fetch("{{ route('informasi.popup') }}");
    const html = await res.text();
    if (!html.trim()) return;

    Swal.fire({
      title: "Informasi Layanan",
      html: `
        <div class="max-h-[40vh] overflow-y-auto pr-1 text-slate-600 text-xs leading-relaxed text-left">
          ${html}
        </div>
      `,
      icon: "info",
      width: window.innerWidth < 768 ? "90%" : "460px",
      padding: "1.25rem",
      background: "#ffffff",
      showCloseButton: true,
      confirmButtonText: "Saya Sudah Membaca",
      confirmButtonColor: "#091426",
      customClass: {
        popup: "rounded-2xl shadow-2xl border border-slate-100 text-sm",
        title: "text-base font-bold text-slate-900 mb-2",
        confirmButton: "px-5 py-2.5 text-xs text-white font-medium rounded-xl mt-3",
      }
    });

    sessionStorage.setItem(shownKey, "1");
  } catch (err) {
    console.warn("⚠️ Gagal load popup info:", err);
  }
});

function showOtpToast(number, otp) {
  const old = document.querySelector('.otp-toast-top');
  if (old) old.remove();

  const toast = document.createElement('div');
  toast.className = 'otp-toast-top';

  toast.innerHTML = `
    <div class="font-bold text-sm">OTP Masuk!</div>
    <div class="text-xs opacity-90 mt-0.5">Nomor: ${number || '-'}</div>
    <div class="text-xs opacity-90 mt-0.5 font-mono">Kode OTP: <span class="font-extrabold text-white underline">${otp || '-'}</span></div>
  `;

  document.body.appendChild(toast);

  setTimeout(() => toast.classList.add('fade-out'), 10000); 
  setTimeout(() => toast.remove(), 10700);
}

// Auto Fetch Loop Engine
let isRunning = false;
let delay = 30000;
let lastBroadcastId = localStorage.getItem('lastBroadcastId') || 0;
let lastSuccessCount = 0;

const audioOtp = new Audio("{{ asset('public/sound/otp-success.mp3') }}");
const audioInbox = new Audio("{{ asset('public/sound/notifikasi-inbox.mp3') }}");

async function mainLoop(){
  if(document.hidden){
    scheduleNext(15000);
    return;
  }

  await Promise.all([
    fetchOrders(),
    checkBroadcast(),
    checkOrders()
  ]);

  playQueue();
  scheduleNext(delay);
}

function scheduleNext(ms){
  clearTimeout(isRunning);
  isRunning = setTimeout(mainLoop, ms);
}

async function fetchOrders(){
  try{
    const res = await fetch(`{{ route('notif.recent') }}`);
    const data = await res.json();
    if(Array.isArray(data)) orderQueue = data;
  }catch(e){}
}

function playQueue(){
  if(isShowing || orderQueue.length === 0) return;

  const next = orderQueue.shift();
  if(!next) return;

  const tgl = new Date(next.created_at).toLocaleString('id-ID', {
    day:'2-digit', month:'short', year:'numeric',
    hour:'2-digit', minute:'2-digit'
  });

  showPurchaseToast({
    layanan: next.service,
    nomor: next.number,
    harga: next.harga,
    status: next.status,
    tanggal: tgl
  });
}

async function checkBroadcast(){
  try{
    const res = await fetch(`{{ route('broadcast.popup') }}`);
    const data = await res.json();
    if(!data.id) return;

    if(Number(data.id) > Number(lastBroadcastId)){
      lastBroadcastId = data.id;
      localStorage.setItem('lastBroadcastId', data.id);
      audioInbox.play().catch(()=>{});
      showBroadcastPopup();
    }
  }catch(e){}
}

async function checkOrders(){
  try{
    const res = await fetch("{{ route('ajax.orders.status') }}");
    const data = await res.json();
    if(!data?.orders) return;

    const now = new Date();
    const recent = data.orders.filter(o =>
      o.status === 'SUCCESS' &&
      (now - new Date(o.created_at)) / 60000 <= 9
    );

    if(recent.length > lastSuccessCount){
      const latest = recent[0];
      audioOtp.play().catch(()=>{});
      showOtpToast(latest.number, latest.otp);
    }

    lastSuccessCount = recent.length;
  }catch(e){}
}

document.addEventListener("visibilitychange", () => {
  if(!document.hidden && !isRunning){
    mainLoop();
  }
});

document.addEventListener("DOMContentLoaded", () => {
  mainLoop();
});
</script>
@endauth

</body>
</html>