/* ============================================
   MODULE SPECIFICATION (per module)
   ============================================ */
function renderAllModuleSpecs() {
    const container = document.getElementById('moduleSpecContainer');
    container.innerHTML = data.modules.map(m => renderModuleSpecSection(m)).join('');
    // Bind editable fields in module specs
    container.querySelectorAll('.editable[data-module-field]').forEach(el => {
        el.addEventListener('blur', function() {
            const code = this.dataset.moduleCode;
            const field = this.dataset.moduleField;
            if (data.moduleSpecs[code]) {
                data.moduleSpecs[code][field] = this.textContent.trim();
                autoSave();
            }
        });
    });
    // Restore currently visible section after re-render
    restoreCurrentSection();
    // Re-initialize inline comment buttons on module spec cards
    if (typeof initInlineComments === 'function') initInlineComments();
}

function renderModuleSpecSection(mod) {
    const code = mod.code;
    const spec = data.moduleSpecs[code] || { useCases: [], businessRules: [], entities: [], permissions: [], notes: '' };

    return `
    <div class="section" id="module-spec-${code}" style="display:none;">
        <h2 class="section-title">${mod.name}</h2>
        <p class="section-subtitle">${mod.description || 'Specification detaillee de ce domaine fonctionnel.'}</p>

        <div class="tab-bar">
            <button class="tab-btn active" onclick="switchTab('${code}', 'uc')">Cas d'utilisation</button>
            <button class="tab-btn" onclick="switchTab('${code}', 'br')">Regles metier</button>
            <button class="tab-btn" onclick="switchTab('${code}', 'ent')">Donnees</button>
            <button class="tab-btn" onclick="switchTab('${code}', 'perm')">Droits d'acces</button>
            <button class="tab-btn" onclick="switchTab('${code}', 'mock')">Maquettes</button>
            <button class="tab-btn" onclick="switchTab('${code}', 'notes')">Notes</button>
            <button class="tab-btn" onclick="switchTab('${code}', 'struct')">Structure</button>
        </div>

        <!-- TAB: Cas d'utilisation -->
        <div class="tab-panel active" id="tab-${code}-uc">
            <p style="font-size:0.85rem;color:var(--text-muted);margin-bottom:1rem;">Decrivez ce que chaque type d'utilisateur peut faire dans ce domaine. Un cas d'utilisation = une action concrete.</p>
            <div id="ucList-${code}" class="uc-list">
                ${spec.useCases.map((uc, i) => renderUseCase(code, uc, i)).join('')}
            </div>
            <button class="add-btn" onclick="toggleForm('addUcForm-${code}')">+ Ajouter un cas d'utilisation</button>
            <div class="inline-form" id="addUcForm-${code}">
                <div class="inline-form-title">Nouveau cas d'utilisation</div>
                <div class="form-group">
                    <label class="form-label">Que fait l'utilisateur ? (exemple : Creer une commande)</label>
                    <input type="text" class="form-input" id="uc-name-${code}" placeholder="Action concrete de l'utilisateur">
                </div>
                <div class="form-group">
                    <label class="form-label">Qui realise cette action ? (profil utilisateur)</label>
                    <input type="text" class="form-input" id="uc-actor-${code}" placeholder="Exemple : Responsable de production">
                </div>
                <div class="form-group">
                    <label class="form-label">Deroulement normal, etape par etape (une par ligne)</label>
                    <textarea class="form-textarea" id="uc-steps-${code}" placeholder="1. L'utilisateur ouvre la page de creation&#10;2. Il remplit les champs obligatoires&#10;3. Il valide le formulaire&#10;4. Le systeme enregistre et confirme"></textarea>
                </div>
                <div class="form-group">
                    <label class="form-label">Que se passe-t-il si quelque chose ne va pas ? (optionnel)</label>
                    <textarea class="form-textarea" id="uc-alt-${code}" placeholder="Exemple : Si les donnees sont incorrectes, le systeme affiche un message d'erreur" style="min-height:50px;"></textarea>
                </div>
                <div class="form-actions">
                    <button class="btn" onclick="toggleForm('addUcForm-${code}')">Annuler</button>
                    <button class="btn btn-primary" onclick="addUseCase('${code}')">Ajouter</button>
                </div>
            </div>
        </div>

        <!-- TAB: Regles metier -->
        <div class="tab-panel" id="tab-${code}-br">
            <p style="font-size:0.85rem;color:var(--text-muted);margin-bottom:1rem;">Les regles que le systeme doit respecter. Formulez-les sous forme de conditions : "Si... alors... sinon..."</p>
            <div id="brList-${code}">
                ${spec.businessRules.map((br, i) => renderBusinessRule(code, br, i)).join('')}
            </div>
            <button class="add-btn" onclick="toggleForm('addBrForm-${code}')">+ Ajouter une regle metier</button>
            <div class="inline-form" id="addBrForm-${code}">
                <div class="inline-form-title">Nouvelle regle metier</div>
                <div class="form-group">
                    <label class="form-label">Nom court de la regle</label>
                    <input type="text" class="form-input" id="br-name-${code}" placeholder="Exemple : Verification du budget disponible">
                </div>
                <div class="form-group">
                    <label class="form-label">Categorie</label>
                    <select class="form-select" id="br-cat-${code}">
                        <option value="validation">Verification (le systeme verifie que...)</option>
                        <option value="calculation">Calcul (le systeme calcule...)</option>
                        <option value="workflow">Processus (quand X se produit, alors...)</option>
                        <option value="security">Securite (seul... peut...)</option>
                        <option value="data">Donnees (les donnees doivent...)</option>
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label">Formulation de la regle (Si... alors... sinon...)</label>
                    <textarea class="form-textarea" id="br-statement-${code}" placeholder="Si le montant de la commande depasse le budget du client, alors la commande est refusee et un message d'erreur s'affiche"></textarea>
                </div>
                <div class="form-group">
                    <label class="form-label">Exemple concret (optionnel)</label>
                    <input type="text" class="form-input" id="br-example-${code}" placeholder="Exemple : Commande de 5000 CHF, budget de 2000 CHF -> refusee">
                </div>
                <div class="form-actions">
                    <button class="btn" onclick="toggleForm('addBrForm-${code}')">Annuler</button>
                    <button class="btn btn-primary" onclick="addBusinessRule('${code}')">Ajouter</button>
                </div>
            </div>
        </div>

        <!-- TAB: Donnees (Entites) -->
        <div class="tab-panel" id="tab-${code}-ent">
            <p style="font-size:0.85rem;color:var(--text-muted);margin-bottom:1rem;">Les types de donnees que ce domaine gere. Decrivez les informations importantes a enregistrer pour chaque type.</p>
            <div id="entList-${code}">
                ${spec.entities.length > 0
                    ? spec.entities.map((ent, i) => renderEntity(code, ent, i)).join('')
                    : (mod.entities || []).length > 0
                        ? '<div class="card" style="color:var(--text-muted);padding:1.5rem;"><p style="margin-bottom:0.75rem;">Les schemas detailles ne sont pas encore disponibles. Entites identifiees :</p><ul style="list-style:disc;padding-left:1.5rem;">' + mod.entities.map(e => '<li>' + e + '</li>').join('') + '</ul><p style="font-size:0.8rem;margin-top:0.75rem;font-style:italic;">Utilisez le bouton ci-dessous pour ajouter les schemas detailles.</p></div>'
                        : ''
                }
            </div>
            <button class="add-btn" onclick="toggleForm('addEntForm-${code}')">+ Ajouter un type de donnees</button>
            <div class="inline-form" id="addEntForm-${code}">
                <div class="inline-form-title">Nouveau type de donnees</div>
                <div class="form-group">
                    <label class="form-label">Nom (exemple : Commande, Client, Facture)</label>
                    <input type="text" class="form-input" id="ent-name-${code}" placeholder="Nom du type de donnees">
                </div>
                <div class="form-group">
                    <label class="form-label">Description : a quoi sert cette donnee ?</label>
                    <textarea class="form-textarea" id="ent-desc-${code}" placeholder="En une ou deux phrases, decrivez ce que represente cette donnee dans votre activite" style="min-height:50px;"></textarea>
                </div>
                <div class="form-group">
                    <label class="form-label">Informations a enregistrer (une par ligne : Nom - Description)</label>
                    <textarea class="form-textarea" id="ent-attrs-${code}" placeholder="Numero - Identifiant unique de la commande&#10;Date - Date de creation de la commande&#10;Montant total - Somme des lignes&#10;Statut - Brouillon, Envoyee, Validee, Refusee"></textarea>
                </div>
                <div class="form-group">
                    <label class="form-label">Relations avec d'autres donnees (optionnel, une par ligne)</label>
                    <textarea class="form-textarea" id="ent-rels-${code}" placeholder="Client - Chaque commande appartient a un client&#10;Ligne de commande - Une commande contient plusieurs lignes" style="min-height:50px;"></textarea>
                </div>
                <div class="form-actions">
                    <button class="btn" onclick="toggleForm('addEntForm-${code}')">Annuler</button>
                    <button class="btn btn-primary" onclick="addEntity('${code}')">Ajouter</button>
                </div>
            </div>
        </div>

        <!-- TAB: Droits d'acces -->
        <div class="tab-panel" id="tab-${code}-perm">
            <p style="font-size:0.85rem;color:var(--text-muted);margin-bottom:1rem;">Definissez qui peut faire quoi dans ce domaine. Cochez les actions autorisees pour chaque profil.</p>
            <div id="permGrid-${code}">
                ${renderPermissionGrid(code)}
            </div>
            <div style="display:flex;gap:0.75rem;margin-top:1rem;flex-wrap:wrap;">
                <button class="add-btn" onclick="toggleForm('addRoleForm-${code}')" style="flex:1;min-width:200px;">+ Ajouter un role</button>
                <button class="add-btn" onclick="toggleForm('addActionForm-${code}')" style="flex:1;min-width:200px;">+ Ajouter une action</button>
            </div>
            <div class="inline-form" id="addRoleForm-${code}">
                <div class="inline-form-title">Nouveau role</div>
                <div class="form-group">
                    <label class="form-label">Nom du role</label>
                    <input type="text" class="form-input" id="role-name-${code}" placeholder="Exemple : Superviseur, Auditeur...">
                </div>
                <div class="form-actions">
                    <button class="btn" onclick="toggleForm('addRoleForm-${code}')">Annuler</button>
                    <button class="btn btn-primary" onclick="addCustomRole('${code}')">Ajouter</button>
                </div>
            </div>
            <div class="inline-form" id="addActionForm-${code}">
                <div class="inline-form-title">Nouvelle action</div>
                <div class="form-group">
                    <label class="form-label">Nom de l'action</label>
                    <input type="text" class="form-input" id="action-name-${code}" placeholder="Exemple : Archiver, Imprimer, Approuver...">
                </div>
                <div class="form-actions">
                    <button class="btn" onclick="toggleForm('addActionForm-${code}')">Annuler</button>
                    <button class="btn btn-primary" onclick="addCustomAction('${code}')">Ajouter</button>
                </div>
            </div>
        </div>

        <!-- TAB: Maquettes -->
        <div class="tab-panel" id="tab-${code}-mock">
            <p style="font-size:0.85rem;color:var(--text-muted);margin-bottom:1rem;">Maquettes validees lors de l'analyse. Ces wireframes montrent la structure exacte des ecrans de ce domaine.</p>
            <div id="mockupContainer-${code}">
                ${renderModuleMockups(code)}
            </div>
        </div>

        <!-- TAB: Notes -->
        <div class="tab-panel" id="tab-${code}-notes">
            <p style="font-size:0.85rem;color:var(--text-muted);margin-bottom:1rem;">Notes libres, questions en suspens, elements a clarifier pour ce domaine.</p>
            <div class="card">
                <div class="editable" contenteditable="true" data-module-code="${code}" data-module-field="notes" data-placeholder="Notez ici tout ce qui concerne ce domaine : questions, precisions, contraintes particulieres...">${spec.notes || ''}</div>
            </div>
        </div>

        <!-- TAB: Structure (sections/resources) -->
        <div class="tab-panel" id="tab-${code}-struct">
            <p style="font-size:0.85rem;color:var(--text-muted);margin-bottom:1rem;">Organisation des ecrans et ressources de ce domaine. Structure hierarchique : sections regroupant des ressources.</p>
            <div id="structContainer-${code}">
                ${renderModuleStructure(code)}
            </div>
        </div>
    </div>`;
}

