<?php

declare(strict_types=1);

require_once __DIR__ . '/../src/secure_workspace.php';
require_once __DIR__ . '/../src/Permissions/require_permission.php';
require_once __DIR__ . '/../src/Projects/ProjectManager.php';
require_once __DIR__ . '/../src/Projects/TaskManager.php';
require_once __DIR__ . '/navigation.php';

requirePermission('projects_view');

// Theme (match members/settings pattern)
$currentTheme = $_GET['theme'] ?? ($_SESSION['theme_preference'] ?? 'dark');
$currentTheme = in_array($currentTheme, ['dark', 'light'], true) ? $currentTheme : 'dark';

$canCreate = hasPermission('projects_create');
$canEdit = hasPermission('projects_edit');
$canManage = hasPermission('projects_manage');
$canCreateTask = hasPermission('tasks_create');
$canEditTask = hasPermission('tasks_edit');

$company = WorkspaceSecurity::getCurrentWorkspace();
$companyId = (int)($company['id'] ?? 0);
$userId = (int)($user['id'] ?? 0);

$workspaceSlugValue = $company['username'] ?? ($company['subdomain'] ?? ($companyId ? (string) $companyId : ''));
$workspaceQuery = $workspaceSlugValue !== '' ? '?workspace=' . urlencode((string) $workspaceSlugValue) : '';
$workspaceQueryAmp = $workspaceSlugValue !== '' ? '&workspace=' . urlencode((string) $workspaceSlugValue) : '';
$workspaceDisplayName = $company['name'] ?? 'Workspace';

// Check if viewing a specific project
$selectedProjectId = (int)($_GET['project'] ?? 0);

// Get filters
$filters = [];
$selectedCategory = $_GET['category'] ?? 'all';
if ($selectedCategory !== 'all' && is_numeric($selectedCategory)) {
    $filters['category_id'] = (int)$selectedCategory;
}
if (!empty($_GET['status'])) {
    $filters['status'] = $_GET['status'];
}
if (!empty($_GET['priority'])) {
    $filters['priority'] = $_GET['priority'];
}
if (!empty($_GET['client_id'])) {
    $filters['client_id'] = (int) $_GET['client_id'];
}
if (!empty($_GET['search'])) {
    $filters['search'] = $_GET['search'];
}

// Get data
$projects = ProjectManager::getProjects($companyId, $filters);
$categories = ProjectManager::getCategories($companyId);
$stats = ProjectManager::getProjectStats($companyId);

// Extract individual stats for display
$projectCount = $stats['total'] ?? 0;
$activeProjectCount = $stats['active'] ?? 0;

$categoryIconChoices = [
    'folder' => ['label' => 'Folder', 'class' => 'fas fa-folder'],
    'bolt' => ['label' => 'Bolt', 'class' => 'fas fa-bolt'],
    'chart-line' => ['label' => 'Growth', 'class' => 'fas fa-chart-line'],
    'bullseye' => ['label' => 'Target', 'class' => 'fas fa-bullseye'],
    'pen-nib' => ['label' => 'Design', 'class' => 'fas fa-pen-nib'],
    'lightbulb' => ['label' => 'Idea', 'class' => 'fas fa-lightbulb'],
    'rocket' => ['label' => 'Launch', 'class' => 'fas fa-rocket'],
    'gear' => ['label' => 'Ops', 'class' => 'fas fa-gear'],
    'file-alt' => ['label' => 'Docs', 'class' => 'fas fa-file-alt'],
    'bullhorn' => ['label' => 'Marketing', 'class' => 'fas fa-bullhorn'],
    'shopping-cart' => ['label' => 'Ecommerce', 'class' => 'fas fa-shopping-cart'],
    'money-bill' => ['label' => 'Finance', 'class' => 'fas fa-money-bill-wave'],
    'bug' => ['label' => 'Bugs', 'class' => 'fas fa-bug'],
    'tasks' => ['label' => 'Tasks', 'class' => 'fas fa-tasks'],
    'users' => ['label' => 'Team', 'class' => 'fas fa-users'],
    'comments' => ['label' => 'Feedback', 'class' => 'fas fa-comments'],
    'star' => ['label' => 'VIP', 'class' => 'fas fa-star'],
    'wrench' => ['label' => 'Maintenance', 'class' => 'fas fa-wrench'],
    'database' => ['label' => 'Data', 'class' => 'fas fa-database'],
    'cloud' => ['label' => 'Cloud', 'class' => 'fas fa-cloud'],
    'shield-alt' => ['label' => 'Security', 'class' => 'fas fa-shield-alt'],
    'bell' => ['label' => 'Alerts', 'class' => 'fas fa-bell'],
    'project-diagram' => ['label' => 'Architecture', 'class' => 'fas fa-project-diagram'],
    'clipboard-check' => ['label' => 'QA', 'class' => 'fas fa-clipboard-check'],
];

$resolveCategoryIcon = static function (?string $iconKey): string {
    $iconKey = trim((string)$iconKey);
    if ($iconKey === '') {
        return 'fas fa-folder';
    }

    $prefixes = ['fas ', 'far ', 'fal ', 'fad ', 'fab '];
    foreach ($prefixes as $prefix) {
        if (str_starts_with($iconKey, $prefix)) {
            return $iconKey;
        }
    }

    if (str_starts_with($iconKey, 'fa-')) {
        return 'fas ' . $iconKey;
    }

    return 'fas fa-' . $iconKey;
};

$categoriesById = [];
foreach ($categories as $category) {
    $categoriesById[$category['id']] = $category;
}

// If viewing a project, get its details
$selectedProject = null;
$tasks = [];
$statuses = [];
if ($selectedProjectId) {
    $selectedProject = ProjectManager::getProject($selectedProjectId, $companyId);
    if ($selectedProject) {
        $tasks = TaskManager::getTasks($selectedProjectId, $companyId);
        $statuses = TaskManager::getStatuses($companyId);
    }
}

// Get clients and members
$pdo = getPDO();
$clientStmt = $pdo->prepare('SELECT id, name FROM clients WHERE company_id = ? ORDER BY name ASC');
$clientStmt->execute([$companyId]);
$clients = $clientStmt->fetchAll(PDO::FETCH_ASSOC) ?: [];

// Determine currently selected client filter (for label in UI)
$currentClientId = $_GET['client_id'] ?? '';
$currentClientName = '';
if ($currentClientId !== '') {
    foreach ($clients as $client) {
        if ((string) $client['id'] === (string) $currentClientId) {
            $currentClientName = $client['name'];
            break;
        }
    }
}

