{% extends "base.html" %}
{% block content %}
<div class="p-4 md:p-6">
    <!-- Header -->
    <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-3 mb-6">
        <div>
            <h2 class="text-2xl font-bold text-gray-800 dark:text-gray-100">Plugins</h2>
            <p class="text-sm text-gray-500 mt-1">Manage event-driven plugins that extend platform functionality</p>
        </div>
        <button onclick="document.getElementById('upload-modal').classList.remove('hidden')"
                class="px-4 py-2 bg-indigo-500 hover:bg-indigo-600 text-white rounded-lg text-sm font-medium transition-colors flex items-center gap-2">
            <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="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"/></svg>
            Upload Plugin
        </button>
    </div>

    <!-- Search -->
    <div class="flex flex-col sm:flex-row gap-3 mb-6">
        <div class="relative">
            <svg class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-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="plugin-search" placeholder="Search plugins..." oninput="filterPlugins()"
                   class="w-full sm:w-64 pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-sm bg-white dark:bg-gray-800 dark:text-gray-100 focus:border-indigo-500 focus:outline-none focus:ring-2 focus:ring-indigo-500/10">
        </div>
    </div>

    <!-- Plugins Grid -->
    <div id="plugins-grid" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3">
        <!-- Populated by JS -->
    </div>

    <div id="empty-state" class="hidden text-center py-16 text-gray-400">
        <svg class="w-16 h-16 mx-auto mb-4 opacity-50" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M13 10V3L4 14h7v7l9-11h-7z"/></svg>
        <p class="text-lg font-medium">No plugins installed</p>
        <p class="text-sm mt-1">Upload a plugin zip package to get started</p>
    </div>
</div>

<!-- Upload Modal -->
<div id="upload-modal" class="hidden fixed inset-0 z-50 flex items-center justify-center">
    <div class="absolute inset-0 bg-black/50" onclick="closeUploadModal()"></div>
    <div class="relative bg-white dark:bg-gray-800 rounded-xl w-[90%] max-w-[480px] shadow-xl">
        <div class="p-6">
            <h3 class="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-4">Upload Plugin Package</h3>
            <div id="drop-zone"
                 class="border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-lg p-8 text-center cursor-pointer hover:border-indigo-400 hover:bg-indigo-50/50 dark:hover:bg-indigo-900/20 transition-colors"
                 onclick="document.getElementById('file-input').click()">
                <svg class="w-10 h-10 mx-auto mb-3 text-gray-400 dark:text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"/></svg>
                <p class="text-sm text-gray-600 dark:text-gray-300 font-medium">Click or drag & drop a .zip file</p>
                <p id="file-name" class="text-xs text-gray-400 dark:text-gray-500 mt-2"></p>
            </div>
            <input type="file" id="file-input" accept=".zip" class="hidden" onchange="onFileSelected(this)">
        </div>
        <div class="flex gap-3 justify-end px-6 pb-5">
            <button onclick="closeUploadModal()" class="px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-md text-sm font-medium text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors">Cancel</button>
            <button id="upload-btn" onclick="uploadPlugin()" disabled
                    class="px-4 py-2 bg-indigo-500 hover:bg-indigo-600 disabled:opacity-50 disabled:cursor-not-allowed text-white rounded-md text-sm font-medium transition-colors">
                Install
            </button>
        </div>
    </div>
</div>

<script>
let selectedFile = null;
let allPlugins = [];

async function loadPlugins() {
    const res = await fetch('/api/plugins');
    const data = await res.json();
    allPlugins = data.plugins || [];
    renderPlugins();
}

function filterPlugins() {
    renderPlugins();
}

