{% extends "base.html" %}

{% block content %}
<div class="p-4 md:p-6 max-w-4xl mx-auto">
    <!-- Header -->
    <div class="flex items-center gap-3 mb-6">
        <a href="/skills" class="text-gray-400 hover:text-gray-600 dark:text-gray-500 dark:hover:text-gray-300 transition-colors">
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/></svg>
        </a>
        <h1 class="text-xl font-semibold text-gray-900 dark:text-gray-100">Edit Skillset</h1>
        <span class="text-sm text-gray-400 dark:text-gray-500 font-mono" id="skill-id-display"></span>
    </div>

    <!-- Form -->
    <form id="edit-form" class="space-y-5">
        <!-- Name -->
        <div>
            <label class="block mb-1 text-sm font-medium text-gray-700 dark:text-gray-300">Name</label>
            <input type="text" id="field-name" class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-200 rounded-md text-sm focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 outline-none" required>
        </div>

        <!-- Description -->
        <div>
            <label class="block mb-1 text-sm font-medium text-gray-700 dark:text-gray-300">Description</label>
            <textarea id="field-description" rows="3" class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-200 rounded-md text-sm focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 outline-none resize-vertical"></textarea>
        </div>

        <!-- System Prompt -->
        <div>
            <label class="block mb-1 text-sm font-medium text-gray-700 dark:text-gray-300">System Prompt</label>
            <textarea id="field-system-prompt" rows="8" class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-200 rounded-md text-sm font-mono focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 outline-none resize-vertical"></textarea>
        </div>

        <!-- Model -->
        <div>
            <label class="block mb-1 text-sm font-medium text-gray-700 dark:text-gray-300">Model (optional)</label>
            <input type="text" id="field-model" class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-200 rounded-md text-sm focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 outline-none">
        </div>

        <!-- Tools -->
        <div>
            <div class="flex items-center justify-between mb-2">
                <label class="text-sm font-medium text-gray-700 dark:text-gray-300">Tools <span id="tools-count" class="ml-1 px-1.5 py-0.5 rounded-full text-xs bg-indigo-100 dark:bg-indigo-900/40 text-indigo-600 dark:text-indigo-400 font-semibold hidden">0</span></label>
                <button type="button" id="tools-clear" class="hidden text-xs text-gray-400 dark:text-gray-500 hover:text-red-500 dark:hover:text-red-400 transition-colors">Clear all</button>
            </div>
            <!-- Selected chips -->
            <div id="tools-tags" class="flex flex-wrap gap-1.5 mb-2 empty:hidden"></div>
            <!-- Search + dropdown -->
            <div id="tools-wrapper" class="relative">
                <div class="flex items-center gap-2 px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 focus-within:ring-2 focus-within:ring-indigo-400 focus-within:border-indigo-400 transition-all">
                    <svg class="w-4 h-4 text-gray-400 dark:text-gray-500 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0"/></svg>
                    <input type="text" id="tools-input" class="flex-1 text-sm border-0 outline-none bg-transparent text-gray-900 dark:text-gray-200 placeholder-gray-400 dark:placeholder-gray-500" placeholder="Search tools…" autocomplete="off">
                </div>
                <div id="tools-dropdown" class="hidden absolute z-50 w-full mt-1 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-xl max-h-56 overflow-y-auto"></div>
            </div>
        </div>

        <!-- Skills -->
        <div>
            <div class="flex items-center justify-between mb-2">
                <label class="text-sm font-medium text-gray-700 dark:text-gray-300">Skills <span id="skills-count" class="ml-1 px-1.5 py-0.5 rounded-full text-xs bg-emerald-100 dark:bg-emerald-900/40 text-emerald-600 dark:text-emerald-400 font-semibold hidden">0</span></label>
                <button type="button" id="skills-clear" class="hidden text-xs text-gray-400 dark:text-gray-500 hover:text-red-500 dark:hover:text-red-400 transition-colors">Clear all</button>
            </div>
            <!-- Selected chips -->
            <div id="skills-tags" class="flex flex-wrap gap-1.5 mb-2 empty:hidden"></div>
            <!-- Search + dropdown -->
            <div id="skills-wrapper" class="relative">
                <div class="flex items-center gap-2 px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 focus-within:ring-2 focus-within:ring-emerald-400 focus-within:border-emerald-400 transition-all">
                    <svg class="w-4 h-4 text-gray-400 dark:text-gray-500 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0"/></svg>
                    <input type="text" id="skills-input" class="flex-1 text-sm border-0 outline-none bg-transparent text-gray-900 dark:text-gray-200 placeholder-gray-400 dark:placeholder-gray-500" placeholder="Search skills…" autocomplete="off">
                </div>
                <div id="skills-dropdown" class="hidden absolute z-50 w-full mt-1 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-xl max-h-56 overflow-y-auto"></div>
            </div>
        </div>

        <!-- Actions -->
        <div class="flex gap-3 pt-2">
            <button type="button" onclick="window.location.href='/skills#skillsets'" class="px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-md text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors">Cancel</button>
            <button type="submit" id="save-btn" class="px-4 py-2 bg-indigo-500 hover:bg-indigo-600 text-white rounded-md text-sm font-medium transition-colors">Save Changes</button>
        </div>
    </form>

    <!-- Toast -->
    <div id="toast" class="hidden fixed bottom-4 right-4 px-4 py-3 rounded-md text-sm font-medium shadow-lg z-50 transition-all"></div>
