<?php
require_once __DIR__ . '/bootstrap.php';
$pageTitle = 'Notifications';
include 'partials/head.php';
?>

<div class="flex h-full min-h-screen">
    <?php include 'partials/sidebar.php'; ?>

    <main class="flex-1 lg:ml-48 pb-16 lg:pb-0">
        <!-- Header -->
        <header class="sticky top-0 bg-white/80 backdrop-blur border-b border-slate-200 px-4 lg:px-5 py-3 z-20">
            <div class="flex items-center justify-between gap-3">
                <h1 class="text-base font-semibold hidden lg:block">Notifications</h1>

                <!-- Search -->
                <div class="flex-1 max-w-md">
                    <div class="relative">
                        <svg class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/>
                        </svg>
                        <input type="text" id="search" placeholder="Search..." class="w-full h-8 pl-9 pr-3 bg-slate-100 border-0 rounded-lg text-sm focus:bg-white focus:ring-2 focus:ring-indigo-500/20">
                    </div>
                </div>

                <a href="/notifier/notifications/new/" class="h-8 w-8 sm:w-auto sm:px-3 bg-indigo-500 hover:bg-indigo-600 text-white rounded-lg text-xs font-medium transition-colors flex items-center justify-center sm:justify-start gap-1.5">
                    <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/></svg>
                    <span class="hidden sm:inline">New</span>
                </a>
            </div>

            <!-- Filters -->
            <div class="flex items-center gap-2 mt-3">
                <!-- Custom Category Dropdown -->
                <div class="relative" id="category-dropdown">
                    <button type="button" class="h-7 px-2 pr-7 bg-slate-100 hover:bg-slate-200 rounded-md text-xs flex items-center gap-1.5 transition-colors" onclick="toggleDropdown('category')">
                        <span id="category-label">All Categories</span>
                        <svg class="w-3.5 h-3.5 absolute right-2 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/></svg>
                    </button>
                    <div id="category-options" class="hidden absolute top-full left-0 mt-1 bg-white rounded-lg shadow-lg border border-slate-200 py-1 min-w-[160px] z-30">
                        <button class="w-full px-3 py-1.5 text-left text-xs hover:bg-slate-50 flex items-center gap-2" onclick="selectCategory('', 'All Categories')">
                            <span class="w-2 h-2 rounded-full bg-slate-300"></span>
                            All Categories
                        </button>
                        <!-- Categories populated by JS -->
                    </div>
                </div>

                <!-- Custom Status Dropdown -->
                <div class="relative" id="status-dropdown">
                    <button type="button" class="h-7 px-2 pr-7 bg-slate-100 hover:bg-slate-200 rounded-md text-xs flex items-center gap-1.5 transition-colors" onclick="toggleDropdown('status')">
                        <span id="status-label">All Status</span>
                        <svg class="w-3.5 h-3.5 absolute right-2 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/></svg>
                    </button>
                    <div id="status-options" class="hidden absolute top-full left-0 mt-1 bg-white rounded-lg shadow-lg border border-slate-200 py-1 min-w-[120px] z-30">
                        <button class="w-full px-3 py-1.5 text-left text-xs hover:bg-slate-50 flex items-center gap-2" onclick="selectStatus('', 'All Status')">
                            <span class="w-2 h-2 rounded-full bg-slate-300"></span>
                            All Status
                        </button>
                        <button class="w-full px-3 py-1.5 text-left text-xs hover:bg-slate-50 flex items-center gap-2" onclick="selectStatus('active', 'Active')">
                            <span class="w-2 h-2 rounded-full bg-emerald-400"></span>
                            Active
                        </button>
                        <button class="w-full px-3 py-1.5 text-left text-xs hover:bg-slate-50 flex items-center gap-2" onclick="selectStatus('paused', 'Paused')">
                            <span class="w-2 h-2 rounded-full bg-amber-400"></span>
                            Paused
                        </button>
                        <button class="w-full px-3 py-1.5 text-left text-xs hover:bg-slate-50 flex items-center gap-2" onclick="selectStatus('completed', 'Completed')">
                            <span class="w-2 h-2 rounded-full bg-slate-400"></span>
                            Completed
                        </button>
                    </div>
                </div>

                <button id="clear-filters" class="hidden h-7 px-2 text-xs text-slate-500 hover:text-slate-700">Clear</button>
            </div>
        </header>

        <div class="p-4 lg:p-5">
            <div id="notifications-list" class="grid grid-cols-1 lg:grid-cols-2 gap-3">
                <!-- Populated by JS -->
            </div>

            <div id="empty-state" class="hidden text-center py-16">
                <div class="w-14 h-14 bg-slate-100 rounded-xl flex items-center justify-center mx-auto mb-4">
                    <svg class="w-7 h-7 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9"/>
                    </svg>
                </div>
                <p class="text-sm font-medium text-slate-700 mb-1">No notifications yet</p>
                <p class="text-xs text-slate-400 mb-4">Create your first notification to get started</p>
                <a href="/notifier/notifications/new/" class="inline-flex items-center gap-1.5 h-8 px-4 bg-indigo-500 hover:bg-indigo-600 text-white rounded-lg text-xs font-medium transition-colors">
                    <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/></svg>
                    Create Notification
                </a>
            </div>
        </div>
    </main>