$memberStmt = $pdo->prepare('
    SELECT u.id, u.name, u.email
    FROM users u
    JOIN user_company_access uca ON u.id = uca.user_id
    WHERE uca.company_id = ?
    ORDER BY u.name ASC
');
$memberStmt->execute([$companyId]);
$members = $memberStmt->fetchAll(PDO::FETCH_ASSOC) ?: [];

$workspace = $company['username'] ?? $company['subdomain'] ?? '';

// Group tasks by status
$tasksByStatus = [];
if ($selectedProject) {
    foreach ($statuses as $status) {
        $tasksByStatus[$status['id']] = [
            'status' => $status,
            'tasks' => []
        ];
    }
    foreach ($tasks as $task) {
        $statusId = $task['status_id'] ?? 0;
        if (isset($tasksByStatus[$statusId])) {
            $tasksByStatus[$statusId]['tasks'][] = $task;
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en" data-theme="<?= htmlspecialchars($currentTheme) ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Projects · <?= htmlspecialchars($workspaceDisplayName) ?></title>
    <link rel="icon" type="image/png" href="/assets/favicon.png">
    <link rel="stylesheet" href="/assets/styles/app.build.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js"></script>
    <script>
        (function() {
            var saved = localStorage.getItem('theme') || '<?= $currentTheme ?>';
            document.documentElement.setAttribute('data-theme', saved);
        })();
    </script>
</head>
<body class="projects-page">
<?php require_once __DIR__ . '/navigation.php'; renderNavigationNew('Projects', $currentTheme); ?>

<div class="main-container">
    <?php
    require_once __DIR__ . '/components/headers/page-header.php';
    $actions = [];
    if ($canManage) {
        $actions[] = [
            'label' => 'Categories',
            'type' => 'secondary',
            'id' => 'projects-categories-btn',
            'icon' => 'M4 5a1 1 0 011-1h14a1 1 0 011 1v2a1 1 0 01-1 1H5a1 1 0 01-1-1V5zM4 13a1 1 0 011-1h6a1 1 0 011 1v6a1 1 0 01-1 1H5a1 1 0 01-1-1v-6zM16 13a1 1 0 011-1h2a1 1 0 011 1v6a1 1 0 01-1 1h-2a1 1 0 01-1-1v-6z',
        ];
    }
    $actions[] = [
        'label' => 'Calendar',
        'url' => '/projects-calendar.php',
        'type' => 'secondary',
        'icon' => 'M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z',
        'append_workspace' => true,
    ];
    if ($canCreate) {
        $actions[] = [
            'label' => 'Create project',
            'type' => 'primary',
            'id' => 'projects-create-btn',
            'icon' => 'M12 4v16m8-8H4',
        ];
    }
    renderPageHeader(
        breadcrumbs: [
            ['label' => 'Home', 'url' => '/index.php', 'icon' => 'M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6'],
        ],
        currentPage: 'Projects',
        actions: $actions,
        workspaceQuery: $workspaceQuery
    );
    ?>

    <div class="dash-container">
        <?php if (!$selectedProject): ?>
            <div class="dash-section">
                <div class="projects-stats-grid">
                    <div class="stat-card">
                        <p class="stat-label">Total projects</p>
                        <p class="stat-value"><?= $stats['total'] ?? 0 ?></p>
                    </div>
                    <div class="stat-card">
                        <p class="stat-label">Active</p>
                        <p class="stat-value"><?= $stats['active'] ?? 0 ?></p>
                    </div>
                    <div class="stat-card">
                        <p class="stat-label">Completed</p>
                        <p class="stat-value"><?= $stats['completed'] ?? 0 ?></p>
                    </div>
                    <div class="stat-card">
                        <p class="stat-label">Overdue</p>
                        <p class="stat-value"><?= $stats['overdue'] ?? 0 ?></p>
                    </div>
                </div>
            </div>

            <div class="dash-section">
                <!-- Status Pills -->
                <?php $currentStatus = $filters['status'] ?? ''; ?>
                <div class="projects-status-pills">
                    <?php
                        $statusPills = [
                            '' => ['label' => 'All', 'icon' => 'fas fa-layer-group'],
                            'active' => ['label' => 'Active', 'icon' => 'fas fa-play'],
                            'on_hold' => ['label' => 'On hold', 'icon' => 'fas fa-pause'],
                            'completed' => ['label' => 'Completed', 'icon' => 'fas fa-check'],
                        ];
                    ?>
                    <?php foreach ($statusPills as $value => $meta): ?>
                        <?php
                            $isActive = $currentStatus === $value || ($value === '' && $currentStatus === '');
                            $pillClasses = $isActive ? 'status-chip active' : 'status-chip inactive';
                        ?>
                        <button type="button" onclick="setStatusQuickFilter('<?= $value ?>')" class="<?= $pillClasses ?>">
                            <i class="<?= $meta['icon'] ?>"></i>
                            <span><?= $meta['label'] ?></span>
                        </button>
                    <?php endforeach; ?>
                </div>
            </div>

                    <!-- Filters -->
                    <?php
                        $categoriesById = [];
                        foreach ($categories as $category) {
                            $categoriesById[$category['id']] = $category;
                        }
                        $priorityOptions = [
                            '' => ['label' => 'All priorities', 'color' => 'bg-gray-400', 'icon' => 'fas fa-slash'],
                            'low' => ['label' => 'Low', 'color' => 'bg-gray-500', 'icon' => 'fas fa-arrow-down'],
                            'medium' => ['label' => 'Medium', 'color' => 'bg-amber-500', 'icon' => 'fas fa-minus'],
                            'high' => ['label' => 'High', 'color' => 'bg-orange-500', 'icon' => 'fas fa-arrow-up'],
                            'urgent' => ['label' => 'Urgent', 'color' => 'bg-orange-500', 'icon' => 'fas fa-exclamation-triangle'],
                        ];
                        $statusOptions = [
                            '' => ['label' => 'All statuses', 'color' => 'bg-gray-400', 'icon' => 'fas fa-layer-group'],
                            'planning' => ['label' => 'Planning', 'color' => 'bg-blue-400', 'icon' => 'fas fa-clipboard-list'],
                            'active' => ['label' => 'Active', 'color' => 'bg-blue-500', 'icon' => 'fas fa-play'],
                            'on_hold' => ['label' => 'On hold', 'color' => 'bg-blue-400', 'icon' => 'fas fa-pause'],
                            'completed' => ['label' => 'Completed', 'color' => 'bg-emerald-500', 'icon' => 'fas fa-check'],
                        ];
                        $currentPriorityFilter = $_GET['priority'] ?? '';
                        $currentPriorityMeta = $priorityOptions[$currentPriorityFilter] ?? $priorityOptions[''];
                        $currentStatusFilter = $_GET['status'] ?? '';
                        $currentStatusMeta = $statusOptions[$currentStatusFilter] ?? $statusOptions[''];
                        $selectedCategory = $selectedCategory ?? 'all';
                        $currentCategoryLabel = $selectedCategory === 'all'
                            ? 'All categories'
                            : ($categoriesById[$selectedCategory]['name'] ?? 'All categories');
                        $currentCategoryIconClass = $selectedCategory === 'all'
                            ? 'fas fa-layer-group'
                            : $resolveCategoryIcon($categoriesById[$selectedCategory]['icon'] ?? 'folder');
                    ?>
                    <div class="bg-neutral-900/50 border border-neutral-800 rounded-lg p-3">
                        <div class="flex flex-wrap items-end gap-3">
                            <!-- Category -->
                            <div class="flex-1 min-w-[190px]">
                                <label class="block text-xs font-medium text-neutral-400 mb-1">Category</label>
                                <div class="relative">
                                    <input type="hidden" id="categoryFilter" value="<?= htmlspecialchars($selectedCategory) ?>">
                                    <button type="button" data-toggle="category-menu"
                                            class="w-full inline-flex items-center justify-between rounded border border-neutral-800 bg-neutral-900 px-3 py-2 text-xs text-neutral-100 focus:outline-none focus:ring-2 focus:ring-neutral-700 transition-all duration-150">
                                        <span class="inline-flex items-center gap-2">
                                            <span id="filterCategoryIconWrap" class="flex h-4 w-4 items-center justify-center rounded-full bg-neutral-700 text-neutral-300 text-[9px]">
                                                <i id="filterCategoryIcon" class="<?= $currentCategoryIconClass ?? 'fas fa-layer-group' ?>"></i>
                                            </span>
                                            <span id="filterCategoryLabel" class="truncate text-neutral-100">
                                                <?= htmlspecialchars($currentCategoryLabel ?? 'All categories') ?>
                                            </span>
                                        </span>
                                        <span class="ml-2 flex items-center text-neutral-400">
                                            <i class="fas fa-chevron-down text-[10px]"></i>
                                        </span>
                                    </button>
                                    <div id="filterCategoryMenu" class="hidden fixed z-50 rounded border border-neutral-800 bg-neutral-950 shadow-lg overflow-visible max-h-60 overflow-y-auto" style="top: auto; left: auto; min-width: 200px;">
                                        <button type="button" data-value="all" data-label="All categories" data-color="bg-neutral-700" data-icon="fas fa-layer-group"
                                                class="filter-category-option w-full text-left px-3 py-2 hover:bg-neutral-800 text-neutral-100 text-xs flex items-center gap-2">
                                            <span class="flex h-4 w-4 items-center justify-center rounded-full bg-neutral-700 text-neutral-300 text-[9px]">
                                                <i class="fas fa-layer-group"></i>
                                            </span>
                                            <span class="truncate">All categories</span>
                                        </button>
                                        <?php foreach ($categories as $category): ?>
                                            <?php $catIconClass = $resolveCategoryIcon($category['icon'] ?? 'folder'); ?>
                                            <button type="button" data-value="<?= $category['id'] ?>" data-label="<?= htmlspecialchars($category['name']) ?>"
                                                    data-icon="<?= htmlspecialchars($catIconClass, ENT_QUOTES) ?>" data-color="<?= $category['color'] ?? 'bg-gray-500' ?>"
                                                    class="filter-category-option w-full text-left px-3 py-2 hover:bg-neutral-800 text-neutral-100 text-xs flex items-center gap-2">
                                                <span class="flex h-4 w-4 items-center justify-center rounded-full <?= $category['color'] ?? 'bg-gray-500' ?> text-neutral-300 text-[9px]">
                                                    <i class="<?= htmlspecialchars($catIconClass, ENT_QUOTES) ?>"></i>
                                                </span>
                                                <span class="truncate"><?= htmlspecialchars($category['name']) ?></span>
                                            </button>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            </div>

                            <!-- Status -->
                            <div class="min-w-[160px]">
                                <label class="block text-xs font-medium text-neutral-400 mb-1">Status</label>
                                <div class="relative">
                                    <input type="hidden" id="statusFilter" value="<?= htmlspecialchars($currentStatusFilter ?? '') ?>">
                                    <button type="button" data-toggle="status-menu"
                                            class="w-full inline-flex items-center justify-between rounded border border-neutral-800 bg-neutral-900 px-3 py-2 text-xs text-neutral-100 focus:outline-none focus:ring-2 focus:ring-neutral-700 transition-all duration-150">
                                        <span class="inline-flex items-center gap-2">
                                            <span id="filterStatusIconWrap" class="flex h-4 w-4 items-center justify-center rounded-full text-neutral-300 <?= $currentStatusMeta['color'] ?? 'bg-gray-400' ?>">
                                                <i id="filterStatusIcon" class="<?= $currentStatusMeta['icon'] ?? 'fas fa-layer-group' ?> text-[9px]"></i>
                                            </span>
                                            <span id="filterStatusLabel" class="truncate text-neutral-100">
                                                <?= htmlspecialchars($currentStatusMeta['label'] ?? 'All statuses') ?>
                                            </span>
                                        </span>
                                        <span class="ml-2 flex items-center text-neutral-400">
                                            <i class="fas fa-chevron-down text-[10px]"></i>
                                        </span>
                                    </button>
                                    <div id="filterStatusMenu" class="hidden fixed z-50 rounded border border-neutral-800 bg-neutral-950 shadow-lg overflow-visible max-h-60 overflow-y-auto" style="top: auto; left: auto; min-width: 200px;">
                                        <?php foreach ($statusOptions as $value => $meta): ?>
                                            <button type="button" data-value="<?= $value ?>" data-label="<?= $meta['label'] ?>" data-color="<?= $meta['color'] ?>" data-icon="<?= $meta['icon'] ?>"
                                                    class="filter-status-option w-full text-left px-3 py-2 hover:bg-neutral-800 text-neutral-100 text-xs flex items-center gap-2">
                                                <span class="flex h-4 w-4 items-center justify-center rounded-full text-neutral-300 <?= $meta['color'] ?>">
                                                    <i class="<?= $meta['icon'] ?> text-[9px]"></i>
                                                </span>
                                                <span class="truncate"><?= $meta['label'] ?></span>
                                            </button>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            </div>

                            <!-- Priority -->
                            <div class="min-w-[160px]">
                                <label class="block text-xs font-medium text-neutral-400 mb-1">Priority</label>
                                <div class="relative">
                                    <input type="hidden" id="priorityFilter" value="<?= htmlspecialchars($currentPriorityFilter ?? '') ?>">
                                    <button type="button" data-toggle="priority-menu"
                                            class="w-full inline-flex items-center justify-between rounded border border-neutral-800 bg-neutral-900 px-3 py-2 text-xs text-neutral-100 focus:outline-none focus:ring-2 focus:ring-neutral-700 transition-all duration-150">
                                        <span class="inline-flex items-center gap-2">
                                            <span id="filterPriorityIconWrap" class="flex h-4 w-4 items-center justify-center rounded-full text-neutral-300 <?= $currentPriorityMeta['color'] ?? 'bg-amber-500' ?>">
                                                <i id="filterPriorityIcon" class="<?= $currentPriorityMeta['icon'] ?? 'fas fa-minus' ?> text-[9px]"></i>
                                            </span>
                                            <span id="filterPriorityLabel" class="truncate text-neutral-100">
                                                <?= htmlspecialchars($currentPriorityMeta['label'] ?? 'All priorities') ?>
                                            </span>
                                        </span>
                                        <span class="ml-2 flex items-center text-neutral-400">
                                            <i class="fas fa-chevron-down text-[10px]"></i>
                                        </span>
                                    </button>
                                    <div id="filterPriorityMenu" class="hidden fixed z-50 rounded border border-neutral-800 bg-neutral-950 shadow-lg overflow-visible max-h-60 overflow-y-auto" style="top: auto; left: auto; min-width: 200px;">
                                        <?php foreach ($priorityOptions as $value => $meta): ?>
                                            <button type="button" data-value="<?= $value ?>" data-label="<?= $meta['label'] ?>" data-level="<?= $value === '' ? 'all' : $value ?>" data-color="<?= $meta['color'] ?>" data-icon="<?= $meta['icon'] ?>"
                                                    class="filter-priority-option w-full text-left px-3 py-2 hover:bg-neutral-800 text-neutral-100 text-xs flex items-center gap-2">
                                                <span class="flex h-4 w-4 items-center justify-center rounded-full text-neutral-300 <?= $meta['color'] ?>">
                                                    <i class="<?= $meta['icon'] ?> text-[9px]"></i>
                                                </span>
                                                <span class="truncate"><?= $meta['label'] ?></span>
                                            </button>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            </div>

                            <!-- Client -->
                            <div class="flex-1 min-w-[220px]">
                                <label class="block text-xs font-medium text-neutral-400 mb-1">Client</label>
                                <div class="relative">
                                    <input type="hidden" id="clientFilter" value="<?= htmlspecialchars($currentClientId ?? '') ?>">
                                    <button type="button" onclick="toggleClientFilterMenu()"
                                            class="w-full inline-flex items-center justify-between rounded border border-neutral-800 bg-neutral-900 px-3 py-2 text-xs text-neutral-100 focus:outline-none focus:ring-2 focus:ring-neutral-700 transition-all duration-150">
                                        <span id="clientFilterLabel" class="truncate text-left">
                                            <?= $currentClientId !== '' && $currentClientName !== '' ? htmlspecialchars($currentClientName) : 'All clients' ?>
                                        </span>
                                        <span class="ml-2 flex items-center text-neutral-400">
                                            <i class="fas fa-chevron-down text-[10px]"></i>
                                        </span>
                                    </button>

                                    <div class="dropdown-container">
                                        <div id="clientFilterMenu" class="hidden fixed z-50 rounded border border-neutral-800 bg-neutral-950 shadow-lg overflow-visible max-h-60 overflow-y-auto" style="top: auto; left: auto; min-width: 200px;">
                                            <div class="p-2 border-b border-neutral-800">
                                                <div class="relative">
                                                    <input type="text" id="clientSearchInput" placeholder="Search clients..."
                                                           class="w-full rounded border border-neutral-800 bg-neutral-900 px-3 py-1.5 text-xs text-neutral-100 placeholder:text-neutral-500 focus:outline-none focus:ring-1 focus:ring-neutral-700">
                                                    <span class="pointer-events-none absolute inset-y-0 right-3 flex items-center text-neutral-400">
                                                        <i class="fas fa-search text-[10px]"></i>
                                                    </span>
                                                </div>
                                            </div>
                                            <div id="clientFilterMenuList" class="py-1 text-xs sm:text-sm max-h-48 overflow-y-auto">
                                            <button type="button" onclick="selectClientFilter('', 'All clients')"
                                                    class="w-full text-left px-3 py-2 hover:bg-neutral-800 text-neutral-100 flex items-center gap-2">
                                                <span class="flex h-4 w-4 items-center justify-center rounded-full bg-neutral-800 text-neutral-400 text-[10px]">
                                                    <i class="fas fa-users"></i>
                                                </span>
                                                <span>All clients</span>
                                            </button>
                                            <?php foreach ($clients as $client): ?>
                                                <button type="button"
                                                        class="client-option w-full text-left px-3 py-2 hover:bg-neutral-800 text-neutral-100 flex items-center gap-2"
                                                        data-value="<?= $client['id'] ?>">
                                                    <span class="flex h-4 w-4 items-center justify-center rounded-full bg-neutral-800 text-neutral-400 text-[10px]">
                                                        <?= strtoupper(substr($client['name'], 0, 1)) ?>
                                                    </span>
                                                    <span class="truncate"><?= htmlspecialchars($client['name']) ?></span>
                                                </button>
                                            <?php endforeach; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Search -->
                        <div class="flex-1 min-w-[220px]">
                            <label class="block text-xs font-medium text-neutral-400 mb-1">Search</label>
                            <input type="text" id="searchInput" placeholder="Search projects..."
                                   value="<?= htmlspecialchars($_GET['search'] ?? '') ?>"
                                   class="w-full rounded border border-neutral-800 bg-neutral-900 px-3 py-2 text-xs text-neutral-100 placeholder:text-neutral-500 focus:outline-none focus:ring-2 focus:ring-neutral-700 transition-all duration-150">
                        </div>

                        <div class="flex items-end gap-2 ml-auto">
                            <button type="button" onclick="clearFilters()"
                                    class="inline-flex items-center gap-1 rounded border border-neutral-800 bg-neutral-900 px-3 py-2 text-xs font-medium text-neutral-400 hover:text-neutral-100 hover:bg-neutral-800 transition-all duration-150 sm:px-3 sm:py-2 px-4 py-2.5"
                                    title="Clear filters">
                                <i class="fas fa-rotate-right text-[11px] sm:text-[11px] text-[13px]"></i>
                                <span class="hidden sm:inline">Reset</span>
                            </button>
                        </div>
                    </div>

                    <!-- Projects List -->
                    <div class="mt-6">
                    <?php if (empty($projects)): ?>
                        <div class="flex flex-col items-center justify-center py-12">
                            <div class="w-16 h-16 rounded-full bg-neutral-800 flex items-center justify-center">
                                <svg class="w-8 h-8 text-neutral-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z"></path>
                                </svg>
                            </div>
                            <h3 class="text-sm font-medium text-neutral-50">No projects yet</h3>
                            <p class="text-xs text-neutral-400 mt-2">Create your first project to get started</p>
                            <?php if ($canCreate): ?>
                                <button onclick="showCreateProject()"
                                        class="btn-primary" style="margin-top: 12px;">
                                    <i class="fas fa-plus" style="margin-right: 8px;"></i>Create project
                                </button>
                            <?php endif; ?>
                        </div>
                    <?php else: ?>
                        <div class="grid gap-6 grid-cols-1">
                            <?php foreach ($projects as $project):
                                $taskCount = isset($project['task_count']) ? (int)$project['task_count'] : 0;
                                $completedCount = isset($project['completed_task_count']) ? (int)$project['completed_task_count'] : 0;
                                $progress = $taskCount > 0
                                    ? (int) round(($completedCount / $taskCount) * 100)
                                    : 0;
                            ?>
                                <div class="project-card-fade group relative overflow-hidden rounded border border-neutral-800 bg-neutral-900/50 p-3 transition-all duration-300 hover:-translate-y-0.5 hover:border-neutral-700 hover:shadow-xl/10">
                                    <div class="absolute inset-x-0 top-0 h-px bg-gradient-to-r from-neutral-700/20 via-neutral-600/40 to-neutral-700/20 opacity-0 group-hover:opacity-100 transition-opacity"></div>
                                    <div class="flex items-start justify-between mb-2 gap-4">
                                        <div class="flex-1">
                                            <div class="flex items-center gap-2 mb-2">
                                                <?php if ($project['category_name']): ?>
                                                    <span class="inline-flex items-center gap-1 px-2 py-0.5 rounded text-[11px] font-medium bg-neutral-800 text-neutral-200">
                                                        <i class="fas fa-<?= htmlspecialchars($project['category_icon'] ?? 'folder') ?>"></i>
                                                        <?= htmlspecialchars($project['category_name']) ?>
                                                    </span>
                                                <?php endif; ?>
                                                <?php
                                                    $statusClass = 'bg-neutral-800 text-neutral-200';
                                                    if ($project['status'] === 'active') {
                                                        $statusClass = 'bg-green-500/10 text-green-400';
                                                    } elseif ($project['status'] === 'completed') {
                                                        $statusClass = 'bg-blue-500/10 text-blue-400';
                                                    } elseif ($project['status'] === 'on_hold') {
                                                        $statusClass = 'bg-amber-500/10 text-amber-400';
                                                    }
                                                ?>
                                                <span class="inline-flex items-center gap-1 rounded px-2 py-0.5 text-[11px] font-medium <?= $statusClass ?>">
                                                    <span class="h-1.5 w-1.5 rounded-full bg-current opacity-70"></span>
                                                    <?= ucfirst($project['status']) ?>
                                                </span>
                                            </div>
                                            <h3 class="text-sm font-semibold text-neutral-50 mb-1 tracking-tight">
                                                <a href="?workspace=<?= urlencode($workspace) ?>&project=<?= $project['id'] ?>" class="hover:text-neutral-200 transition-colors">
                                                    <?= htmlspecialchars($project['name']) ?>
                                                </a>
                                            </h3>
                                            <?php if ($project['description']): ?>
                                                <p class="text-xs text-neutral-400 line-clamp-2 mb-2">
                                                    <?= htmlspecialchars($project['description']) ?>
                                                </p>
                                            <?php endif; ?>
                                            <?php if ($project['client_name'] || $project['due_date']): ?>
                                                <div class="flex items-center gap-3 text-xs text-neutral-500">
                                                    <?php if ($project['client_name']): ?>
                                                        <div class="inline-flex items-center gap-1 rounded bg-neutral-800 px-2 py-0.5">
                                                            <i class="fas fa-user text-[11px]"></i>
                                                            <span><?= htmlspecialchars($project['client_name']) ?></span>
                                                        </div>
                                                    <?php endif; ?>
                                                    <?php if ($project['due_date']): ?>
                                                        <div class="inline-flex items-center gap-1 rounded bg-amber-500/10 px-2 py-0.5 text-[11px] text-amber-400">
                                                            <i class="fas fa-calendar-day text-[11px]"></i>
                                                            <span>Due <?= date('M j', strtotime($project['due_date'])) ?></span>
                                                        </div>
                                                    <?php endif; ?>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                        <div class="flex flex-col items-end gap-2 ml-2 text-xs text-neutral-500">
                                            <a href="?workspace=<?= urlencode($workspace) ?>&project=<?= $project['id'] ?>"
                                               class="mt-auto inline-flex items-center gap-1 rounded border border-neutral-700 bg-neutral-800 px-2 py-1 text-xs font-medium text-neutral-300 hover:bg-neutral-700 hover:border-neutral-600 transition-colors">
                                                <span>Open board</span>
                                                <i class="fas fa-arrow-right text-[11px]"></i>
                                            </a>
                                        </div>
                                    </div>

                                    <div class="mt-2 flex flex-col gap-2">
                                        <div class="flex items-center justify-between text-[11px] text-neutral-500">
                                            <div class="flex items-center gap-3">
                                                <span class="inline-flex items-center gap-1">
                                                    <i class="fas fa-tasks text-[11px]"></i>
                                                    <span><?= $taskCount ?> tasks</span>
                                                </span>
                                                <span class="inline-flex items-center gap-1">
                                                    <i class="fas fa-check-circle text-[11px]"></i>
                                                    <span><?= $completedCount ?> done</span>
                                                </span>
                                            </div>
                                            <span class="font-medium text-neutral-400"><?= $progress ?>%</span>
                                        </div>
                                        <div class="h-1.5 rounded-full bg-neutral-800 overflow-hidden">
                                            <div class="h-full rounded-full bg-gradient-to-r from-blue-400 via-sky-500 to-blue-600 transition-all" style="width: <?= $progress ?>%"></div>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>

                    </div>

                <?php else: ?>
                    <!-- Project Detail View with Tasks -->
                    <!-- Back Button -->
                    <div class="mb-1">
                        <a href="?workspace=<?= urlencode($workspace) ?>" class="inline-flex items-center gap-2 px-2 py-1.5 text-xs text-neutral-400 hover:text-neutral-100 hover:bg-neutral-800 rounded transition-colors">
                            <i class="fas fa-arrow-left"></i>
                            <span>Back to Projects</span>
                        </a>
                    </div>

                    <!-- Project Header -->
                    <?php
                        $selectedTaskCount = isset($selectedProject['task_count']) ? (int)$selectedProject['task_count'] : 0;
                        $selectedCompletedCount = isset($selectedProject['completed_task_count']) ? (int)$selectedProject['completed_task_count'] : 0;
                        $selectedProgress = $selectedTaskCount > 0
                            ? (int) round(($selectedCompletedCount / $selectedTaskCount) * 100)
                            : 0;
                    ?>
                    <div class="bg-neutral-900/50 border border-neutral-800 rounded-lg p-3 mt-2">
                        <!-- Project Title Section -->
                            <div class="flex items-start justify-between mb-2 gap-4">
                                <div class="flex-1">
                                    <div class="flex items-center gap-2 mb-2">
                                        <?php if ($selectedProject && $selectedProject['category_name']): ?>
                                            <span class="inline-flex items-center gap-1 px-2 py-0.5 rounded text-[11px] font-medium bg-neutral-800 text-neutral-200">
                                                <i class="fas fa-<?= htmlspecialchars($selectedProject['category_icon'] ?? 'folder') ?>"></i>
                                                <?= htmlspecialchars($selectedProject['category_name']) ?>
                                            </span>
                                        <?php endif; ?>
                                        <?php
                                            $statusClass = 'bg-neutral-800 text-neutral-200';
                                            if ($selectedProject['status'] === 'active') {
                                                $statusClass = 'bg-green-500/10 text-green-400';
                                            } elseif ($selectedProject['status'] === 'completed') {
                                                $statusClass = 'bg-blue-500/10 text-blue-400';
                                            } elseif ($selectedProject['status'] === 'on_hold') {
                                                $statusClass = 'bg-yellow-500/10 text-yellow-400';
                                            }
                                        ?>
                                        <span class="inline-flex items-center gap-1 px-2 py-0.5 rounded text-[11px] font-medium <?= $statusClass ?>">
                                            <?= htmlspecialchars(ucfirst(str_replace('_', ' ', $selectedProject['status'] ?? 'draft'))) ?>
                                        </span>
                                    </div>
                                    <h3 class="text-sm font-medium text-neutral-50 leading-tight">
                                        <?= $selectedProject ? htmlspecialchars($selectedProject['name']) : 'Project Not Found' ?>
                                    </h3>
                                </div>
                                <div class="flex items-center gap-2">
                                    <button class="p-1.5 hover:bg-neutral-800 rounded text-neutral-400 transition-colors">
                                        <i class="fas fa-ellipsis-h text-xs"></i>
                                    </button>
                                </div>
                            </div>

                            <!-- Description -->
                            <?php if ($selectedProject && !empty($selectedProject['description'])): ?>
                                <p class="text-xs text-neutral-400 mb-2 line-clamp-2">
                                    <?= htmlspecialchars($selectedProject['description']) ?>
                                </p>
                            <?php endif; ?>

                            <!-- Project Stats - Compact Grid -->
                            <div class="flex items-center justify-between pt-3 border-t border-neutral-800 text-xs">
                                <div>
                                    <p class="text-neutral-500">Tasks</p>
                                    <p class="font-medium text-neutral-50" id="project-task-count"><?= $selectedTaskCount ?></p>
                                </div>
                                <div>
                                    <p class="text-neutral-500">Progress</p>
                                    <p class="font-medium text-neutral-50" id="project-progress"><?= $selectedProgress ?>%</p>
                                </div>
                                <div>
                                    <p class="text-neutral-500">Due</p>
                                    <p class="font-medium text-neutral-50">
                                        <?= $selectedProject && $selectedProject['due_date'] ? date('M j', strtotime($selectedProject['due_date'])) : 'No date' ?>
                                    </p>
                                </div>
                                <button type="button" onclick="showEditProject(<?= (int) $selectedProjectId ?>)" class="btn-secondary">
                                    <i class="fas fa-edit mr-1"></i>
                                    Edit Project
                                </button>
                            </div>
                        </div>

                        <!-- Task Board -->
                        <div class="mt-4 -mx-3 md:-mx-6 px-3 md:px-6">
                            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3">
                            <?php foreach ($tasksByStatus as $statusGroup):
                                $status = $statusGroup['status'];
                                $statusTasks = $statusGroup['tasks'];
                            ?>
                                <div class="w-full">
                                    <!-- Column Header -->
                                    <div class="flex items-center justify-between mb-3 px-1">
                                        <div class="flex items-center gap-2">
                                            <div class="w-2 h-2 rounded-full" style="background-color: <?= htmlspecialchars($status['color']) ?>"></div>
                                            <h3 class="font-semibold text-neutral-50 text-sm"><?= htmlspecialchars($status['name']) ?></h3>
                                            <span class="px-1.5 py-0.5 rounded-full bg-neutral-800 text-neutral-400 text-[11px] font-medium">
                                                <?= count($statusTasks) ?>
                                            </span>
                                        </div>
                                        <button class="text-neutral-500 hover:text-neutral-300 transition-colors">
                                            <i class="fas fa-ellipsis-h text-xs"></i>
                                        </button>
                                    </div>

                                    <!-- Tasks Column -->
                                    <div class="task-column min-h-[400px] space-y-2" data-status-id="<?= $status['id'] ?>">
                                        <?php if (empty($statusTasks)): ?>
                                            <!-- Static empty state -->
                                            <div class="empty-state text-center py-8">
                                                <div class="w-8 h-8 mx-auto mb-2 rounded-full bg-neutral-800 flex items-center justify-center">
                                                    <i class="fas fa-inbox text-neutral-600 text-sm"></i>
                                                </div>
                                                <p class="text-xs text-neutral-500">No tasks yet</p>
                                            </div>
                                        <?php else: ?>
                                            <?php foreach ($statusTasks as $task): ?>
                                                <div class="task-card bg-neutral-800/50 border border-neutral-700/50 rounded-lg p-3 hover:bg-neutral-800 hover:border-neutral-600 transition-all cursor-pointer group"
                                                     data-task-id="<?= $task['id'] ?>"
                                                     onclick="openTaskPage(<?= $task['id'] ?>)">
                                                    <!-- Task Header -->
                                                    <div class="flex items-start justify-between mb-2">
                                                        <h4 class="text-sm font-medium text-neutral-50 flex-1 leading-tight pr-2"><?= htmlspecialchars($task['title']) ?></h4>
                                                        <?php if ($task['priority'] === 'urgent'): ?>
                                                            <div class="w-2 h-2 rounded-full bg-red-500 flex-shrink-0 mt-1"></div>
                                                        <?php elseif ($task['priority'] === 'high'): ?>
                                                            <div class="w-2 h-2 rounded-full bg-amber-500 flex-shrink-0 mt-1"></div>
                                                        <?php endif; ?>
                                                    </div>

                                                    <!-- Task Description -->
                                                    <?php if ($task['description']): ?>
                                                        <p class="text-xs text-neutral-400 mb-3 line-clamp-2 leading-relaxed"><?= htmlspecialchars($task['description']) ?></p>
                                                    <?php endif; ?>

                                                    <!-- Task Footer -->
                                                    <div class="flex items-center justify-between">
                                                        <div class="flex items-center gap-3 text-xs text-neutral-500">
                                                            <?php if ($task['comment_count'] > 0): ?>
                                                                <span class="flex items-center gap-1">
                                                                    <i class="fas fa-comment text-[10px]"></i>
                                                                    <span class="text-[11px]"><?= $task['comment_count'] ?></span>
                                                                </span>
                                                            <?php endif; ?>
                                                            <?php if ($task['attachment_count'] > 0): ?>
                                                                <span class="flex items-center gap-1">
                                                                    <i class="fas fa-paperclip text-[10px]"></i>
                                                                    <span class="text-[11px]"><?= $task['attachment_count'] ?></span>
                                                                </span>
                                                            <?php endif; ?>
                                                            <?php if ($task['due_date']): ?>
                                                                <span class="flex items-center gap-1 <?= strtotime($task['due_date']) < time() ? 'text-red-400' : '' ?>">
                                                                    <i class="fas fa-clock text-[10px]"></i>
                                                                    <span class="text-[11px]"><?= date('M j', strtotime($task['due_date'])) ?></span>
                                                                </span>
                                                            <?php endif; ?>
                                                        </div>

                                                        <?php if (!empty($task['assignees'])): ?>
                                                            <div class="flex -space-x-1.5">
                                                                <?php foreach (array_slice($task['assignees'], 0, 3) as $assignee): ?>
                                                                    <div class="w-5 h-5 rounded-full bg-gradient-to-br from-purple-500 to-pink-500 text-white flex items-center justify-center text-[10px] font-medium border border-neutral-800"
                                                                         title="<?= htmlspecialchars($assignee['name']) ?>">
                                                                        <?= strtoupper(substr($assignee['name'], 0, 1)) ?>
                                                                    </div>
                                                                <?php endforeach; ?>
                                                                <?php if (count($task['assignees']) > 3): ?>
                                                                    <div class="w-5 h-5 rounded-full bg-neutral-700 text-neutral-300 flex items-center justify-center text-[10px] font-medium border border-neutral-800">
                                                                        +<?= count($task['assignees']) - 3 ?>
                                                                    </div>
                                                                <?php endif; ?>
                                                            </div>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                            <?php endforeach; ?>
                                        <?php endif; ?>
                                    </div>

                                    <!-- Add Task Button -->
                                    <?php if ($canCreateTask): ?>
                                        <button onclick="showQuickAddTask(<?= $status['id'] ?>)"
                                                class="w-full mt-2 px-3 py-2 border border-neutral-700/50 border-dashed rounded-lg text-xs text-neutral-500 hover:border-neutral-600 hover:bg-neutral-800/50 hover:text-neutral-300 transition-all duration-200 flex items-center justify-center gap-2">
                                            <i class="fas fa-plus text-[10px]"></i>
                                            <span>Add task</span>
                                        </button>
                                    <?php endif; ?>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>

            </div>
        </div>
    </div>
</div>

<!-- Create Project Modal -->
<div id="createProjectModal" class="hidden fixed inset-0 bg-black/60 backdrop-blur-md z-50 overflow-y-auto">
	<div class="flex items-center justify-center min-h-screen px-4 py-6">
		<div class="bg-neutral-900 rounded-2xl shadow-2xl border border-neutral-800 max-w-2xl w-full transform transition-all duration-150 ease-out">
			<div class="border-b border-neutral-800 px-6 py-4">
				<div class="flex items-center justify-between">
					<div>
						<p class="text-[11px] font-medium uppercase tracking-wide text-neutral-400">New project</p>
						<h2 class="mt-1 text-xl font-semibold text-neutral-50">Create New Project</h2>
					</div>
					<button onclick="hideCreateProject()" class="inline-flex h-8 w-8 items-center justify-center rounded-full text-neutral-400 hover:text-neutral-100 hover:bg-neutral-800 transition-all duration-200">
						<i class="fas fa-times text-sm"></i>
					</button>
				</div>
			</div>
			<form id="createProjectForm" class="p-6 space-y-5">
				<div>
					<label class="block text-xs font-medium text-neutral-300 mb-1">Project name *</label>
					<input type="text" name="name" required
						   class="w-full rounded-lg border border-neutral-700 bg-neutral-800 px-3 py-2 text-sm text-neutral-100 placeholder:text-neutral-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-150">
				</div>
				<div>
					<label class="block text-xs font-medium text-neutral-300 mb-1">Description</label>
					<textarea name="description" rows="3"
							  class="w-full rounded-lg border border-neutral-700 bg-neutral-800 px-3 py-2 text-sm text-neutral-100 placeholder:text-neutral-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-150" placeholder="What are you planning to ship?"></textarea>
				</div>
				<div class="grid grid-cols-2 gap-4">
					<div>
						<label class="block text-xs font-medium text-neutral-300 mb-1">Client</label>
						<div class="relative">
							<input type="hidden" name="client_id" id="modalClientId">
							<button type="button" onclick="toggleModalClientMenu()"
							        class="w-full inline-flex items-center justify-between rounded-lg border border-neutral-700 bg-neutral-800 px-3 py-2 text-sm text-neutral-100 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-150">
								<span id="modalClientLabel" class="truncate text-neutral-300">No client</span>
								<span class="ml-2 flex items-center text-neutral-400">
									<i class="fas fa-chevron-down text-xs"></i>
								</span>
							</button>
							<div id="modalClientMenu" class="hidden absolute z-40 mt-1 w-full rounded-xl border border-neutral-700 bg-neutral-800 shadow-lg py-1 text-xs sm:text-sm">
								<div class="px-2 py-1 border-b border-neutral-700">
									<input type="text" id="modalClientSearch" placeholder="Search clients..." 
									       class="w-full px-2 py-1 text-xs border border-neutral-600 bg-neutral-700 rounded focus:outline-none focus:ring-1 focus:ring-blue-500 text-neutral-100 placeholder:text-neutral-500">
								</div>
								<div id="modalClientMenuList">
									<button type="button" data-value="" data-label="No client"
									        class="modal-client-option w-full text-left px-3 py-2 hover:bg-neutral-700 text-neutral-400 truncate">
										No client
									</button>
									<?php foreach ($clients as $client): ?>
										<button type="button" data-value="<?= $client['id'] ?>" data-label="<?= htmlspecialchars($client['name']) ?>"
										        class="modal-client-option w-full text-left px-3 py-2 hover:bg-neutral-700 text-neutral-300 truncate">
											<?= htmlspecialchars($client['name']) ?>
										</button>
									<?php endforeach; ?>
								</div>
							</div>
						</div>
					</div>
					<div>
						<label class="block text-xs font-medium text-neutral-300 mb-1">Priority</label>
						<div class="relative">
							<input type="hidden" name="priority" id="modalPriorityValue" value="medium">
							<button type="button" onclick="toggleModalPriorityMenu()"
							        class="w-full inline-flex items-center justify-between rounded-lg border border-neutral-700 bg-neutral-800 px-3 py-2 text-sm text-neutral-100 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-150">
								<span class="inline-flex items-center gap-2">
									<span id="modalPriorityIconWrap" class="flex h-5 w-5 items-center justify-center rounded-full bg-amber-500 text-[10px] text-white">
										<i class="fas fa-minus"></i>
									</span>
									<span id="modalPriorityLabel" class="truncate">Medium</span>
								</span>
								<span class="ml-2 flex items-center text-neutral-400">
									<i class="fas fa-chevron-down text-xs"></i>
								</span>
							</button>
							<div id="modalPriorityMenu" class="hidden absolute z-40 mt-1 w-full rounded-xl border border-neutral-700 bg-neutral-800 shadow-lg py-1 text-xs sm:text-sm">
								<button type="button" onclick="selectModalPriority('low', 'Low', 'bg-gray-500')" class="w-full text-left px-3 py-2 hover:bg-neutral-700 text-neutral-300 flex items-center gap-2">
									<span class="flex h-5 w-5 items-center justify-center rounded-full bg-gray-500 text-[10px] text-white">
										<i class="fas fa-arrow-down"></i>
									</span>
									Low
								</button>
								<button type="button" onclick="selectModalPriority('medium', 'Medium', 'bg-amber-500')" class="w-full text-left px-3 py-2 hover:bg-neutral-700 text-neutral-300 flex items-center gap-2">
									<span class="flex h-5 w-5 items-center justify-center rounded-full bg-amber-500 text-[10px] text-white">
										<i class="fas fa-minus"></i>
									</span>
									Medium
								</button>
								<button type="button" onclick="selectModalPriority('high', 'High', 'bg-red-500')" class="w-full text-left px-3 py-2 hover:bg-neutral-700 text-neutral-300 flex items-center gap-2">
									<span class="flex h-5 w-5 items-center justify-center rounded-full bg-red-500 text-[10px] text-white">
										<i class="fas fa-arrow-up"></i>
									</span>
									High
								</button>
								<button type="button" onclick="selectModalPriority('urgent', 'Urgent', 'bg-orange-500')" class="w-full text-left px-3 py-2 hover:bg-neutral-700 text-neutral-300 flex items-center gap-2">
									<span class="flex h-5 w-5 items-center justify-center rounded-full bg-orange-500 text-[10px] text-white">
										<i class="fas fa-exclamation-triangle"></i>
									</span>
									Urgent
								</button>
							</div>
						</div>
					</div>
				</div>
				<div class="grid grid-cols-2 gap-4">
					<div>
						<label class="block text-xs font-medium text-neutral-300 mb-1">Category</label>
						<div class="relative">
							<input type="hidden" name="category_id" id="modalCategoryId">
							<button type="button" onclick="toggleModalCategoryMenu()"
							        class="w-full inline-flex items-center justify-between rounded-lg border border-neutral-700 bg-neutral-800 px-3 py-2 text-sm text-neutral-100 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-150">
								<span class="inline-flex items-center gap-2">
									<span id="modalCategoryIcon" class="flex h-5 w-5 items-center justify-center rounded-full bg-gray-600 text-[10px] text-white">
										<i class="fas fa-folder"></i>
									</span>
									<span id="modalCategoryLabel" class="truncate text-neutral-300">No category</span>
								</span>
								<span class="ml-2 flex items-center text-neutral-400">
									<i class="fas fa-chevron-down text-xs"></i>
								</span>
							</button>
							<div id="modalCategoryMenu" class="hidden absolute z-40 mt-1 w-full rounded-xl border border-neutral-700 bg-neutral-800 shadow-lg py-1 text-xs sm:text-sm">
								<button type="button" data-value="" data-label="No category" data-icon="fas fa-minus" data-color="bg-gray-600"
								        class="modal-category-option w-full text-left px-3 py-2 hover:bg-neutral-700 text-neutral-400 flex items-center gap-2">
									<span class="flex h-5 w-5 items-center justify-center rounded-full bg-gray-600 text-[10px] text-white">
										<i class="fas fa-minus"></i>
									</span>
									<span class="truncate">No category</span>
								</button>
								<?php foreach ($categories as $category): ?>
									<?php $catIconClass = $resolveCategoryIcon($category['icon'] ?? 'folder'); ?>
									<button type="button" data-value="<?= $category['id'] ?>" data-label="<?= htmlspecialchars($category['name']) ?>" data-icon="<?= htmlspecialchars($catIconClass, ENT_QUOTES) ?>" data-color="<?= $category['color'] ?>"
									        class="modal-category-option w-full text-left px-3 py-2 hover:bg-neutral-700 text-neutral-300 flex items-center gap-2">
										<span class="flex h-5 w-5 items-center justify-center rounded-full <?= $category['color'] ?> text-[10px] text-white">
											<i class="<?= htmlspecialchars($catIconClass, ENT_QUOTES) ?>"></i>
										</span>
										<?= htmlspecialchars($category['name']) ?>
									</button>
								<?php endforeach; ?>
							</div>
						</div>
					</div>
					<div>
						<label class="block text-xs font-medium text-neutral-300 mb-1">Due Date</label>
						<div class="relative">
							<span class="pointer-events-none absolute inset-y-0 left-3 flex items-center text-neutral-400">
								<svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
									<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"></path>
								</svg>
							</span>
							<input type="date" name="due_date"
							       class="w-full rounded-lg border border-neutral-700 bg-neutral-800 pl-9 pr-3 py-2 text-sm text-neutral-100 placeholder:text-neutral-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-150">
						</div>
					</div>
				</div>
				<div class="flex items-center justify-end gap-3 pt-4 border-t border-neutral-800">
					<button type="button" onclick="hideCreateProject()" class="inline-flex items-center justify-center px-4 py-2 rounded-lg border border-neutral-700 bg-neutral-800 text-sm font-medium text-neutral-300 hover:bg-neutral-700">
						Cancel
					</button>
					<button type="submit" class="inline-flex items-center justify-center px-4 py-2 rounded-lg border border-neutral-700 bg-neutral-800 text-sm font-medium text-neutral-300 hover:bg-neutral-700">
						Create Project
					</button>
				</div>
			</form>
		</div>
	</div>
</div>

<!-- Edit Project Modal -->
<div id="editProjectModal" class="is-hidden edit-project-modal-overlay">
	<div class="edit-project-modal-align">
		<div class="card edit-project-modal-card">
			<div class="edit-project-modal-header">
				<div>
					<p class="section-title">Project</p>
					<h2 class="card-title" style="margin-top: 6px;">Edit project</h2>
				</div>
				<button type="button" onclick="hideEditProject()" class="btn-icon" aria-label="Close">
					<i class="fas fa-times"></i>
				</button>
			</div>

			<form id="editProjectForm" class="edit-project-form">
				<input type="hidden" name="id" id="editProjectId" value="">
				<div>
					<label class="form-label" for="editProjectName">Project name</label>
					<input type="text" name="name" id="editProjectName" required class="form-input">
				</div>
				<div>
					<label class="form-label" for="editProjectDescription">Description</label>
					<textarea name="description" id="editProjectDescription" rows="3" class="form-textarea"></textarea>
				</div>
				<div class="edit-project-grid-2">
					<div>
						<label class="form-label" for="editProjectStatus">Status</label>
						<select name="status" id="editProjectStatus" class="form-select">
							<option value="planning">Planning</option>
							<option value="active">Active</option>
							<option value="on_hold">On hold</option>
							<option value="completed">Completed</option>
						</select>
					</div>
					<div>
						<label class="form-label" for="editProjectDueDate">Due date</label>
						<input type="date" name="due_date" id="editProjectDueDate" class="form-input">
					</div>
				</div>
				<div class="edit-project-actions">
					<button type="button" onclick="hideEditProject()" class="btn-secondary">Cancel</button>
					<button type="submit" class="btn-primary">Save changes</button>
				</div>
			</form>
		</div>
	</div>
</div>

<!-- Category Manager Modal -->
<div id="categoryModal" class="hidden fixed inset-0 bg-black/60 backdrop-blur-md z-50 overflow-y-auto">
	<div class="flex items-center justify-center min-h-screen px-4 py-6">
		<div class="bg-neutral-900 rounded-2xl shadow-2xl border border-neutral-800 max-w-2xl w-full">
			<div class="border-b border-neutral-800 px-6 py-5">
				<div class="flex flex-col gap-1">
					<div class="flex items-center justify-between">
						<div>
							<p class="text-[11px] font-medium uppercase tracking-wide text-neutral-400">Workspace settings</p>
							<h2 class="text-xl font-semibold text-neutral-50">Manage Categories</h2>
						</div>
						<button onclick="hideCategoryManager()" class="inline-flex h-8 w-8 items-center justify-center rounded-full text-neutral-400 hover:text-neutral-100 hover:bg-neutral-800 transition-all duration-200">
							<i class="fas fa-times text-sm"></i>
						</button>
					</div>
					<p class="text-sm text-neutral-400">Pair each category with an icon for instant recognition in boards, filters, and modals.</p>
				</div>
			</div>
			<div class="p-6 space-y-6">
				<form id="addCategoryForm" class="space-y-4">
					<div>
						<label class="block text-xs font-medium text-neutral-300 mb-1">Category name</label>
						<input type="text" name="name" required placeholder="e.g. Product, Marketing, Ops"
						       class="w-full rounded-lg border border-neutral-700 bg-neutral-800 px-3 py-2 text-sm text-neutral-100 placeholder:text-neutral-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-150">
					</div>
					<div>
						<div class="flex items-center justify-between mb-2">
							<label class="block text-xs font-medium text-neutral-300">Icon</label>
							<span class="text-[11px] text-neutral-500">Search and pick one that feels right</span>
						</div>
						<div class="mb-2">
							<input type="text" id="categoryIconSearch" placeholder="Search icons..." class="w-full rounded-full border border-neutral-700 bg-neutral-800 px-3 py-1.5 text-xs text-neutral-100 placeholder:text-neutral-500 focus:outline-none focus:ring-1 focus:ring-blue-500">
						</div>
						<input type="hidden" name="icon" id="newCategoryIcon" value="folder">
						<div class="grid grid-cols-4 gap-2" id="categoryIconChoices">
							<?php foreach ($categoryIconChoices as $iconKey => $meta): ?>
								<?php $isActive = $iconKey === 'folder'; ?>
								<button type="button" data-icon="<?= $iconKey ?>" data-label="<?= htmlspecialchars($meta['label']) ?>"
							        class="category-icon-choice flex flex-col items-center gap-1 rounded-lg border px-3 py-2 text-xs font-medium transition-all <?= $isActive ? 'border-blue-500 bg-blue-500/10 text-blue-400 ring-2 ring-blue-500/20' : 'border-neutral-700 text-neutral-400 hover:border-neutral-600 hover:text-neutral-300' ?>">
								<span class="flex h-9 w-9 items-center justify-center rounded-full bg-neutral-700 text-white text-sm">
									<i class="<?= htmlspecialchars($meta['class'], ENT_QUOTES) ?>"></i>
								</span>
								<?= htmlspecialchars($meta['label']) ?>
							</button>
							<?php endforeach; ?>
						</div>
					</div>
					<div class="flex items-center justify-end gap-2">
						<button type="button" onclick="hideCategoryManager()" class="inline-flex items-center justify-center rounded-lg border border-neutral-700 bg-neutral-800 px-4 py-2 text-sm font-medium text-neutral-300 hover:bg-neutral-700 hover:border-neutral-600 transition-all">
							Cancel
						</button>
						<button type="submit" class="inline-flex items-center justify-center rounded-lg border border-neutral-700 bg-neutral-800 px-4 py-2 text-sm font-medium text-neutral-300 hover:bg-neutral-700 hover:border-neutral-600 transition-all">
							Add category
						</button>
					</div>
				</form>
				<div class="space-y-3 max-h-[320px] overflow-y-auto" id="categoryList">
					<?php if (empty($categories)): ?>
						<div class="rounded-xl border border-dashed border-neutral-700 bg-neutral-800/50 px-4 py-6 text-center text-sm text-neutral-400">
							No categories yet. Create your first one to keep projects organized.
						</div>
					<?php else: ?>
						<?php foreach ($categories as $category): ?>
							<?php $iconClass = $resolveCategoryIcon($category['icon'] ?? null); ?>
							<div class="flex items-center justify-between rounded-xl border border-neutral-700 bg-neutral-800 px-3 py-2.5 hover:border-neutral-600 hover:bg-neutral-750 transition">
								<div class="flex items-center gap-3">
									<span class="flex h-9 w-9 items-center justify-center rounded-full bg-neutral-700 text-white text-sm">
										<i class="<?= htmlspecialchars($iconClass, ENT_QUOTES) ?>"></i>
									</span>
									<div>
										<p class="text-sm font-semibold text-neutral-100"><?= htmlspecialchars($category['name']) ?></p>
										<p class="text-xs text-neutral-400"><?= (int)$category['project_count'] ?> <?= (int)$category['project_count'] === 1 ? 'project' : 'projects' ?></p>
									</div>
								</div>
								<div class="flex items-center gap-2">
									<button type="button" onclick="deleteCategory(<?= $category['id'] ?>)" class="inline-flex items-center gap-1 rounded-lg border border-transparent px-3 py-1.5 text-sm font-medium text-red-400 hover:border-red-800/30 hover:bg-red-900/20 transition-all">
										<i class="fas fa-trash"></i>
										Remove
									</button>
								</div>
							</div>
						<?php endforeach; ?>
					<?php endif; ?>
				</div>
			</div>
		</div>
	</div>
</div>

<!-- Quick Add Task Modal -->
<div id="quickAddModal" class="is-hidden quick-add-modal-overlay">
    <div class="quick-add-modal-align">
        <div class="card quick-add-modal-card">
            <div class="quick-add-modal-header">
                <div>
                    <p class="section-title">New task</p>
                    <h2 class="card-title" style="margin-top: 6px;">Add task</h2>
                </div>
                <button type="button" onclick="hideQuickAddTask()" class="btn-icon" aria-label="Close">
                    <i class="fas fa-times"></i>
                </button>
            </div>

            <form id="quickAddForm" class="quick-add-form">
                <input type="hidden" name="project_id" value="<?= $selectedProjectId ?>">

                <div>
                    <label class="form-label" for="quickAddTitle">Title</label>
                    <input id="quickAddTitle" type="text" name="title" required class="form-input">
                </div>

                <div>
                    <label class="form-label" for="quickAddDescription">Description</label>
                    <textarea id="quickAddDescription" name="description" rows="3" class="form-textarea" placeholder="What needs to get done?"></textarea>
                </div>

                <div class="quick-add-grid-3">
                    <div>
                        <label class="form-label" for="quickAddStatusSelect">Status</label>
                        <select id="quickAddStatusSelect" name="status_id" class="form-select">
                            <?php foreach ($statuses as $status): ?>
                                <option value="<?= $status['id'] ?>" <?= $status['is_default'] ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($status['name']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label class="form-label" for="quickAddPriority">Priority</label>
                        <select id="quickAddPriority" name="priority" class="form-select">
                            <option value="low">Low</option>
                            <option value="medium" selected>Medium</option>
                            <option value="high">High</option>
                            <option value="urgent">Urgent</option>
                        </select>
                    </div>
                    <div>
                        <label class="form-label" for="quickAddDueDate">Due date</label>
                        <input id="quickAddDueDate" type="date" name="due_date" class="form-input">
                    </div>
                </div>

                <div class="quick-add-grid-2">
                    <div>
                        <label class="form-label" for="quickAddEstimated">Estimated hours</label>
                        <input id="quickAddEstimated" type="number" name="estimated_hours" step="0.5" min="0" placeholder="e.g. 2.5" class="form-input">
                    </div>
                    <div>
                        <label class="form-label" for="quickAddAssignee">Assign to</label>
                        <select id="quickAddAssignee" name="assignee_id" class="form-select">
                            <option value="">Unassigned</option>
                            <?php foreach ($members as $member): ?>
                                <option value="<?= (int)$member['id'] ?>"><?= htmlspecialchars($member['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>

                <div class="quick-add-actions">
                    <button type="submit" class="btn-primary">Add task</button>
                    <button type="button" onclick="hideQuickAddTask()" class="btn-secondary">Cancel</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Task Detail Modal -->
<div id="taskDetailModal" class="hidden fixed inset-0 bg-black/50 z-50 overflow-y-auto">
    <div class="flex items-center justify-center min-h-screen px-4 py-6">
        <div class="bg-neutral-900 border border-neutral-800 rounded-lg shadow-xl max-w-3xl w-full max-h-[90vh] overflow-y-auto">
            <div class="border-b border-neutral-800 px-6 py-4 sticky top-0 bg-neutral-900">
                <div class="flex items-center justify-between">
                    <h2 class="text-lg font-semibold text-neutral-50">Task Details</h2>
                    <button onclick="hideTaskDetail()" class="text-neutral-400 hover:text-neutral-200">
                        <svg class="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                        </svg>
                    </button>
                </div>
            </div>
            <div id="taskDetailContent" class="p-6">
                <!-- Content loaded via AJAX -->
            </div>
        </div>
    </div>
</div>

<script>
// Modal functions
function showModal(modalId) {
    // Hide all modals first
    document.querySelectorAll('.modal-overlay').forEach(modal => {
        modal.classList.remove('active');
    });
    // Show the requested modal
    const modal = document.getElementById(modalId);
    if (modal) {
        modal.classList.add('active');
    }
}

function hideModal(modalId) {
    const modal = document.getElementById(modalId);
    if (modal) {
        modal.classList.remove('active');
    }
    // Reset forms if needed
    if (modalId === 'createProjectModal') {
        const form = document.getElementById('createProjectForm');
        if (form) form.reset();
    }
}

// Specific modal functions
function showCreateProject() {
    const modal = document.getElementById('createProjectModal');
    if (modal) modal.classList.remove('hidden');
}

function hideCreateProject() {
    const modal = document.getElementById('createProjectModal');
    if (modal) modal.classList.add('hidden');
    const form = document.getElementById('createProjectForm');
    if (form) form.reset();
}

function showCategoryManager() {
    const modal = document.getElementById('categoryModal');
    if (modal) modal.classList.remove('hidden');
}

function hideCategoryManager() {
    const modal = document.getElementById('categoryModal');
    if (modal) modal.classList.add('hidden');
}

function showQuickAddTask(statusId) {
    const modal = document.getElementById('quickAddModal');
    if (!modal) return;
    modal.classList.remove('is-hidden');

    const statusSelect = document.getElementById('quickAddStatusSelect');
    if (statusSelect && statusId) {
        statusSelect.value = String(statusId);
    }

    const titleInput = document.querySelector('#quickAddForm input[name="title"]');
    if (titleInput) {
        setTimeout(() => titleInput.focus(), 0);
    }
}

function hideQuickAddTask() {
    const modal = document.getElementById('quickAddModal');
    if (modal) modal.classList.add('is-hidden');
    const form = document.getElementById('quickAddForm');
    if (form) form.reset();
}

function hideTaskDetail() {
    const modal = document.getElementById('taskDetailModal');
    if (modal) modal.classList.add('hidden');
}

function getWorkspaceSlug() {
    const existing = (window.PROJECTS_WORKSPACE || '').toString();
    if (existing) return existing;
    try {
        const params = new URLSearchParams(window.location.search || '');
        return (params.get('workspace') || '').toString();
    } catch (e) {
        return '';
    }
}

function showEditProject(projectId) {
    const modal = document.getElementById('editProjectModal');
    if (!modal) return;
    modal.classList.remove('is-hidden');

    document.getElementById('editProjectId').value = String(projectId || '');
    document.getElementById('editProjectName').value = '';
    document.getElementById('editProjectDescription').value = '';

    const workspaceSlug = getWorkspaceSlug();
    fetch(`/api/projects.php?id=${encodeURIComponent(projectId)}&workspace=${encodeURIComponent(workspaceSlug)}`)
        .then(r => r.json())
        .then(result => {
            if (!result || !result.success || !result.project) return;
            const p = result.project;
            document.getElementById('editProjectId').value = String(p.id || projectId);
            document.getElementById('editProjectName').value = p.name || '';
            document.getElementById('editProjectDescription').value = p.description || '';
            document.getElementById('editProjectStatus').value = p.status || 'planning';
            document.getElementById('editProjectDueDate').value = (p.due_date || '').slice(0, 10);
        })
        .catch(() => {});
}

function hideEditProject() {
    const modal = document.getElementById('editProjectModal');
    if (modal) modal.classList.add('is-hidden');
    const form = document.getElementById('editProjectForm');
    if (form) form.reset();
}

document.addEventListener('DOMContentLoaded', function() {
    window.PROJECTS_WORKSPACE = <?= json_encode($workspace) ?>;
    const createBtn = document.getElementById('projects-create-btn');
    if (createBtn) createBtn.addEventListener('click', showCreateProject);

    const categoriesBtn = document.getElementById('projects-categories-btn');
    if (categoriesBtn) categoriesBtn.addEventListener('click', showCategoryManager);

    // Click outside to close
    const overlayBindings = [
        { id: 'createProjectModal', close: hideCreateProject },
        { id: 'editProjectModal', close: hideEditProject },
        { id: 'categoryModal', close: hideCategoryManager },
        { id: 'quickAddModal', close: hideQuickAddTask },
        { id: 'taskDetailModal', close: hideTaskDetail },
    ];

    overlayBindings.forEach(({ id, close }) => {
        const overlay = document.getElementById(id);
        if (!overlay) return;
        overlay.addEventListener('click', (e) => {
            if (e.target === overlay) close();
        });
    });

    // Escape to close
    document.addEventListener('keydown', (e) => {
        if (e.key !== 'Escape') return;
        overlayBindings.forEach(({ id, close }) => {
            const modal = document.getElementById(id);
            if (modal && !modal.classList.contains('hidden')) {
                close();
            }
        });
    });
});

// Modal client combobox (Create Project)
function toggleModalClientMenu() {
    const menu = document.getElementById('modalClientMenu');
    if (!menu) return;
    menu.classList.toggle('hidden');
}

function closeModalClientMenu() {
    const menu = document.getElementById('modalClientMenu');
    if (!menu) return;
    menu.classList.add('hidden');
}

function selectModalClient(value, label) {
    const idInput = document.getElementById('modalClientId');
    const labelEl = document.getElementById('modalClientLabel');
    if (idInput) idInput.value = value;
    if (labelEl) labelEl.textContent = label || 'No client';
    closeModalClientMenu();
}

function selectModalCategory(value, label, icon, color) {
    const idInput = document.getElementById('modalCategoryId');
    const labelEl = document.getElementById('modalCategoryLabel');
    const iconEl = document.getElementById('modalCategoryIcon');
    
    if (idInput) idInput.value = value;
    if (labelEl) labelEl.textContent = label || 'No category';
    
    if (iconEl && icon && color) {
        iconEl.className = 'flex h-5 w-5 items-center justify-center rounded-full ' + color + ' text-[10px] text-white';
        iconEl.innerHTML = '<i class="' + icon + '"></i>';
    }
    
    closeModalCategoryMenu();
}

function toggleCategoryIconPicker() {
    const panel = document.getElementById('categoryIconPickerPanel');
    if (!panel) return;
    panel.classList.toggle('hidden');
}

// Modal priority dropdown (Create Project)
function toggleModalPriorityMenu() {
    const menu = document.getElementById('modalPriorityMenu');
    if (!menu) return;
    menu.classList.toggle('hidden');
}

function closeModalPriorityMenu() {
    const menu = document.getElementById('modalPriorityMenu');
    if (!menu) return;
    menu.classList.add('hidden');
}

function selectModalPriority(value, label, color) {
    const valueInput = document.getElementById('modalPriorityValue');
    const labelEl = document.getElementById('modalPriorityLabel');
    const iconWrap = document.getElementById('modalPriorityIconWrap');
    if (valueInput) valueInput.value = value;
    if (labelEl) labelEl.textContent = label;

    if (iconWrap) {
        let bgClass = color || 'bg-amber-500';
        let iconClass = 'fas fa-minus';
        
        if (value === 'low') {
            bgClass = 'bg-gray-500';
            iconClass = 'fas fa-arrow-down';
        } else if (value === 'high') {
            bgClass = 'bg-red-500';
            iconClass = 'fas fa-arrow-up';
        } else if (value === 'urgent') {
            bgClass = 'bg-orange-500';
            iconClass = 'fas fa-exclamation-triangle';
        }
        
        iconWrap.className = 'flex h-5 w-5 items-center justify-center rounded-full text-white text-[10px] ' + bgClass;
        iconWrap.innerHTML = '<i class="' + iconClass + '"></i>';
    }
    closeModalPriorityMenu();
}

// Modal category dropdown (Create Project)
function toggleModalCategoryMenu() {
    const menu = document.getElementById('modalCategoryMenu');
    if (!menu) return;
    menu.classList.toggle('hidden');
}

function closeModalCategoryMenu() {
    const menu = document.getElementById('modalCategoryMenu');
    if (!menu) return;
    menu.classList.add('hidden');
}

// Filter category dropdown
function toggleFilterCategoryMenu() {
    const menu = document.getElementById('filterCategoryMenu');
    if (!menu) return;
    menu.classList.toggle('hidden');
}

function closeFilterCategoryMenu() {
    const menu = document.getElementById('filterCategoryMenu');
    if (!menu) return;
    menu.classList.add('hidden');
}

function selectFilterCategory(value, label, iconClass, color) {
    const input = document.getElementById('categoryFilter');
    const labelEl = document.getElementById('filterCategoryLabel');
    const iconWrap = document.getElementById('filterCategoryIconWrap');
    const iconEl = document.getElementById('filterCategoryIcon');
    if (input) input.value = value;
    if (labelEl) labelEl.textContent = label;
    if (iconWrap) iconWrap.className = 'flex h-4 w-4 items-center justify-center rounded-full text-white ' + (color || 'bg-neutral-700');
    if (iconEl) iconEl.className = (iconClass || 'fas fa-layer-group') + ' text-[9px]';
    closeFilterCategoryMenu();
    applyFilters();
}

// Filter status dropdown
function toggleFilterStatusMenu() {
    const menu = document.getElementById('filterStatusMenu');
    if (!menu) return;
    menu.classList.toggle('hidden');
}

function closeFilterStatusMenu() {
    const menu = document.getElementById('filterStatusMenu');
    if (!menu) return;
    menu.classList.add('hidden');
}

function selectFilterStatus(value, label, color, icon) {
    const input = document.getElementById('statusFilter');
    const labelEl = document.getElementById('filterStatusLabel');
    const iconWrap = document.getElementById('filterStatusIconWrap');
    const iconEl = document.getElementById('filterStatusIcon');
    if (input) input.value = value;
    if (labelEl) labelEl.textContent = label;
    if (iconWrap) iconWrap.className = 'flex h-4 w-4 items-center justify-center rounded-full text-neutral-300 ' + (color || 'bg-gray-400');
    if (iconEl) iconEl.className = (icon || 'fas fa-layer-group') + ' text-[9px]';
    closeFilterStatusMenu();
    applyFilters();
}

// Priority filter dropdown (top filters)
function toggleFilterPriorityMenu() {
    const menu = document.getElementById('filterPriorityMenu');
    if (!menu) return;
    menu.classList.toggle('hidden');
}

function closeFilterPriorityMenu() {
    const menu = document.getElementById('filterPriorityMenu');
    if (!menu) return;
    menu.classList.add('hidden');
}

function selectFilterPriority(value, label, level) {
    const valueInput = document.getElementById('priorityFilter');
    const labelEl = document.getElementById('filterPriorityLabel');
    const iconWrap = document.getElementById('filterPriorityIconWrap');
    const iconEl = document.getElementById('filterPriorityIcon');
    if (valueInput) valueInput.value = value;
    if (labelEl) labelEl.textContent = label;

    if (iconWrap && iconEl) {
        let bgClass = 'bg-amber-500';
        let iconClass = 'fas fa-minus';
        
        if (level === 'low') {
            bgClass = 'bg-gray-500';
            iconClass = 'fas fa-arrow-down';
        } else if (level === 'medium') {
            bgClass = 'bg-amber-500';
            iconClass = 'fas fa-minus';
        } else if (level === 'high') {
            bgClass = 'bg-orange-500';
            iconClass = 'fas fa-arrow-up';
        } else if (level === 'urgent') {
            bgClass = 'bg-orange-500';
            iconClass = 'fas fa-exclamation-triangle';
        } else {
            bgClass = 'bg-gray-400';
            iconClass = 'fas fa-slash';
        }
        
        iconWrap.className = 'flex h-4 w-4 items-center justify-center rounded-full text-neutral-300 ' + bgClass;
        iconEl.className = iconClass + ' text-[9px]';
    }
    closeFilterPriorityMenu();
    applyFilters();
}

// Wire up modal client search & option clicks
document.addEventListener('DOMContentLoaded', () => {
    const search = document.getElementById('modalClientSearch');
    const options = document.querySelectorAll('#modalClientMenuList .modal-client-option');
    if (search && options.length) {
        search.addEventListener('input', () => {
            const term = search.value.toLowerCase();
            options.forEach(opt => {
                const text = opt.textContent.toLowerCase();
                opt.style.display = text.includes(term) ? '' : 'none';
            });
        });
    }

    options.forEach(opt => {
        opt.addEventListener('click', () => {
            const value = opt.dataset.value || '';
            const label = opt.dataset.label || opt.textContent.trim();
            selectModalClient(value, label);
        });
    });

    const priorityOptions = document.querySelectorAll('#modalPriorityMenu .modal-priority-option');
    priorityOptions.forEach(opt => {
        opt.addEventListener('click', () => {
            const value = opt.dataset.value || 'medium';
            const label = opt.dataset.label || 'Medium';
            const level = opt.dataset.color || 'medium';
            selectModalPriority(value, label, level);
        });
    });

    const categoryOptions = document.querySelectorAll('#modalCategoryMenu .modal-category-option');
    categoryOptions.forEach(opt => {
        opt.addEventListener('click', () => {
            const value = opt.dataset.value || '';
            const label = opt.dataset.label || opt.textContent.trim();
            const icon = opt.dataset.icon || 'fas fa-folder';
            const color = opt.dataset.color || 'bg-gray-900';
            selectModalCategory(value, label, icon, color);
        });
    });

    const filterCategoryOptions = document.querySelectorAll('#filterCategoryMenu .filter-category-option');
    filterCategoryOptions.forEach(opt => {
        opt.addEventListener('click', () => {
            const value = opt.dataset.value || 'all';
            const label = opt.dataset.label || 'All categories';
            const icon = opt.dataset.icon || 'fas fa-layer-group';
            const color = opt.dataset.color || 'bg-neutral-700';
            selectFilterCategory(value, label, icon, color);
        });
    });

    const filterStatusOptions = document.querySelectorAll('#filterStatusMenu .filter-status-option');
    filterStatusOptions.forEach(opt => {
        opt.addEventListener('click', () => {
            const value = opt.dataset.value || '';
            const label = opt.dataset.label || 'All statuses';
            const color = opt.dataset.color || 'bg-gray-400';
            const icon = opt.dataset.icon || 'fas fa-layer-group';
            selectFilterStatus(value, label, color, icon);
        });
    });

    const iconChoices = document.querySelectorAll('#categoryIconChoices .category-icon-choice');
    const iconInput = document.getElementById('newCategoryIcon');
    const iconSearch = document.getElementById('categoryIconSearch');
    const previewIcon = document.getElementById('selectedCategoryIconPreview');
    const previewLabel = document.getElementById('selectedCategoryIconLabel');
    if (iconChoices.length && iconInput) {
        iconChoices.forEach(choice => {
            choice.addEventListener('click', () => {
                iconChoices.forEach(btn => btn.classList.remove('ring-2', 'ring-blue-500/20', 'border-blue-500', 'bg-blue-500/10', 'text-blue-400'));
                iconChoices.forEach(btn => btn.classList.add('border-neutral-700', 'text-neutral-400'));
                choice.classList.remove('border-neutral-700', 'text-neutral-400');
                choice.classList.add('ring-2', 'ring-blue-500/20', 'border-blue-500', 'bg-blue-500/10', 'text-blue-400');
                iconInput.value = choice.dataset.icon || 'folder';

                if (previewIcon) {
                    const inner = choice.querySelector('i');
                    if (inner && inner.className) {
                        previewIcon.className = inner.className;
                    }
                }
                if (previewLabel) {
                    previewLabel.textContent = choice.dataset.label || previewLabel.textContent || '';
                }
            });
        });

        if (iconSearch) {
            iconSearch.addEventListener('input', () => {
                const term = iconSearch.value.toLowerCase();
                iconChoices.forEach(choice => {
                    const label = (choice.dataset.label || choice.textContent || '').toLowerCase();
                    choice.style.display = label.includes(term) ? '' : 'none';
                });
            });
        }
    }
});

// Edit project
const editProjectFormEl = document.getElementById('editProjectForm');
if (editProjectFormEl) {
    editProjectFormEl.addEventListener('submit', async (e) => {
        e.preventDefault();
        const formData = new FormData(e.target);
        const data = Object.fromEntries(formData.entries());

        try {
            const workspaceSlug = getWorkspaceSlug();
            const response = await fetch(`/api/projects.php?workspace=${encodeURIComponent(workspaceSlug)}`, {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(data)
            });
            const result = await response.json();
            if (result.success) {
                window.location.reload();
            } else {
                alert('Error: ' + (result.error || 'Failed to update project'));
            }
        } catch (error) {
            alert('Error updating project');
        }
    });
}

function openTaskPage(taskId) {
    const workspaceSlug = getWorkspaceSlug();
    const projectId = <?= (int) $selectedProjectId ?>;
    window.location.href = `/task.php?id=${encodeURIComponent(taskId)}&project_id=${encodeURIComponent(projectId)}&workspace=${encodeURIComponent(workspaceSlug)}`;
}

// Create project
document.getElementById('createProjectForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    const formData = new FormData(e.target);
    const data = Object.fromEntries(formData.entries());

    try {
        const response = await fetch('/api/projects.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(data)
        });
        const result = await response.json();
        if (result.success) {
            window.location.reload();
        } else {
            alert('Error: ' + result.error);
        }
    } catch (error) {
        alert('Error creating project');
    }
});

// Add category
document.getElementById('addCategoryForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    const formData = new FormData(e.target);
    const data = Object.fromEntries(formData.entries());

    try {
        const response = await fetch('/api/project-categories.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(data)
        });
        const result = await response.json();
        if (result.success) {
            window.location.reload();
        } else {
            alert('Error: ' + result.error);
        }
    } catch (error) {
        alert('Error adding category');
    }
});

// Delete category
async function deleteCategory(id) {
    if (!confirm('Delete this category?')) return;
    try {
        const response = await fetch('/api/project-categories.php?id=' + encodeURIComponent(id) + '&company_id=<?= $companyId ?>', {method: 'DELETE'});
        const result = await response.json();
        if (result.success) {
            window.location.reload();
        } else {
            alert('Error: ' + result.error);
        }
    } catch (error) {
        alert('Error deleting category');
    }
}

// Quick add task
document.getElementById('quickAddForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    const formData = new FormData(e.target);
    const data = Object.fromEntries(formData.entries());

    if (!data.description) delete data.description;
    if (!data.due_date) delete data.due_date;
    if (!data.status_id) delete data.status_id;
    if (!data.estimated_hours) {
        delete data.estimated_hours;
    } else {
        const parsed = parseFloat(String(data.estimated_hours));
        data.estimated_hours = Number.isFinite(parsed) ? parsed : data.estimated_hours;
    }

    if (data.assignee_id) {
        const assigneeId = parseInt(String(data.assignee_id), 10);
        if (Number.isFinite(assigneeId) && assigneeId > 0) {
            data.assignees = [assigneeId];
        }
    }
    delete data.assignee_id;

    try {
        const workspaceSlug = getWorkspaceSlug();
        const response = await fetch(`/api/tasks.php?workspace=${encodeURIComponent(workspaceSlug)}`, {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(data)
        });
        const result = await response.json();
        if (result.success) {
            window.location.reload();
        } else {
            alert('Error: ' + result.error);
        }
    } catch (error) {
        alert('Error adding task');
    }
});

// Show task detail
async function showTaskDetail(taskId) {
    document.getElementById('taskDetailModal').classList.remove('hidden');
    document.getElementById('taskDetailContent').innerHTML = '<div class="text-center py-8"><i class="fas fa-spinner fa-spin text-2xl text-neutral-400"></i></div>';

    try {
        const workspaceSlug = (window.PROJECTS_WORKSPACE || '').toString();
        const response = await fetch(`/api/tasks.php?id=${taskId}&workspace=${encodeURIComponent(workspaceSlug)}`);
        const result = await response.json();
        if (result.success) {
            renderTaskDetail(result.task);
        } else {
            document.getElementById('taskDetailContent').innerHTML = '<p class="text-red-400">Error loading task</p>';
        }
    } catch (error) {
        document.getElementById('taskDetailContent').innerHTML = '<p class="text-red-400">Error loading task</p>';
    }
}

function renderTaskDetail(task) {
    function formatTaskDueDate(value) {
        if (!value) return 'Not set';
        const raw = String(value).slice(0, 10);
        const d = new Date(raw + 'T00:00:00');
        if (Number.isNaN(d.getTime())) return raw;
        return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
    }

    document.getElementById('taskDetailContent').innerHTML = `
        <div class="space-y-4">
            <div>
                <h3 class="text-xl font-bold text-neutral-50 mb-2">${task.title}</h3>
                <p class="text-sm text-neutral-400">${task.description || 'No description'}</p>
            </div>
            <div class="grid grid-cols-3 gap-4 text-sm">
                <div>
                    <p class="text-xs text-neutral-500 mb-1">Status</p>
                    <p class="font-medium">${task.status_name || 'No status'}</p>
                </div>
                <div>
                    <p class="text-xs text-neutral-500 mb-1">Priority</p>
                    <p class="font-medium">${task.priority}</p>
                </div>
                <div>
                    <p class="text-xs text-neutral-500 mb-1">Due Date</p>
                    <p class="font-medium">${formatTaskDueDate(task.due_date)}</p>
                </div>
            </div>
            <div class="pt-4 border-t border-neutral-800">
                <a href="/task.php?id=${task.id}&project_id=<?= $selectedProjectId ?>&workspace=<?= urlencode($workspace) ?>"
                   class="inline-flex items-center px-4 py-2 bg-neutral-700 text-neutral-100 rounded hover:bg-neutral-600">
                    View Full Details
                </a>
            </div>
        </div>
    `;
}

// Filters
let searchTimeout;
const searchInputEl = document.getElementById('searchInput');
if (searchInputEl) {
    searchInputEl.addEventListener('input', () => {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(applyFilters, 500);
    });
}

function applyFilters() {
    const params = new URLSearchParams(window.location.search);
    const categoryEl = document.getElementById('categoryFilter');
    const statusEl = document.getElementById('statusFilter');
    const priorityEl = document.getElementById('priorityFilter');
    const clientEl = document.getElementById('clientFilter');
    const searchEl = document.getElementById('searchInput');

    if (categoryEl) params.set('category', categoryEl.value);
    if (statusEl) params.set('status', statusEl.value);
    if (priorityEl) params.set('priority', priorityEl.value);
    if (clientEl) params.set('client_id', clientEl.value);
    if (searchEl) params.set('search', searchEl.value);
    window.location.href = '?' + params.toString();
}

function clearFilters() {
    const params = new URLSearchParams(window.location.search);
    params.delete('category');
    params.delete('status');
    params.delete('priority');
    params.delete('client_id');
    params.delete('search');
    window.location.href = '?' + params.toString();
}

// Quick status pills helper
function setStatusQuickFilter(statusValue) {
    const statusEl = document.getElementById('statusFilter');
    if (statusEl) {
        statusEl.value = statusValue;
    }
    // Small delay so the press animation is visible before navigation
    setTimeout(() => {
        applyFilters();
    }, 80);
}

function toggleClientFilterMenu() {
    const menu = document.getElementById('clientFilterMenu');
    const button = document.querySelector('button[onclick="toggleClientFilterMenu()"]');
    if (!menu || !button) return;

    const isHidden = menu.classList.contains('hidden');

    if (isHidden) {
        const rect = button.getBoundingClientRect();
        menu.style.top = (rect.bottom + window.scrollY) + 'px';
        menu.style.left = (rect.left + window.scrollX) + 'px';
        menu.style.minWidth = rect.width + 'px';
        menu.classList.remove('hidden');
    } else {
        closeClientFilterMenu();
    }
}

function closeClientFilterMenu() {
    const menu = document.getElementById('clientFilterMenu');
    if (!menu) return;
    menu.classList.add('hidden');
    menu.style.top = 'auto';
    menu.style.left = 'auto';
    menu.style.minWidth = '';
}

function selectClientFilter(value, label) {
    const hiddenInput = document.getElementById('clientFilter');
    const labelEl = document.getElementById('clientFilterLabel');
    if (hiddenInput) hiddenInput.value = value;
    if (labelEl) labelEl.textContent = label;

    // Update URL param and reapply filters
    const params = new URLSearchParams(window.location.search);
    if (value) {
        params.set('client_id', value);
    } else {
        params.delete('client_id');
    }
    window.location.href = '?' + params.toString();
}

// Filter client list on search input and wire option clicks
document.addEventListener('DOMContentLoaded', () => {
    const searchInput = document.getElementById('clientSearchInput');
    const options = document.querySelectorAll('#clientFilterMenuList .client-option');
    if (searchInput && options.length) {
        searchInput.addEventListener('input', () => {
            const term = searchInput.value.toLowerCase();
            options.forEach(opt => {
                const text = opt.textContent.toLowerCase();
                opt.style.display = text.includes(term) ? '' : 'none';
            });
        });
    }

    options.forEach(opt => {
        opt.addEventListener('click', () => {
            const value = opt.dataset.value || '';
            const label = opt.querySelector('span.truncate')?.textContent?.trim() || 'Client';
            selectClientFilter(value, label);
        });
    });
});

// Filter option click handlers
document.addEventListener('DOMContentLoaded', () => {
    // Filter button click handlers
    const categoryButton = document.querySelector('button[data-toggle="category-menu"]');
    const statusButton = document.querySelector('button[data-toggle="status-menu"]');
    const priorityButton = document.querySelector('button[data-toggle="priority-menu"]');

    if (categoryButton) {
        categoryButton.addEventListener('click', toggleFilterCategoryMenu);
    }
    if (statusButton) {
        statusButton.addEventListener('click', toggleFilterStatusMenu);
    }
    if (priorityButton) {
        priorityButton.addEventListener('click', toggleFilterPriorityMenu);
    }

    // Category filter options
    const filterCategoryOptions = document.querySelectorAll('#filterCategoryMenu .filter-category-option');
    filterCategoryOptions.forEach(opt => {
        opt.addEventListener('click', () => {
            const value = opt.dataset.value || 'all';
            const label = opt.dataset.label || 'All categories';
            const icon = opt.dataset.icon || 'fas fa-layer-group';
            const color = opt.dataset.color || 'bg-neutral-700';
            selectFilterCategory(value, label, icon, color);
        });
    });

    // Status filter options
    const filterStatusOptions = document.querySelectorAll('#filterStatusMenu .filter-status-option');
    filterStatusOptions.forEach(opt => {
        opt.addEventListener('click', () => {
            const value = opt.dataset.value || '';
            const label = opt.dataset.label || 'All statuses';
            const color = opt.dataset.color || 'bg-gray-400';
            const icon = opt.dataset.icon || 'fas fa-layer-group';
            selectFilterStatus(value, label, color, icon);
        });
    });

    // Priority filter options
    const filterPriorityOptions = document.querySelectorAll('#filterPriorityMenu .filter-priority-option');
    filterPriorityOptions.forEach(opt => {
        opt.addEventListener('click', () => {
            const value = opt.dataset.value || '';
            const label = opt.dataset.label || '';
            const level = opt.dataset.level || '';
            const color = opt.dataset.color || '';
            const icon = opt.dataset.icon || '';

            // Update hidden input
            const hiddenInput = document.getElementById('priorityFilter');
            if (hiddenInput) hiddenInput.value = value;

            // Update display label, icon and color
            const labelEl = document.getElementById('filterPriorityLabel');
            const iconEl = document.getElementById('filterPriorityIcon');
            const iconWrapEl = document.getElementById('filterPriorityIconWrap');
            if (labelEl) labelEl.textContent = label;
            if (iconEl) iconEl.className = icon + ' text-[9px]';
            if (iconWrapEl) iconWrapEl.className = `flex h-4 w-4 items-center justify-center rounded-full text-white ${color}`;

            closeFilterPriorityMenu();
            applyFilters();
        });
    });
});

// Category dropdown behaviour
function toggleFilterCategoryMenu() {
    const menu = document.getElementById('filterCategoryMenu');
    const button = document.querySelector('button[data-toggle="category-menu"]');
    if (!menu || !button) return;

    const isHidden = menu.classList.contains('hidden');

    if (isHidden) {
        // Position the dropdown
        const rect = button.getBoundingClientRect();
        menu.style.top = (rect.bottom + window.scrollY) + 'px';
        menu.style.left = (rect.left + window.scrollX) + 'px';
        menu.style.minWidth = rect.width + 'px';
        menu.classList.remove('hidden');
    } else {
        menu.classList.add('hidden');
    }
}

function closeFilterCategoryMenu() {
    const menu = document.getElementById('filterCategoryMenu');
    if (!menu) return;
    menu.classList.add('hidden');
    menu.style.top = 'auto';
    menu.style.left = 'auto';
    menu.style.minWidth = '';
}

// Status dropdown behaviour
function toggleFilterStatusMenu() {
    const menu = document.getElementById('filterStatusMenu');
    const button = document.querySelector('button[data-toggle="status-menu"]');
    if (!menu || !button) return;

    const isHidden = menu.classList.contains('hidden');

    if (isHidden) {
        // Position the dropdown
        const rect = button.getBoundingClientRect();
        menu.style.top = (rect.bottom + window.scrollY) + 'px';
        menu.style.left = (rect.left + window.scrollX) + 'px';
        menu.style.minWidth = rect.width + 'px';
        menu.classList.remove('hidden');
    } else {
        menu.classList.add('hidden');
    }
}

function closeFilterStatusMenu() {
    const menu = document.getElementById('filterStatusMenu');
    if (!menu) return;
    menu.classList.add('hidden');
    menu.style.top = 'auto';
    menu.style.left = 'auto';
    menu.style.minWidth = '';
}

// Priority dropdown behaviour
function toggleFilterPriorityMenu() {
    const menu = document.getElementById('filterPriorityMenu');
    const button = document.querySelector('button[data-toggle="priority-menu"]');
    if (!menu || !button) return;

    const isHidden = menu.classList.contains('hidden');

    if (isHidden) {
        // Position the dropdown
        const rect = button.getBoundingClientRect();
        menu.style.top = (rect.bottom + window.scrollY) + 'px';
        menu.style.left = (rect.left + window.scrollX) + 'px';
        menu.style.minWidth = rect.width + 'px';
        menu.classList.remove('hidden');
    } else {
        menu.classList.add('hidden');
    }
}

function closeFilterPriorityMenu() {
    const menu = document.getElementById('filterPriorityMenu');
    if (!menu) return;
    menu.classList.add('hidden');
    menu.style.top = 'auto';
    menu.style.left = 'auto';
    menu.style.minWidth = '';
}

// Close dropdowns on outside click
document.addEventListener('click', (e) => {
    // Client dropdown
    const clientMenu = document.getElementById('clientFilterMenu');
    const clientButton = e.target.closest('button[onclick^="toggleClientFilterMenu"]');
    if (clientMenu && !clientButton && !clientMenu.contains(e.target)) {
        closeClientFilterMenu();
    }

    // Category dropdown
    const categoryMenu = document.getElementById('filterCategoryMenu');
    const categoryButton = e.target.closest('button[data-toggle="category-menu"]');
    if (categoryMenu && !categoryButton && !categoryMenu.contains(e.target)) {
        closeFilterCategoryMenu();
    }

    // Status dropdown
    const statusMenu = document.getElementById('filterStatusMenu');
    const statusButton = e.target.closest('button[data-toggle="status-menu"]');
    if (statusMenu && !statusButton && !statusMenu.contains(e.target)) {
        closeFilterStatusMenu();
    }

    // Priority dropdown
    const priorityMenu = document.getElementById('filterPriorityMenu');
    const priorityButton = e.target.closest('button[data-toggle="priority-menu"]');
    if (priorityMenu && !priorityButton && !priorityMenu.contains(e.target)) {
        closeFilterPriorityMenu();
    }
});

// Close dropdowns on escape key
document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') {
        closeClientFilterMenu();
        closeFilterCategoryMenu();
        closeFilterStatusMenu();
        closeFilterPriorityMenu();
    }
});