</div>

<script>
const skillId = {{ skillset.id | tojson }};
let currentTools = {{ skillset.tools | tojson }};
let currentSkills = {{ skillset.skills | tojson }};
let availableTools = [];
let availableSkills = [];

// Track keyboard focus index for dropdowns
let toolsFocusIdx = -1;
let skillsFocusIdx = -1;

document.getElementById('skill-id-display').textContent = skillId;
document.getElementById('field-name').value = {{ skillset.name | tojson }};
document.getElementById('field-description').value = {{ skillset.description | tojson }};
document.getElementById('field-system-prompt').value = {{ skillset.system_prompt | tojson }};
document.getElementById('field-model').value = {{ skillset.model | tojson }};

// ── Helpers ─────────────────────────────────────────────────────────────────

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

function escJs(s) {
    return (s || '').replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/"/g, '\\"');
}

function showToast(message, type) {
    const toast = document.getElementById('toast');
    toast.textContent = message;
    toast.className = `fixed bottom-4 right-4 px-4 py-3 rounded-md text-sm font-medium shadow-lg z-50 transition-all ${type === 'error' ? 'bg-red-500 text-white' : 'bg-green-500 text-white'}`;
    toast.classList.remove('hidden');
    setTimeout(() => toast.classList.add('hidden'), 3000);
}

function hideDropdown(id) {
    document.getElementById(id).classList.add('hidden');
    if (id === 'tools-dropdown') toolsFocusIdx = -1;
    if (id === 'skills-dropdown') skillsFocusIdx = -1;
}

// ── Tools ────────────────────────────────────────────────────────────────────

async function loadTools() {
    try {
        const res = await fetch('/api/settings/tools');
        const data = await res.json();
        availableTools = (data.tools || []).filter(t => !t.id || (!t.id.startsWith('skill:') && !t.id.startsWith('builtin:')));
        renderToolTags();
    } catch (e) {
        console.error('Failed to load tools:', e);
    }
}

function getToolFunctionName(t) {
    if (t.function && t.function.name) return String(t.function.name);
    if (t.id && !t.id.startsWith('builtin:')) return String(t.id);
    if (t.id) return String(t.id.split(':').pop());
    return String(t.name || t.id || '');
}

function getToolDisplayName(t) {
    return String(t.name || getToolFunctionName(t) || '');
}

function getToolDescription(t) {
    return (t.function && t.function.description) || t.description || '';
}

function renderToolTags() {
    const container = document.getElementById('tools-tags');
    const countBadge = document.getElementById('tools-count');
    const clearBtn = document.getElementById('tools-clear');

    container.innerHTML = currentTools.map(fnName => {
        const t = availableTools.find(t => getToolFunctionName(t) === fnName);
        const display = t ? getToolDisplayName(t) : fnName;
        return `<span class="inline-flex items-center gap-1 pl-2.5 pr-1 py-1 rounded-full text-xs font-medium bg-indigo-50 dark:bg-indigo-900/30 text-indigo-700 dark:text-indigo-300 border border-indigo-200 dark:border-indigo-800 group">
            ${escHtml(display)}
            <button type="button" onclick="removeTool('${escJs(fnName)}')" class="flex items-center justify-center w-4 h-4 rounded-full text-indigo-400 dark:text-indigo-500 hover:bg-indigo-200 dark:hover:bg-indigo-800 hover:text-indigo-700 dark:hover:text-indigo-300 transition-colors ml-0.5" title="Remove">
                <svg class="w-2.5 h-2.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M6 18L18 6M6 6l12 12"/></svg>
            </button>
        </span>`;
    }).join('');

    if (currentTools.length > 0) {
        countBadge.textContent = currentTools.length;
        countBadge.classList.remove('hidden');
        clearBtn.classList.remove('hidden');
    } else {
        countBadge.classList.add('hidden');
        clearBtn.classList.add('hidden');
    }
}