</div>

<?php include 'partials/mobile-nav.php'; ?>

<?php include 'partials/scripts.php'; ?>
<script>
    let notifications = [];
    let categories = [];
    let searchQuery = '';
    let filterCategory = '';
    let filterStatus = '';
    let searchTimer = null;

    const listEl = document.getElementById('notifications-list');
    const emptyEl = document.getElementById('empty-state');
    const searchEl = document.getElementById('search');
    const clearFiltersEl = document.getElementById('clear-filters');

    // Custom dropdown functions
    function toggleDropdown(type) {
        const options = document.getElementById(type + '-options');
        const isHidden = options.classList.contains('hidden');

        // Close all dropdowns first
        document.querySelectorAll('[id$="-options"]').forEach(el => el.classList.add('hidden'));

        if (isHidden) {
            options.classList.remove('hidden');
        }
    }

    function selectCategory(value, label) {
        filterCategory = value;
        document.getElementById('category-label').textContent = label;
        document.getElementById('category-options').classList.add('hidden');
        loadNotifications();
        updateClearFilters();
    }

    function selectStatus(value, label) {
        filterStatus = value;
        document.getElementById('status-label').textContent = label;
        document.getElementById('status-options').classList.add('hidden');
        loadNotifications();
        updateClearFilters();
    }

    // Close dropdowns when clicking outside
    document.addEventListener('click', (e) => {
        if (!e.target.closest('#category-dropdown') && !e.target.closest('#status-dropdown')) {
            document.querySelectorAll('[id$="-options"]').forEach(el => el.classList.add('hidden'));
        }
    });

    async function init() {
        const params = new URLSearchParams(window.location.search);
        const preselectCategoryId = params.get('category_id');

        await loadCategories();

        if (preselectCategoryId) {
            const match = categories.find(c => String(c.id) === String(preselectCategoryId));
            if (match) {
                filterCategory = String(match.id);
                document.getElementById('category-label').textContent = match.name;
            }
        }

        await loadNotifications();
        updateClearFilters();
    }

    async function loadCategories() {
        try {
            categories = await Api.getCategories();
            const categoryOptions = document.getElementById('category-options');
            categoryOptions.innerHTML = `
                <button class="w-full px-3 py-1.5 text-left text-xs hover:bg-slate-50 flex items-center gap-2" onclick="selectCategory('', 'All Categories')">
                    <span class="w-2 h-2 rounded-full bg-slate-300"></span>
                    All Categories
                </button>
            ` + categories.map(c => `
                <button class="w-full px-3 py-1.5 text-left text-xs hover:bg-slate-50 flex items-center gap-2" onclick="selectCategory('${c.id}', '${escapeHtml(c.name)}')">
                    <span class="w-2 h-2 rounded-full" style="background-color: ${c.color}"></span>
                    ${escapeHtml(c.name)}
                </button>
            `).join('');
        } catch (error) {
            Toast.error('Error', 'Failed to load categories');
        }
    }

    async function loadNotifications() {
        listEl.innerHTML = '<div class="col-span-full text-center py-8 text-slate-400 text-sm">Loading...</div>';
        listEl.classList.remove('hidden');
        emptyEl.classList.add('hidden');

        const params = {};
        if (searchQuery) params.search = searchQuery;
        if (filterCategory) params.category_id = filterCategory;
        if (filterStatus) params.status = filterStatus;

        try {
            notifications = await Api.getNotifications(params);
            render();
        } catch (error) {
            listEl.innerHTML = `<div class="col-span-full text-center py-8 text-red-500 text-sm">Failed to load notifications: ${escapeHtml(error.message)}</div>`;
            Toast.error('Error', 'Failed to load notifications');
        }
    }

    function escapeHtml(str) {
        if (!str) return '';
        return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
    }

    function normalizeIcon(icon) {
        if (!icon || !/^bi-[a-z0-9-]+$/i.test(icon)) return 'bi-tag';
        return icon;
    }

    function normalizeUtc(dateStr) {
        if (!dateStr) return null;
        if (dateStr.includes('T')) return dateStr;
        return dateStr.replace(' ', 'T') + 'Z';
    }

    function formatNextTrigger(notification) {
        if (notification.status === 'paused') return 'Paused';
        if (notification.status === 'completed') return 'Completed';
        const raw = notification.next_trigger_at || notification.next_trigger;
        if (!raw) return 'Not scheduled';
        const iso = normalizeUtc(raw);
        return iso ? DateUtils.formatRelative(iso) : 'Not scheduled';
    }

    function render() {
        if (notifications.length === 0) {
            listEl.classList.add('hidden');
            emptyEl.classList.remove('hidden');
            return;
        }

        listEl.classList.remove('hidden');
        emptyEl.classList.add('hidden');

        listEl.innerHTML = notifications.map(n => {
            const category = categories.find(c => c.id === n.category_id);
            const categoryName = category?.name || n.category_name;
            const categoryColor = category?.color || n.category_color || '#94a3b8';
            const categoryIcon = normalizeIcon(category?.icon || n.category_icon);
            const nextTrigger = formatNextTrigger(n);
            const dotColor = n.status === 'active'
                ? 'bg-emerald-400'
                : (n.status === 'paused' ? 'bg-amber-400' : 'bg-slate-400');
            const message = (n.message || '').replace(/\\\\/g, '');
            const statusBadge = n.status === 'paused'
                ? '<span class="text-[11px] px-2 py-0.5 rounded-full bg-amber-100 text-amber-600 font-medium">Paused</span>'
                : (n.status === 'completed' ? '<span class="text-[11px] px-2 py-0.5 rounded-full bg-slate-100 text-slate-500 font-medium">Completed</span>' : '');
            const canToggle = n.status !== 'completed';
            const toggleButton = canToggle
                ? `<button onclick="toggleStatus(${n.id})" class="w-7 h-7 rounded-lg hover:bg-slate-100 flex items-center justify-center text-slate-400 hover:text-slate-600" title="${n.status === 'active' ? 'Pause' : 'Resume'}">
                        ${n.status === 'active'
                            ? '<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 9v6m4-6v6m7-3a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>'
                            : '<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>'
                        }
                    </button>`
                : `<button class="w-7 h-7 rounded-lg flex items-center justify-center text-slate-300 cursor-not-allowed" title="Completed" disabled>
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
                    </button>`;

            return `
                <div class="bg-white rounded-xl border border-slate-200 overflow-hidden hover:shadow-md transition-shadow">
                    <div class="p-4 flex items-start gap-2">
                        <div class="w-2 h-2 rounded-full ${dotColor} mt-1.5 flex-shrink-0"></div>
                        <div class="flex-1 min-w-0">
                            <div class="font-medium text-sm truncate">${escapeHtml(n.title)}</div>
                            <div class="text-xs text-slate-400 truncate mt-0.5">${escapeHtml(message)}</div>
                        </div>
                        <div class="flex items-center gap-1">
                            ${toggleButton}
                            <button onclick="testNotification(${n.id})" class="w-7 h-7 rounded-lg hover:bg-slate-100 flex items-center justify-center text-slate-400 hover:text-slate-600" title="Test Send">
                                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"/></svg>
                            </button>
                            <a href="/notifier/notifications/edit/${n.id}/" class="w-7 h-7 rounded-lg hover:bg-slate-100 flex items-center justify-center text-slate-400 hover:text-slate-600" title="Edit">
                                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
                            </a>
                            <button onclick="deleteNotification(${n.id})" class="w-7 h-7 rounded-lg hover:bg-red-50 flex items-center justify-center text-slate-400 hover:text-red-500" title="Delete">
                                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
                            </button>
                        </div>
                    </div>
                    <div class="px-4 py-2 bg-slate-50 border-t border-slate-100 flex items-center gap-2">
                        ${categoryName ? `<span class="text-[11px] px-2 py-0.5 rounded-full font-medium inline-flex items-center gap-1.5" style="background-color: ${categoryColor}15; color: ${categoryColor}"><i class="${categoryIcon} text-[11px]"></i>${escapeHtml(categoryName)}</span>` : ''}
                        ${statusBadge}
                        <span class="text-[11px] text-slate-400 flex items-center gap-1">
                            <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
                            ${escapeHtml(nextTrigger)}
                        </span>
                    </div>
                </div>
            `;
        }).join('');
    }

    async function toggleStatus(id) {
        const n = notifications.find(n => n.id === id);
        if (!n) return;
        if (n.status === 'completed') return;

        try {
            if (n.status === 'active') {
                await Api.pauseNotification(id);
                n.status = 'paused';
                Toast.success('Paused', `"${n.title}" has been paused`);
            } else {
                await Api.resumeNotification(id);
                n.status = 'active';
                Toast.success('Resumed', `"${n.title}" is now active`);
            }
            render();
        } catch (error) {
            Toast.error('Error', error.message);
        }
    }

    async function testNotification(id) {
        try {
            await Api.testNotification(id);
            Toast.success('Sent!', 'Test message sent');
        } catch (error) {
            Toast.error('Error', error.message);
        }
    }

    async function deleteNotification(id) {
        const n = notifications.find(n => n.id === id);
        if (n && confirm(`Delete "${n.title}"?`)) {
            try {
                await Api.deleteNotification(id);
                notifications = notifications.filter(n => n.id !== id);
                Toast.success('Deleted', `"${n.title}" has been removed`);
                render();
            } catch (error) {
                Toast.error('Error', error.message);
            }
        }
    }

    searchEl.addEventListener('input', (e) => {
        searchQuery = e.target.value.trim();
        clearTimeout(searchTimer);
        searchTimer = setTimeout(() => loadNotifications(), 300);
        updateClearFilters();
    });
    clearFiltersEl.addEventListener('click', () => {
        searchQuery = ''; filterCategory = ''; filterStatus = '';
        searchEl.value = '';
        document.getElementById('category-label').textContent = 'All Categories';
        document.getElementById('status-label').textContent = 'All Status';
        loadNotifications();
        updateClearFilters();
    });

    function updateClearFilters() {
        clearFiltersEl.classList.toggle('hidden', !searchQuery && !filterCategory && !filterStatus);
    }

    init();
</script>
</body>
</html>
