/* ============================================
   HTML MOCKUP RENDERER
   Generates realistic HTML mockups from screens[] specs
   ============================================ */

function renderScreenMockups(code) {
    var spec = data.moduleSpecs[code] || {};
    var screens = spec.screens || [];

    if (screens.length === 0) return '';

    return screens.map(function(screen, si) {
        var resources = screen.resources || [];
        return '<div class="screen-section" id="screen-' + code + '-' + screen.sectionCode + '" style="margin-bottom:2rem;">' +
            '<h3 style="color:var(--text-bright);font-size:1rem;margin-bottom:1rem;">' +
            '<span style="color:var(--accent);">&#9656;</span> ' + escapeHtml(screen.sectionLabel || screen.sectionCode) +
            '</h3>' +
            resources.map(function(res, ri) {
                return renderResourceMockup(code, screen.sectionCode, res, ri);
            }).join('') +
        '</div>';
    }).join('');
}

function renderResourceMockup(code, sectionCode, res, index) {
    var mockupId = 'mockup-' + code + '-' + sectionCode + '-' + index;
    var html = '<div class="mockup-frame" style="margin-bottom:1.5rem;">';

    // Browser chrome
    html += '<div class="mockup-toolbar">';
    html += '<div class="mockup-dot mockup-dot-red"></div>';
    html += '<div class="mockup-dot mockup-dot-yellow"></div>';
    html += '<div class="mockup-dot mockup-dot-green"></div>';
    html += '<span class="mockup-title">' + escapeHtml(res.label || res.code) + ' (' + res.type + ')</span>';
    if (res.permission) {
        html += '<span style="margin-left:auto;font-size:0.65rem;color:var(--text-muted);background:var(--bg-dark);padding:0.15rem 0.5rem;border-radius:4px;">' + escapeHtml(res.permission) + '</span>';
    }
    html += '</div>';

    // Mockup content
    html += '<div class="mockup-content" id="' + mockupId + '">';
    switch (res.type) {
        case 'SmartTable':
            html += renderSmartTableMockup(res);
            break;
        case 'SmartForm':
            html += renderSmartFormMockup(res);
            break;
        case 'SmartCard':
            html += renderSmartCardMockup(res);
            break;
        case 'SmartKanban':
            html += renderSmartKanbanMockup(res);
            break;
        case 'SmartDashboard':
            html += renderSmartDashboardMockup(res);
            break;
        case 'SmartFilter':
            html += renderSmartFilterMockup(res);
            break;
        default:
            html += '<div style="padding:2rem;text-align:center;color:var(--text-muted);">Composant ' + res.type + ' - maquette non disponible</div>';
    }
    html += '</div>';

    // Notes
    if (res.notes) {
        html += '<div style="padding:0.5rem 1rem;font-size:0.8rem;color:var(--text-muted);border-top:1px solid var(--border);background:var(--bg-input);">';
        html += '<strong>Notes:</strong> ' + escapeHtml(res.notes);
        html += '</div>';
    }

    // Comment area
    html += '<div class="wireframe-comment">';
    html += '<label style="font-size:0.8rem;color:var(--text-muted);display:block;margin-bottom:0.3rem;">Commentaire :</label>';
    html += '<textarea class="form-textarea" placeholder="Commentaire sur cette maquette..."';
    html += ' onblur="updateWireframeComment(\'' + code + '\', \'' + (res.code || sectionCode + '-' + index) + '\', this.value)"';
    html += ' style="min-height:50px;font-size:0.85rem;resize:vertical;">';
    html += getWireframeComment(code, res.code || sectionCode + '-' + index);
    html += '</textarea>';
    html += '</div>';

    html += '</div>';
    return html;
}