function addTool(fnName) {
    if (!currentTools.includes(fnName)) {
        currentTools.push(fnName);
        renderToolTags();
        refreshToolsDropdown();
    }
    document.getElementById('tools-input').value = '';
    document.getElementById('tools-input').focus();
    showToolsDropdown(getFilteredTools(''));
}

function removeTool(fnName) {
    currentTools = currentTools.filter(t => t !== fnName);
    renderToolTags();
}

function clearAllTools() {
    currentTools = [];
    renderToolTags();
    hideDropdown('tools-dropdown');
}

function getFilteredTools(query) {
    const q = query.toLowerCase();
    if (!q) return availableTools;
    return availableTools.filter(t => {
        const fnName = getToolFunctionName(t);
        const displayName = getToolDisplayName(t);
        return displayName.toLowerCase().includes(q) || fnName.toLowerCase().includes(q);
    });
}

function refreshToolsDropdown() {
    const q = document.getElementById('tools-input').value.trim();
    const dd = document.getElementById('tools-dropdown');
    if (!dd.classList.contains('hidden')) {
        showToolsDropdown(getFilteredTools(q));
    }
}

function showToolsDropdown(results) {
    const dd = document.getElementById('tools-dropdown');
    toolsFocusIdx = -1;

    if (results.length === 0) {
        dd.innerHTML = '<div class="px-4 py-3 text-xs text-gray-400 dark:text-gray-500 text-center">No tools found</div>';
    } else {
        dd.innerHTML = results.map((t, i) => {
            const fnName = getToolFunctionName(t);
            const displayName = getToolDisplayName(t);
            const desc = getToolDescription(t);
            const already = currentTools.includes(fnName);
            return `<div class="dd-item flex items-center gap-3 px-4 py-2.5 cursor-pointer transition-colors ${already ? 'opacity-50 cursor-not-allowed' : 'hover:bg-indigo-50 dark:hover:bg-indigo-900/20'}"
                data-idx="${i}" data-fn="${escHtml(fnName)}" data-already="${already}"
                ${already ? '' : `onclick="addTool('${escJs(fnName)}')"`}>
                <div class="flex-1 min-w-0">
                    <div class="text-sm font-medium text-gray-800 dark:text-gray-200 truncate">${escHtml(displayName)}</div>
                    ${desc ? `<div class="text-xs text-gray-400 dark:text-gray-500 truncate">${escHtml(desc)}</div>` : ''}
                </div>
                ${already ? `<svg class="w-4 h-4 text-indigo-400 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M5 13l4 4L19 7"/></svg>` : ''}
            </div>`;
        }).join('');
    }
    dd.classList.remove('hidden');
}

// ── Skills ───────────────────────────────────────────────────────────────────

async function loadSkills() {
    try {
        const res = await fetch('/api/skills');
        const data = await res.json();
        availableSkills = data.skills || [];
        renderSkillTags();
    } catch (e) {
        console.error('Failed to load skills:', e);
    }
}

function renderSkillTags() {
    const container = document.getElementById('skills-tags');
    const countBadge = document.getElementById('skills-count');
    const clearBtn = document.getElementById('skills-clear');

    container.innerHTML = currentSkills.map(name => {
        return `<span class="inline-flex items-center gap-1 pl-2.5 pr-1 py-1 rounded-full text-xs font-medium bg-emerald-50 dark:bg-emerald-900/30 text-emerald-700 dark:text-emerald-300 border border-emerald-200 dark:border-emerald-800 group">
            ${escHtml(name)}
            <button type="button" onclick="removeSkill('${escJs(name)}')" class="flex items-center justify-center w-4 h-4 rounded-full text-emerald-400 dark:text-emerald-500 hover:bg-emerald-200 dark:hover:bg-emerald-800 hover:text-emerald-700 dark:hover:text-emerald-300 transition-colors ml-0.5" title="Remove">
                <svg class="w-2.5 h-2.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M6 18L18 6M6 6l12 12"/></svg>
            </button>
        </span>`;
    }).join('');

    if (currentSkills.length > 0) {
        countBadge.textContent = currentSkills.length;
        countBadge.classList.remove('hidden');
        clearBtn.classList.remove('hidden');
    } else {
        countBadge.classList.add('hidden');
        clearBtn.classList.add('hidden');
    }
}

