<header class="bg-surface sticky top-0 z-50 flex justify-between items-center px-container-margin w-full h-16 shadow-sm">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<div class="flex items-center">

    <img
        src="<?php echo e(asset('public/assets/logo-nusaotp.png')); ?>"
        alt="NusaOTP"
        class="h-8 w-auto object-contain">

</div>
<div class="flex items-center gap-3">

<button

        onclick="openOtpModal()"

        class="relative hover:opacity-80 active:scale-95">

        <span id="otpBell"

              class="material-symbols-outlined text-primary text-[26px]">

            notifications

        </span>

        <span id="otpBadge"

              class="hidden absolute -top-1 -right-1

                     w-3 h-3 rounded-full bg-red-500 border-2 border-white">

        </span>

    </button>

    <button
    onclick="openInbox()"
    class="relative hover:opacity-80 transition-opacity active:scale-95 transition-transform">
<span id="inbox"

              class="material-symbols-outlined text-primary text-[26px]">

            mail

        </span>
   
    <span
        id="inboxBadge"
        class="absolute -top-1 -right-1 w-3 h-3 bg-red-500 rounded-full border-2 border-white">
    </span>

</button>
</div>
</header>
<div id="inboxModal" class="hidden fixed inset-0 z-[120]">

<div
    onclick="closeInbox()"
    class="absolute inset-0 bg-black/40 backdrop-blur-sm">
</div>

<div
    class="absolute bottom-0 left-0 right-0 bg-white rounded-t-[32px] max-h-[85vh] overflow-hidden shadow-2xl">

    <div class="p-5 border-b">

        <div class="w-12 h-1.5 bg-gray-300 rounded-full mx-auto mb-4"></div>

        <div class="flex items-center justify-between">

            <h3 class="font-bold text-lg">
                Inbox
            </h3>

            <button onclick="closeInbox()">
                <span class="material-symbols-outlined">
                    close
                </span>
            </button>

        </div>

    </div>

    <div
        id="inboxContent"
        class="overflow-y-auto p-4"
        style="max-height:70vh;">

        <div class="text-center py-10">

            <div class="animate-spin inline-block w-8 h-8 border-4 border-blue-500 border-t-transparent rounded-full"></div>

            <p class="mt-3 text-sm text-gray-500">
                Memuat pesan...
            </p>

        </div>

    </div>

</div>
</div>
<div id="otpModal" class="hidden fixed inset-0 z-[130]">

    <div
        onclick="closeOtpModal()"
        class="absolute inset-0 bg-black/40 backdrop-blur-sm">
    </div>

    <div
        class="absolute bottom-0 left-0 right-0 bg-white rounded-t-[32px] max-h-[85vh] overflow-hidden shadow-2xl">

        <div class="p-5 border-b">

            <div class="w-12 h-1.5 bg-gray-300 rounded-full mx-auto mb-4"></div>

            <div class="flex justify-between items-center">

                <h3 class="font-bold text-lg">
                    OTP Notification
                </h3>

                <button onclick="closeOtpModal()">
                    <span class="material-symbols-outlined">
                        close
                    </span>
                </button>

            </div>

        </div>

        <div
            id="otpContent"
            class="overflow-y-auto p-4"
            style="max-height:70vh">

        </div>

    </div>

</div>
<script>

function formatMessage(text) {
    return (text || '-')
        .replace(
            /(https?:\/\/[^\s<]+)/gi,
            '<a href="$1" onclick="window.open(this.href, \'_blank\'); return false;" class="text-blue-600 font-medium underline break-all">$1</a>'
        )
        .replace(/\n/g, '<br>');
}

/* ===========================
   Inbox
=========================== */

