---
import CrmLayout from '@/layouts/CrmLayout.astro';
import { computeKpis } from '@/lib/crm/kpis';
import { opportunities, contacts } from '@/lib/crm/store';
import { isNewLead } from '@/lib/crm/lead-urgency';
import { formatMxn, formatDate } from '@/lib/util/format';

export const prerender = false;

const k = computeKpis();
const recent = opportunities.list().slice(-6).reverse();
const contactName = (id: string | null) => (id ? contacts.get(id)?.fullName ?? '—' : '—');
const newLeadsCount = contacts.list().filter((c) => isNewLead(c.lifecycleStage)).length;

const STAGE_LABELS: Record<string, string> = {
  lead_nuevo: 'Lead nuevo',
  contactado: 'Contactado',
  cotizacion_enviada: 'Cotización enviada',
  seguimiento: 'Seguimiento',
  negociacion: 'Negociación',
  ganado: 'Ganado',
  perdido: 'Perdido',
};
const STAGE_COLOR: Record<string, string> = {
  lead_nuevo: '#8a8aff',
  contactado: '#6f8aff',
  cotizacion_enviada: '#5a9bf0',
  seguimiento: '#4bb3d8',
  negociacion: '#f1c40f',
  ganado: '#2ecc71',
  perdido: '#ff7a8a',
};
const maxStageAmount = Math.max(1, ...k.pipelineByStage.map((s) => s.amount));

const cards = [
  { label: 'Pipeline activo', value: formatMxn(k.totalPipelineMxn), sub: `${k.activeOpportunities} oportunidades`, accent: true },
  { label: 'Ganado del mes', value: formatMxn(k.wonThisMonthValue), sub: `${k.wonThisMonthCount} cierres` },
  { label: 'Conversión', value: `${k.conversionRate}%`, sub: 'ganadas / cerradas' },
  { label: 'Ticket promedio', value: formatMxn(k.avgDealMxn), sub: 'por oportunidad' },
  { label: 'Estancadas', value: String(k.stalledOpportunities), sub: '+5 días sin actividad' },
  { label: 'Tareas pendientes', value: String(k.pendingTasks), sub: `${k.overdueTasks} vencidas` },
];

const taskTypeLabel: Record<string, string> = {
  call: 'Llamada', whatsapp: 'WhatsApp', email: 'Email', review_quote: 'Revisar cotización', follow_up: 'Seguimiento',
};
---