function renderUseCase(code, uc, index) {
    return `
        <div class="uc-item">
            <div class="uc-header">
                <span class="uc-id">UC-${String(index + 1).padStart(3, '0')}</span>
                <span class="uc-title">${uc.name}</span>
                <div class="uc-actions">
                    <button class="btn btn-sm" onclick="removeUseCase('${code}',${index})">Supprimer</button>
                </div>
            </div>
            <div class="uc-actors"><div class="uc-actor">${uc.actor}</div></div>
            ${uc.steps ? `<div class="uc-detail-label">Deroulement</div><div class="uc-detail">${uc.steps.replace(/\n/g, '<br>')}</div>` : ''}
            ${uc.alternative ? `<div class="uc-detail-label">En cas de probleme</div><div class="uc-detail" style="color:var(--warning);">${uc.alternative}</div>` : ''}
            <div style="padding:0.5rem 0.75rem;border-top:1px solid var(--border);background:var(--bg-input);border-radius:0 0 8px 8px;">
                <label style="font-size:0.75rem;color:var(--text-muted);display:block;margin-bottom:0.25rem;">Commentaire / Feedback :</label>
                <textarea class="form-textarea" placeholder="Ajouter un commentaire sur ce cas d'utilisation..."
                    onblur="updateSpecComment('${code}','uc',${index},this.value)"
                    style="min-height:45px;font-size:0.8rem;resize:vertical;">${getSpecComment(code, 'uc', index)}</textarea>
            </div>
        </div>`;
}