// Reposition dropdown on window resize
window.addEventListener('resize', () => {
    // Client dropdown
    const clientMenu = document.getElementById('clientFilterMenu');
    const clientButton = document.querySelector('button[onclick="toggleClientFilterMenu()"]');
    if (clientMenu && clientButton && !clientMenu.classList.contains('hidden')) {
        const rect = clientButton.getBoundingClientRect();
        clientMenu.style.top = (rect.bottom + window.scrollY) + 'px';
        clientMenu.style.left = (rect.left + window.scrollX) + 'px';
        clientMenu.style.minWidth = rect.width + 'px';
    }

    // Category dropdown
    const categoryMenu = document.getElementById('filterCategoryMenu');
    const categoryButton = document.querySelector('button[data-toggle="category-menu"]');
    if (categoryMenu && categoryButton && !categoryMenu.classList.contains('hidden')) {
        const rect = categoryButton.getBoundingClientRect();
        categoryMenu.style.top = (rect.bottom + window.scrollY) + 'px';
        categoryMenu.style.left = (rect.left + window.scrollX) + 'px';
        categoryMenu.style.minWidth = rect.width + 'px';
    }

    // Status dropdown
    const statusMenu = document.getElementById('filterStatusMenu');
    const statusButton = document.querySelector('button[data-toggle="status-menu"]');
    if (statusMenu && statusButton && !statusMenu.classList.contains('hidden')) {
        const rect = statusButton.getBoundingClientRect();
        statusMenu.style.top = (rect.bottom + window.scrollY) + 'px';
        statusMenu.style.left = (rect.left + window.scrollX) + 'px';
        statusMenu.style.minWidth = rect.width + 'px';
    }

    // Priority dropdown
    const priorityMenu = document.getElementById('filterPriorityMenu');
    const priorityButton = document.querySelector('button[data-toggle="priority-menu"]');
    if (priorityMenu && priorityButton && !priorityMenu.classList.contains('hidden')) {
        const rect = priorityButton.getBoundingClientRect();
        priorityMenu.style.top = (rect.bottom + window.scrollY) + 'px';
        priorityMenu.style.left = (rect.left + window.scrollX) + 'px';
        priorityMenu.style.minWidth = rect.width + 'px';
    }
});

