// Módulo 4 — Inteligencia Comercial

function InteligenciaComercial() {
  const D = window.APP_DATA;

  const kpis = [
    { label: "CUOTA DE MERCADO", value: "23.4%", sub: "+1.2% vs trimestre ant.", subType: "ok" },
    { label: "ALMACENES CONSTRUCCIÓN ES", value: "10.234", sub: "2.847 en zona activa", subType: "" },
    { label: "SCORE RIESGO SECTOR", value: "B+ (13.2)", sub: "Riesgo bajo-medio", subType: "ok" },
    { label: "OPORTUNIDADES DETECTADAS", value: "14", sub: "6 alta prioridad", subType: "info" },
    { label: "NUEVAS CONSTITUCIONES", value: "342", sub: "Sector construcción Q2", subType: "" },
  ];

  const sources = ["InAtlas Geomarketing", "Informa D&B", "Dynamics AX", "SABI", "Catastro"];

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 8 }}>
        <div style={{ display: "flex", gap: 6, flexWrap: "wrap", alignItems: "center" }}>
          <span style={{ fontSize: 11, color: "var(--ink-muted)", textTransform: "uppercase", letterSpacing: "0.05em", fontWeight: 600, marginRight: 6 }}>FUENTES DE DATOS:</span>
          {sources.map(s => <span key={s} className="badge info">{s}</span>)}
        </div>
        <div style={{ fontSize: 12, color: "var(--ink-muted)" }}>Últ. actualización: hoy 08:30</div>
      </div>

      <div className="kpi-row">
        {kpis.map(k => <KPI key={k.label} {...k} />)}
      </div>

      <div className="grid-chart">
        <div className="card">
          <h3 className="with-sub">Cuota de Mercado por Competidor — Selladores</h3>
          <div className="h3-sub">Fuente: datos estimados sector construcción España Q4 2025</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 10, marginTop: 8 }}>
            {D.marketShare.map(m => (
              <div key={m.name} style={{ display: "grid", gridTemplateColumns: "120px 1fr 50px", gap: 10, alignItems: "center", fontSize: 13 }}>
                <div>{m.name}</div>
                <HBar value={m.value} max={30} color={m.color} />
                <div style={{ textAlign: "right", fontVariantNumeric: "tabular-nums" }}>{m.value}%</div>
              </div>
            ))}
          </div>
        </div>

        <div className="card">
          <h3>Heat Map de Ventas por Zona</h3>
          <HeatMap />
        </div>
      </div>

      <div className="card">
        <h3>Oportunidades Detectadas</h3>
        <table className="table">
          <thead><tr><th>Cliente / Prospecto</th><th>Tipo</th><th>Potencial</th><th>Motivo</th><th></th></tr></thead>
          <tbody>
            <tr><td>OBRAMAT Rivas</td><td><Badge variant="info">Cross-sell</Badge></td><td style={{ fontWeight: 600 }}>42K €/año</td><td style={{ color: "var(--ink-soft)" }}>Compra selladores, no compra espumas PU</td><td><button className="btn-ghost" style={{ padding: "4px 10px", fontSize: 12, borderRadius: 6 }}>Ver</button></td></tr>
            <tr><td>Leroy Merlin Getafe</td><td><Badge variant="warn">Up-sell</Badge></td><td style={{ fontWeight: 600 }}>28K €/año</td><td style={{ color: "var(--ink-soft)" }}>Consumo creciente 18% YoY, sin rappel activo</td><td><button className="btn-ghost" style={{ padding: "4px 10px", fontSize: 12, borderRadius: 6 }}>Ver</button></td></tr>
            <tr><td>Reformas Rivas S.L.</td><td><Badge variant="ok">Prospecto</Badge></td><td style={{ fontWeight: 600 }}>18K €/año</td><td style={{ color: "var(--ink-soft)" }}>No captado, empresa con CNAE 4120 y 25 emp.</td><td><button className="btn-ghost" style={{ padding: "4px 10px", fontSize: 12, borderRadius: 6 }}>Ver</button></td></tr>
            <tr><td>Materiales García</td><td><Badge variant="err">Riesgo fuga</Badge></td><td style={{ fontWeight: 600 }}>45K €/año</td><td style={{ color: "var(--ink-soft)" }}>Caída pedidos 32% en últimos 60 días</td><td><button className="btn-ghost" style={{ padding: "4px 10px", fontSize: 12, borderRadius: 6 }}>Ver</button></td></tr>
          </tbody>
        </table>
      </div>
    </div>
  );
}

function HeatMap() {
  // Composición geo estilizada con círculos de calor
  const regions = [
    { name: "Madrid", x: 50, y: 50, r: 48, v: 0.95 },
    { name: "Barcelona", x: 82, y: 35, r: 34, v: 0.75 },
    { name: "Valencia", x: 72, y: 55, r: 28, v: 0.58 },
    { name: "Sevilla", x: 30, y: 72, r: 30, v: 0.62 },
    { name: "Bilbao", x: 55, y: 20, r: 22, v: 0.45 },
    { name: "Zaragoza", x: 65, y: 40, r: 18, v: 0.38 },
  ];
  return (
    <div style={{ position: "relative", height: 280, background: "oklch(0.95 0.015 80)", borderRadius: 8, overflow: "hidden" }}>
      {/* Silueta estilizada de España */}
      <svg viewBox="0 0 100 85" style={{ position: "absolute", inset: 0, width: "100%", height: "100%" }}>
        <path d="M15 25 Q 20 18 30 18 L 50 15 Q 65 15 75 22 L 88 25 Q 92 35 88 45 L 85 58 Q 78 72 65 76 L 45 78 Q 28 78 20 72 L 14 60 Q 10 45 15 25 Z"
          fill="oklch(0.92 0.015 80)" stroke="oklch(0.82 0.02 80)" strokeWidth="0.3" />
        {regions.map(r => (
          <g key={r.name}>
            <circle cx={r.x} cy={r.y} r={r.r / 8} fill={`oklch(0.62 0.17 45 / ${r.v * 0.55})`} />
            <circle cx={r.x} cy={r.y} r={r.r / 16} fill="var(--accent)" />
          </g>
        ))}
      </svg>
      {regions.map(r => (
        <div key={r.name} style={{ position: "absolute", left: `${r.x}%`, top: `${r.y + 4}%`, transform: "translate(-50%, 0)", fontSize: 10, color: "var(--ink-soft)", fontWeight: 600, pointerEvents: "none" }}>
          {r.name}
        </div>
      ))}
      <div style={{ position: "absolute", bottom: 10, right: 10, display: "flex", alignItems: "center", gap: 6, fontSize: 10, color: "var(--ink-muted)" }}>
        <div style={{ width: 40, height: 6, background: "linear-gradient(90deg, oklch(0.62 0.17 45 / 0.15), var(--accent))", borderRadius: 99 }} /> Ventas
      </div>
    </div>
  );
}

Object.assign(window, { InteligenciaComercial });