function addUseCase(code) {
    const name = document.getElementById('uc-name-' + code).value.trim();
    if (!name) return;
    if (!data.moduleSpecs[code]) data.moduleSpecs[code] = { useCases: [], businessRules: [], entities: [], permissions: [], notes: '' };

    data.moduleSpecs[code].useCases.push({
        name: name,
        actor: document.getElementById('uc-actor-' + code).value.trim(),
        steps: document.getElementById('uc-steps-' + code).value.trim(),
        alternative: document.getElementById('uc-alt-' + code).value.trim()
    });

    renderAllModuleSpecs();
    updateCounts();
    autoSave();
}

function removeUseCase(code, index) {
    data.moduleSpecs[code].useCases.splice(index, 1);
    renderAllModuleSpecs();
    updateCounts();
    autoSave();
}

function renderBusinessRule(code, br, index) {
    const catColors = { validation: 'br-cat-validation', calculation: 'br-cat-calculation', workflow: 'br-cat-workflow', security: 'br-cat-security', data: 'br-cat-data' };
    const catLabels = { validation: 'Verification', calculation: 'Calcul', workflow: 'Processus', security: 'Securite', data: 'Donnees' };
    return `
        <div style="margin-bottom:0.5rem;">
            <div class="br-item" style="margin-bottom:0;border-radius:8px 8px 0 0;">
                <span class="br-category ${catColors[br.category] || 'br-cat-validation'}">${catLabels[br.category] || br.category}</span>
                <div class="br-text" style="flex:1;">
                    <div style="font-weight:600;color:var(--text-bright);margin-bottom:0.2rem;">${br.name}</div>
                    <div>${br.statement}</div>
                    ${br.example ? `<div style="font-size:0.8rem;color:var(--text-muted);margin-top:0.25rem;font-style:italic;">Exemple : ${br.example}</div>` : ''}
                </div>
                <button class="btn btn-sm" onclick="removeBusinessRule('${code}',${index})" style="opacity:0.5;flex-shrink:0;">&#10005;</button>
            </div>
            <div style="padding:0.4rem 0.75rem 0.6rem;background:var(--bg-input);border:1px solid var(--border);border-top:0;border-radius:0 0 8px 8px;">
                <textarea class="form-textarea" placeholder="Commentaire sur cette regle..."
                    onblur="updateSpecComment('${code}','br',${index},this.value)"
                    style="min-height:35px;font-size:0.8rem;resize:vertical;">${getSpecComment(code, 'br', index)}</textarea>
            </div>
        </div>`;
}