// Subtle fade-in for project cards on first load
document.addEventListener('DOMContentLoaded', () => {
    const cards = document.querySelectorAll('.project-card-fade');
    cards.forEach((card, index) => {
        card.style.opacity = '0';
        card.style.transform = 'translateY(4px)';
        setTimeout(() => {
            card.style.transition = 'opacity 200ms ease-out, transform 200ms ease-out';
            card.style.opacity = '1';
            card.style.transform = 'translateY(0)';
        }, 40 * index);
    });
});

// Drag and drop - Completely rewritten
document.querySelectorAll('.task-column').forEach(column => {
    new Sortable(column, {
        group: 'tasks',
        animation: 150,
        ghostClass: 'sortable-ghost',
        chosenClass: 'sortable-chosen',
        dragClass: 'sortable-drag',
        onEnd: async function(evt) {
            const taskId = evt.item.dataset.taskId;
            const newStatusId = evt.to.dataset.statusId;
            const fromColumn = evt.from;
            const toColumn = evt.to;

            try {
                const response = await fetch('/api/tasks.php', {
                    method: 'PUT',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({id: taskId, status_id: newStatusId})
                });
                
                if (!response.ok) {
                    // Revert the move if it failed
                    fromColumn.insertBefore(evt.item, fromColumn.children[evt.oldIndex]);
                    alert('Failed to update task');
                    return;
                }
                
                // Update counts and empty states after successful move
                updateColumnState(fromColumn);
                updateColumnState(toColumn);
                updateProjectStats();
                
            } catch (error) {
                // Revert the move if it failed
                fromColumn.insertBefore(evt.item, fromColumn.children[evt.oldIndex]);
                alert('Error updating task');
            }
        }
    });
});

