// engine/dashboard/templates-project.ts — Project and spec HTML renderers.
import { groupSpecsByStatus, computeDashboardMetrics, computeHealthScore } from './kanban-logic.js';
import { renderLayout, escapeHtml, markdownToHtml } from './templates-layout.js';
import { renderKanbanBoard, renderMetricsPanel } from './templates-kanban.js';
/** Render a single spec card HTML fragment */
function renderSpecCard(spec) {
    const hasProgress = spec.criteriaTotal > 0;
    const progressBar = hasProgress
        ? `<div class="progress-bar-wrap">
        <div class="progress-bar-fill" style="width:${spec.progressPercent}%"></div>
       </div>
       <div class="progress-text">
         <span class="criteria-text">${spec.criteriaImplemented}/${spec.criteriaTotal} criterios</span>
         <span class="progress-pct">${spec.progressPercent}%</span>
       </div>`
        : `<div style="font-size:0.75rem;color:var(--text-muted)">Sin datos de progreso</div>`;
    return `<a href="/spec/${encodeURIComponent(spec.id.split('-')[0] ?? spec.id)}/${encodeURIComponent(spec.id)}"
     class="spec-card status-${escapeHtml(spec.status)}" data-spec-id="${escapeHtml(spec.id)}">
    <div class="spec-id" style="color:var(--status-${escapeHtml(spec.status)})">${escapeHtml(spec.id)}</div>
    <div class="spec-title">${escapeHtml(spec.title)}</div>
    <span class="status-badge">${escapeHtml(spec.status)}</span>
    ${progressBar}
  </a>`;
}
/** Render the usage stats panel */
function renderUsagePanel(usage) {
    if (!usage.isAvailable) {
        return `<div class="usage-panel">
      <h3>Uso</h3>
      <div style="color:var(--text-muted);font-size:0.85rem">Sin datos de uso disponibles</div>
    </div>`;
    }
    const tierLabel = usage.tier.charAt(0).toUpperCase() + usage.tier.slice(1);
    const limitLabel = usage.dailyLimit !== null ? String(usage.dailyLimit) : '∞';
    const callsLabel = `${usage.callsToday} / ${limitLabel}`;
    let trialHtml = '';
    if (usage.trialDaysLeft !== null) {
        const isCritical = usage.trialDaysLeft <= 3;
        trialHtml = `<div class="trial-warning ${isCritical ? 'trial-critical' : ''}">
      Trial: ${usage.trialDaysLeft} día${usage.trialDaysLeft !== 1 ? 's' : ''} restante${usage.trialDaysLeft !== 1 ? 's' : ''}
    </div>`;
    }
    return `<div class="usage-panel">
    <h3>Uso</h3>
    <div class="usage-tier">${escapeHtml(tierLabel)}</div>
    <div style="font-size:0.82rem;color:var(--text-muted);margin-top:0.35rem">Llamadas hoy: ${escapeHtml(callsLabel)}</div>
    ${trialHtml}
  </div>`;
}
/** Render the health metrics panel */
function renderHealthPanel(metrics) {
    const estimLabel = metrics.totalEstimation !== null ? `${metrics.totalEstimation}h` : 'Sin estimación';
    return `<div>
    <h2 style="margin-bottom:1rem;font-size:1rem;color:var(--text-muted)">Project Health</h2>
    <div class="grid grid-2" style="gap:0.75rem">
      <div class="metric-card">
        <div class="metric-value">${metrics.totalSpecs}</div>
        <div class="metric-label">Total specs</div>
      </div>
      <div class="metric-card">
        <div class="metric-value">${metrics.donePercent}%</div>
        <div class="metric-label">Completado</div>
      </div>
      <div class="metric-card">
        <div class="metric-value">${metrics.pendingApproval}</div>
        <div class="metric-label">Pendientes aprobación</div>
      </div>
      <div class="metric-card">
        <div class="metric-value">${metrics.activeImplementation}</div>
        <div class="metric-label">En implementación</div>
      </div>
    </div>
    <div style="margin-top:0.75rem;font-size:0.82rem;color:var(--text-muted)">
      Estimación total: <strong>${escapeHtml(estimLabel)}</strong>
    </div>
  </div>`;
}
/** Render the home page — list of all projects */
export function renderHomePage(projects, usage) {
    const projectContent = projects.length === 0
        ? `<div class="empty-state">
          <h2>No hay proyectos registrados</h2>
          <p>Usa el tool <code>init_project</code> desde tu cliente MCP para crear tu primer proyecto.</p>
        </div>`
        : `<h2 style="margin-bottom:1rem">Proyectos</h2>
         <div class="project-list">
           ${projects
            .map((p) => `<a href="/project/${encodeURIComponent(p.id)}" class="project-card">
               <div class="project-info">
                 <h2>${escapeHtml(p.name)}</h2>
                 <div class="meta">${escapeHtml(p.stack)} &bull; ${escapeHtml(p.path)} &bull; Última actividad: ${escapeHtml(p.lastActivity)}</div>
               </div>
               <div class="project-stats">
                 <div>${p.specCount} specs</div>
                 <div class="done">${p.doneCount} done</div>
               </div>
             </a>`)
            .join('\n')}
         </div>`;
    const body = `${projectContent}${renderUsagePanel(usage)}`;
    return renderLayout('Inicio', body);
}
/** CSS styles for kanban board and metrics panel */
function getKanbanStyles() {
    return `.kanban-board { display: flex; gap: 1rem; overflow-x: auto; min-height: 400px; }
    .kanban-column { flex: 1; min-width: 200px; background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); padding: 0.75rem; display: flex; flex-direction: column; }
    .kanban-column-over { border-color: #ef4444; }
    .kanban-column-header { margin-bottom: 0.75rem; font-weight: 600; font-size: 0.85rem; flex-shrink: 0; }
    .kanban-column-title { color: var(--text-muted); }
    .kanban-column-body { flex: 1; overflow-y: auto; max-height: 60vh; }
    .kanban-card { background: var(--bg); border: 1px solid var(--border); border-radius: 6px; padding: 0.75rem; margin-bottom: 0.5rem; cursor: grab; transition: opacity 0.2s, transform 0.3s, border-color 0.2s; outline: none; }
    .kanban-card:hover { border-color: var(--accent); }
    .kanban-card:focus { border-color: var(--accent); box-shadow: 0 0 0 2px rgba(59,130,246,0.3); }
    .kanban-card.dragging { opacity: 0.5; }
    .kanban-card-moving { animation: cardSlideIn 0.3s ease-out; }
    @keyframes cardSlideIn { from { opacity: 0; transform: translateY(-10px); } to { opacity: 1; transform: translateY(0); } }
    .kanban-column.drop-target { background: rgba(59,130,246,0.08); }
    .kanban-card-id { font-size: 0.72rem; font-weight: 700; color: var(--accent); text-transform: uppercase; }
    .kanban-card-title { font-size: 0.82rem; margin: 0.25rem 0; }
    .kanban-card-progress { font-size: 0.72rem; color: var(--text-muted); }
    .kanban-empty { text-align: center; padding: 2rem 0.5rem; color: var(--text-muted); font-size: 0.78rem; font-style: italic; }
    .view-toggle { display: flex; gap: 0.5rem; margin-bottom: 1rem; }
    .view-toggle button { padding: 0.4rem 1rem; border: 1px solid var(--border); border-radius: 4px; background: var(--surface); color: var(--text-muted); cursor: pointer; font-size: 0.82rem; }
    .view-toggle button.active { background: var(--accent); color: #fff; border-color: var(--accent); }
    .view-hidden { display: none; }
    .metrics-panel { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); padding: 1rem; margin-top: 1rem; }
    .health-score { text-align: center; margin-bottom: 1rem; position: relative; cursor: help; }
    .health-score-value { font-size: 2.5rem; font-weight: 700; line-height: 1; }
    .health-score-label { font-size: 0.78rem; color: var(--text-muted); margin-top: 0.25rem; }
    .health-tooltip { display: none; position: absolute; top: 100%; left: 50%; transform: translateX(-50%); background: var(--bg); border: 1px solid var(--border); border-radius: 6px; padding: 0.75rem; font-size: 0.75rem; width: 220px; z-index: 10; text-align: left; color: var(--text-muted); }
    .health-score:hover .health-tooltip { display: block; }
    .health-tooltip-row { display: flex; justify-content: space-between; padding: 0.15rem 0; }
    .health-tooltip-weight { color: var(--text-muted); font-size: 0.68rem; }
    .metrics-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 0.5rem; }
    .metric-item { text-align: center; padding: 0.5rem; }
    .metric-item-value { font-size: 1.2rem; font-weight: 700; color: var(--accent); }
    .metric-item-label { font-size: 0.72rem; color: var(--text-muted); }
    .health-components { margin-top: 0.75rem; font-size: 0.78rem; }
    .health-component { display: flex; justify-content: space-between; padding: 0.2rem 0; color: var(--text-muted); }`;
}
/** Client-side JS for kanban drag & drop and view toggling */
function getKanbanScript() {
    return `(function() {
      var gridBtn = document.getElementById('view-grid');
      var kanbanBtn = document.getElementById('view-kanban');
      var gridView = document.getElementById('grid-view');
      var kanbanView = document.getElementById('kanban-view');
      if (!gridBtn || !kanbanBtn || !gridView || !kanbanView) return;
      gridBtn.addEventListener('click', function() {
        gridBtn.classList.add('active'); kanbanBtn.classList.remove('active');
        gridView.classList.remove('view-hidden'); kanbanView.classList.add('view-hidden');
      });
      kanbanBtn.addEventListener('click', function() {
        kanbanBtn.classList.add('active'); gridBtn.classList.remove('active');
        kanbanView.classList.remove('view-hidden'); gridView.classList.add('view-hidden');
      });
      window.handleDrop = function(e, newStatus) {
        e.preventDefault();
        var col = e.currentTarget || (e.target.closest ? e.target.closest('.kanban-column') : null);
        if (col) col.classList.remove('drop-target');
        var specId = e.dataTransfer.getData('text/plain');
        if (!specId) return;
        var projectId = window.location.pathname.split('/')[2];
        fetch('/api/spec/' + encodeURIComponent(projectId) + '/' + encodeURIComponent(specId), {
          method: 'PATCH',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ status: newStatus })
        }).then(function(r) { return r.json(); }).then(function(d) {
          if (d.success) location.reload();
        });
      };
      document.querySelectorAll('.kanban-card').forEach(function(card) {
        card.addEventListener('dragstart', function(e) {
          e.dataTransfer.setData('text/plain', card.dataset.specId);
          card.classList.add('dragging');
        });
        card.addEventListener('dragend', function() {
          card.classList.remove('dragging');
        });
      });
      document.querySelectorAll('.kanban-column').forEach(function(col) {
        col.addEventListener('dragenter', function(e) {
          e.preventDefault();
          col.classList.add('drop-target');
        });
        col.addEventListener('dragleave', function(e) {
          if (!col.contains(e.relatedTarget)) {
            col.classList.remove('drop-target');
          }
        });
      });
    })();`;
}
/** Render the project detail page — spec cards + kanban board + health panel */
export function renderProjectPage(project, metrics, usage) {
    const specCards = project.specs.length === 0
        ? `<div class="empty-state"><p>Este proyecto no tiene specs aún.</p></div>`
        : project.specs.map(renderSpecCard).join('\n');
    const specsByStatus = groupSpecsByStatus(project.specs);
    const kanbanHtml = renderKanbanBoard(specsByStatus);
    const dashMetrics = computeDashboardMetrics(project.specs);
    const healthScore = computeHealthScore(dashMetrics);
    const metricsHtml = renderMetricsPanel(dashMetrics, healthScore);
    const body = `
    <div class="breadcrumb">
      <a href="/">Inicio</a> &rsaquo; ${escapeHtml(project.name)}
    </div>
    <div style="display:grid;grid-template-columns:1fr 280px;gap:2rem;align-items:start">
      <div>
        <h2 style="margin-bottom:1.25rem">${escapeHtml(project.name)}</h2>
        <div class="view-toggle">
          <button id="view-grid" class="active">Grid</button>
          <button id="view-kanban">Kanban</button>
        </div>
        <div id="grid-view">
          <div id="spec-grid" class="spec-grid">${specCards}</div>
        </div>
        <div id="kanban-view" class="view-hidden">${kanbanHtml}</div>
      </div>
      <div>
        ${renderHealthPanel(metrics)}
        ${metricsHtml}
        ${renderUsagePanel(usage)}
      </div>
    </div>
  `;
    return renderLayout(project.name, body, getKanbanStyles(), getKanbanScript());
}
/** Render the spec detail page — HU, FICHA, PROGRESS tabs */
export function renderSpecPage(projectId, projectName, specId, hu, ficha, progress) {
    const huHtml = hu !== null ? markdownToHtml(hu) : '<p style="color:var(--text-muted)">HU.md no encontrado</p>';
    const fichaHtml = ficha !== null
        ? markdownToHtml(ficha)
        : '<p style="color:var(--text-muted)">FICHA-TECNICA.md no encontrado</p>';
    const progressHtml = progress !== null
        ? markdownToHtml(progress)
        : '<p style="color:var(--text-muted)">PROGRESS.md no encontrado</p>';
    const body = `
    <div class="breadcrumb">
      <a href="/">Inicio</a> &rsaquo;
      <a href="/project/${encodeURIComponent(projectId)}">${escapeHtml(projectName)}</a> &rsaquo;
      ${escapeHtml(specId)}
    </div>
    <div class="tabs">
      <button class="tab-btn active" data-tab="hu">Historia de Usuario</button>
      <button class="tab-btn" data-tab="ficha">Ficha Técnica</button>
      <button class="tab-btn" data-tab="progress">Progreso</button>
    </div>
    <div id="tab-hu" class="tab-content active">
      <div class="md-content card">${huHtml}</div>
    </div>
    <div id="tab-ficha" class="tab-content">
      <div class="md-content card">${fichaHtml}</div>
    </div>
    <div id="tab-progress" class="tab-content">
      <div class="md-content card">${progressHtml}</div>
    </div>
  `;
    return renderLayout(specId, body);
}
/** Render a 404 not found page */
export function render404Page(path) {
    return renderLayout('404', `<div class="empty-state">
      <h2>404 — Página no encontrada</h2>
      <p>La ruta <code>${escapeHtml(path)}</code> no existe.</p>
      <p style="margin-top:1rem"><a href="/">Volver al inicio</a></p>
    </div>`);
}
//# sourceMappingURL=templates-project.js.map