function addBusinessRule(code) {
    const name = document.getElementById('br-name-' + code).value.trim();
    if (!name) return;
    if (!data.moduleSpecs[code]) data.moduleSpecs[code] = { useCases: [], businessRules: [], entities: [], permissions: [], notes: '' };

    data.moduleSpecs[code].businessRules.push({
        name: name,
        category: document.getElementById('br-cat-' + code).value,
        statement: document.getElementById('br-statement-' + code).value.trim(),
        example: document.getElementById('br-example-' + code).value.trim()
    });

    renderAllModuleSpecs();
    autoSave();
}

function removeBusinessRule(code, index) {
    data.moduleSpecs[code].businessRules.splice(index, 1);
    renderAllModuleSpecs();
    autoSave();
}

function renderEntity(code, ent, index) {
    return `
        <div class="entity-block">
            <div class="entity-header">
                <div>
                    <div class="entity-name">${ent.name}</div>
                    <div class="entity-desc">${ent.description || ''}</div>
                </div>
                <button class="btn btn-sm" onclick="removeEntity('${code}',${index})" style="opacity:0.5;">Supprimer</button>
            </div>
            ${(ent.attributes || []).length > 0 ? `
            <table class="attr-table">
                <thead><tr><th>Information</th><th>Description</th></tr></thead>
                <tbody>
                    ${ent.attributes.map(a => `<tr><td style="font-weight:500;color:var(--text-bright);">${a.name}</td><td>${a.description || ''}</td></tr>`).join('')}
                </tbody>
            </table>
            <div style="padding:0.3rem 0.75rem;">
                <button class="add-btn" style="font-size:0.75rem;padding:0.4rem;" onclick="addEntityAttribute('${code}',${index})">+ Ajouter un attribut</button>
            </div>` : ''}
            ${(ent.relationships || []).length > 0 ? `
            <div style="padding:0.5rem 0.75rem;font-size:0.8rem;color:var(--text-muted);border-top:1px solid var(--border);">
                Relations : ${ent.relationships.map(r => `<span style="color:var(--accent);">${r}</span>`).join(', ')}
            </div>` : ''}
            <div style="padding:0.4rem 0.75rem 0.6rem;background:var(--bg-input);border-top:1px solid var(--border);border-radius:0 0 8px 8px;">
                <label style="font-size:0.75rem;color:var(--text-muted);display:block;margin-bottom:0.25rem;">Commentaire :</label>
                <textarea class="form-textarea" placeholder="Commentaire sur cette entite..."
                    onblur="updateSpecComment('${code}','ent',${index},this.value)"
                    style="min-height:35px;font-size:0.8rem;resize:vertical;">${getSpecComment(code, 'ent', index)}</textarea>
            </div>
        </div>`;
}

