<?php
require_once __DIR__ . '/bootstrap.php';
$pageTitle = 'Categories';
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 flex items-center justify-between z-10">
            <div>
                <h1 class="text-base font-semibold">Categories</h1>
                <p class="text-xs text-slate-400">Organize your notifications</p>
            </div>
            <button onclick="openModal()" 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">Add</span>
            </button>
        </header>

        <div class="p-4 lg:p-5">
            <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="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z"/>
                    </svg>
                </div>
                <p class="text-sm font-medium text-slate-700 mb-1">No categories yet</p>
                <p class="text-xs text-slate-400 mb-4">Create categories to organize notifications</p>
                <button onclick="openModal()" 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>
                    Add Category
                </button>
            </div>

            <div id="categories-grid" class="grid grid-cols-2 lg:grid-cols-3 gap-3">
                <!-- Populated by JS -->
            </div>
        </div>
    </main>
</div>

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

<!-- Modal -->
<div id="category-modal" class="hidden fixed inset-0 z-50">
    <div class="absolute inset-0 bg-black/50" onclick="closeModal()"></div>
    <div class="absolute bottom-0 left-0 right-0 lg:bottom-auto lg:top-1/2 lg:left-1/2 lg:-translate-x-1/2 lg:-translate-y-1/2 lg:max-w-sm lg:w-full bg-white rounded-t-2xl lg:rounded-2xl p-5 max-h-[85vh] overflow-y-auto">
        <h3 class="text-base font-semibold mb-4" id="modal-title">New Category</h3>
        <div class="space-y-4">
            <div>
                <label class="text-xs font-medium text-slate-500 mb-1.5 block">Name</label>
                <input type="text" id="category-name" placeholder="e.g., Bills, Health, Work" class="w-full h-9 px-3 bg-slate-100 border-0 rounded-lg text-sm focus:bg-white focus:ring-2 focus:ring-indigo-500/20">
            </div>
            <div>
                <label class="text-xs font-medium text-slate-500 mb-1.5 block">Icon</label>
                <div class="grid grid-cols-10 gap-1.5 max-h-32 overflow-y-auto p-1 bg-slate-50 rounded-lg" id="icon-picker"></div>
            </div>
            <div>
                <label class="text-xs font-medium text-slate-500 mb-1.5 block">Color</label>
                <div class="grid grid-cols-10 gap-2" id="color-picker"></div>
            </div>
        </div>
        <div class="flex gap-2 mt-5">
            <button onclick="closeModal()" class="flex-1 h-9 px-3 bg-slate-100 hover:bg-slate-200 rounded-lg text-sm font-medium transition-colors">Cancel</button>
            <button onclick="saveCategory()" id="save-btn" class="flex-1 h-9 px-3 bg-indigo-500 hover:bg-indigo-600 text-white rounded-lg text-sm font-medium transition-colors">Create</button>
        </div>
    </div>
</div>

