import { buildGanttChart } from './proposal-gantt-builder.js';
import { buildKpiGrid } from './proposal-kpi-builder.js';
import { t } from './proposal-i18n.js';
// ── Internal helpers ──────────────────────────────────────────────────────────
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 })}`;
}
const STATUS_BADGE_CLASS = {
    done: 'badge-status-done',
    implementing: 'badge-status-implementing',
    approved: 'badge-status-approved',
    review: 'badge-status-review',
    draft: 'badge-status-draft',
};
const RISK_BADGE_CLASS = {
    low: 'badge-risk-low',
    medium: 'badge-risk-medium',
    high: 'badge-risk-high',
    critical: 'badge-risk-critical',
};
// ── Tier 1: Core sections ─────────────────────────────────────────────────────
export function buildHeroSection(data) {
    const lang = langFrom(data);
    const title = data.config.title ?? data.projectName;
    const subtitle = data.config.subtitle ?? '';
    const client = data.config.client ? `Client: ${data.config.client}` : '';
    const author = data.config.author ? `Author: ${data.config.author}` : '';
    const date = new Date().toLocaleDateString('en-US', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
    });
    const totalSpecs = data.specs.length;
    const totalHours = data.specs.reduce((s, sp) => s + sp.estimation.devHours + sp.estimation.reviewHours, 0);
    const totalWeeks = Math.ceil(totalHours / 40);
    const logoHtml = data.config.logo
        ? `<img src="${escapeHtml(data.config.logo)}" alt="logo" style="height:48px;margin-bottom:16px;" />`
        : '';
    const confidentialBanner = data.config.confidential
        ? `<div class="confidential-banner">${t(lang, 'confidential')}</div>`
        : '';
    const expiresHtml = data.config.expiresAt
        ? `<span>&#128197; ${t(lang, 'expires')}: ${escapeHtml(data.config.expiresAt)}</span>`
        : '';
    const metaItems = [
        `<span>&#128197; ${escapeHtml(date)}</span>`,
        totalSpecs > 0 ? `<span>&#128196; ${String(totalSpecs)} specs</span>` : '',
        totalWeeks > 0 ? `<span>&#128336; ~${String(totalWeeks)} ${t(lang, 'weeks')}</span>` : '',
        client ? `<span>&#127983; ${escapeHtml(client)}</span>` : '',
        author ? `<span>&#128100; ${escapeHtml(author)}</span>` : '',
        expiresHtml,
    ]
        .filter(Boolean)
        .join('');
    return `${confidentialBanner}
<div class="hero">
  ${logoHtml}
  <div class="hero-badge">Planu · Spec Driven Development</div>
  <h1>${escapeHtml(title)}</h1>
  ${subtitle ? `<h2>${escapeHtml(subtitle)}</h2>` : ''}
  <div class="hero-meta">${metaItems}</div>
</div>`;
}
export function buildExecutiveSummarySection(data) {
    const lang = langFrom(data);
    const curr = currency(data);
    const specs = data.specs;
    if (specs.length === 0) {
        return '';
    }
    const totalCost = specs.reduce((s, sp) => s + sp.estimation.totalCostUsd, 0);
    const totalHours = specs.reduce((s, sp) => s + sp.estimation.devHours + sp.estimation.reviewHours, 0);
    const doneCount = specs.filter((s) => s.status === 'done').length;
    const completionPct = specs.length > 0 ? Math.round((doneCount / specs.length) * 100) : 0;
    const totalWeeks = Math.max(1, Math.ceil(totalHours / 40));
    const riskScores = [];
    if (data.risks) {
        for (const r of data.risks) {
            riskScores.push(r.aggregateRiskScore);
        }
    }
    const avgRisk = riskScores.length > 0
        ? Math.round(riskScores.reduce((a, b) => a + b, 0) / riskScores.length)
        : 0;
    const kpis = [
        {
            value: formatMoney(totalCost, curr),
            label: t(lang, 'totalInvestment'),
            variant: 'default',
        },
        {
            value: `${String(totalHours)}h`,
            label: t(lang, 'estimatedHours'),
            variant: 'secondary',
        },
        { value: String(specs.length), label: t(lang, 'totalSpecs'), variant: 'default' },
        {
            value: `${String(totalWeeks)} wk`,
            label: t(lang, 'timeline'),
            variant: 'secondary',
        },
        ...(avgRisk > 0
            ? [{ value: `${String(avgRisk)}/100`, label: t(lang, 'avgRisk'), variant: 'accent' }]
            : []),
        {
            value: `${String(completionPct)}%`,
            label: t(lang, 'completionRate'),
            variant: 'default',
        },
    ];
    const stack = data.knowledge?.stack ?? [];
    const summaryPara = stack.length > 0
        ? `<p class="summary-paragraph">
        Project built with <strong>${escapeHtml(stack.slice(0, 4).join(', '))}</strong>.
        A total of <strong>${String(specs.length)} specs</strong> are planned,
        requiring approximately <strong>${String(totalHours)} hours</strong> of work
        distributed across <strong>${String(totalWeeks)} weeks</strong>.
      </p>`
        : '';
    return `<section>
  ${sectionTitle('&#128200;', t(lang, 'executiveSummary'))}
  ${buildKpiGrid(kpis)}
  ${summaryPara}
</section>`;
}
export function buildScopeSection(data) {
    const lang = langFrom(data);
    const specs = data.specs;
    if (specs.length === 0) {
        return '';
    }
    const inScopeItems = specs
        .map((s) => `<li><strong>${escapeHtml(s.id)}</strong> — ${escapeHtml(s.title)}</li>`)
        .join('');
    const paymentTerms = data.config.paymentTerms
        ? `<p style="margin-top:12px;"><strong>Payment Terms:</strong> ${escapeHtml(data.config.paymentTerms)}</p>`
        : '';
    return `<section>
  ${sectionTitle('&#127919;', t(lang, 'scope'))}
  <div class="card-grid">
    <div class="card">
      <h3 style="margin-bottom:12px;">${t(lang, 'inScope')}</h3>
      <ul>${inScopeItems}</ul>
      ${paymentTerms}
    </div>
    <div class="card">
      <h3 style="margin-bottom:12px;">${t(lang, 'outOfScope')}</h3>
      <p class="text-muted">Any features, integrations, or deliverables not listed in the spec breakdown are considered out of scope and will require a change order.</p>
    </div>
  </div>
</section>`;
}
function renderPhaseRows(label, phaseSpecs, curr, lang, color) {
    const rows = phaseSpecs
        .map((s) => {
        const statusClass = STATUS_BADGE_CLASS[s.status] ?? 'badge-status-draft';
        const riskClass = RISK_BADGE_CLASS[s.risk] ?? 'badge-risk-low';
        const diffClass = `badge-diff-${String(s.difficulty)}`;
        return `<tr>
  <td><code>${escapeHtml(s.id)}</code></td><td>${escapeHtml(s.title)}</td>
  <td>${escapeHtml(s.type)}</td>
  <td><span class="badge ${diffClass}">${escapeHtml(String(s.difficulty))}</span></td>
  <td><span class="badge ${riskClass}">${escapeHtml(s.risk)}</span></td>
  <td class="right">${String(s.estimation.devHours)}h</td>
  <td class="right">${String(s.estimation.reviewHours)}h</td>
  <td class="right">${formatMoney(s.estimation.totalCostUsd, curr)}</td>
  <td><span class="badge ${statusClass}">${escapeHtml(s.status)}</span></td>
</tr>`;
    })
        .join('');
    if (label === 'all') {
        return rows;
    }
    const subtotalCost = phaseSpecs.reduce((s, sp) => s + sp.estimation.totalCostUsd, 0);
    const subtotalHours = phaseSpecs.reduce((s, sp) => s + sp.estimation.devHours + sp.estimation.reviewHours, 0);
    const bg = color ? escapeHtml(color) : '#1a1a2e';
    const phaseHeader = `<tr style="background:${bg};color:#fff;"><td colspan="9" style="padding:10px 14px;font-weight:700;">${escapeHtml(label)}</td></tr>`;
    const subtotalRow = `<tr class="subtotal-row"><td colspan="5" style="padding:10px 14px;">${t(lang, 'subtotal')} — ${escapeHtml(label)}</td><td colspan="2" class="right">${String(subtotalHours)}h</td><td class="right">${formatMoney(subtotalCost, curr)}</td><td></td></tr>`;
    return `${phaseHeader}${rows}${subtotalRow}`;
}
export function buildSpecBreakdownSection(data) {
    const lang = langFrom(data);
    const curr = currency(data);
    const specs = data.specs;
    if (specs.length === 0) {
        return '';
    }
    const phases = data.config.phases;
    const PHASE_COLORS = ['#7c3aed', '#0891b2', '#059669', '#d97706', '#e94560'];
    const tableBody = phases && phases.length > 0
        ? phases
            .map((ph, i) => renderPhaseRows(ph.name, specs.filter((s) => ph.specIds.includes(s.id)), curr, lang, ph.color ?? PHASE_COLORS[i % PHASE_COLORS.length]))
            .join('')
        : renderPhaseRows('all', specs, curr, lang);
    const totalCost = specs.reduce((s, sp) => s + sp.estimation.totalCostUsd, 0);
    const totalDevHours = specs.reduce((s, sp) => s + sp.estimation.devHours, 0);
    const totalRevHours = specs.reduce((s, sp) => s + sp.estimation.reviewHours, 0);
    return `<section>
  ${sectionTitle('&#128202;', t(lang, 'specBreakdown'))}
  <div class="table-wrap"><table class="spec-table">
    <thead><tr>
      <th>${t(lang, 'specId')}</th><th>${t(lang, 'title')}</th><th>${t(lang, 'type')}</th>
      <th>${t(lang, 'difficulty')}</th><th>${t(lang, 'risk')}</th>
      <th class="right">${t(lang, 'devHours')}</th><th class="right">${t(lang, 'reviewHours')}</th>
      <th class="right">${t(lang, 'cost')}</th><th>${t(lang, 'status')}</th>
    </tr></thead>
    <tbody>${tableBody}
      <tr class="total-row">
        <td colspan="5">${t(lang, 'total')}</td>
        <td class="right">${String(totalDevHours)}h</td><td class="right">${String(totalRevHours)}h</td>
        <td class="right">${formatMoney(totalCost, curr)}</td><td></td>
      </tr>
    </tbody>
  </table></div>
</section>`;
}
export function buildTimelineSection(data) {
    const lang = langFrom(data);
    const specs = data.specs;
    if (specs.length === 0) {
        return '';
    }
    const ganttHtml = buildGanttChart(specs, data.config.phases, data.config.ganttStartDate);
    if (!ganttHtml) {
        return '';
    }
    return `<section>
  ${sectionTitle('&#128197;', t(lang, 'timeline_section'))}
  ${ganttHtml}
</section>`;
}
export function buildBudgetSection(data) {
    const lang = langFrom(data);
    const curr = currency(data);
    const specs = data.specs;
    if (specs.length === 0) {
        return '';
    }
    const totalHumanCost = specs.reduce((s, sp) => s + sp.estimation.humanCostUsd, 0);
    const totalApiCost = specs.reduce((s, sp) => s + sp.estimation.apiCostUsd, 0);
    const totalCost = specs.reduce((s, sp) => s + sp.estimation.totalCostUsd, 0);
    return `<section>
  ${sectionTitle('&#128176;', t(lang, 'budget'))}
  <div class="table-wrap">
    <table class="spec-table">
      <thead>
        <tr>
          <th>Category</th>
          <th class="right">Amount</th>
          <th class="right">%</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>${t(lang, 'humanCosts')}</td>
          <td class="right">${formatMoney(totalHumanCost, curr)}</td>
          <td class="right">${totalCost > 0 ? String(Math.round((totalHumanCost / totalCost) * 100)) : '0'}%</td>
        </tr>
        <tr>
          <td>${t(lang, 'apiCosts')}</td>
          <td class="right">${formatMoney(totalApiCost, curr)}</td>
          <td class="right">${totalCost > 0 ? String(Math.round((totalApiCost / totalCost) * 100)) : '0'}%</td>
        </tr>
        <tr class="total-row">
          <td>${t(lang, 'total')}</td>
          <td class="right">${formatMoney(totalCost, curr)}</td>
          <td class="right">100%</td>
        </tr>
      </tbody>
    </table>
  </div>
</section>`;
}
export function buildInvestmentSummarySection(data) {
    const lang = langFrom(data);
    const curr = currency(data);
    const specs = data.specs;
    if (specs.length === 0) {
        return '';
    }
    const totalCost = specs.reduce((s, sp) => s + sp.estimation.totalCostUsd, 0);
    return `<section>
  ${sectionTitle('&#9889;', t(lang, 'investmentSummary'))}
  <div class="investment-box">
    <div class="big-number">${formatMoney(totalCost, curr)}</div>
    <div class="label">${t(lang, 'totalInvestment')} · ${String(specs.length)} specs</div>
  </div>
</section>`;
}
// ── Tier 2: Technical credibility ─────────────────────────────────────────────
export function buildArchitectureSection(data) {
    const lang = langFrom(data);
    const knowledge = data.knowledge;
    if (!knowledge) {
        return '';
    }
    const stack = knowledge.stack;
    const apps = knowledge.apps;
    const layers = knowledge.layers;
    if (stack.length === 0 && apps.length === 0) {
        return '';
    }
    const stackBadges = stack
        .map((s) => `<span class="badge badge-status-draft">${escapeHtml(s)}</span>`)
        .join(' ');
    const appsHtml = apps.length > 0
        ? `<div style="margin-top:16px;">
        <strong>Apps:</strong>
        ${apps.map((a) => `<span class="badge badge-status-draft" style="margin:2px;">${escapeHtml(a.name)} (${escapeHtml(a.type)})</span>`).join('')}
      </div>`
        : '';
    const layersHtml = layers.length > 0
        ? `<div style="margin-top:12px;"><strong>Layers:</strong> ${escapeHtml(layers.join(' → '))}</div>`
        : '';
    return `<section>
  ${sectionTitle('&#127760;', t(lang, 'architecture'))}
  <div class="card">
    <div><strong>Stack:</strong> ${stackBadges}</div>
    ${appsHtml}
    ${layersHtml}
  </div>
</section>`;
}
export function buildRiskSection(data) {
    const lang = langFrom(data);
    const risks = data.risks;
    if (!risks || risks.length === 0) {
        return '';
    }
    const allRisks = risks.flatMap((r) => r.risks);
    if (allRisks.length === 0) {
        return '';
    }
    const rows = allRisks
        .slice(0, 20)
        .map((r) => {
        const riskClass = RISK_BADGE_CLASS[r.category] ?? 'badge-risk-low';
        return `<tr>
  <td>${escapeHtml(r.description.slice(0, 60))}${r.description.length > 60 ? '…' : ''}</td>
  <td><span class="badge ${riskClass}">${escapeHtml(r.category)}</span></td>
  <td class="right">${String(r.probability)}%</td>
  <td class="right">${r.impactUsd > 0 ? `$${String(r.impactUsd)}` : '—'}</td>
  <td class="right">${r.impactDays > 0 ? `${String(r.impactDays)}d` : '—'}</td>
  <td>${escapeHtml(r.mitigationPlan.slice(0, 60))}${r.mitigationPlan.length > 60 ? '…' : ''}</td>
  <td>${escapeHtml(r.owner)}</td>
</tr>`;
    })
        .join('');
    return `<section>
  ${sectionTitle('&#9888;', t(lang, 'riskAnalysis'))}
  <div class="table-wrap">
    <table class="spec-table">
      <thead>
        <tr>
          <th>Risk</th>
          <th>${t(lang, 'category')}</th>
          <th class="right">${t(lang, 'probability')}</th>
          <th class="right">${t(lang, 'impactUsd')}</th>
          <th class="right">${t(lang, 'impactDays')}</th>
          <th>${t(lang, 'mitigation')}</th>
          <th>${t(lang, 'owner')}</th>
        </tr>
      </thead>
      <tbody>${rows}</tbody>
    </table>
  </div>
</section>`;
}
export function buildDecisionsSection(data) {
    const lang = langFrom(data);
    const decisions = data.decisions;
    if (!decisions || decisions.length === 0) {
        return '';
    }
    const rows = decisions
        .slice(0, 15)
        .map((d) => {
        const alts = Array.isArray(d.alternatives) ? d.alternatives.join(', ') : '';
        return `<tr>
  <td>${escapeHtml(d.what.slice(0, 80))}${d.what.length > 80 ? '…' : ''}</td>
  <td>${escapeHtml(d.why.slice(0, 80))}${d.why.length > 80 ? '…' : ''}</td>
  <td>${escapeHtml(alts.slice(0, 60))}${alts.length > 60 ? '…' : ''}</td>
  <td><span class="badge badge-status-draft">${escapeHtml(d.decidedBy)}</span></td>
  <td><span class="badge badge-status-draft">${escapeHtml(d.category)}</span></td>
</tr>`;
    })
        .join('');
    return `<section>
  ${sectionTitle('&#128161;', t(lang, 'decisions'))}
  <div class="table-wrap">
    <table class="spec-table">
      <thead>
        <tr>
          <th>${t(lang, 'what')}</th>
          <th>${t(lang, 'why')}</th>
          <th>${t(lang, 'alternatives')}</th>
          <th>${t(lang, 'decidedBy')}</th>
          <th>${t(lang, 'category')}</th>
        </tr>
      </thead>
      <tbody>${rows}</tbody>
    </table>
  </div>
</section>`;
}
export { buildImpactAnalysisSection, buildTeamResourcesSection, buildPricingMethodologySection, buildQualityMetricsSection, buildLivingSpecSection, buildAssumptionsSection, buildAlternativesSection, buildPostLaunchSection, buildModuleMappingSection, buildFooterSection, buildGapAnalysisSection, buildDesignSystemSection, } from './proposal-section-builders-advanced.js';
//# sourceMappingURL=proposal-section-builders.js.map