function addEntity(code) {
    const name = document.getElementById('ent-name-' + code).value.trim();
    if (!name) return;
    if (!data.moduleSpecs[code]) data.moduleSpecs[code] = { useCases: [], businessRules: [], entities: [], permissions: [], notes: '' };

    const attrs = document.getElementById('ent-attrs-' + code).value.split('\n').filter(l => l.trim()).map(l => {
        const parts = l.split(' - ');
        return { name: parts[0]?.trim() || l.trim(), description: parts.slice(1).join(' - ').trim() };
    });
    const rels = document.getElementById('ent-rels-' + code).value.split('\n').filter(l => l.trim());

    data.moduleSpecs[code].entities.push({
        name: name,
        description: document.getElementById('ent-desc-' + code).value.trim(),
        attributes: attrs,
        relationships: rels
    });

    renderAllModuleSpecs();
    autoSave();
}

function removeEntity(code, index) {
    data.moduleSpecs[code].entities.splice(index, 1);
    renderAllModuleSpecs();
    autoSave();
}

function addEntityAttribute(code, entityIndex) {
    var attrName = prompt('Nom de l\'attribut :');
    if (!attrName) return;
    var attrDesc = prompt('Description (optionnel) :') || '';
    if (!data.moduleSpecs[code]?.entities?.[entityIndex]) return;
    if (!data.moduleSpecs[code].entities[entityIndex].attributes) {
        data.moduleSpecs[code].entities[entityIndex].attributes = [];
    }
    data.moduleSpecs[code].entities[entityIndex].attributes.push({ name: attrName, description: attrDesc });
    renderAllModuleSpecs();
    autoSave();
}

function getSpecComment(code, type, index) {
    const key = code + '.' + type + '.' + index;
    return data.specComments[key] || '';
}

function updateSpecComment(code, type, index, value) {
    const key = code + '.' + type + '.' + index;
    data.specComments[key] = value.trim();
    autoSave();
}

function getWireframeComment(code, screen) {
    return (data.wireframeComments[code] || {})[screen] || '';
}

function updateWireframeComment(code, screen, value) {
    if (!data.wireframeComments[code]) data.wireframeComments[code] = {};
    data.wireframeComments[code][screen] = value.trim();
    autoSave();
}