// Update individual column state
function updateColumnState(column) {
    const tasks = Array.from(column.children).filter(c => c.classList.contains('task-card'));
    const emptyState = column.querySelector('.empty-state');
    const countSpan = column.parentElement.querySelector('span[class*="rounded-full"][class*="bg-neutral-800"]');

    // Update count badge
    if (countSpan) {
        countSpan.textContent = String(tasks.length);
    }

    // Show/hide empty state
    if (tasks.length === 0) {
        if (!emptyState) {
            const emptyDiv = document.createElement('div');
            emptyDiv.className = 'empty-state text-center py-8';
            emptyDiv.innerHTML = `
                <div class="w-8 h-8 mx-auto mb-2 rounded-full bg-neutral-800 flex items-center justify-center">
                    <i class="fas fa-inbox text-neutral-600 text-sm"></i>
                </div>
                <p class="text-xs text-neutral-500">No tasks yet</p>
            `;
            column.appendChild(emptyDiv);
        }
    } else if (emptyState) {
        emptyState.remove();
    }
}

// Update project stats
function updateProjectStats() {
    const allTasks = document.querySelectorAll('.task-card');
    const totalTasks = allTasks.length;
    
    // Find completed tasks by checking which column they're in
    let completedCount = 0;
    
    // Look for the column with "Done" in the header text (this is the completed column)
    document.querySelectorAll('.task-column').forEach(column => {
        const headerText = column.parentElement.querySelector('h3')?.textContent;
        if (headerText && headerText.includes('Done')) {
            completedCount = column.querySelectorAll('.task-card').length;
        }
    });
    
    const progress = totalTasks > 0 ? Math.round((completedCount / totalTasks) * 100) : 0;
    
    const taskCountEl = document.getElementById('project-task-count');
    const progressEl = document.getElementById('project-progress');
    
    if (taskCountEl) taskCountEl.textContent = totalTasks;
    if (progressEl) progressEl.textContent = progress + '%';
    
    console.log('Stats update:', { totalTasks, completedCount, progress }); // Debug log
}

// Close modals on escape
document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') {
        hideCreateProject();
        hideQuickAddTask();
        hideCategoryManager();
        hideTaskDetail();
    }
});

// Mobile menu
document.addEventListener('DOMContentLoaded', function() {
    const mobileMenuBtn = document.getElementById('mobile-menu-btn');
    if (mobileMenuBtn && window.openAppSidebar) {
        mobileMenuBtn.addEventListener('click', window.openAppSidebar);
    }
});
</script>
</body>
</html>
