import { t } from './proposal-i18n.js';
function escapeHtml(str) {
    return str
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;');
}
function sectionTitle(icon, text) {
    return `<h2 class="section-title"><span class="icon">${icon}</span>${escapeHtml(text)}</h2>`;
}
function langFrom(data) {
    return data.config.language ?? 'en';
}
function currency(data) {
    return data.config.currency ?? 'USD';
}
function formatMoney(amount, curr) {
    return `${curr} ${amount.toLocaleString('en-US', { minimumFractionDigits: 0, maximumFractionDigits: 0 })}`;
}
export function buildImpactAnalysisSection(data) {
    const lang = langFrom(data);
    const specs = data.specs;
    const specsWithImpact = specs.filter((s) => s.impactAnalysis !== null);
    if (specsWithImpact.length === 0) {
        return '';
    }
    const allModules = [
        ...new Set(specsWithImpact.flatMap((s) => s.impactAnalysis?.affectedModules ?? [])),
    ];
    const hasBreaking = specsWithImpact.some((s) => s.impactAnalysis?.breakingChanges);
    const breakingBadge = hasBreaking
        ? `<span class="badge badge-risk-high">BREAKING CHANGES</span>`
        : `<span class="badge badge-status-done">No Breaking Changes</span>`;
    const modulesHtml = allModules.length > 0
        ? `<p><strong>${t(lang, 'affectedModules')}:</strong> ${allModules.map(escapeHtml).join(', ')}</p>`
        : '';
    return `<section>
  ${sectionTitle('&#128295;', t(lang, 'impactAnalysis'))}
  <div class="card"><p>${breakingBadge}</p>${modulesHtml}</div>
</section>`;
}
export function buildTeamResourcesSection(data) {
    const lang = langFrom(data);
    const specs = data.specs;
    if (specs.length === 0) {
        return '';
    }
    const hourlyRate = data.config.hourlyRate;
    const devHours = specs.reduce((s, sp) => s + sp.estimation.devHours, 0);
    const reviewHours = specs.reduce((s, sp) => s + sp.estimation.reviewHours, 0);
    const rateHtml = hourlyRate
        ? `<p><strong>Hourly Rate:</strong> ${formatMoney(hourlyRate, currency(data))}/hr</p>`
        : '';
    return `<section>
  ${sectionTitle('&#128101;', t(lang, 'teamResources'))}
  <div class="card">
    <p><strong>${t(lang, 'devHours')}:</strong> ${String(devHours)}h</p>
    <p><strong>${t(lang, 'reviewHours')}:</strong> ${String(reviewHours)}h</p>
    ${rateHtml}
  </div>
</section>`;
}
export function buildPricingMethodologySection(data) {
    const lang = langFrom(data);
    const hourlyRate = data.config.hourlyRate;
    return `<section>
  ${sectionTitle('&#128178;', t(lang, 'pricingMethodology'))}
  <div class="card">
    <p>All estimates are calculated using the Planu estimation engine.</p>
    ${hourlyRate ? `<p><strong>Rate:</strong> ${formatMoney(hourlyRate, currency(data))}/hr</p>` : ''}
    <p>Each spec includes dev hours and review hours (QA, code review, documentation).</p>
  </div>
</section>`;
}
export function buildQualityMetricsSection(data) {
    const lang = langFrom(data);
    const metrics = data.metrics;
    if (!metrics || metrics.entries.length === 0) {
        return '';
    }
    const entries = metrics.entries.slice(-10);
    const avgAccuracy = entries.length > 0
        ? Math.round(entries.reduce((s, e) => s + e.accuracyScore, 0) / entries.length)
        : 0;
    return `<section>
  ${sectionTitle('&#128200;', t(lang, 'qualityMetrics'))}
  <div class="card">
    <p><strong>${t(lang, 'accuracyScore')}:</strong> ${String(avgAccuracy)}/100 (avg of last ${String(entries.length)} specs)</p>
    <div class="progress-track" style="margin-top:8px;">
      <div class="progress-bar ${avgAccuracy >= 80 ? 'high' : avgAccuracy >= 60 ? 'medium' : 'low'}" style="width:${String(avgAccuracy)}%;"></div>
    </div>
  </div>
</section>`;
}
export function buildLivingSpecSection(data) {
    const lang = langFrom(data);
    const specs = data.specs;
    if (specs.length === 0) {
        return '';
    }
    const doneCount = specs.filter((s) => s.status === 'done').length;
    const pct = Math.round((doneCount / specs.length) * 100);
    return `<section>
  ${sectionTitle('&#127775;', t(lang, 'livingSpec'))}
  <div class="card">
    <p><strong>${t(lang, 'completion')}:</strong> ${String(pct)}% (${String(doneCount)} / ${String(specs.length)} specs)</p>
    <div class="progress-track" style="margin-top:8px;">
      <div class="progress-bar ${pct >= 80 ? 'high' : pct >= 50 ? 'medium' : 'low'}" style="width:${String(pct)}%;"></div>
    </div>
  </div>
</section>`;
}
export function buildAssumptionsSection(data) {
    const lang = langFrom(data);
    return `<section>
  ${sectionTitle('&#128220;', t(lang, 'assumptions'))}
  <div class="card">
    <ul>
      <li>All estimations assume a senior engineer profile unless otherwise specified.</li>
      <li>Specs marked as "draft" are subject to change and may affect final costs.</li>
      <li>Infrastructure and third-party service costs are estimated and may vary.</li>
      <li>Timeline assumes no major blocking dependencies or team changes.</li>
    </ul>
  </div>
</section>`;
}
export function buildAlternativesSection(data) {
    const lang = langFrom(data);
    const decisions = data.decisions;
    if (!decisions || decisions.length === 0) {
        return '';
    }
    const archDecisions = decisions.filter((d) => d.category === 'architecture' && d.alternatives.length > 0);
    if (archDecisions.length === 0) {
        return '';
    }
    const items = archDecisions
        .slice(0, 8)
        .map((d) => `<div class="card">
  <h3>${escapeHtml(d.what)}</h3>
  <p><strong>Chosen:</strong> ${escapeHtml(d.why)}</p>
  <p><strong>${t(lang, 'alternatives')}:</strong> ${d.alternatives.map(escapeHtml).join(', ')}</p>
</div>`)
        .join('');
    return `<section>${sectionTitle('&#128260;', 'Alternatives Considered')}${items}</section>`;
}
export function buildPostLaunchSection(data) {
    const lang = langFrom(data);
    return `<section>
  ${sectionTitle('&#128640;', t(lang, 'postLaunch'))}
  <div class="card">
    <ul>
      <li>Living spec monitoring via Planu drift detection</li>
      <li>Quarterly spec review and reconciliation cycle</li>
      <li>Knowledge base maintenance for onboarding new team members</li>
      <li>Automated quality metrics tracking via metrics-store</li>
    </ul>
  </div>
</section>`;
}
export function buildModuleMappingSection(data) {
    const lang = langFrom(data);
    const knowledge = data.knowledge;
    if (!knowledge || knowledge.apps.length === 0) {
        return '';
    }
    const rows = knowledge.apps
        .slice(0, 15)
        .map((app) => {
        const relatedSpecs = data.specs.filter((s) => s.impactAnalysis?.affectedModules.includes(app.name));
        return `<tr>
  <td><strong>${escapeHtml(app.name)}</strong></td>
  <td>${escapeHtml(app.type)}</td>
  <td>${escapeHtml(app.language)}</td>
  <td>${String(relatedSpecs.length)} specs</td>
</tr>`;
    })
        .join('');
    return `<section>
  ${sectionTitle('&#128218;', t(lang, 'moduleMapping'))}
  <div class="table-wrap"><table class="spec-table">
    <thead><tr>
      <th>${t(lang, 'module')}</th><th>${t(lang, 'type')}</th><th>Language</th><th>Specs</th>
    </tr></thead>
    <tbody>${rows}</tbody>
  </table></div>
</section>`;
}
export function buildFooterSection(data) {
    const lang = langFrom(data);
    const date = new Date().toISOString();
    const confidentialNote = data.config.confidential
        ? `<span>&#128274; ${t(lang, 'confidential')}</span>`
        : '';
    return `<footer class="footer">
  <span>${t(lang, 'footer')}</span>
  <span>${escapeHtml(date.slice(0, 10))}</span>
  ${confidentialNote}
</footer>`;
}
export function buildGapAnalysisSection(data) {
    const specs = data.specs;
    const specsWithImpact = specs.filter((s) => s.impactAnalysis !== null);
    if (specsWithImpact.length === 0) {
        return '';
    }
    const allFiles = [
        ...new Set(specsWithImpact.flatMap((s) => s.impactAnalysis?.affectedFiles ?? [])),
    ];
    const dbFiles = allFiles.filter((f) => /migrat|schema|sql|db/i.test(f));
    if (dbFiles.length === 0) {
        return '';
    }
    const items = dbFiles
        .slice(0, 10)
        .map((f) => `<li style="border-left:3px solid #d97706;padding-left:8px;margin:4px 0;"><code>${escapeHtml(f)}</code></li>`)
        .join('');
    return `<section>
  ${sectionTitle('&#128451;', 'Gap Analysis — DB & Infra')}
  <div class="card">
    <p>Database and infrastructure files requiring changes:</p>
    <ul style="list-style:none;padding:0;margin-top:8px;">${items}</ul>
  </div>
</section>`;
}
// SPEC-145: Enhanced proposal section builders
function scoreDeltaClass(delta, isHigherBetter) {
    if (delta === 0) {
        return 'delta-neutral';
    }
    const isPositive = isHigherBetter ? delta > 0 : delta < 0;
    return isPositive ? 'delta-positive' : 'delta-negative';
}
function formatScoreValue(val) {
    return typeof val === 'number' ? val.toLocaleString('en-US') : escapeHtml(val);
}
export function buildScorecardSection(items, title = 'Scorecard') {
    if (items.length === 0) {
        return '';
    }
    const numericDeltas = items
        .map((item) => item.delta ?? 0)
        .filter((d) => typeof d === 'number');
    const totalDelta = numericDeltas.reduce((sum, d) => sum + d, 0);
    const cards = items.map((item) => {
        const isHigherBetter = item.isHigherBetter !== false;
        const delta = item.delta ?? 0;
        const deltaClass = scoreDeltaClass(delta, isHigherBetter);
        const deltaSign = delta > 0 ? '+' : '';
        const deltaHtml = typeof item.delta === 'number'
            ? `<span class="score-delta ${deltaClass}">${deltaSign}${String(delta)}</span>`
            : '';
        return `<div class="kpi-card">
  <div class="kpi-label">${escapeHtml(item.label)}</div>
  <div class="score-values">
    <span class="score-before">${formatScoreValue(item.before)}</span>
    <span class="score-after kpi-value">${formatScoreValue(item.after)}</span>
  </div>
  ${deltaHtml}
</div>`;
    });
    const totalSign = totalDelta > 0 ? '+' : '';
    const totalCard = `<div class="kpi-card">
  <div class="kpi-label">Score Total</div>
  <div class="score-values">
    <span class="score-after kpi-value">${totalSign}${String(totalDelta)}</span>
  </div>
  <span class="score-delta ${totalDelta > 0 ? 'delta-positive' : totalDelta < 0 ? 'delta-negative' : 'delta-neutral'}">${totalSign}${String(totalDelta)}</span>
</div>`;
    return `<section>
  ${sectionTitle('&#128200;', escapeHtml(title))}
  <div class="kpi-grid">
    ${cards.join('\n    ')}
    ${totalCard}
  </div>
</section>`;
}
export function buildMermaidSection(diagrams) {
    if (diagrams.length === 0) {
        return '';
    }
    const containerItems = diagrams.map((d) => {
        const caption = d.caption ? `<p class="mermaid-caption">${escapeHtml(d.caption)}</p>` : '';
        return `<div class="mermaid-container">
  <h3>${escapeHtml(d.title)}</h3>
  <pre class="mermaid">${d.code}</pre>
  ${caption}
</div>`;
    });
    const inner = diagrams.length === 2
        ? `<div class="arch-grid">${containerItems.join('\n')}</div>`
        : containerItems.join('\n');
    return `<section>
  ${sectionTitle('&#128444;', 'Architecture Diagrams')}
  ${inner}
</section>`;
}
export function buildVerdictSection(data) {
    if (!data) {
        return '';
    }
    const confidenceColors = {
        high: 'background:#d1fae5;color:#065f46;',
        medium: 'background:#fef3c7;color:#92400e;',
        low: 'background:#fee2e2;color:#991b1b;',
    };
    const badgeStyle = confidenceColors[data.confidence] ?? confidenceColors.medium;
    const nextStepsHtml = data.nextSteps && data.nextSteps.length > 0
        ? `<ol>${data.nextSteps.map((s) => `<li>${escapeHtml(s)}</li>`).join('')}</ol>`
        : '';
    return `<section>
  <div class="verdict">
    <h2>${escapeHtml(data.verdict)}</h2>
    <p>${escapeHtml(data.justification)}</p>
    <span class="confidence-badge" style="${badgeStyle}">${escapeHtml(data.confidence.toUpperCase())}</span>
    ${nextStepsHtml}
  </div>
</section>`;
}
export function buildDesignSystemSection(data) {
    const knowledge = data.knowledge;
    if (!knowledge) {
        return '';
    }
    const toolEntries = Object.entries(knowledge.tooling ?? {});
    if (toolEntries.length === 0) {
        return '';
    }
    const badges = toolEntries
        .slice(0, 8)
        .map(([key, val]) => `<span class="badge badge-status-draft">${escapeHtml(key)}: ${escapeHtml(val)}</span>`)
        .join(' ');
    return `<section>
  ${sectionTitle('&#127912;', 'Design System & Reuse')}
  <div class="card">
    <p><strong>Tooling detected:</strong> ${badges}</p>
    <p>Component reuse is estimated to reduce implementation time by 15-30% for UI-heavy specs.</p>
  </div>
</section>`;
}
//# sourceMappingURL=proposal-section-builders-advanced.js.map