function renderModuleMockups(code) {
    var spec = data.moduleSpecs[code] || {};
    var screens = spec.screens || [];
    var wireframes = EMBEDDED_ARTIFACTS?.wireframes?.[code] || [];

    // Priority 1: HTML mockups from screens[] specs
    if (screens.length > 0) {
        var html = '';
        if (typeof renderScreenMockups === 'function') {
            html = renderScreenMockups(code);
        }
        // Also show wireframes below if available
        if (wireframes.length > 0) {
            html += '<h3 style="color:var(--text-bright);font-size:1rem;margin:2rem 0 1rem;">Wireframes</h3>';
            html += wireframes.map(function(wf, i) { return renderWireframeMockup(code, wf, i); }).join('');
        }
        return html;
    }

    // Priority 2: Wireframes from EMBEDDED_ARTIFACTS
    if (wireframes.length === 0) {
        return `
            <div class="card" style="text-align:center;padding:2rem;color:var(--text-muted);">
                <p>Aucune maquette disponible pour ce module.</p>
                <p style="font-size:0.85rem;margin-top:0.5rem;">Les maquettes seront generees lors de la specification detaillee.</p>
            </div>`;
    }

    return wireframes.map(function(wf, i) { return renderWireframeMockup(code, wf, i); }).join('');
}

function renderWireframeMockup(code, wf, i) {
    const hasSvg = !!wf.svgContent;
    const wireframeId = `wf-${code}-${i}`;

    return `
    <div class="mockup-frame" style="${i > 0 ? 'margin-top:1.5rem;' : ''}">
        <div class="mockup-toolbar">
            <div class="mockup-dot mockup-dot-red"></div>
            <div class="mockup-dot mockup-dot-yellow"></div>
            <div class="mockup-dot mockup-dot-green"></div>
            <span class="mockup-title">${wf.screen || wf.section}</span>
            ${hasSvg ? `
            <div class="wireframe-toggle">
                <button class="wireframe-toggle-btn active" data-target="${wireframeId}" data-view="svg" onclick="toggleWireframeView('${wireframeId}', 'svg')">SVG</button>
                <button class="wireframe-toggle-btn" data-target="${wireframeId}" data-view="ascii" onclick="toggleWireframeView('${wireframeId}', 'ascii')">ASCII</button>
            </div>` : ''}
        </div>
        <div class="mockup-content" id="${wireframeId}">
            ${hasSvg
                ? `<div class="svg-wireframe wireframe-view active" data-view="svg">${wf.svgContent}</div>
                   <pre class="ascii-wireframe wireframe-view" data-view="ascii" style="display:none;">${wf.content || ''}</pre>`
                : (wf.format === 'ascii'
                    ? `<pre class="ascii-wireframe">${wf.content || ''}</pre>`
                    : `<div class="svg-wireframe">${wf.content || ''}</div>`)}
        </div>
        ${wf.description ? `
        <div class="wireframe-description">
            <strong>Description:</strong> ${wf.description}
        </div>` : ''}
        ${(wf.elements || []).length > 0 ? `
        <div class="wireframe-metadata">
            <div><strong>Elements:</strong> ${wf.elements.map(e => typeof e === 'string' ? e : (e.type || e.label || e.id || '')).filter(Boolean).join(', ')}</div>
        </div>` : ''}
        ${(() => {
            const cm = wf.componentMapping;
            const mappings = Array.isArray(cm) ? cm
                : (typeof cm === 'object' && cm !== null) ? Object.entries(cm).map(([k,v]) => ({wireframeElement: k, reactComponent: v}))
                : [];
            return mappings.length > 0 ? `
        <details class="wireframe-details">
            <summary>Mapping composants SmartStack</summary>
            <table class="mapping-table">
                <thead><tr><th>Element maquette</th><th>Composant React</th></tr></thead>
                <tbody>
                    ${mappings.map(m =>
                        '<tr><td>' + (m.wireframeElement || '') + '</td><td><code>' + (m.reactComponent || '') + '</code></td></tr>'
                    ).join('')}
                </tbody>
            </table>
        </details>` : '';
        })()}
        <div class="wireframe-comment">
            <label style="font-size:0.8rem;color:var(--text-muted);display:block;margin-bottom:0.3rem;">Commentaire / Feedback :</label>
            <textarea class="form-textarea"
                data-module="${code}"
                data-screen="${wf.screen}"
                placeholder="Ajouter un commentaire sur cette maquette (ex: deplacer ce bouton, ajouter une colonne...)"
                onblur="updateWireframeComment('${code}', '${wf.screen}', this.value)"
                style="min-height:60px;font-size:0.85rem;resize:vertical;"
            >${getWireframeComment(code, wf.screen)}</textarea>
        </div>
    </div>
    `;
}