function addSkill(name) {
    if (!currentSkills.includes(name)) {
        currentSkills.push(name);
        renderSkillTags();
        refreshSkillsDropdown();
    }
    document.getElementById('skills-input').value = '';
    document.getElementById('skills-input').focus();
    showSkillsDropdown(getFilteredSkills(''));
}

function removeSkill(name) {
    currentSkills = currentSkills.filter(s => s !== name);
    renderSkillTags();
}

function clearAllSkills() {
    currentSkills = [];
    renderSkillTags();
    hideDropdown('skills-dropdown');
}

function getFilteredSkills(query) {
    const q = query.toLowerCase();
    if (!q) return availableSkills;
    return availableSkills.filter(s => {
        const name = String(s.id || (typeof s === 'string' ? s : '') || '');
        const displayName = String(s.name || name || '');
        return name.toLowerCase().includes(q) || displayName.toLowerCase().includes(q);
    });
}

function refreshSkillsDropdown() {
    const q = document.getElementById('skills-input').value.trim();
    const dd = document.getElementById('skills-dropdown');
    if (!dd.classList.contains('hidden')) {
        showSkillsDropdown(getFilteredSkills(q));
    }
}

function showSkillsDropdown(results) {
    const dd = document.getElementById('skills-dropdown');
    skillsFocusIdx = -1;

    if (results.length === 0) {
        dd.innerHTML = '<div class="px-4 py-3 text-xs text-gray-400 dark:text-gray-500 text-center">No skills found</div>';
    } else {
        dd.innerHTML = results.map((s, i) => {
            const name = s.id || s;
            const displayName = s.name || name;
            const desc = s.description || '';
            const already = currentSkills.includes(name);
            return `<div class="dd-item flex items-center gap-3 px-4 py-2.5 cursor-pointer transition-colors ${already ? 'opacity-50 cursor-not-allowed' : 'hover:bg-emerald-50 dark:hover:bg-emerald-900/20'}"
                data-idx="${i}" data-name="${escHtml(name)}" data-already="${already}"
                ${already ? '' : `onclick="addSkill('${escJs(name)}')"`}>
                <div class="flex-1 min-w-0">
                    <div class="text-sm font-medium text-gray-800 dark:text-gray-200 truncate">${escHtml(displayName)}</div>
                    ${desc ? `<div class="text-xs text-gray-400 dark:text-gray-500 truncate">${escHtml(desc)}</div>` : ''}
                </div>
                ${already ? `<svg class="w-4 h-4 text-emerald-400 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M5 13l4 4L19 7"/></svg>` : ''}
            </div>`;
        }).join('');
    }
    dd.classList.remove('hidden');
}

// ── Keyboard navigation helper ────────────────────────────────────────────────

function navigateDropdown(ddId, delta, selectFn, dataAttr) {
    const dd = document.getElementById(ddId);
    const items = [...dd.querySelectorAll('.dd-item[data-already="false"]')];
    if (items.length === 0) return;

    const currentFocusIdx = ddId === 'tools-dropdown' ? toolsFocusIdx : skillsFocusIdx;
    const newIdx = Math.max(0, Math.min(items.length - 1, currentFocusIdx + delta));

    items.forEach((el, i) => {
        if (ddId === 'tools-dropdown') {
            el.classList.toggle('bg-indigo-50', i === newIdx);
            el.classList.toggle('dark:bg-indigo-900/20', i === newIdx);
        }
        if (ddId === 'skills-dropdown') {
            el.classList.toggle('bg-emerald-50', i === newIdx);
            el.classList.toggle('dark:bg-emerald-900/20', i === newIdx);
        }
    });
    items[newIdx]?.scrollIntoView({ block: 'nearest' });

    if (ddId === 'tools-dropdown') toolsFocusIdx = newIdx;
    else skillsFocusIdx = newIdx;
}