<?php include 'partials/scripts.php'; ?>
<script>
    let editingId = null;
    let selectedColor = '#6366f1';
    let selectedIcon = 'bi-tag';
    let categories = []; // Cache for current categories

    const COLORS = [
        '#ef4444', '#f97316', '#f59e0b', '#eab308', '#84cc16',
        '#22c55e', '#10b981', '#14b8a6', '#06b6d4', '#0ea5e9',
        '#3b82f6', '#6366f1', '#8b5cf6', '#a855f7', '#d946ef',
        '#ec4899', '#f43f5e', '#78716c', '#64748b', '#6b7280'
    ];

    const ICONS = [
        'bi-tag', 'bi-bell', 'bi-calendar', 'bi-clock', 'bi-star',
        'bi-heart', 'bi-house', 'bi-briefcase', 'bi-cart', 'bi-cash',
        'bi-credit-card', 'bi-wallet', 'bi-bank', 'bi-piggy-bank', 'bi-gift',
        'bi-trophy', 'bi-flag', 'bi-bookmark', 'bi-folder', 'bi-file-text',
        'bi-envelope', 'bi-chat', 'bi-telephone', 'bi-camera', 'bi-image',
        'bi-music-note', 'bi-film', 'bi-tv', 'bi-controller', 'bi-puzzle',
        'bi-cup-hot', 'bi-egg-fried', 'bi-basket', 'bi-droplet', 'bi-sun',
        'bi-moon', 'bi-cloud', 'bi-umbrella', 'bi-snow', 'bi-lightning',
        'bi-airplane', 'bi-car-front', 'bi-bicycle', 'bi-train-front', 'bi-bus-front',
        'bi-fuel-pump', 'bi-building', 'bi-shop', 'bi-hospital', 'bi-mortarboard',
        'bi-book', 'bi-journal', 'bi-pencil', 'bi-brush', 'bi-palette',
        'bi-tools', 'bi-wrench', 'bi-hammer', 'bi-scissors', 'bi-bandaid',
        'bi-capsule', 'bi-activity', 'bi-heart-pulse', 'bi-lungs', 'bi-eye',
        'bi-ear', 'bi-person', 'bi-people', 'bi-person-workspace', 'bi-emoji-smile',
        'bi-hand-thumbs-up', 'bi-hand-thumbs-down', 'bi-check-circle', 'bi-x-circle', 'bi-exclamation-circle',
        'bi-question-circle', 'bi-info-circle', 'bi-shield-check', 'bi-lock', 'bi-key',
        'bi-gear', 'bi-sliders', 'bi-toggles', 'bi-cpu', 'bi-wifi',
        'bi-bluetooth', 'bi-printer', 'bi-display', 'bi-laptop', 'bi-phone',
        'bi-tablet', 'bi-watch', 'bi-headphones', 'bi-speaker', 'bi-mic',
        'bi-globe', 'bi-geo-alt', 'bi-compass', 'bi-map', 'bi-signpost'
    ];

    async function init() {
        renderIconPicker();
        renderColorPicker();
        await loadCategories();
    }

    function renderIconPicker() {
        document.getElementById('icon-picker').innerHTML = ICONS.map(icon => `
            <button type="button" onclick="selectIcon('${icon}')" data-icon="${icon}"
                class="w-7 h-7 rounded-lg flex items-center justify-center transition-all hover:bg-slate-200 ${selectedIcon === icon ? 'bg-indigo-100 ring-2 ring-indigo-500' : 'bg-white'}"
                title="${icon.replace('bi-', '')}">
                <i class="${icon} text-sm"></i>
            </button>
        `).join('');
    }

    function selectIcon(icon) {
        selectedIcon = icon;
        renderIconPicker();
    }

    function renderColorPicker() {
        document.getElementById('color-picker').innerHTML = COLORS.map(color => `
            <button type="button" onclick="selectColor('${color}')" data-color="${color}"
                class="w-6 h-6 rounded-full transition-transform hover:scale-110 ${selectedColor === color ? 'ring-2 ring-offset-2 ring-indigo-500' : ''}"
                style="background-color: ${color}"></button>
        `).join('');
    }

    function selectColor(color) {
        selectedColor = color;
        renderColorPicker();
    }

    async function loadCategories() {
        const grid = document.getElementById('categories-grid');
        const emptyState = document.getElementById('empty-state');

        // Show loading state
        grid.innerHTML = '<div class="col-span-full text-center py-8 text-slate-400 text-sm">Loading...</div>';
        grid.classList.remove('hidden');
        emptyState.classList.add('hidden');

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

    function renderCategories() {
        const grid = document.getElementById('categories-grid');
        const emptyState = document.getElementById('empty-state');

        if (categories.length === 0) {
            grid.classList.add('hidden');
            emptyState.classList.remove('hidden');
            return;
        }

        grid.classList.remove('hidden');
        emptyState.classList.add('hidden');

        grid.innerHTML = categories.map(cat => {
            const count = cat.notification_count || 0;
            const icon = ICONS.includes(cat.icon) ? cat.icon : 'bi-tag';
            return `
                <div class="bg-white rounded-xl border border-slate-200 p-4 group hover:shadow-md transition-shadow">
                    <div class="flex items-start justify-between mb-3">
                        <div class="w-10 h-10 rounded-xl flex items-center justify-center" style="background-color: ${cat.color}15">
                            <i class="${icon} text-lg" style="color: ${cat.color}"></i>
                        </div>
                        <div class="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                            <a href="/notifier/notifications/?category_id=${cat.id}" class="w-7 h-7 rounded-md hover:bg-slate-100 flex items-center justify-center text-slate-400 hover:text-slate-600" title="View notifications">
                                <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="M3 4a1 1 0 011-1h7a1 1 0 011 1v4a1 1 0 01-1 1H5v10h14v-5a1 1 0 112 0v6a1 1 0 01-1 1H4a1 1 0 01-1-1V4zM15 3h6m0 0v6m0-6L10 14"/></svg>
                            </a>
                            <button onclick="editCategory(${cat.id})" class="w-7 h-7 rounded-md hover:bg-slate-100 flex items-center justify-center text-slate-400 hover:text-slate-600">
                                <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="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>
                            </button>
                            <button onclick="deleteCategory(${cat.id})" class="w-7 h-7 rounded-md hover:bg-red-50 flex items-center justify-center text-slate-400 hover:text-red-500">
                                <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>
                    <h3 class="font-medium text-sm mb-0.5">${cat.name}</h3>
                    <p class="text-xs text-slate-400">${count} notification${count !== 1 ? 's' : ''}</p>
                </div>
            `;
        }).join('');
    }

    function openModal(id = null) {
        editingId = id;
        const nameInput = document.getElementById('category-name');

        if (id) {
            const cat = categories.find(c => c.id === id);
            if (cat) {
                document.getElementById('modal-title').textContent = 'Edit Category';
                nameInput.value = cat.name;
                selectedColor = cat.color;
                selectedIcon = ICONS.includes(cat.icon) ? cat.icon : 'bi-tag';
                document.getElementById('save-btn').textContent = 'Save';
            }
        } else {
            document.getElementById('modal-title').textContent = 'New Category';
            nameInput.value = '';
            selectedColor = '#6366f1';
            selectedIcon = 'bi-tag';
            document.getElementById('save-btn').textContent = 'Create';
        }

        renderIconPicker();
        renderColorPicker();
        document.getElementById('category-modal').classList.remove('hidden');
        nameInput.focus();
    }

    function closeModal() {
        document.getElementById('category-modal').classList.add('hidden');
        editingId = null;
    }

    async function saveCategory() {
        const name = document.getElementById('category-name').value.trim();
        if (!name) {
            Toast.warning('Missing name', 'Please enter a category name');
            return;
        }

        const saveBtn = document.getElementById('save-btn');
        const originalText = saveBtn.textContent;
        saveBtn.textContent = 'Saving...';
        saveBtn.disabled = true;

        try {
            const data = { name, color: selectedColor, icon: selectedIcon };

            if (editingId) {
                await Api.updateCategory(editingId, data);
                Toast.success('Category updated', `"${name}" has been saved`);
            } else {
                await Api.createCategory(data);
                Toast.success('Category created', `"${name}" has been added`);
            }

            closeModal();
            await loadCategories();
        } catch (error) {
            Toast.error('Error', error.message);
        } finally {
            saveBtn.textContent = originalText;
            saveBtn.disabled = false;
        }
    }

    function editCategory(id) { openModal(id); }

    async function deleteCategory(id) {
        const cat = categories.find(c => c.id === id);
        if (cat && confirm(`Delete "${cat.name}"? Notifications using this category will become uncategorized.`)) {
            try {
                await Api.deleteCategory(id);
                Toast.success('Category deleted', `"${cat.name}" has been removed`);
                await loadCategories();
            } catch (error) {
                Toast.error('Error', error.message);
            }
        }
    }

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