/* ---------- SmartTable ---------- */
function renderSmartTableMockup(res) {
    var columns = res.columns || [];
    if (columns.length === 0) return '<div style="padding:2rem;text-align:center;color:var(--text-muted);">Table sans colonnes définies</div>';

    var html = '';

    // Header with actions
    html += '<div class="mock-header">';
    html += '<span class="mock-title">' + escapeHtml(res.label || 'Liste') + '</span>';
    html += '<div style="display:flex;gap:0.4rem;">';
    (res.actions || []).forEach(function(action) {
        var isPrimary = action === 'create' || action === 'export';
        html += '<span class="mock-btn' + (isPrimary ? '' : '" style="background:var(--bg-hover);color:var(--text)') + '">' + formatActionLabel(action) + '</span>';
    });
    html += '</div></div>';

    // Filters
    if (res.filters && res.filters.length > 0) {
        html += '<div style="display:flex;gap:0.5rem;margin-bottom:1rem;">';
        res.filters.forEach(function(f) {
            html += '<span class="mock-input" style="width:auto;min-width:120px;font-size:0.8rem;color:var(--text-muted);">' + f + ' &#9662;</span>';
        });
        html += '<span class="mock-input" style="width:auto;min-width:200px;font-size:0.8rem;color:var(--text-muted);">Rechercher...</span>';
        html += '</div>';
    }

    // Table
    html += '<table class="mock-table">';
    html += '<thead><tr>';
    columns.forEach(function(col) {
        html += '<th>' + escapeHtml(col.label || col.field);
        if (col.sortable) html += ' <span style="font-size:0.6rem;color:var(--text-muted);">&#9650;&#9660;</span>';
        html += '</th>';
    });
    html += '<th style="width:80px;">Actions</th>';
    html += '</tr></thead>';

    // Sample rows
    html += '<tbody>';
    var sampleData = generateSampleRows(columns, 4);
    sampleData.forEach(function(row) {
        html += '<tr>';
        columns.forEach(function(col) {
            var val = row[col.field] || '';
            if (col.type === 'badge') {
                html += '<td><span class="mock-status mock-status-active">' + val + '</span></td>';
            } else if (col.type === 'lookup') {
                html += '<td style="color:var(--accent);">' + val + '</td>';
            } else {
                html += '<td>' + val + '</td>';
            }
        });
        html += '<td style="text-align:center;"><span style="cursor:pointer;color:var(--text-muted);">&#9998; &#128465;</span></td>';
        html += '</tr>';
    });
    html += '</tbody></table>';

    // Pagination
    html += '<div style="display:flex;justify-content:space-between;align-items:center;padding:0.75rem 0;font-size:0.8rem;color:var(--text-muted);">';
    html += '<span>1-4 sur 24 résultats</span>';
    html += '<div style="display:flex;gap:0.3rem;">';
    html += '<span class="mock-btn" style="background:var(--primary);font-size:0.75rem;padding:0.2rem 0.5rem;">1</span>';
    html += '<span class="mock-btn" style="background:var(--bg-hover);font-size:0.75rem;padding:0.2rem 0.5rem;">2</span>';
    html += '<span class="mock-btn" style="background:var(--bg-hover);font-size:0.75rem;padding:0.2rem 0.5rem;">3</span>';
    html += '</div></div>';

    return html;
}

/* ---------- SmartForm ---------- */
function renderSmartFormMockup(res) {
    var tabs = res.tabs || [];
    if (tabs.length === 0 && res.fields) {
        tabs = [{ label: 'Informations', fields: res.fields }];
    }
    if (tabs.length === 0) return '<div style="padding:2rem;text-align:center;color:var(--text-muted);">Formulaire sans champs définis</div>';

    var html = '';

    // Header
    html += '<div class="mock-header">';
    html += '<span class="mock-title">' + escapeHtml(res.label || 'Formulaire') + '</span>';
    html += '<div style="display:flex;gap:0.4rem;">';
    (res.actions || ['save', 'cancel']).forEach(function(action) {
        var isPrimary = action === 'save';
        html += '<span class="mock-btn' + (isPrimary ? '' : '" style="background:var(--bg-hover);color:var(--text)') + '">' + formatActionLabel(action) + '</span>';
    });
    html += '</div></div>';

    // Tabs
    if (tabs.length > 1) {
        html += '<div style="display:flex;gap:0;border-bottom:1px solid var(--border);margin-bottom:1.5rem;">';
        tabs.forEach(function(tab, i) {
            html += '<span style="padding:0.5rem 1rem;font-size:0.85rem;cursor:pointer;border-bottom:2px solid ' + (i === 0 ? 'var(--primary)' : 'transparent') + ';color:' + (i === 0 ? 'var(--primary-light)' : 'var(--text-muted)') + ';">' + escapeHtml(tab.label) + '</span>';
        });
        html += '</div>';
    }

    // Fields (first tab only)
    var fields = tabs[0].fields || [];
    var rows = [];
    for (var i = 0; i < fields.length; i += 2) {
        rows.push(fields.slice(i, i + 2));
    }

    rows.forEach(function(row) {
        if (row.length === 1 && row[0].type === 'subtable') {
            html += renderSubtableMockup(row[0]);
        } else {
            html += '<div class="mock-form-row">';
            row.forEach(function(field) {
                html += '<div class="mock-form-group">';
                html += '<label class="mock-label">' + escapeHtml(field.label || field.field);
                if (field.required) html += ' <span style="color:var(--error);">*</span>';
                html += '</label>';
                html += renderFormFieldMockup(field);
                html += '</div>';
            });
            html += '</div>';
        }
    });

    return html;
}

