/* ============================================================
   INside One — Dashboard Comercial (admin)
   Métricas derivadas de quotes + pipeline sin Firestore extra.
   ============================================================ */

function fmtDashMoney(n) {
  if (n >= 1000000) return "$" + (n/1000000).toFixed(1) + "M";
  if (n >= 1000)    return "$" + (n/1000).toFixed(1) + "k";
  return window.fmtMoney(n);
}

function DashKpi({ label, value, sub, color, onClick, active }) {
  return (
    <div onClick={onClick} style={{ background:"var(--surface)", border:`1px solid ${active?"var(--gold)":"var(--border)"}`,
      borderRadius:12, padding:"18px 20px", cursor: onClick?"pointer":"default",
      transition:"border-color .15s, transform .12s",
      transform: active ? "translateY(-2px)" : "" }}
      onMouseEnter={e => onClick && (e.currentTarget.style.transform="translateY(-1px)")}
      onMouseLeave={e => onClick && !active && (e.currentTarget.style.transform="")}>
      <div style={{ fontSize:11, fontWeight:600, color:"var(--muted)", textTransform:"uppercase", letterSpacing:".06em", marginBottom:6 }}>
        {label}
      </div>
      <div style={{ fontSize:28, fontWeight:800, color: color||"var(--text)", lineHeight:1.1 }}>{value}</div>
      {sub && <div style={{ fontSize:12, color:"var(--muted)", marginTop:4 }}>{sub}</div>}
    </div>
  );
}

// Mini SVG bar chart (last 6 months revenue)
function MonthlyChart({ quotes }) {
  const months = React.useMemo(() => {
    const map = {};
    const now = new Date();
    for (let i = 5; i >= 0; i--) {
      const d = new Date(now.getFullYear(), now.getMonth()-i, 1);
      const key = d.toISOString().slice(0,7);
      const label = d.toLocaleDateString("es-PA",{month:"short"}).replace(".","");
      map[key] = { label, total:0, won:0 };
    }
    quotes.forEach(q => {
      const m = (q.date||"").slice(0,7);
      if (map[m]) {
        map[m].total += q.total||0;
        if (q.status==="accepted") map[m].won += q.total||0;
      }
    });
    return Object.values(map);
  }, [quotes]);

  const maxVal = Math.max(...months.map(m => m.total), 1);
  const W = 540, H = 140, PAD = 12, barW = Math.floor((W - PAD*2) / months.length * 0.55);
  const gap = (W - PAD*2) / months.length;

  return (
    <div style={{ overflowX:"auto" }}>
      <svg viewBox={`0 0 ${W} ${H+30}`} style={{ width:"100%", maxWidth:W, display:"block" }}>
        {months.map((m, i) => {
          const x = PAD + i*gap + gap/2 - barW/2;
          const totalH = Math.max(2, (m.total/maxVal)*(H-20));
          const wonH   = Math.max(0, (m.won/maxVal)*(H-20));
          return (
            <g key={i}>
              <rect x={x} y={H-totalH} width={barW} height={totalH} rx={3}
                fill="color-mix(in srgb, var(--gold) 22%, transparent)" />
              {wonH > 0 && (
                <rect x={x} y={H-wonH} width={barW} height={wonH} rx={3} fill="var(--gold)" />
              )}
              <text x={x+barW/2} y={H+18} textAnchor="middle" fontSize={10}
                fill="var(--muted)" fontFamily="var(--body)">{m.label}</text>
              {m.total > 0 && (
                <text x={x+barW/2} y={H-totalH-5} textAnchor="middle" fontSize={9}
                  fill="var(--muted)" fontFamily="var(--mono)">{fmtDashMoney(m.total)}</text>
              )}
            </g>
          );
        })}
      </svg>
    </div>
  );
}

