import { state } from './state.js';

export function closeModal(modalId) {
    const modal = document.getElementById(modalId);
    if (modal) modal.classList.remove('active');
}

export function openResourceModal(resource = null) {
    const titleEl = document.getElementById('resourceModalTitle');
    const form = document.getElementById('resourceForm');
    form.reset();

    if (resource) {
        titleEl.textContent = 'カードの編集';
        document.getElementById('cardId').value = resource.id;
        document.getElementById('resourceTitle').value = resource.title || '';
        document.getElementById('resourceContent').value = resource.content || '';
        document.getElementById('resourceTags').value = (resource.tags || []).join(', ');
    } else {
        titleEl.textContent = '新規カードの作成';
        document.getElementById('cardId').value = '';
        document.getElementById('resourceTags').value = '';
    }

    state.modals.resource.classList.add('active');
    setTimeout(() => document.getElementById('resourceTitle').focus(), 50);
}

let _confirmResolveFn = null;

function resolveGenericConfirm(result) {
    if (!_confirmResolveFn) return;
    const resolve = _confirmResolveFn;
    _confirmResolveFn = null;
    closeModal('genericConfirmModal');
    resolve(result);
}

export function showConfirmDialog(title, message, buttonText = 'OK', isDanger = false) {
    return new Promise((resolve) => {
        _confirmResolveFn = resolve;

        document.getElementById('genericConfirmTitle').textContent = title;
        document.getElementById('genericConfirmMessage').textContent = message;

        const actionBtn = document.getElementById('btnGenericConfirmAction');
        actionBtn.textContent = buttonText;
        actionBtn.classList.toggle('text-danger', isDanger);

        document.getElementById('genericConfirmModal').classList.add('active');
    });
}

document.getElementById('btnGenericConfirmAction')?.addEventListener('click', () => resolveGenericConfirm(true));
document.getElementById('btnGenericConfirmCancel')?.addEventListener('click', () => resolveGenericConfirm(false));
document.getElementById('genericConfirmModal')?.addEventListener('mousedown', (e) => {
    if (e.target === e.currentTarget) resolveGenericConfirm(false);
});
document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape' && document.getElementById('genericConfirmModal')?.classList.contains('active')) {
        resolveGenericConfirm(false);
    }
});

export function toggleTag(tagStr) {
    const input = document.getElementById('resourceTags');
    let tags = input.value.split(',').map(t => t.trim()).filter(t => t !== '');
    
    const lowerTagStr = tagStr.toLowerCase();
    const index = tags.findIndex(t => t.toLowerCase() === lowerTagStr);
    
    if (index !== -1) {
        tags.splice(index, 1);
    } else {
        tags.push(tagStr);
    }
    
    input.value = tags.join(', ');
    input.focus();
}
