<?php
namespace App\Components;

use Core\Component;

class NotificationDropdown extends Component
{
    public static function make(): static
    {
        return new static();
    }

    public function render(): string
    {
        $app_url = APP_URL;
        return <<<HTML
        <li class="dropdown notification-list">
            <a class="nav-link dropdown-toggle arrow-none" data-bs-toggle="dropdown" href="#" role="button"
                aria-haspopup="false" aria-expanded="false">
                <i class="ri-notification-3-line fs-22"></i>
                <!-- badge always rendered -->
                <span id="notification-badge" class="noti-icon-badge badge text-bg-pink d-none">0</span>
            </a>
            <div class="dropdown-menu dropdown-menu-end dropdown-menu-animated dropdown-lg py-0">
                <div class="p-2 border-top-0 border-start-0 border-end-0 border-dashed border">
                    <div class="row align-items-center">
                        <div class="col">
                            <h6 class="m-0 fs-16 fw-semibold">Notification</h6>
                        </div>
                    </div>
                </div>

                <div id="notification-list" style="max-height: 300px;" data-simplebar>
                    <div class="text-center p-3 text-muted">Loading...</div>
                </div>

                <!-- All -->
                <a href="{$app_url}/notifications"
                    class="dropdown-item text-center text-primary text-decoration-underline fw-bold notify-item border-top border-light py-2">
                    View All
                </a>
            </div>
        </li>

        <script>
        document.addEventListener("DOMContentLoaded", function () {
            function loadNotifications(page = 1) {
                fetch(`{$app_url}/notifications/list?page=\${page}&per_page=5`)
                    .then(res => res.json())
                    .then(data => {
                        if (data.status !== "success") return;

                        const badge = document.getElementById("notification-badge");
                        const list = document.getElementById("notification-list");

                        // badge shows unread count only
                        if (data.unread_total > 0) {
                            badge.textContent = data.unread_total;
                            badge.classList.remove("d-none");
                        } else {
                            badge.textContent = "0";
                            badge.classList.add("d-none");
                        }

                        console.log(data)
                        // list items
                        if (data.notifications.length === 0) {
                            list.innerHTML = `<div class="text-center p-3 text-muted">No notifications</div>`;
                        } else {
                            list.innerHTML = data.notifications.map(n => `
                                <a href="javascript:void(0);" 
                                class="dropdown-item notify-item \${n.read_at === null ? 'active' : ''}" 
                                data-id="\${n.id}" 
                                data-link="\${n.link}">
                                    <div class="notify-icon bg-primary-subtle">
                                        <i class="mdi mdi-bell-outline text-primary"></i>
                                    </div>
                                    <p class="notify-details">
                                        \${n.title || 'Notification'}
                                        <small class="noti-time">\${new Date(n.created_at).toLocaleString()}</small>
                                    </p>
                                </a>
                            `).join("");
                        }

                    });
            }

            // Initial + interval refresh
            loadNotifications();
            setInterval(() => loadNotifications(), 30000);

            // Mark one as read + redirect
            document.addEventListener("click", function (e) {
                const item = e.target.closest(".notify-item");
                if (item && item.hasAttribute("data-id")) {
                    let id = item.getAttribute("data-id");
                    let link = item.getAttribute("data-link");

                    fetch(`{$app_url}/notifications/\${id}/read`, { method: "POST" })
                        .then(() => {
                            // redirect after marking read
                            if (link && link !== "null") {
                                window.location.href = link;
                            } else {
                                window.location.href = `{$app_url}/notifications/view/\${id}`;
                            }
                        });
                }
            });
        });
        </script>
        HTML;
    }
}
