/**
 * 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>';
            
            let data;
            let isModular = false;
            
            try {
                // Try modular folder structure first
                const metaRes = await fetch(`data/${id}/meta.json`);
                if (metaRes.ok) {
                    data = await metaRes.json();
                    isModular = true;
                } else {
                    throw new Error('Not modular');
                }
            } catch(e) {
                // Fallback to legacy single JSON file
                const response = await fetch(`data/${id}.json`);
                data = await response.json();
            }

            if (isModular) {
                await renderModularRecipe(id, data);
            } else {
                renderRecipe(data);
            }
            
            markAsRead(id);
        } catch (err) {
            console.error('Error loading recipe:', err);
            recipeContent.innerHTML = `<div style="color:#ef4444; padding:20px;">Lỗi khi tải recipe <b>${id}</b>: ${err.message}</div>`;
        }
    }

    async function renderModularRecipe(id, meta) {
        let html = `
            <h1 class="recipe-title">${meta.title}</h1>
            <p class="recipe-desc">${meta.description || ''}</p>
        `;

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

        // Inline Table of Contents for Modular Recipes
        if (meta.sections && meta.sections.length > 0) {
            html += `
                <div class="toc-container" style="background:var(--bg); border:1px solid var(--border); padding: 16px; border-radius: 8px; margin-bottom: 24px;">
                    <h3 style="margin-top:0; font-size: 14px; margin-bottom: 12px; color:var(--text-main);">Nội dung tài liệu</h3>
                    <ul style="list-style:none; padding-left:0; margin:0;">
                        ${meta.sections.map(s => `<li style="margin-bottom: 8px;"><a href="#sec-${s.id}" style="color:var(--gold); text-decoration:none; font-size:13px; font-weight:600;">${s.title}</a></li>`).join('')}
                    </ul>
                </div>
            `;
        }

        // Fetch section files concurrently
        const sectionPromises = meta.sections.map(async sec => {
            const res = await fetch(`data/${id}/${sec.file}`);
            const content = await res.text();
            return { ...sec, rawContent: content };
        });

        const loadedSections = await Promise.all(sectionPromises);

        // Initialize parser libraries
        if (window.marked) {
            marked.setOptions({ breaks: true, gfm: true, sanitize: false });
        }
        if (window.mermaid) {
            mermaid.initialize({ startOnLoad: false, theme: document.body.classList.contains('light-theme') ? 'default' : 'dark' });
        }

        loadedSections.forEach(sec => {
            html += `<h2 class="section-title" id="sec-${sec.id}" style="padding-top: 20px;">${sec.title}</h2>`;
            
            if (sec.type === 'markdown') {
                if (window.marked) {
                    let parsedHtml = marked.parse(sec.rawContent);
                    // Extract mermaid blocks for rendering
                    parsedHtml = parsedHtml.replace(/<code class="language-mermaid">([\s\S]*?)<\/code>/g, '<div class="mermaid">$1</div>');
                    // Prevent wrapping mermaid block in a pre tag from markdown
                    parsedHtml = parsedHtml.replace(/<pre>\s*<div class="mermaid">([\s\S]*?)<\/div>\s*<\/pre>/g, '<div class="mermaid">$1</div>');
                    // Unescape HTML entities so Mermaid can parse correctly (e.g. ->> instead of -&gt;&gt;)
                    parsedHtml = parsedHtml.replace(/<div class="mermaid">([\s\S]*?)<\/div>/g, function(match, p1) {
                        let unescaped = p1.replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&#39;/g, "'");
                        return '<div class="mermaid">' + unescaped + '</div>';
                    });
                    html += `<div class="text-block" style="font-size: 14px; line-height: 1.6;">${parsedHtml}</div>`;
                } else {
                    html += `<pre>${sec.rawContent}</pre>`;
                }
            } else if (sec.type === 'api') {
                try {
                    const apiData = JSON.parse(sec.rawContent);
                    html += `
                        <div style="overflow-x: auto; margin-top: 16px;">
                        <table class="api-table">
                            <thead>
                                <tr>
                                    <th>Method</th>
                                    <th>Endpoint</th>
                                    <th>Mô tả</th>
                                </tr>
                            </thead>
                            <tbody>
                                ${apiData.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>
                    `;
                } catch(e) {
                    html += `<p style="color:red">Lỗi parse API JSON</p>`;
                }
            }
        });

        recipeContent.innerHTML = html;
        
        if (window.Prism) Prism.highlightAll();
        
        // Render mermaid diagrams
        if (window.mermaid) {
            try {
                mermaid.run({ querySelectorAll: '.mermaid' });
            } catch(e) { console.error('Mermaid render error:', e); }
        }
    }

    // 4. Render Recipe (Legacy JSON Fallback)
    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';
        
        const scrollable = recipeContent.scrollHeight - recipeContent.clientHeight;
        if (scrollable > 0) {
            const scrolled = (recipeContent.scrollTop / scrollable) * 100;
            const bar = document.getElementById('readingProgressBar');
            if (bar) bar.style.width = `${scrolled}%`;
        }
    };

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

    window.copyAnchor = (id) => {
        const url = new URL(window.location.href);
        url.hash = id;
        navigator.clipboard.writeText(url.toString());
        const hashEl = document.querySelector(`#${id} .anchor-link`);
        if (hashEl) {
            const og = hashEl.textContent;
            hashEl.textContent = '✓';
            setTimeout(() => hashEl.textContent = og, 2000);
        }
    };

    window.loadRecipeFromNav = (id, groupName, title) => {
        loadRecipe(id, groupName, title);
    };

    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}%`;
    }
    });
