/**
 * Canifa AI Platform Cookbook — Core Logic (Updated)
 */

document.addEventListener('DOMContentLoaded', async () => {
    const recipeNav = document.getElementById('recipeNav');
    const recipeContent = document.getElementById('recipeContent');
    const recipeSearch = document.getElementById('recipeSearch');
    const breadcrumb = document.getElementById('breadcrumb');
    const zoomOverlay = document.getElementById('zoomOverlay');
    const zoomedImage = document.getElementById('zoomedImage');
    const closeZoom = document.querySelector('.close-zoom');
    const sidebar = document.getElementById('sidebar');
    const menuToggle = document.getElementById('menuToggle');
    const themeToggle = document.getElementById('themeToggle');
    const backToTop = document.getElementById('backToTop');
    const mainContainer = document.querySelector('.recipe-content');

    let recipesRegistry = [];

    // 1. Load Registry
    try {
        const response = await fetch('data/registry.json');
        recipesRegistry = await response.json();
        renderSidebar(recipesRegistry);
        updateProgress();
    } catch (err) {
        console.error('Failed to load registry:', err);
    }

    // 2. Render Sidebar
    function renderSidebar(data) {
        recipeNav.innerHTML = '';
        data.groups.forEach(group => {
            const groupEl = document.createElement('div');
            groupEl.className = 'nav-group';
            
            const titleEl = document.createElement('div');
            titleEl.className = 'nav-group-title';
            titleEl.innerHTML = `<span>${group.name}</span> <span class="toggle-icon"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"></polyline></svg></span>`;
            
            const listEl = document.createElement('ul');
            listEl.className = 'recipe-list';
            
            group.recipes.forEach(recipe => {
                const itemEl = document.createElement('li');
                itemEl.className = 'recipe-item';
                itemEl.textContent = recipe.title;
                itemEl.onclick = () => {
                    loadRecipe(recipe.id, group.name, recipe.title);
                    if (window.innerWidth <= 768) sidebar.classList.remove('open');
                };
                listEl.appendChild(itemEl);
            });

            groupEl.appendChild(titleEl);
            groupEl.appendChild(listEl);
            recipeNav.appendChild(groupEl);

            titleEl.onclick = () => {
                const isHidden = listEl.style.display === 'none';
                listEl.style.display = isHidden ? 'block' : 'none';
                titleEl.querySelector('.toggle-icon').innerHTML = isHidden 
                    ? '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"></polyline></svg>'
                    : '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 18 15 12 9 6"></polyline></svg>';
            };
        });
    }

    // 3. Load Recipe
    async function loadRecipe(id, groupName, recipeTitle) {
        document.querySelectorAll('.recipe-item').forEach(el => el.classList.remove('active'));
        const activeItem = Array.from(document.querySelectorAll('.recipe-item')).find(el => el.textContent === recipeTitle);
        if (activeItem) activeItem.classList.add('active');

        breadcrumb.innerHTML = `<span>Cookbook</span> <span>${groupName}</span> <span>${recipeTitle}</span>`;
        recipeContent.scrollTop = 0;

        try {
            recipeContent.innerHTML = '<div style="text-align:center; padding-top:100px;">Đang tải recipe...</div>';
            const response = await fetch(`data/${id}.json`);
            const data = await response.json();
            renderRecipe(data);
            markAsRead(id);
        } catch (err) {
            recipeContent.innerHTML = `<div style="color:#ef4444; padding:20px;">Lỗi: Không tìm thấy data cho recipe <b>${id}</b>.</div>`;
        }
    }

    // 4. Render Recipe
    function renderRecipe(data) {
        let html = `
            <h1 class="recipe-title">${data.title}</h1>
            <p class="recipe-desc">${data.description}</p>
        `;

        if (data.diagram) {
            html += `
                <div class="diagram-container" onclick="zoomDiagram('${data.diagram}')">
                    <img src="${data.diagram}" alt="${data.title} Architecture">
                    <p style="font-size: 11px; color: #94a3b8; margin-top: 12px; font-weight: 600;">(CLICK TO ZOOM DIAGRAM)</p>
                </div>
            `;
        }

        data.sections.forEach(section => {
            html += `<h2 class="section-title">${section.title}</h2>`;
            
            if (section.type === 'text') {
                html += `<div class="text-block">${section.content}</div>`;
            } else if (section.type === 'api') {
                html += `
                    <div style="overflow-x: auto;">
                    <table class="api-table">
                        <thead>
                            <tr>
                                <th>Method</th>
                                <th>Endpoint</th>
                                <th>Mô tả</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${section.endpoints.map(ep => `
                                <tr>
                                    <td><span class="method-badge method-${ep.method.toLowerCase()}">${ep.method}</span></td>
                                    <td><code>${ep.path}</code></td>
                                    <td>${ep.description}</td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>
                    </div>
                `;
            } else if (section.type === 'code') {
                html += `
                    <div class="code-container">
                        <div class="code-header">
                            <span>${section.language.toUpperCase()}</span>
                            <button class="btn-copy" onclick="copyCode(this)">Copy</button>
                        </div>
                        <pre><code class="language-${section.language}">${section.code}</code></pre>
                    </div>
                `;
            }
        });

        recipeContent.innerHTML = html;
        if (window.Prism) Prism.highlightAll();
    }

    // UI Logic
    menuToggle.onclick = () => sidebar.classList.toggle('open');
    
    themeToggle.onclick = () => {
        document.body.classList.toggle('light-theme');
        localStorage.setItem('cb_theme', document.body.classList.contains('light-theme') ? 'light' : 'dark');
    };

    if (localStorage.getItem('cb_theme') === 'light') {
        document.body.classList.add('light-theme');
    }

    recipeContent.onscroll = () => {
        backToTop.style.display = recipeContent.scrollTop > 300 ? 'block' : 'none';
    };

    backToTop.onclick = () => {
        recipeContent.scrollTo({ top: 0, behavior: 'smooth' });
    };

    recipeSearch.oninput = (e) => {
        const term = e.target.value.toLowerCase();
        document.querySelectorAll('.recipe-item').forEach(el => {
            const visible = el.textContent.toLowerCase().includes(term);
            el.style.display = visible ? 'block' : 'none';
        });
        document.querySelectorAll('.nav-group').forEach(group => {
            const hasVisible = Array.from(group.querySelectorAll('.recipe-item')).some(i => i.style.display !== 'none');
            group.style.display = hasVisible ? 'block' : 'none';
        });
    };

    window.zoomDiagram = (src) => {
        zoomedImage.src = src;
        zoomOverlay.style.display = 'flex';
    };

    zoomOverlay.onclick = () => zoomOverlay.style.display = 'none';

    window.copyCode = (btn) => {
        const code = btn.parentElement.nextElementSibling.innerText;
        navigator.clipboard.writeText(code);
        btn.textContent = 'Copied!';
        setTimeout(() => btn.textContent = 'Copy', 2000);
    };

    function markAsRead(id) {
        let read = JSON.parse(localStorage.getItem('cb_read') || '[]');
        if (!read.includes(id)) {
            read.push(id);
            localStorage.setItem('cb_read', JSON.stringify(read));
            updateProgress();
        }
    }

    function updateProgress() {
        const read = JSON.parse(localStorage.getItem('cb_read') || '[]');
        const total = 26; 
        const percent = Math.min(100, Math.round((read.length / total) * 100));
        const progressEl = document.getElementById('progressPercent');
        if (progressEl) progressEl.textContent = `${percent}%`;
    }
});