function selectFocused(ddId, dataAttr, selectFn) {
    const dd = document.getElementById(ddId);
    const items = [...dd.querySelectorAll('.dd-item[data-already="false"]')];
    const currentFocusIdx = ddId === 'tools-dropdown' ? toolsFocusIdx : skillsFocusIdx;
    if (currentFocusIdx >= 0 && items[currentFocusIdx]) {
        selectFn(items[currentFocusIdx].dataset[dataAttr]);
        return true;
    }
    return false;
}

// ── Event bindings ────────────────────────────────────────────────────────────

document.getElementById('tools-input').addEventListener('focus', function() {
    showToolsDropdown(getFilteredTools(this.value.trim()));
});

document.getElementById('tools-input').addEventListener('input', function() {
    showToolsDropdown(getFilteredTools(this.value.trim()));
});

document.getElementById('tools-input').addEventListener('keydown', function(e) {
    const dd = document.getElementById('tools-dropdown');
    const isOpen = !dd.classList.contains('hidden');
    if (e.key === 'ArrowDown') { e.preventDefault(); if (!isOpen) showToolsDropdown(getFilteredTools('')); navigateDropdown('tools-dropdown', 1); return; }
    if (e.key === 'ArrowUp') { e.preventDefault(); navigateDropdown('tools-dropdown', -1); return; }
    if (e.key === 'Escape') { hideDropdown('tools-dropdown'); return; }
    if (e.key === 'Enter') {
        e.preventDefault();
        if (selectFocused('tools-dropdown', 'fn', addTool)) return;
        const results = getFilteredTools(this.value.trim()).filter(t => !currentTools.includes(getToolFunctionName(t)));
        if (results.length > 0) addTool(getToolFunctionName(results[0]));
    }
});

document.getElementById('skills-input').addEventListener('focus', function() {
    showSkillsDropdown(getFilteredSkills(this.value.trim()));
});

document.getElementById('skills-input').addEventListener('input', function() {
    showSkillsDropdown(getFilteredSkills(this.value.trim()));
});

document.getElementById('skills-input').addEventListener('keydown', function(e) {
    const dd = document.getElementById('skills-dropdown');
    const isOpen = !dd.classList.contains('hidden');
    if (e.key === 'ArrowDown') { e.preventDefault(); if (!isOpen) showSkillsDropdown(getFilteredSkills('')); navigateDropdown('skills-dropdown', 1); return; }
    if (e.key === 'ArrowUp') { e.preventDefault(); navigateDropdown('skills-dropdown', -1); return; }
    if (e.key === 'Escape') { hideDropdown('skills-dropdown'); return; }
    if (e.key === 'Enter') {
        e.preventDefault();
        if (selectFocused('skills-dropdown', 'name', addSkill)) return;
        const results = getFilteredSkills(this.value.trim()).filter(s => !currentSkills.includes(s.id || s));
        if (results.length > 0) addSkill(results[0].id || results[0]);
    }
});

document.getElementById('tools-clear').addEventListener('click', clearAllTools);
document.getElementById('skills-clear').addEventListener('click', clearAllSkills);

// Close dropdowns when clicking outside
document.addEventListener('click', function(e) {
    if (!e.target.closest('#tools-wrapper') && !e.target.closest('#tools-tags')) hideDropdown('tools-dropdown');
    if (!e.target.closest('#skills-wrapper') && !e.target.closest('#skills-tags')) hideDropdown('skills-dropdown');
});

// ── Form submit ───────────────────────────────────────────────────────────────

document.getElementById('edit-form').addEventListener('submit', async function(e) {
    e.preventDefault();
    const btn = document.getElementById('save-btn');
    btn.disabled = true;
    btn.textContent = 'Saving...';

    const payload = {
        name: document.getElementById('field-name').value,
        description: document.getElementById('field-description').value,
        system_prompt: document.getElementById('field-system-prompt').value,
        model: document.getElementById('field-model').value,
        tools: currentTools,
        skills: currentSkills,
    };

    try {
        const res = await fetch(`/api/skillsets/${skillId}`, {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload),
        });
        const data = await res.json();
        if (!res.ok) {
            showToast(data.error || 'Failed to save', 'error');
        } else {
            showToast('Skillset updated successfully!', 'success');
            setTimeout(() => { window.location.href = '/skills#skillsets'; }, 1000);
        }
    } catch (e) {
        showToast('Network error: ' + e.message, 'error');
    }

    btn.disabled = false;
    btn.textContent = 'Save Changes';
});

loadTools();
loadSkills();
</script>
{% endblock %}