<CrmLayout title="Dashboard · CRM">
  <h1>Dashboard</h1>
  <p class="muted" style="margin-top:2px">{k.contactsCount} contactos · {k.quotesCount} cotizaciones · {k.activeOpportunities} oportunidades activas</p>

  <!-- KPIs -->
  <div class="kpi-row6" style="display:grid;grid-template-columns:repeat(2,1fr);gap:12px;margin:18px 0 26px">
    {
      cards.map((c) => (
        <div
          class="kpi"
          style={`background:${c.accent ? 'linear-gradient(135deg, var(--pf-accent), var(--pf-accent-700))' : 'var(--pf-surface)'};${c.accent ? 'border-color:transparent' : ''}`}
        >
          <div class="kpi-value" style={c.accent ? 'color:#fff' : ''}>{c.value}</div>
          <div class="kpi-label" style={c.accent ? 'color:rgba(255,255,255,.85)' : ''}>{c.label}</div>
          <div style={`font-size:.74rem;margin-top:4px;${c.accent ? 'color:rgba(255,255,255,.7)' : 'color:var(--pf-text-dim)'}`}>{c.sub}</div>
        </div>
      ))
    }
  </div>
  <style>
    @media (min-width: 720px) {
      .kpi-row6 { grid-template-columns: repeat(3, 1fr) !important; }
    }
    @media (min-width: 1080px) {
      .kpi-row6 { grid-template-columns: repeat(6, 1fr) !important; }
    }
  </style>

  <!-- Leads nuevos sin contactar (arriba del pipeline) -->
  <a
    href="/crm/leads"
    class="card"
    style="display:flex;align-items:center;justify-content:space-between;gap:12px;padding:14px 18px;margin-bottom:16px;text-decoration:none;border-left:4px solid #ff7a8a"
  >
    <span style="display:flex;align-items:center;gap:10px">
      <span style="font-size:1.5rem" role="img" aria-label="Leads nuevos">🔥</span>
      <span>
        <strong style="font-size:1.35rem">{newLeadsCount}</strong>
        <span class="muted"> leads nuevos sin contactar</span>
      </span>
    </span>
    <span class="muted" style="font-size:.85rem;white-space:nowrap">Ver leads →</span>
  </a>

  <!-- Pipeline por etapa (funnel) -->
  <div class="card" style="padding:18px">
    <h2 style="font-size:1.1rem">Pipeline por etapa</h2>
    <div style="display:flex;flex-direction:column;gap:10px;margin-top:14px">
      {
        k.pipelineByStage.map((s) => (
          <div>
            <div style="display:flex;justify-content:space-between;font-size:.85rem;margin-bottom:4px">
              <span><strong>{STAGE_LABELS[s.stage]}</strong> <span class="muted">· {s.count}</span></span>
              <span class="muted">{formatMxn(s.amount)}</span>
            </div>
            <div style="height:10px;background:var(--pf-surface-2);border-radius:999px;overflow:hidden">
              <div style={`height:100%;border-radius:999px;width:${Math.max(3, Math.round((s.amount / maxStageAmount) * 100))}%;background:${STAGE_COLOR[s.stage]}`}></div>
            </div>
          </div>
        ))
      }
    </div>
  </div>

  <!-- Oportunidades recientes (arriba de las dos columnas) -->
  <h2 style="font-size:1.2rem;margin-top:26px">Oportunidades recientes</h2>
  {
    recent.length === 0 ? (
      <p class="notice" style="margin-top:12px">
        Aún no hay oportunidades. Genera datos de prueba en <a href="/crm/demo">/crm/demo</a> o cotiza en <a href="/cotizar">/cotizar</a>.
      </p>
    ) : (
      <div class="table-wrap" style="margin-top:12px">
        <table class="data">
          <thead>
            <tr><th>Contacto</th><th>Oportunidad</th><th>Monto</th><th>Etapa</th><th>Últ. actividad</th></tr>
          </thead>
          <tbody>
            {recent.map((o) => (
              <tr>
                <td><a href={`/crm/oportunidades/${o.id}`} style="color:var(--pf-accent-300);font-weight:600">{contactName(o.contactId)}</a></td>
                <td>{o.title}</td>
                <td>{formatMxn(o.amountEstimated)}</td>
                <td>{STAGE_LABELS[o.stage] ?? o.stage}</td>
                <td>{formatDate(o.lastActivityAt)}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    )
  }

  <!-- Dos columnas: Tareas | Actividades -->
  <div class="dash-2col" style="display:grid;grid-template-columns:1fr;gap:16px;margin-top:26px">
    <div class="card" style="padding:18px">
      <h2 style="font-size:1.1rem">Tareas próximas</h2>
      <div style="display:flex;flex-direction:column;gap:8px;margin-top:12px">
        {k.upcomingTasks.length === 0 && <p class="muted" style="font-size:.85rem">Sin tareas pendientes.</p>}
        {
          k.upcomingTasks.map((t) => (
            <div style="display:flex;justify-content:space-between;gap:10px;padding:8px 10px;border:1px solid var(--pf-border);border-radius:8px">
              <span style="font-size:.88rem">{t.title}</span>
              <span style={`font-size:.75rem;white-space:nowrap;${t.status === 'overdue' ? 'color:var(--pf-danger,#ff7a8a)' : 'color:var(--pf-text-dim)'}`}>
                {taskTypeLabel[t.type] ?? t.type} · {formatDate(t.dueAt)}
              </span>
            </div>
          ))
        }
      </div>
    </div>

    <div class="card" style="padding:18px">
      <h2 style="font-size:1.1rem">Actividad reciente</h2>
      <div style="display:flex;flex-direction:column;gap:8px;margin-top:12px">
        {k.recentActivities.length === 0 && <p class="muted" style="font-size:.85rem">Sin actividad.</p>}
        {
          k.recentActivities.map((a) => (
            <div style="padding-bottom:8px;border-bottom:1px solid var(--pf-border)">
              <div style="font-size:.85rem">{a.body}</div>
              <div class="muted" style="font-size:.72rem">{a.type} · {formatDate(a.createdAt)}</div>
            </div>
          ))
        }
      </div>
    </div>
  </div>

  <style>
    @media (min-width: 860px) {
      .dash-2col { grid-template-columns: 1fr 1fr !important; }
    }
  </style>
</CrmLayout>