function openInbox() {

    const modal = document.getElementById('inboxModal');

    modal.classList.remove('hidden');

    fetch('/broadcast/list')
    .then(r => r.json())
    .then(data => {

        let html = '';

        if (!data.length) {

            html = `
            <div class="text-center py-10">
                <svg class="mx-auto mb-3 text-gray-400" width="60" height="60" viewBox="0 0 24 24" fill="none">
                    <path d="M4 5H20V19H4V5Z" stroke="currentColor" stroke-width="2"/>
                </svg>

                <p class="text-gray-500">
                    Belum ada pesan.
                </p>
            </div>
            `;

        } else {

            data.forEach(item => {

                html += `
                <div class="bg-gray-50 rounded-2xl p-4 mb-3 border">

                    <div class="flex items-start gap-3">

                        <div class="w-10 h-10 rounded-xl bg-blue-100 flex items-center justify-center">

                            <svg xmlns="http://www.w3.org/2000/svg"
                                 class="w-5 h-5 text-blue-600"
                                 viewBox="0 0 24 24"
                                 fill="currentColor">

                                <path d="M1.5 8.67v8.58A2.25 2.25 0 0 0 3.75 19.5h16.5a2.25 2.25 0 0 0 2.25-2.25V8.67l-9.57 5.74a1.5 1.5 0 0 1-1.54 0L1.5 8.67Z"/>
                                <path d="M22.5 6.91V6.75A2.25 2.25 0 0 0 20.25 4.5H3.75A2.25 2.25 0 0 0 1.5 6.75v.16l10.5 6.3 10.5-6.3Z"/>

                            </svg>

                        </div>

                        <div class="flex-1">

                            <h4 class="font-semibold text-sm mb-1">
                                ${item.title}
                            </h4>

                            <div class="text-sm text-gray-600 break-words">
                                ${formatMessage(item.content ?? item.message ?? item.isi)}
                            </div>

                            <p class="text-xs text-gray-400 mt-2">
                                ${item.time ?? ''}
                            </p>

                        </div>

                    </div>

                </div>
                `;

            });

        }

        document.getElementById('inboxContent').innerHTML = html;

        document.getElementById('inboxBadge')?.remove();

    });

}

function closeInbox() {

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

}

/* ===========================
   OTP Notification
=========================== */

let latestOrders = [];

function showOtpBadge() {

    document
        .getElementById("otpBadge")
        .classList
        .remove("hidden");

}

function closeOtpModal() {

    document
        .getElementById("otpModal")
        .classList
        .add("hidden");

}

async function openOtpModal() {

    document
        .getElementById("otpBadge")
        .classList
        .add("hidden");

    document
        .getElementById("otpModal")
        .classList
        .remove("hidden");

    const orders = latestOrders
        .filter(item => item.status === "SUCCESS")
        .sort((a,b)=>
            new Date(b.created_at)-new Date(a.created_at)
        );

    if(!orders.length){

        document.getElementById("otpContent").innerHTML = `
            <div class="text-center py-10 text-gray-400">
                Belum ada OTP.
            </div>
        `;

        return;

    }

    document.getElementById("otpContent").innerHTML = orders.map(item=>`

<div
class="bg-white rounded-2xl border border-slate-200 shadow-sm p-4 mb-3 cursor-pointer hover:border-blue-300 hover:shadow-md transition"
onclick="copyOtp('${item.otp}')">

    <div class="flex justify-between items-start">

        <div>

            <div class="flex items-center gap-1 text-green-600 text-xs font-semibold">

                <span class="material-symbols-outlined text-[16px]">
                    verified
                </span>

                OTP Berhasil Diterima

            </div>

            <div class="text-3xl font-black tracking-[6px] text-primary mt-2">
                ${item.otp ?? '-'}
            </div>

            <div class="mt-3 text-xs text-slate-500">
                ${item.number ?? '-'}
            </div>
        </div>

        <button
        class="w-10 h-10 rounded-xl bg-blue-50 hover:bg-blue-100 flex items-center justify-center">

            <span class="material-symbols-outlined text-primary">
                content_copy
            </span>

        </button>

    </div>

</div>

`).join("");

}

function copyOtp(otp){

    navigator.clipboard.writeText(otp);

    Swal.fire({

        toast:true,
        position:'top',
        timer:1500,
        showConfirmButton:false,
        icon:'success',
        title:'OTP berhasil disalin'

    });

}

/* ===========================
   Polling
=========================== */

const otpSound = new Audio("<?php echo e(asset('public/sound/otp-success.mp3')); ?>");

let lastSuccessCount = 0;

async function checkOrders(){

    try{

        const res = await fetch("<?php echo e(route('ajax.orders.status')); ?>");

        const data = await res.json();

        if(!data.orders) return;

        latestOrders = data.orders;

        const now = new Date();

        const recent = latestOrders.filter(order =>

            order.status === "SUCCESS" &&
            ((now - new Date(order.created_at))/60000) <= 9

        );

        if(recent.length > lastSuccessCount){

            otpSound.play().catch(()=>{});

            showOtpBadge();

        }

        lastSuccessCount = recent.length;

    }catch(e){

        console.log(e);

    }

}

setInterval(checkOrders,5000);

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

    checkOrders();

});

</script><?php /**PATH /home/nusaotp/public_html/resources/views/apk/partials/header.blade.php ENDPATH**/ ?>