/* ============================================
   EDITABLE FIELDS
   ============================================ */
function initEditableFields() {
    document.querySelectorAll('.editable[data-field]').forEach(el => {
        const field = el.dataset.field;
        const value = getNestedValue(data, 'cadrage.' + field);
        if (value) el.textContent = value;

        el.addEventListener('blur', function() {
            setNestedValue(data, 'cadrage.' + field, this.textContent.trim());
            autoSave();
        });
    });
}

/* ============================================
   STAKEHOLDERS
   ============================================ */
function addStakeholder() {
    const role = document.getElementById('sh-role').value.trim();
    if (!role) return;

    data.cadrage.stakeholders.push({
        role: role,
        function: document.getElementById('sh-function').value.trim(),
        tasks: document.getElementById('sh-tasks').value.split('\n').filter(t => t.trim()),
        frequency: document.getElementById('sh-frequency').value,
        access: document.getElementById('sh-access').value,
        frustrations: document.getElementById('sh-frustrations').value.trim()
    });

    renderStakeholders();
    toggleForm('addStakeholderForm');
    clearForm('addStakeholderForm');
    updateCounts();
    autoSave();
}

function renderStakeholders() {
    const grid = document.getElementById('stakeholderGrid');
    grid.innerHTML = data.cadrage.stakeholders.map((s, i) => `
        <div class="stakeholder-card">
            <div style="display:flex;justify-content:space-between;align-items:start;">
                <div class="stakeholder-role">${escapeHtml(s.role)}</div>
                <button class="btn btn-sm" onclick="removeStakeholder(${i})" style="opacity:0.5;font-size:0.7rem;">Supprimer</button>
            </div>
            <div class="stakeholder-function">${escapeHtml(s.function || '')}</div>
            <ul class="stakeholder-tasks">
                ${(Array.isArray(s.tasks) ? s.tasks : typeof s.tasks === 'string' ? s.tasks.split(',').map(t => t.trim()).filter(Boolean) : []).map(t => '<li>' + escapeHtml(t) + '</li>').join('')}
            </ul>
            <div class="stakeholder-meta">
                <span>${formatFrequency(s.frequency)}</span>
                <span>${formatAccess(s.access)}</span>
            </div>
            ${s.frustrations ? '<div style="font-size:0.8rem;color:var(--warning);margin-top:0.5rem;font-style:italic;">' + escapeHtml(s.frustrations) + '</div>' : ''}
        </div>
    `).join('');
}

function removeStakeholder(index) {
    if (!confirm('Supprimer ce profil utilisateur ?')) return;
    data.cadrage.stakeholders.splice(index, 1);
    renderStakeholders();
    updateCounts();
    autoSave();
}

/* ============================================
   SCOPE ITEMS
   ============================================ */
function addScopeItem(priority) {
    const name = document.getElementById('scope-name-' + priority).value.trim();
    if (!name) return;
    const description = document.getElementById('scope-desc-' + priority).value.trim();

    data.cadrage.scope[priority].push({ name, description });
    renderScope();
    toggleForm('addScopeForm-' + priority);
    document.getElementById('scope-name-' + priority).value = '';
    document.getElementById('scope-desc-' + priority).value = '';
    autoSave();
}

function renderScope() {
    ['inscope', 'outofscope'].forEach(p => {
        const container = document.getElementById('scope' + (p === 'inscope' ? 'InScope' : 'OutOfScope'));
        if (!container) return;
        container.innerHTML = (data.cadrage.scope[p] || []).map((item, i) => `
            <div class="uc-item">
                <div class="uc-header">
                    <span class="priority priority-${p}">${formatPriority(p)}</span>
                    <span class="uc-title">${escapeHtml(item.name)}</span>
                    <div class="uc-actions">
                        <button class="btn btn-sm" onclick="removeScopeItem('${p}',${i})">Supprimer</button>
                    </div>
                </div>
                ${item.description ? '<div class="uc-detail">' + escapeHtml(item.description) + '</div>' : ''}
            </div>
        `).join('');
    });
}

function removeScopeItem(priority, index) {
    data.cadrage.scope[priority].splice(index, 1);
    renderScope();
    autoSave();
}

/* ============================================
   ACCEPTANCE CRITERIA
   ============================================ */
function addCriterion() {
    const text = document.getElementById('criterion-text').value.trim();
    if (!text) return;
    if (!data.cadrage.criteria) data.cadrage.criteria = [];
    data.cadrage.criteria.push({ text, validated: false });
    renderCriteria();
    toggleForm('addCriterionForm');
    document.getElementById('criterion-text').value = '';
    autoSave();
}

function removeCriterion(index) {
    data.cadrage.criteria.splice(index, 1);
    renderCriteria();
    autoSave();
}

function toggleCriterion(index) {
    data.cadrage.criteria[index].validated = !data.cadrage.criteria[index].validated;
    renderCriteria();
    autoSave();
}

function renderCriteria() {
    const container = document.getElementById('criteriaList');
    if (!container) return;
    const criteria = data.cadrage.criteria || [];
    container.innerHTML = criteria.map((c, i) => `
        <div class="uc-item" style="display:flex;align-items:center;gap:0.75rem;">
            <input type="checkbox" ${c.validated ? 'checked' : ''} onchange="toggleCriterion(${i})" style="cursor:pointer;width:18px;height:18px;flex-shrink:0;">
            <span style="flex:1;${c.validated ? 'text-decoration:line-through;color:var(--text-muted);' : ''}">${escapeHtml(c.text)}</span>
            <button class="btn btn-sm" onclick="removeCriterion(${i})" style="opacity:0.5;flex-shrink:0;">&#10005;</button>
        </div>
    `).join('');
}

/* ============================================
   CONTEXT RENDERING (merged problem/current/vision)
   ============================================ */
function renderContext() {
    // context fields are handled by initEditableFields() via data-field="context.*"
    // This function ensures backward compat data is displayed as strings
    const ctx = data.cadrage.context || {};
    if (Array.isArray(ctx.painPoints)) {
        data.cadrage.context.painPoints = ctx.painPoints.join('\n');
    }
    if (Array.isArray(ctx.acceptanceCriteria)) {
        data.cadrage.context.acceptanceCriteria = ctx.acceptanceCriteria.join('\n');
    }
}