function renderFormFieldMockup(field) {
    var val = generateSampleValue(field);
    switch (field.type) {
        case 'select':
            return '<span class="mock-input" style="display:block;">' + val + ' &#9662;</span>';
        case 'lookup':
            return '<span class="mock-input" style="display:block;color:var(--accent);">' + val + ' &#128269;</span>';
        case 'date':
            return '<span class="mock-input" style="display:block;">' + val + ' &#128197;</span>';
        case 'textarea':
            return '<span class="mock-input" style="display:block;min-height:60px;">' + val + '</span>';
        case 'checkbox':
            return '<div style="display:flex;align-items:center;gap:0.5rem;"><input type="checkbox" checked disabled style="width:16px;height:16px;"><span style="font-size:0.85rem;color:var(--text);">' + val + '</span></div>';
        default:
            return '<span class="mock-input" style="display:block;' + (field.readonly ? 'opacity:0.6;' : '') + '">' + val + '</span>';
    }
}

function renderSubtableMockup(field) {
    var cols = field.columns || [];
    var entity = field.entity || 'Element';
    var html = '<div style="margin:1rem 0;border:1px solid var(--border);border-radius:8px;overflow:hidden;">';
    html += '<div style="display:flex;justify-content:space-between;align-items:center;padding:0.5rem 0.75rem;background:var(--bg-hover);">';
    html += '<span style="font-weight:500;color:var(--text-bright);font-size:0.85rem;">' + escapeHtml(entity) + '</span>';
    html += '<span class="mock-btn" style="font-size:0.75rem;padding:0.2rem 0.5rem;">+ Ajouter</span>';
    html += '</div>';
    html += '<table class="mock-table"><thead><tr>';
    cols.forEach(function(c) { html += '<th>' + escapeHtml(c) + '</th>'; });
    html += '</tr></thead><tbody>';
    html += '<tr>' + cols.map(function() { return '<td style="color:var(--text-muted);font-style:italic;">...</td>'; }).join('') + '</tr>';
    html += '</tbody></table></div>';
    return html;
}

/* ---------- SmartCard ---------- */
function renderSmartCardMockup(res) {
    var columns = res.columns || res.fields || [];
    var html = '<div class="mock-header"><span class="mock-title">' + escapeHtml(res.label || 'Cartes') + '</span></div>';
    html += '<div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(240px,1fr));gap:1rem;">';

    for (var i = 0; i < 4; i++) {
        html += '<div style="background:var(--bg-hover);border:1px solid var(--border);border-radius:8px;padding:1rem;">';
        columns.forEach(function(col, ci) {
            var label = col.label || col.field || col;
            if (ci === 0) {
                html += '<div style="font-weight:600;color:var(--text-bright);margin-bottom:0.5rem;">' + escapeHtml(label) + ' #' + (i + 1) + '</div>';
            } else {
                html += '<div style="font-size:0.8rem;color:var(--text-muted);margin-bottom:0.25rem;">' + escapeHtml(label) + ': <span style="color:var(--text);">valeur</span></div>';
            }
        });
        html += '</div>';
    }
    html += '</div>';
    return html;
}

/* ---------- SmartKanban ---------- */
function renderSmartKanbanMockup(res) {
    var options = res.options || res.columns || ['À faire', 'En cours', 'Terminé'];
    var html = '<div class="mock-header"><span class="mock-title">' + escapeHtml(res.label || 'Kanban') + '</span></div>';
    html += '<div style="display:flex;gap:1rem;overflow-x:auto;padding-bottom:0.5rem;">';

    options.forEach(function(col, ci) {
        var colLabel = typeof col === 'string' ? col : (col.label || col.field || 'Colonne');
        html += '<div style="min-width:200px;flex:1;background:var(--bg-hover);border-radius:8px;padding:0.75rem;">';
        html += '<div style="font-weight:600;font-size:0.85rem;color:var(--text-bright);margin-bottom:0.75rem;display:flex;justify-content:space-between;">';
        html += escapeHtml(colLabel) + ' <span style="font-size:0.7rem;background:var(--bg-card);padding:0.1rem 0.4rem;border-radius:4px;color:var(--text-muted);">' + (3 - ci) + '</span>';
        html += '</div>';
        for (var j = 0; j < Math.max(1, 3 - ci); j++) {
            html += '<div style="background:var(--bg-card);border:1px solid var(--border);border-radius:6px;padding:0.5rem;margin-bottom:0.5rem;font-size:0.8rem;">';
            html += '<div style="color:var(--text-bright);font-weight:500;">Élément ' + (j + 1) + '</div>';
            html += '<div style="color:var(--text-muted);font-size:0.7rem;margin-top:0.25rem;">Description...</div>';
            html += '</div>';
        }
        html += '</div>';
    });
    html += '</div>';
    return html;
}

