/* ============================================
   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">${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">${s.function || ''}</div>
            <ul class="stakeholder-tasks">
                ${(s.tasks || []).map(t => '<li>' + 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;">' + s.frustrations + '</div>' : ''}
        </div>
    `).join('');
}

function removeStakeholder(index) {
    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() {
    ['vital', 'important', 'optional', 'excluded'].forEach(p => {
        const container = document.getElementById('scope' + p.charAt(0).toUpperCase() + p.slice(1));
        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">${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">' + 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);' : ''}">${c.text}</span>
            <button class="btn btn-sm" onclick="removeCriterion(${i})" style="opacity:0.5;flex-shrink:0;">&#10005;</button>
        </div>
    `).join('');
}

/* ============================================
   RISKS
   ============================================ */
function addRisk() {
    const desc = document.getElementById('risk-desc').value.trim();
    if (!desc) return;

    data.cadrage.risks.push({
        description: desc,
        probability: document.getElementById('risk-probability').value,
        impact: document.getElementById('risk-impact').value,
        mitigation: document.getElementById('risk-mitigation').value.trim()
    });

    renderRisks();
    toggleForm('addRiskForm');
    clearForm('addRiskForm');
    autoSave();
}

function renderRisks() {
    const list = document.getElementById('risksList');
    list.innerHTML = data.cadrage.risks.map((r, i) => {
        const level = (r.probability === 'high' && r.impact === 'high') ? 'critical'
            : (r.probability === 'low' && r.impact === 'low') ? 'low' : 'medium';
        return `
            <div class="risk-item">
                <div class="risk-level risk-${level}"></div>
                <div>
                    <div class="risk-text">${r.description}</div>
                    ${r.mitigation ? '<div style="font-size:0.75rem;color:var(--text-muted);margin-top:0.25rem;">Prevention : ' + r.mitigation + '</div>' : ''}
                </div>
                <div class="risk-probability">${formatLevel(r.probability)}</div>
                <div class="risk-impact">${formatLevel(r.impact)}</div>
            </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');
    }
}