// Pipeline funnel by stage
function PipelineFunnel({ opps }) {
  const STAGES = [
    { key:"prospecto",     label:"Prospecto",      color:"#6366f1" },
    { key:"cotizando",     label:"Cotizando",       color:"#0ea5e9" },
    { key:"negociacion",   label:"En negociación",  color:"#f59e0b" },
    { key:"adjudicado",    label:"Adjudicado",      color:"#22c55e" },
    { key:"no_adjudicado", label:"No adjudicado",   color:"#ef4444" },
  ];
  const rows = STAGES.map(s => ({
    ...s,
    count: opps.filter(o => o.stage===s.key).length,
    value: opps.filter(o => o.stage===s.key).reduce((sum,o)=>sum+(o.value||0),0),
  }));
  const maxCount = Math.max(...rows.map(r=>r.count), 1);

  return (
    <div style={{ display:"flex", flexDirection:"column", gap:8 }}>
      {rows.map(r => (
        <div key={r.key} style={{ display:"flex", alignItems:"center", gap:12 }}>
          <div style={{ width:120, fontSize:12, color:"var(--muted)", flexShrink:0,
            overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap" }}>{r.label}</div>
          <div style={{ flex:1, height:20, background:"var(--bg)", borderRadius:4, overflow:"hidden", position:"relative" }}>
            <div style={{ height:"100%", width: r.count>0 ? `${(r.count/maxCount)*100}%` : "0%",
              background:r.color+"88", borderRadius:4, transition:"width .5s", minWidth: r.count>0?4:0 }} />
          </div>
          <div style={{ width:30, fontFamily:"var(--mono)", fontSize:12, fontWeight:700, color:"var(--text)", textAlign:"right", flexShrink:0 }}>
            {r.count}
          </div>
          <div style={{ width:80, fontFamily:"var(--mono)", fontSize:11, color:"var(--muted)", textAlign:"right", flexShrink:0 }}>
            {r.value>0?fmtDashMoney(r.value):""}
          </div>
        </div>
      ))}
    </div>
  );
}

// Top clients
function TopClients({ quotes }) {
  const clients = React.useMemo(() => {
    const map = {};
    quotes.forEach(q => {
      const key = q.client_company || q.client_name || "Desconocido";
      if (!map[key]) map[key] = { name:key, count:0, total:0, won:0 };
      map[key].count++;
      map[key].total += q.total||0;
      if (q.status==="accepted") map[key].won += q.total||0;
    });
    return Object.values(map).sort((a,b)=>b.total-a.total).slice(0,6);
  }, [quotes]);

  if (clients.length===0) return <div style={{ color:"var(--muted)", fontSize:13, padding:"20px 0" }}>Sin datos aún.</div>;

  return (
    <div style={{ display:"flex", flexDirection:"column", gap:0 }}>
      {clients.map((c, i) => (
        <div key={i} style={{ display:"flex", alignItems:"center", gap:12, padding:"10px 0",
          borderBottom: i<clients.length-1?"1px solid var(--border)":"none" }}>
          <div style={{ width:20, fontSize:11, fontWeight:700, color:"var(--muted)", textAlign:"center", flexShrink:0 }}>
            {i+1}
          </div>
          <div style={{ flex:1, minWidth:0 }}>
            <div style={{ fontWeight:600, fontSize:13, overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap" }}>
              {c.name}
            </div>
            <div style={{ fontSize:11, color:"var(--muted)" }}>{c.count} cotizaciones</div>
          </div>
          <div style={{ textAlign:"right", flexShrink:0 }}>
            <div style={{ fontFamily:"var(--mono)", fontWeight:700, fontSize:13 }}>{fmtDashMoney(c.total)}</div>
            {c.won>0 && <div style={{ fontSize:11, color:"#22c55e" }}>{fmtDashMoney(c.won)} adjudicado</div>}
          </div>
        </div>
      ))}
    </div>
  );
}

// ── DashboardView ─────────────────────────────────────────────
function DashboardView() {
  const { quotes, opps = [] } = React.useContext(window.AppCtx);

  const stats = React.useMemo(() => {
    const sent     = quotes.filter(q=>q.status==="sent");
    const accepted = quotes.filter(q=>q.status==="accepted");
    const rejected = quotes.filter(q=>q.status==="rejected");
    const closed   = accepted.length + rejected.length;
    const winRate  = closed>0 ? Math.round(accepted.length/closed*100) : 0;
    const totalQuoted = quotes.reduce((s,q)=>s+(q.total||0),0);
    const totalWon    = accepted.reduce((s,q)=>s+(q.total||0),0);
    const totalPending= sent.reduce((s,q)=>s+(q.total||0),0);
    const avgMargin   = quotes.length>0
      ? quotes.reduce((s,q)=>s+(q.margin_pct||0),0)/quotes.length : 0;
    const pipelineVal = opps.filter(o=>o.stage!=="adjudicado"&&o.stage!=="no_adjudicado")
      .reduce((s,o)=>s+(o.value||0),0);
    return { sent, accepted, rejected, closed, winRate, totalQuoted, totalWon, totalPending, avgMargin, pipelineVal };
  }, [quotes, opps]);

  return (
    <div style={{ padding:"28px 28px 80px" }}>
      <div style={{ marginBottom:28 }}>
        <h1 style={{ margin:0, fontSize:22, fontWeight:800 }}>Dashboard Comercial</h1>
        <div style={{ fontSize:13, color:"var(--muted)", marginTop:4 }}>Resumen de métricas del área comercial</div>
      </div>

      {/* KPI row */}
      <div style={{ display:"grid", gridTemplateColumns:"repeat(auto-fit,minmax(160px,1fr))", gap:12, marginBottom:28 }}>
        <DashKpi label="Total cotizado" value={fmtDashMoney(stats.totalQuoted)}
          sub={`${quotes.length} cotizaciones`} color="var(--gold,#c9a84c)" />
        <DashKpi label="Adjudicado" value={fmtDashMoney(stats.totalWon)}
          sub={`${stats.accepted.length} proyectos`} color="#22c55e" />
        <DashKpi label="En negociación" value={fmtDashMoney(stats.totalPending)}
          sub={`${stats.sent.length} cotizaciones`} color="#f59e0b" />
        <DashKpi label="Tasa de cierre" value={stats.winRate+"%"}
          sub={`${stats.closed} cerradas`}
          color={stats.winRate>=40?"#22c55e":stats.winRate>=20?"#f59e0b":"#ef4444"} />
        <DashKpi label="Margen promedio" value={(stats.avgMargin).toFixed(1)+"%"}
          color={stats.avgMargin>=28?"#22c55e":stats.avgMargin>=18?"#f59e0b":"#ef4444"} />
        <DashKpi label="Pipeline activo" value={fmtDashMoney(stats.pipelineVal)}
          sub={`${opps.filter(o=>o.stage!=="adjudicado"&&o.stage!=="no_adjudicado").length} oportunidades`} />
      </div>

      {/* Charts row */}
      <div style={{ display:"grid", gridTemplateColumns:"minmax(0,1.6fr) minmax(0,1fr)", gap:16, marginBottom:20 }}>
        <div style={{ background:"var(--surface)", border:"1px solid var(--border)", borderRadius:13, padding:"20px 22px" }}>
          <div style={{ fontSize:14, fontWeight:700, marginBottom:16 }}>Cotizaciones por mes (últimos 6 meses)</div>
          <MonthlyChart quotes={quotes} />
          <div style={{ display:"flex", gap:16, marginTop:12 }}>
            <div style={{ display:"flex", alignItems:"center", gap:6, fontSize:12, color:"var(--muted)" }}>
              <div style={{ width:10, height:10, borderRadius:2, background:"var(--gold)" }} /> Adjudicado
            </div>
            <div style={{ display:"flex", alignItems:"center", gap:6, fontSize:12, color:"var(--muted)" }}>
              <div style={{ width:10, height:10, borderRadius:2, background:"color-mix(in srgb,var(--gold) 22%,transparent)" }} /> Total cotizado
            </div>
          </div>
        </div>
        <div style={{ background:"var(--surface)", border:"1px solid var(--border)", borderRadius:13, padding:"20px 22px" }}>
          <div style={{ fontSize:14, fontWeight:700, marginBottom:16 }}>Funnel de pipeline</div>
          {opps.length > 0 ? <PipelineFunnel opps={opps} /> : (
            <div style={{ color:"var(--muted)", fontSize:13, padding:"20px 0" }}>Sin oportunidades en pipeline.</div>
          )}
        </div>
      </div>

      {/* Status breakdown + Top clients */}
      <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:16 }}>
        <div style={{ background:"var(--surface)", border:"1px solid var(--border)", borderRadius:13, padding:"20px 22px" }}>
          <div style={{ fontSize:14, fontWeight:700, marginBottom:16 }}>Estado de cotizaciones</div>
          {[
            { label:"Borrador",       key:"draft",    color:"#6b7280" },
            { label:"En negociación", key:"sent",     color:"#f59e0b" },
            { label:"Adjudicado",     key:"accepted", color:"#22c55e" },
            { label:"No adjudicado",  key:"rejected", color:"#ef4444" },
            { label:"Pendiente",      key:"pending",  color:"#0ea5e9" },
          ].map(s => {
            const count = quotes.filter(q=>q.status===s.key).length;
            const pct   = quotes.length>0 ? (count/quotes.length)*100 : 0;
            return (
              <div key={s.key} style={{ display:"flex", alignItems:"center", gap:10, marginBottom:10 }}>
                <div style={{ width:90, fontSize:12, color:"var(--muted)", flexShrink:0,
                  overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap" }}>{s.label}</div>
                <div style={{ flex:1, height:8, background:"var(--bg)", borderRadius:4, overflow:"hidden" }}>
                  <div style={{ height:"100%", width:`${pct}%`, background:s.color, borderRadius:4, transition:"width .5s" }} />
                </div>
                <div style={{ width:24, textAlign:"right", fontFamily:"var(--mono)", fontSize:12, fontWeight:700, flexShrink:0 }}>
                  {count}
                </div>
              </div>
            );
          })}
        </div>
        <div style={{ background:"var(--surface)", border:"1px solid var(--border)", borderRadius:13, padding:"20px 22px" }}>
          <div style={{ fontSize:14, fontWeight:700, marginBottom:4 }}>Top clientes</div>
          <div style={{ fontSize:12, color:"var(--muted)", marginBottom:14 }}>Por volumen total cotizado</div>
          <TopClients quotes={quotes} />
        </div>
      </div>
    </div>
  );
}

window.DashboardView = DashboardView;