function renderPlugins() {
    const query = document.getElementById('plugin-search').value.toLowerCase().trim();
    const grid = document.getElementById('plugins-grid');
    const empty = document.getElementById('empty-state');

    let filtered = allPlugins;
    if (query) {
        filtered = allPlugins.filter(p => {
            return (p.name || '').toLowerCase().includes(query) ||
                   (p.id || '').toLowerCase().includes(query) ||
                   (p.description || '').toLowerCase().includes(query) ||
                   (p.author || '').toLowerCase().includes(query);
        });
    }

    if (filtered.length === 0) {
        grid.innerHTML = '';
        empty.classList.remove('hidden');
        if (query) {
            empty.querySelector('p:first-child').textContent = 'No plugins found';
            empty.querySelector('p:last-child').textContent = 'Try a different search term.';
        } else {
            empty.querySelector('p:first-child').textContent = 'No plugins installed';
            empty.querySelector('p:last-child').textContent = 'Upload a plugin zip package to get started';
        }
        return;
    }
    empty.classList.add('hidden');

    grid.innerHTML = filtered.map(p => {
        const isSystem = p.is_system;
        const categoryBadge = isSystem
            ? '<span class="inline-flex items-center gap-1 text-xs font-medium text-purple-600 bg-purple-50 px-2 py-1 rounded-full"><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 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"/></svg>System</span>'
            : '';
        return `
        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-100 dark:border-gray-700 hover:shadow-md transition-shadow overflow-hidden">
            <div class="p-3">
                <div class="flex items-start gap-2">
                    <div class="flex-1 min-w-0 cursor-pointer" onclick="window.location.href='/plugins/${p.id}'">
                        <div class="flex items-center gap-2 flex-wrap">
                            <h3 class="font-semibold text-sm text-gray-800 dark:text-gray-100 truncate">${esc(p.name || p.id)}</h3>
                            ${categoryBadge}
                        </div>
                        <p class="text-xs text-gray-400 mt-0.5">v${esc(p.version || '?')} by ${esc(p.author || 'Unknown')}</p>
                        <p class="text-xs text-gray-500 line-clamp-2 mt-1">${esc(p.description || 'No description')}</p>
                    </div>
                    <div class="flex items-center gap-2 flex-shrink-0">
                        <span class="inline-flex items-center gap-1 text-xs font-medium text-amber-600 bg-amber-50 px-2 py-1 rounded-full">
                            <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="M13 10V3L4 14h7v7l9-11h-7z"/></svg>
                            ${(p.events || []).length} events
                        </span>
                        ${mkToggle({ checked: !!p.enabled, onChange: `togglePlugin('${p.id}', this.checked)`, extraClass: 'flex-shrink-0' })}
                    </div>
                </div>
            </div>
        </div>
    `}).join('');
}

async function togglePlugin(pluginId, enabled) {
    const res = await fetch(`/api/plugins/${pluginId}/toggle`, {
        method: 'PUT',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({enabled})
    });
    if (!res.ok) {
        const err = await res.json();
        alert(err.error || 'Failed to toggle plugin');
        loadPlugins();
        return;
    }
    const p = allPlugins.find(p => p.id === pluginId);
    if (p) p.enabled = enabled;
    renderPlugins();
}


function onFileSelected(input) {
    selectedFile = input.files[0];
    document.getElementById('file-name').textContent = selectedFile ? selectedFile.name : '';
    document.getElementById('upload-btn').disabled = !selectedFile;
}

async function uploadPlugin() {
    if (!selectedFile) return;
    const btn = document.getElementById('upload-btn');
    btn.disabled = true;
    btn.textContent = 'Installing...';

    const form = new FormData();
    form.append('file', selectedFile);

    try {
        const res = await fetch('/api/plugins/upload', {method: 'POST', body: form});
        const data = await res.json();
        if (!res.ok || data.error) {
            alert(data.error || 'Upload failed');
            return;
        }
        closeUploadModal();
        loadPlugins();
    } catch (e) {
        alert('Upload failed: ' + e.message);
    } finally {
        btn.disabled = false;
        btn.textContent = 'Install';
    }
}

function closeUploadModal() {
    document.getElementById('upload-modal').classList.add('hidden');
    selectedFile = null;
    document.getElementById('file-input').value = '';
    document.getElementById('file-name').textContent = '';
    document.getElementById('upload-btn').disabled = true;
}

// Drag & drop
const dropZone = document.getElementById('drop-zone');
if (dropZone) {
    ['dragenter', 'dragover'].forEach(e => dropZone.addEventListener(e, ev => {
        ev.preventDefault();
        dropZone.classList.add('border-indigo-400', 'bg-indigo-50/50');
    }));
    ['dragleave', 'drop'].forEach(e => dropZone.addEventListener(e, ev => {
        ev.preventDefault();
        dropZone.classList.remove('border-indigo-400', 'bg-indigo-50/50');
    }));
    dropZone.addEventListener('drop', ev => {
        const file = ev.dataTransfer.files[0];
        if (file && file.name.endsWith('.zip')) {
            selectedFile = file;
            document.getElementById('file-name').textContent = file.name;
            document.getElementById('upload-btn').disabled = false;
        }
    });
}

function esc(s) {
    const d = document.createElement('div');
    d.textContent = s || '';
    return d.innerHTML;
}

loadPlugins();
</script>
{% endblock %}