/* ---------- SmartDashboard ---------- */
function renderSmartDashboardMockup(res) {
    var html = '<div class="mock-header"><span class="mock-title">' + escapeHtml(res.label || 'Tableau de bord') + '</span></div>';

    // KPI cards
    html += '<div class="mock-kpi-grid">';
    var kpis = res.kpis || [
        { label: 'Total', value: '1,234' },
        { label: 'Actifs', value: '987' },
        { label: 'En attente', value: '156' },
        { label: 'Taux', value: '80%' }
    ];
    kpis.forEach(function(kpi) {
        var displayValue = kpiDisplayValue(kpi);
        html += '<div class="mock-kpi"><div class="mock-kpi-value">' + escapeHtml(displayValue) + '</div><div class="mock-kpi-label">' + escapeHtml(kpi.label || '') + '</div></div>';
    });
    html += '</div>';

    // Chart placeholders
    var charts = res.charts || [{ label: 'Graphique' }];
    charts.forEach(function(chart) {
        html += '<div class="mock-chart-placeholder">' + escapeHtml(chart.label || chart.type || 'Graphique') + '</div>';
    });

    return html;
}

function kpiDisplayValue(kpi) {
    var v = kpi.value || '0';
    // If value is already a simple display value (number, percentage), use it
    if (/^\d[\d,.\s]*%?$/.test(v)) return v;
    // Detect formula patterns and generate realistic sample values
    if (v.indexOf('(') !== -1) {
        var label = (kpi.label || '').toLowerCase();
        var color = (kpi.color || '').toLowerCase();
        // Percentage indicators
        if (v.indexOf('ratio') !== -1 || v.indexOf('%') !== -1 || label.indexOf('taux') !== -1 || label.indexOf('rate') !== -1)
            return '87.5%';
        // Average
        if (v.indexOf('avg') !== -1 || label.indexOf('moyen') !== -1 || label.indexOf('average') !== -1)
            return '12.4';
        // Sum (monetary or hours)
        if (v.indexOf('sum') !== -1)
            return label.indexOf('jour') !== -1 || label.indexOf('day') !== -1 ? '156' : '45,678';
        // Count (default)
        return '1,234';
    }
    return v;
}

/* ---------- SmartFilter ---------- */
function renderSmartFilterMockup(res) {
    var options = res.options || [];
    var html = '<div style="display:flex;gap:0.4rem;flex-wrap:wrap;padding:0.5rem 0;">';
    html += '<span style="padding:0.3rem 0.7rem;border-radius:16px;font-size:0.8rem;background:var(--primary);color:#fff;cursor:pointer;">Tous</span>';
    options.forEach(function(opt) {
        html += '<span style="padding:0.3rem 0.7rem;border-radius:16px;font-size:0.8rem;background:var(--bg-hover);color:var(--text);border:1px solid var(--border);cursor:pointer;">' + escapeHtml(opt) + '</span>';
    });
    html += '</div>';
    return html;
}

/* ---------- Helpers ---------- */
function formatActionLabel(action) {
    var labels = {
        create: 'Nouveau', edit: 'Modifier', delete: 'Supprimer',
        export: 'Exporter', save: 'Enregistrer', cancel: 'Annuler',
        validate: 'Valider', archive: 'Archiver', print: 'Imprimer'
    };
    return labels[action] || action;
}

function generateSampleRows(columns, count) {
    var rows = [];
    for (var i = 0; i < count; i++) {
        var row = {};
        columns.forEach(function(col) {
            row[col.field] = generateSampleValue(col, i);
        });
        rows.push(row);
    }
    return rows;
}

function generateSampleValue(field, index) {
    var idx = (index || 0) + 1;
    var t = field.type || 'text';
    var f = field.field || '';

    if (field.options && field.options.length > 0) {
        return field.options[idx % field.options.length];
    }

    if (t === 'date') return '0' + idx + '/03/2026';
    if (t === 'badge' || t === 'select') return 'Actif';
    if (t === 'lookup') return f.replace(/Id$/, '') + ' #' + idx;
    if (t === 'number') return String(idx * 100);
    if (t === 'checkbox') return idx % 2 === 0 ? 'Oui' : 'Non';

    if (f.toLowerCase().includes('code')) return 'CODE-' + String(idx).padStart(3, '0');
    if (f.toLowerCase().includes('name') || f.toLowerCase().includes('nom')) return 'Nom ' + idx;
    if (f.toLowerCase().includes('email')) return 'user' + idx + '@example.com';
    if (f.toLowerCase().includes('date')) return '0' + idx + '/03/2026';
    if (f.toLowerCase().includes('status') || f.toLowerCase().includes('statut')) return 'Actif';

    return f + ' ' + idx;
}