function toggleWireframeView(wireframeId, view) {
    const container = document.getElementById(wireframeId);
    if (!container) return;

    // Toggle visibility of wireframe views
    container.querySelectorAll('.wireframe-view').forEach(el => {
        const isTarget = el.dataset.view === view;
        el.style.display = isTarget ? '' : 'none';
        el.classList.toggle('active', isTarget);
    });

    // Toggle button active states
    const toolbar = container.closest('.mockup-frame').querySelector('.wireframe-toggle');
    if (toolbar) {
        toolbar.querySelectorAll('.wireframe-toggle-btn').forEach(btn => {
            btn.classList.toggle('active', btn.dataset.view === view);
        });
    }
}

function getPermRoles() {
    // Extract roles from actual permission data (handles English role names from JSON data)
    const rolesFromPerms = [];
    const seen = new Set();
    data.modules.forEach(m => {
        (data.moduleSpecs[m.code]?.permissions || []).forEach(p => {
            const role = p.split('|')[0];
            if (role && !seen.has(role)) { seen.add(role); rolesFromPerms.push(role); }
        });
    });
    if (rolesFromPerms.length > 0) return [...rolesFromPerms, ...(data.customRoles || [])];
    // Fallback: use stakeholder names if no permission data exists
    const baseRoles = data.cadrage.stakeholders.length > 0
        ? data.cadrage.stakeholders.map(s => s.role)
        : ['Administrateur', 'Responsable', 'Contributeur', 'Lecteur'];
    return [...baseRoles, ...(data.customRoles || [])];
}

function getPermActions() {
    const baseActions = ['Consulter', 'Creer', 'Modifier', 'Supprimer', 'Valider', 'Exporter'];
    return [...baseActions, ...(data.customActions || [])];
}

function renderPermissionGrid(code) {
    const roles = getPermRoles();
    const actions = getPermActions();
    const baseRolesCount = roles.length - (data.customRoles || []).length;
    const baseActionsCount = 6;

    const perms = data.moduleSpecs[code]?.permissions || [];

    return `
        <table class="mock-table" style="background:var(--bg-card);border-radius:8px;overflow:hidden;">
            <thead><tr>
                <th>Profil</th>
                ${actions.map((a, i) => `<th style="text-align:center;">${a}${i >= baseActionsCount ? ' <span onclick="removeCustomAction('+`'${code}','${a}'`+')" style="cursor:pointer;color:var(--danger);font-size:0.7rem;" title="Supprimer cette action">&#10005;</span>' : ''}</th>`).join('')}
            </tr></thead>
            <tbody>
                ${roles.map((role, ri) => `
                    <tr>
                        <td style="font-weight:500;color:var(--text-bright);">${role}${ri >= baseRolesCount ? ' <span onclick="removeCustomRole('+`'${code}','${role}'`+')" style="cursor:pointer;color:var(--danger);font-size:0.7rem;" title="Supprimer ce role">&#10005;</span>' : ''}</td>
                        ${actions.map(action => {
                            const key = role + '|' + action;
                            const wildcardKey = role + '|*';
                            const checked = perms.includes(key) || perms.includes(wildcardKey);
                            return `<td style="text-align:center;"><input type="checkbox" ${checked ? 'checked' : ''} onchange="togglePermission('${code}','${key}',this.checked)" style="cursor:pointer;width:16px;height:16px;"></td>`;
                        }).join('')}
                    </tr>
                `).join('')}
            </tbody>
        </table>`;
}

function togglePermission(code, key, checked) {
    if (!data.moduleSpecs[code]) data.moduleSpecs[code] = { useCases: [], businessRules: [], entities: [], permissions: [], notes: '' };
    if (!data.moduleSpecs[code].permissions) data.moduleSpecs[code].permissions = [];
    if (checked) {
        if (!data.moduleSpecs[code].permissions.includes(key)) data.moduleSpecs[code].permissions.push(key);
    } else {
        data.moduleSpecs[code].permissions = data.moduleSpecs[code].permissions.filter(p => p !== key);
    }
    autoSave();
}

