<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tools Editor</title>
    <?php include "data/styles.php"?>
    <style>
        @keyframes fade-in {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .animate-fade-in { animation: fade-in 0.6s ease-out both; }

        input, select, textarea, .tool-item, .advanced-fields, button {
            transition: all 0.15s ease;
        }
        .toggle-advanced:hover, .tool-delete:hover {
            background-color: #e5e7eb;
        }
        @media (max-width: 640px) {
            .category-item .delete-container {
                position: absolute;
                top: 0;
                right: 0;
            }
            .advanced-fields textarea {
                width: 100%;
                margin-top: 0.5rem;
            }
            .advanced-fields {
                flex-direction: column;
            }
        }
    </style>
</head>
<body class="bg-gray-100 min-h-screen">
    <div class="max-w-4xl mx-auto p-6">
        <div class="bg-white rounded-2xl shadow-lg p-6 animate-fade-in">

            <div class="flex items-center justify-between mb-3">
                <div class="flex items-center gap-2">
                    <i data-lucide="box" class="w-6 h-6 text-indigo-600"></i>
                    <h1 class="text-2xl font-semibold text-gray-800">Tools List Editor</h1>
                </div>
                <label class="inline-flex items-center cursor-pointer">
                    <input type="checkbox" id="toggle-all-advanced" class="sr-only peer">
                    <div class="relative w-9 h-4 bg-gray-200 rounded-full peer peer-checked:bg-indigo-600 peer-checked:after:translate-x-[20px] after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-3 after:w-3 after:transition-all"></div>
                    <span class="ml-2 text-sm font-medium text-gray-600">More</span>
                </label>
            </div>

            <?php
            require_once '../config.php';
            
            // Load tools data with a fallback
            $tools_data = ['categories' => [['name' => 'None', 'desc' => '']], 'tools' => []];
            if (file_exists('../inc/data.tools.php')) {
                $tools_data = include '../inc/data.tools.php';
            }
            
            // Ensure categories is an array of arrays with name and desc
            if (!is_array($tools_data['categories']) || empty($tools_data['categories'])) {
                $tools_data['categories'] = [['name' => 'None', 'desc' => '']];
            }
            
            // Scan tools directory
            $tools_dir = __DIR__ . '/../tools/';
            $tool_files = glob($tools_dir . '*.php');
            $tool_files = array_map('basename', $tool_files);
            
            $success = false;
            $error = '';
            
            // Handle ?update query parameter
            if (isset($_GET['update'])) {
                $existing_files = array_column($tools_data['tools'], 'file');
                $new_tools = $tools_data['tools'];
                $added_tools = [];
                
                foreach ($tool_files as $file) {
                    if (!in_array($file, $existing_files)) {
                        $tool_name = str_replace('.php', '', $file);
                        $tool_name = str_replace('-', ' ', ucwords($tool_name));
                        $new_tools[] = [
                            'name' => $tool_name,
                            'desc' => 'Boost productivity instantly with powerful ' . $tool_name,
                            'icon' => 'tool',
                            'badge' => 'New',
                            'category' => 'None',
                            'file' => $file,
                            'custom_url' => ''
                        ];
                        $added_tools[] = $tool_name;
                    }
                }
                
                if (!empty($added_tools)) {
                    // Update data.tools.php
                    $content = "<?php\nreturn [\n";
                    $content .= "    'categories' => [\n";
                    foreach ($tools_data['categories'] as $category) {
                        $content .= "        [\n";
                        $content .= "            'name' => '" . addslashes($category['name']) . "',\n";
                        $content .= "            'desc' => '" . addslashes($category['desc']) . "',\n";
                        $content .= "        ],\n";
                    }
                    $content .= "    ],\n";
                    $content .= "    'tools' => [\n";
                    foreach ($new_tools as $tool) {
                        $content .= "        [\n";
                        $content .= "            'name' => '" . addslashes($tool['name']) . "',\n";
                        $content .= "            'desc' => '" . addslashes($tool['desc']) . "',\n";
                        $content .= "            'icon' => '" . addslashes($tool['icon']) . "',\n";
                        $content .= "            'badge' => '" . addslashes($tool['badge']) . "',\n";
                        $content .= "            'category' => '" . addslashes($tool['category']) . "',\n";
                        $content .= "            'file' => '" . addslashes($tool['file']) . "',\n";
                        $content .= "            'custom_url' => '" . addslashes($tool['custom_url']) . "',\n";
                        $content .= "        ],\n";
                    }
                    $content .= "    ],\n";
                    $content .= "];\n";
                    
                    if (file_put_contents('../inc/data.tools.php', $content)) {
                        $success = true;
                        $tools_data['tools'] = $new_tools;
                        $success_message = 'New tools added: ' . implode(', ', $added_tools);
                    } else {
                        $error = 'Failed to update tools data. Check file permissions.';
                    }
                } else {
                    $success = true;
                    $success_message = 'No new tools found to add.';
                }
            }
            
            // Handle POST request
            if ($_SERVER['REQUEST_METHOD'] === 'POST') {
                $posted_categories = $_POST['categories'] ?? [];
                $new_categories = [];
                foreach ($posted_categories as $cat) {
                    if (!empty($cat['name']) || $cat['name'] === 'None') {
                        $new_categories[] = [
                            'name' => $cat['name'] ?? 'None',
                            'desc' => $cat['desc'] ?? ''
                        ];
                    }
                }
                if (empty($new_categories)) {
                    $new_categories = [['name' => 'None', 'desc' => '']];
                }
                
                $posted_tools = $_POST['tools'] ?? [];
                $new_tools = [];
                $valid_category_names = array_column($new_categories, 'name');
                $skipped_tools = [];
                
                foreach ($posted_tools as $index => $tool) {
                    if (!empty($tool['name']) && !empty($tool['desc'])) {
                        $new_tools[] = [
                            'name' => $tool['name'],
                            'desc' => $tool['desc'],
                            'icon' => $tool['icon'] ?? 'tool',
                            'badge' => $tool['badge'] ?? '',
                            'category' => in_array($tool['category'] ?? 'None', $valid_category_names) ? $tool['category'] : 'None',
                            'file' => $tool['link_type'] === 'file' ? ($tool['file'] ?? '') : '',
                            'custom_url' => $tool['link_type'] === 'custom' ? ($tool['custom_url'] ?? '') : ''
                        ];
                    } else {
                        $skipped_tools[] = "Tool at index $index (Name: " . ($tool['name'] ?? 'empty') . ", Desc: " . ($tool['desc'] ?? 'empty') . ")";
                    }
                }
                
                // Beautify the array output
                $content = "<?php\nreturn [\n";
                $content .= "    'categories' => [\n";
                foreach ($new_categories as $category) {
                    $content .= "        [\n";
                    $content .= "            'name' => '" . addslashes($category['name']) . "',\n";
                    $content .= "            'desc' => '" . addslashes($category['desc']) . "',\n";
                    $content .= "        ],\n";
                }
                $content .= "    ],\n";
                $content .= "    'tools' => [\n";
                foreach ($new_tools as $tool) {
                    $content .= "        [\n";
                    $content .= "            'name' => '" . addslashes($tool['name']) . "',\n";
                    $content .= "            'desc' => '" . addslashes($tool['desc']) . "',\n";
                    $content .= "            'icon' => '" . addslashes($tool['icon']) . "',\n";
                    $content .= "            'badge' => '" . addslashes($tool['badge']) . "',\n";
                    $content .= "            'category' => '" . addslashes($tool['category']) . "',\n";
                    $content .= "            'file' => '" . addslashes($tool['file']) . "',\n";
                    $content .= "            'custom_url' => '" . addslashes($tool['custom_url']) . "',\n";
                    $content .= "        ],\n";
                }
                $content .= "    ],\n";
                $content .= "];\n";
                
                if (file_put_contents('../inc/data.tools.php', $content)) {
                    $success = true;
                    $tools_data = ['categories' => $new_categories, 'tools' => $new_tools];
                    $success_message = 'Tools saved successfully!';
                    if (!empty($skipped_tools)) {
                        $error = 'Some tools were not saved due to missing name or description: ' . implode('; ', $skipped_tools);
                    }
                } else {
                    $error = 'Failed to save tools data. Check file permissions.';
                }
            }
            ?>

            <?php if ($success): ?>
                <div class="mb-4 p-3 bg-emerald-100 text-emerald-700 rounded-md flex items-center gap-2 text-sm">
                    <i data-lucide="check-circle" class="w-4 h-4"></i>
                    <?php echo htmlspecialchars($success_message ?? 'Tools saved successfully!'); ?>
                </div>
            <?php endif; ?>

            <?php if ($error): ?>
                <div class="mb-4 p-3 bg-red-100 text-red-700 rounded-md flex items-center gap-2 text-sm">
                    <i data-lucide="alert-circle" class="w-4 h-4"></i>
                    <?php echo htmlspecialchars($error); ?>
                </div>
            <?php endif; ?>

            <form method="POST" class="space-y-4" onsubmit="return validateForm()">
                <!-- Tools Section -->
                <div class="pt-4">
                    <div id="categories-container" class="space-y-4">
                        <?php foreach ($tools_data['categories'] as $cat_index => $category): ?>
                            <div class="category-item border-gray-200 pt-5 pb-10 relative" data-category-name="<?php echo htmlspecialchars($category['name']); ?>">
                                <div class="flex flex-col sm:flex-row gap-2 mb-8 max-w-3xl m-auto">
                                    <label class="block text-sm mt-1 font-medium text-gray-400">Category:</label>
                                    <div class="flex-2">
                                        <label class="block text-sm mb-2 font-medium text-gray-400 sr-only">Category Name</label>
                                        <input type="text" name="categories[<?php echo $cat_index; ?>][name]" value="<?php echo htmlspecialchars($category['name']); ?>" placeholder="Category Name" class="w-full p-1.5 bg-blue-50 text-blue-600 rounded-md focus:ring-1 focus:ring-indigo-500 text-sm font-semibold">
                                    </div>
                                    <div class="flex-1">
                                        <label class="block text-sm mb-2 font-medium text-gray-400 sr-only">Category Description</label>
                                        <input type="text" name="categories[<?php echo $cat_index; ?>][desc]" value="<?php echo htmlspecialchars($category['desc']); ?>" placeholder="Category Description" class="w-full p-1.5 border border-gray-200 rounded-lg focus:shadow-sm text-sm font-medium text-gray-600">
                                    </div>
                                    <div class="delete-container flex items-end sm:items-center">
                                        <button type="button" onclick="this.closest('.category-item').remove(); updateCategoryOptions();" class="p-2 text-red-600 hover:text-red-800">
                                            <i data-lucide="trash-2" class="w-5 h-5"></i>
                                        </button>
                                    </div>
                                </div>
                                <div class="tools-items space-y-3 pl-3">
                                    <?php foreach ($tools_data['tools'] as $tool_index => $tool): ?>
                                        <?php if ($tool['category'] === $category['name']): ?>
                                            <div class="tool-item relative p-3 rounded-md transition-all">
                                                <div class="absolute top-4 -left-5 sm:left-4 flex flex-col gap-1">
                                                    <span class="w-6 h-6 bg-red-600 text-white rounded-full shadow flex items-center justify-center text-sm font-semibold"><?php echo $tool_index + 1; ?></span>
                                                    <button type="button" class="tool-delete bg-gray-100 rounded-full p-1 text-gray-600 hover:text-gray-800 hidden" onclick="this.closest('.tool-item').remove()">
                                                        <i data-lucide="trash-2" class="w-4 h-4"></i>
                                                    </button>
                                                    <button type="button" class="toggle-advanced bg-gray-100 rounded-full p-1 text-gray-600 hover:text-gray-800" data-tool-index="<?php echo $tool_index; ?>">
                                                        <i data-lucide="chevron-down" class="w-4 h-4"></i>
                                                    </button>
                                                </div>
                                                <div class="flex flex-col gap-2 max-w-2xl m-auto">
                                                    <!-- Name, Category, and Badge -->
                                                    <div class="flex flex-col sm:flex-row gap-2">
                                                        <div class="flex-1">
                                                            <label class="block text-xs mb-1 font-medium text-gray-400 sr-onlyx">Tool Name</label>
                                                            <input type="text" name="tools[<?php echo $tool_index; ?>][name]" value="<?php echo htmlspecialchars($tool['name'] ?? ''); ?>" placeholder="Tool Name" class="w-full p-1.5 border border-gray-200 rounded-lg focus:shadow-sm text-sm">
                                                        </div>
                                                        <div class="flex flex-row gap-2 sm:flex-row">
                                                            <div class="w-1/2 sm:w-1/2">
                                                                <label class="block text-xs mb-1 font-medium text-gray-400 sr-onlyx">Category</label>
                                                                <select name="tools[<?php echo $tool_index; ?>][category]" class="w-full p-2 bg-gray-50 rounded-lg text-gray-700 cursor-pointer rounded-md hover:bg-gray-100 text-sm">
                                                                    <?php foreach ($tools_data['categories'] as $cat): ?>
                                                                        <option value="<?php echo htmlspecialchars($cat['name']); ?>" <?php echo $tool['category'] === $cat['name'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($cat['name']); ?></option>
                                                                    <?php endforeach; ?>
                                                                </select>
                                                            </div>
                                                            <div class="w-1/2 sm:w-1/2">
                                                                <label class="block text-xs mb-1 font-medium text-gray-400 sr-onlyx">Badge</label>
                                                                <select name="tools[<?php echo $tool_index; ?>][badge]" class="w-full p-2 bg-gray-50 rounded-lg text-gray-700 cursor-pointer rounded-md hover:bg-gray-100 text-sm">
                                                                    <option value="" <?php echo $tool['badge'] === '' ? 'selected' : ''; ?>>None</option>
                                                                    <option value="New" <?php echo $tool['badge'] === 'New' ? 'selected' : ''; ?>>New</option>
                                                                    <option value="Pro" <?php echo $tool['badge'] === 'Pro' ? 'selected' : ''; ?>>Pro</option>
                                                                    <option value="Free" <?php echo $tool['badge'] === 'Free' ? 'selected' : ''; ?>>Free</option>
                                                                </select>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <!-- Advanced: Icon, Link -->
                                                    <div class="advanced-fields hidden">
                                                        <div class="sm:flex sm:flex-row sm:gap-2">
                                                            <label class="block text-sm mb-2 font-medium text-gray-400 sr-only">Description</label>
                                                            <textarea name="tools[<?php echo $tool_index; ?>][desc]" placeholder="Tool Description" class="w-full p-1.5 border border-gray-200 rounded-lg shadow-sm focus:ring-1 focus:ring-indigo-500 h-14 text-sm resize-y"><?php echo htmlspecialchars($tool['desc'] ?? ''); ?></textarea>
                                                            <div class="flex flex-row gap-2">
                                                                <div class="w-24 sm:w-24">
                                                                    <label class="block text-sm mb-1 font-medium text-gray-400">Icon</label>
                                                                    <input type="text" name="tools[<?php echo $tool_index; ?>][icon]" value="<?php echo htmlspecialchars($tool['icon'] ?? 'tool'); ?>" placeholder="Icon Name" class="w-24 p-1.5 border border-gray-200 rounded-lg shadow-sm focus:ring-1 focus:ring-indigo-500 text-sm">
                                                                </div>
                                                                <div class="flex-1">
                                                                    <label class="block text-sm mb-1 font-medium text-gray-400">Link</label>
                                                                    <div class="flex items-center gap-2">
                                                                        <select name="tools[<?php echo $tool_index; ?>][link_type]" class="w-26 p-2 bg-gray-50 rounded-lg text-gray-700 cursor-pointer rounded-md hover:bg-gray-100 text-sm link-type">
                                                                            <option value="file" <?php echo $tool['custom_url'] === '' ? 'selected' : ''; ?>>Tool File</option>
                                                                            <option value="custom" <?php echo $tool['custom_url'] !== '' ? 'selected' : ''; ?>>Custom URL</option>
                                                                        </select>
                                                                        <select name="tools[<?php echo $tool_index; ?>][file]" class="flex-2 p-2 bg-gray-50 rounded-lg text-gray-700 cursor-pointer rounded-md hover:bg-gray-100 text-sm link-field file-field" <?php echo $tool['custom_url'] !== '' ? 'style="display:none;"' : ''; ?>>
                                                                            <?php foreach ($tool_files as $file): ?>
                                                                                <option value="<?php echo htmlspecialchars($file); ?>" <?php echo $tool['file'] === $file ? 'selected' : ''; ?>><?php echo htmlspecialchars($file); ?></option>
                                                                            <?php endforeach; ?>
                                                                        </select>
                                                                        <input type="text" name="tools[<?php echo $tool_index; ?>][custom_url]" value="<?php echo htmlspecialchars($tool['custom_url'] ?? ''); ?>" placeholder="Custom URL or Text" class="flex-2 p-1.5 border border-gray-200 rounded-md shadow-sm focus:ring-1 focus:ring-indigo-500 text-sm link-field custom-field" <?php echo $tool['custom_url'] === '' ? 'style="display:none;"' : ''; ?>>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        <?php endif; ?>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                    <div class="flex gap-3 mt-3">
                        <button type="button" onclick="addToolItem()" class="mt-4 inline-flex items-center gap-2 px-4 py-2 text-sm bg-blue-100 text-blue-700 rounded-md hover:bg-blue-200">
                            <i data-lucide="plus" class="w-4 h-4"></i> Add Tool
                        </button>
                        <button type="button" onclick="addCategory()" class="mt-4 inline-flex items-center gap-2 px-4 py-2 text-sm bg-red-100 text-red-700 rounded-md hover:bg-red-200">
                            <i data-lucide="plus" class="w-4 h-4"></i> New Category
                        </button>
                    </div>
                </div>
                <div class="flex justify-end">
                    <button type="submit" class="bg-blue-600 text-white px-6 py-2 shadow rounded-xl hover:bg-blue-700 flex items-center justify-center gap-2 transition-transform w-full sm:w-auto">
                        <i data-lucide="save" class="w-4 h-4"></i> Save Tools
                    </button>
                </div>
            </form>
        </div>
    </div>

    <script>
        let toolIndex = <?php echo count($tools_data['tools']); ?>;
        let categoryIndex = <?php echo count($tools_data['categories']); ?>;
        
        function addToolItem() {
            // Default to 'None' category if no categories exist
            let selectedCategory = 'None';
            const categorySelects = document.querySelectorAll('select[name$="[category]"]');
            if (categorySelects.length > 0) {
                selectedCategory = categorySelects[categorySelects.length - 1].value || 'None';
            }
            
            // Find the category container matching the selected category
            let container = document.querySelector(`.category-item[data-category-name="${selectedCategory}"] .tools-items`);
            if (!container) {
                // Fallback to first category if selected category not found
                container = document.querySelector('#categories-container .category-item .tools-items');
            }
            
            const index = toolIndex++;
            
            const div = document.createElement('div');
            div.className = 'tool-item relative p-3 rounded-md transition-all';
            div.innerHTML = `
                <div class="absolute top-4 -left-5 sm:left-4 flex flex-col gap-1">
                    <span class="w-6 h-6 bg-red-600 text-white rounded-full shadow flex items-center justify-center text-sm font-semibold">${index + 1}</span>
                    <button type="button" class="tool-delete bg-gray-100 rounded-full p-1 text-gray-600 hover:text-gray-800 hidden" onclick="this.closest('.tool-item').remove()">
                        <i data-lucide="trash-2" class="w-4 h-4"></i>
                    </button>
                    <button type="button" class="toggle-advanced bg-gray-100 rounded-full p-1 text-gray-600 hover:text-gray-800" data-tool-index="${index}">
                        <i data-lucide="chevron-down" class="w-4 h-4"></i>
                    </button>
                </div>
                <div class="flex flex-col gap-2 max-w-2xl m-auto">
                    <!-- Name, Category, and Badge -->
                    <div class="flex flex-col sm:flex-row gap-2">
                        <div class="flex-1">
                            <label class="block text-xs mb-1 font-medium text-gray-400 sr-onlyx">Tool Name</label>
                            <input type="text" name="tools[${index}][name]" placeholder="Tool Name" class="w-full p-1.5 border border-gray-200 rounded-lg focus:shadow-sm text-sm">
                        </div>
                        <div class="flex flex-row gap-2 sm:flex-row">
                            <div class="w-1/2 sm:w-1/2">
                                <label class="block text-xs mb-1 font-medium text-gray-400 sr-onlyx">Category</label>
                                <select name="tools[${index}][category]" class="w-full p-2 bg-gray-50 rounded-lg text-gray-700 cursor-pointer rounded-md hover:bg-gray-100 text-sm">
                                    <?php foreach ($tools_data['categories'] as $cat): ?>
                                        <option value="<?php echo htmlspecialchars($cat['name']); ?>" <?php echo $cat['name'] === 'None' ? 'selected' : ''; ?>><?php echo htmlspecialchars($cat['name']); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="w-1/2 sm:w-1/2">
                                <label class="block text-xs mb-1 font-medium text-gray-400 sr-onlyx">Badge</label>
                                <select name="tools[${index}][badge]" class="w-full p-2 bg-gray-50 rounded-lg text-gray-700 cursor-pointer rounded-md hover:bg-gray-100 text-sm">
                                    <option value="">None</option>
                                    <option value="New">New</option>
                                    <option value="Pro">Pro</option>
                                    <option value="Free">Free</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <!-- Advanced: Icon, Link -->
                    <div class="advanced-fields hidden">
                        <div class="sm:flex sm:flex-row sm:gap-2">
                            <label class="block text-sm mb-2 font-medium text-gray-400 sr-only">Description</label>
                            <textarea name="tools[${index}][desc]" placeholder="Tool Description" class="w-full p-1.5 border border-gray-200 rounded-lg shadow-sm focus:ring-1 focus:ring-indigo-500 h-14 text-sm resize-y"></textarea>
                            <div class="flex flex-row gap-2">
                                <div class="w-24 sm:w-24">
                                    <label class="block text-sm mb-1 font-medium text-gray-400">Icon</label>
                                    <input type="text" name="tools[${index}][icon]" placeholder="Icon Name" value="box" class="w-24 p-1.5 border border-gray-200 rounded-lg shadow-sm focus:ring-1 focus:ring-indigo-500 text-sm">
                                </div>
                                <div class="flex-1">
                                    <label class="block text-sm mb-1 font-medium text-gray-400">Link</label>
                                    <div class="flex items-center gap-2">
                                        <select name="tools[${index}][link_type]" class="w-26 p-2 bg-gray-50 rounded-lg text-gray-700 cursor-pointer rounded-md hover:bg-gray-100 text-sm link-type">
                                            <option value="file">Tool File</option>
                                            <option value="custom">Custom URL</option>
                                        </select>
                                        <select name="tools[${index}][file]" class="flex-2 p-2 bg-gray-50 rounded-lg text-gray-700 cursor-pointer rounded-md hover:bg-gray-100 text-sm link-field file-field">
                                            <?php foreach ($tool_files as $file): ?>
                                                <option value="<?php echo htmlspecialchars($file); ?>"><?php echo htmlspecialchars($file); ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                        <input type="text" name="tools[${index}][custom_url]" placeholder="Custom URL or Text" class="flex-2 p-1.5 border border-gray-200 rounded-md shadow-sm focus:ring-1 focus:ring-indigo-500 text-sm link-field custom-field" style="display:none;">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            container.appendChild(div);
            lucide.createIcons();
            setupToggleAdvanced(div);
            updateLinkFields(div);
        }

        function addCategory() {
            const container = document.getElementById('categories-container');
            const index = categoryIndex++;
            
            const div = document.createElement('div');
            div.className = 'category-item border-gray-200 pt-5 pb-10 relative';
            div.setAttribute('data-category-name', '');
            div.innerHTML = `
                <div class="flex flex-col sm:flex-row gap-2 mb-8 max-w-3xl m-auto">
                    <label class="block text-sm mt-1 font-medium text-gray-400">Category:</label>
                    <div class="flex-2">
                        <label class="block text-sm mb-2 font-medium text-gray-400 sr-only">Category Name</label>
                        <input type="text" name="categories[${index}][name]" placeholder="Category Name" class="w-full p-1.5 bg-blue-50 text-blue-600 rounded-md focus:ring-1 focus:ring-indigo-500 text-sm font-semibold" oninput="this.closest('.category-item').setAttribute('data-category-name', this.value)">
                    </div>
                    <div class="flex-1">
                        <label class="block text-sm mb-2 font-medium text-gray-400 sr-only">Category Description</label>
                        <input type="text" name="categories[${index}][desc]" placeholder="Category Description" class="w-full p-1.5 border border-gray-200 rounded-lg focus:shadow-sm text-sm font-medium text-gray-600">
                    </div>
                    <div class="delete-container flex items-end sm:items-center">
                        <button type="button" onclick="this.closest('.category-item').remove(); updateCategoryOptions();" class="p-2 text-red-600 hover:text-red-800">
                            <i data-lucide="trash-2" class="w-5 h-5"></i>
                        </button>
                    </div>
                </div>
                <div class="tools-items space-y-3 pl-3"></div>
            `;
            container.appendChild(div);
            lucide.createIcons();
            updateCategoryOptions();
        }

        function updateCategoryOptions() {
            const categories = Array.from(document.querySelectorAll('input[name$="[name]"]')).map(input => input.value || 'None');
            const selects = document.querySelectorAll('select[name$="[category]"]');
            selects.forEach(select => {
                const currentValue = select.value;
                select.innerHTML = categories.map(cat => `<option value="${cat}" ${cat === currentValue ? 'selected' : ''}>${cat}</option>`).join('');
            });
        }

        function updateLinkFields(container) {
            const linkTypes = container.querySelectorAll('.link-type');
            linkTypes.forEach(select => {
                select.addEventListener('change', () => {
                    const parent = select.closest('.tool-item');
                    const fileField = parent.querySelector('.file-field');
                    const customField = parent.querySelector('.custom-field');
                    if (select.value === 'file') {
                        fileField.style.display = 'block';
                        customField.style.display = 'none';
                    } else {
                        fileField.style.display = 'none';
                        customField.style.display = 'block';
                    }
                });
            });
        }

        function setupToggleAdvanced(container) {
            const toggleButtons = container.querySelectorAll('.toggle-advanced');
            toggleButtons.forEach(button => {
                button.addEventListener('click', () => {
                    const toolIndex = button.getAttribute('data-tool-index');
                    const advancedFields = button.closest('.tool-item').querySelector('.advanced-fields');
                    const deleteButton = button.closest('.tool-item').querySelector('.tool-delete');
                    const icon = button.querySelector('i');
                    advancedFields.classList.toggle('hidden');
                    deleteButton.classList.toggle('hidden', advancedFields.classList.contains('hidden'));
                    icon.setAttribute('data-lucide', advancedFields.classList.contains('hidden') ? 'chevron-down' : 'chevron-up');
                    lucide.createIcons();
                });
            });
        }

        function validateForm() {
            const tools = document.querySelectorAll('.tool-item');
            for (let tool of tools) {
                const name = tool.querySelector('input[name$="[name]"]').value.trim();
                const desc = tool.querySelector('textarea[name$="[desc]"]').value.trim();
            }
            return true;
        }

        document.getElementById('toggle-all-advanced').addEventListener('change', (e) => {
            const advancedFields = document.querySelectorAll('.advanced-fields');
            const deleteButtons = document.querySelectorAll('.tool-delete');
            const toggleButtons = document.querySelectorAll('.toggle-advanced i');
            advancedFields.forEach(field => {
                field.classList.toggle('hidden', !e.target.checked);
            });
            deleteButtons.forEach(button => {
                button.classList.toggle('hidden', !e.target.checked);
            });
            toggleButtons.forEach(icon => {
                icon.setAttribute('data-lucide', e.target.checked ? 'chevron-up' : 'chevron-down');
            });
            lucide.createIcons();
        });

        document.querySelectorAll('.tool-item').forEach(setupToggleAdvanced);
        document.querySelectorAll('.tool-item').forEach(updateLinkFields);
        lucide.createIcons();
    </script>
</body>
</html>