
export function showToast(message, type = 'info') {
    const container = document.getElementById('toastContainer');
    const toast = document.createElement('div');
    toast.className = `toast ${type}`;
    toast.textContent = message;

    container.appendChild(toast);

    setTimeout(() => toast.classList.add('show'), 10);

    setTimeout(() => {
        toast.classList.remove('show');
        setTimeout(() => toast.remove(), 300);
    }, 3000);
}

export function getIntersectingZone(x, y, width, height, binderPlacements) {
    if (!binderPlacements) return null;
    const zones = binderPlacements.filter(p => p.type === 'zone');
    for (const zone of zones) {
        const overlapX = x < zone.x + zone.width && x + width > zone.x;
        const overlapY = y < zone.y + zone.height && y + height > zone.y;
        if (overlapX && overlapY) return zone;
    }
    return null;
}

export function classifyResourceKind(res) {
    const pathOrTitle = res.file_path || res.title || '';
    const tags = res.tags || [];

    if (pathOrTitle.startsWith('http://') || pathOrTitle.startsWith('https://')) return 'url';
    if (tags.some(t => t.toLowerCase() === 'task')) return 'task';
    if (tags.some(t => t.toLowerCase() === 'memo' || t === 'メモ')) return 'memo';

    const isFolder = pathOrTitle.endsWith('\\') || pathOrTitle.endsWith('/') || !pathOrTitle.includes('.');
    if (isFolder && pathOrTitle) return 'folder';

    const extMatch = pathOrTitle.match(/\.([^.]+)$/);
    const ext = extMatch ? extMatch[1].toLowerCase() : '';
    const imageExts = ['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'svg'];
    const textExts = ['txt', 'md', 'csv', 'json', 'ini', 'log', 'js', 'php', 'css', 'html', 'xml'];

    if (imageExts.includes(ext)) return 'image';
    if (textExts.includes(ext)) return 'text';
    return 'other';
}

export function buildCardTransform(x, y, rotation = 0, scale = 1) {
    const rot = Number(rotation) || 0;
    const rotatePart = rot !== 0 ? ` rotate(${rot}deg)` : '';
    const scalePart = scale !== 1 ? ` scale(${scale})` : '';
    return `translate(${x}px, ${y}px)${rotatePart}${scalePart}`;
}

export function bindGuardedFormSubmit(formEl, handler) {
    if (!formEl) return;

    let isSubmitting = false;
    formEl.addEventListener('submit', async (e) => {
        e.preventDefault();
        if (isSubmitting) return;
        isSubmitting = true;

        const submitBtn = formEl.querySelector('button[type="submit"]');
        if (submitBtn) submitBtn.disabled = true;

        try {
            await handler(e);
        } finally {
            isSubmitting = false;
            if (submitBtn) submitBtn.disabled = false;
        }
    });
}

export function escapeHtml(unsafe) {
    if (!unsafe) return '';
    return unsafe
         .replace(/&/g, "&amp;")
         .replace(/</g, "&lt;")
         .replace(/>/g, "&gt;")
         .replace(/"/g, "&quot;")
         .replace(/'/g, "&#039;");
}