function addCustomRole(code) {
    const input = document.getElementById('role-name-' + code);
    const name = input.value.trim();
    if (!name) return;
    if (!data.customRoles) data.customRoles = [];
    if (!data.customRoles.includes(name) && !getPermRoles().includes(name)) {
        data.customRoles.push(name);
    }
    input.value = '';
    toggleForm('addRoleForm-' + code);
    refreshAllPermGrids();
    autoSave();
}

function addCustomAction(code) {
    const input = document.getElementById('action-name-' + code);
    const name = input.value.trim();
    if (!name) return;
    if (!data.customActions) data.customActions = [];
    if (!data.customActions.includes(name) && !getPermActions().includes(name)) {
        data.customActions.push(name);
    }
    input.value = '';
    toggleForm('addActionForm-' + code);
    refreshAllPermGrids();
    autoSave();
}

function removeCustomRole(code, role) {
    data.customRoles = (data.customRoles || []).filter(r => r !== role);
    data.modules.forEach(m => {
        if (data.moduleSpecs[m.code]?.permissions) {
            data.moduleSpecs[m.code].permissions = data.moduleSpecs[m.code].permissions.filter(p => !p.startsWith(role + '|'));
        }
    });
    refreshAllPermGrids();
    autoSave();
}

function removeCustomAction(code, action) {
    data.customActions = (data.customActions || []).filter(a => a !== action);
    data.modules.forEach(m => {
        if (data.moduleSpecs[m.code]?.permissions) {
            data.moduleSpecs[m.code].permissions = data.moduleSpecs[m.code].permissions.filter(p => !p.endsWith('|' + action));
        }
    });
    refreshAllPermGrids();
    autoSave();
}

function refreshAllPermGrids() {
    data.modules.forEach(m => {
        const container = document.getElementById('permGrid-' + m.code);
        if (container) container.innerHTML = renderPermissionGrid(m.code);
    });
}

function renderModuleStructure(code) {
    const mod = data.modules.find(m => m.code === code);
    const sections = mod ? (mod.anticipatedSections || []) : [];

    if (sections.length === 0) {
        return '<div class="card" style="text-align:center;padding:2rem;color:var(--text-muted);">' +
            '<p>Aucune section definie pour ce module.</p>' +
            '<p style="font-size:0.85rem;margin-top:0.5rem;">Les sections et ressources seront identifiees lors de l\'analyse approfondie.</p>' +
            '</div>';
    }

    return sections.map(function(section) {
        var resources = section.resources || [];
        var html = '<div class="struct-section">';
        html += '<div class="struct-section-header">';
        html += '<span class="struct-section-code">' + (section.code || section.name || '') + '</span>';
        if (section.description) {
            html += '<span class="struct-section-desc">' + section.description + '</span>';
        }
        html += '<span class="struct-section-badge">' + resources.length + ' ressource' + (resources.length !== 1 ? 's' : '') + '</span>';
        html += '</div>';

        if (resources.length > 0) {
            html += '<div class="struct-resources">';
            resources.forEach(function(res) {
                var resName = typeof res === 'string' ? res : (res.code || res.name || '');
                var resDesc = typeof res === 'object' ? (res.description || '') : '';
                html += '<div class="struct-resource">';
                html += '<span class="struct-resource-icon">&#8226;</span>';
                html += '<span class="struct-resource-name">' + resName + '</span>';
                if (resDesc) html += '<span class="struct-resource-desc">' + resDesc + '</span>';
                html += '</div>';
            });
            html += '</div>';
        }

        html += '</div>';
        return html;
    }).join('');
}

function switchTab(code, tabId) {
    const section = document.getElementById('module-spec-' + code);
    if (!section) return;
    section.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
    section.querySelectorAll('.tab-panel').forEach(panel => panel.classList.remove('active'));
    const targetPanel = document.getElementById('tab-' + code + '-' + tabId);
    if (targetPanel) targetPanel.classList.add('active');
    const buttons = section.querySelectorAll('.tab-btn');
    const tabIndex = { uc: 0, br: 1, ent: 2, perm: 3, mock: 4, notes: 5, struct: 6 }[tabId];
    if (buttons[tabIndex]) buttons[tabIndex].classList.add('active');
}
