// Módulo 7 — Rutas y Prospección

function RutasProspeccion() {
  const [zone, setZone] = React.useState("Rivas-Vaciamadrid");
  const [priority, setPriority] = React.useState("potencial");
  const [selected, setSelected] = React.useState([0, 1]);
  const D = window.APP_DATA;
  const zones = ["Rivas-Vaciamadrid", "Alcorcón", "Getafe", "Leganés", "Móstoles"];

  const clientsInZone = D.clients.filter(c => c.city === zone);
  const prospects = D.prospects.filter(p => p.zone === zone.split("-")[0]);

  return (
    <div style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 16 }}>
      <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
        <div className="card">
          <h3>Selecciona Zona</h3>
          <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
            {zones.map(z => (
              <button key={z} className={z === zone ? "btn" : "btn-secondary"} onClick={() => setZone(z)} style={{ padding: "6px 14px", fontSize: 12.5 }}>{z}</button>
            ))}
          </div>
        </div>

        <div className="card" style={{ padding: 0, overflow: "hidden" }}>
          <MapMock zone={zone} />
        </div>

        <div className="card">
          <h3>Clientes Potenciales (Fuente: SABI)</h3>
          <div style={{ fontSize: 12, color: "var(--ink-muted)", marginBottom: 12 }}>Empresas del sector construcción en la zona no captadas</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {prospects.length > 0 ? prospects.map((p, i) => (
              <div key={i} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "10px 12px", background: "var(--surface-2)", borderRadius: 8 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                  <div style={{ width: 28, height: 28, background: "var(--warn-soft)", color: "oklch(0.48 0.14 75)", borderRadius: 99, display: "grid", placeItems: "center", fontSize: 12, fontWeight: 600 }}>P</div>
                  <div>
                    <div style={{ fontWeight: 500, fontSize: 13 }}>{p.name} <Badge variant="warn">PROSPECTO</Badge></div>
                    <div style={{ fontSize: 11, color: "var(--ink-muted)" }}>CNAE: {p.cnae} · {p.employees} empleados · Fact: {p.turnover}</div>
                  </div>
                </div>
                <button className="btn-ghost" style={{ padding: "4px 10px", fontSize: 12, borderRadius: 6 }}>Ver ficha</button>
              </div>
            )) : <div style={{ color: "var(--ink-muted)", textAlign: "center", padding: 24, fontSize: 13 }}>Sin prospectos en esta zona</div>}
          </div>
        </div>
      </div>

      <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
        <div className="card">
          <h3>Priorizar por</h3>
          <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
            {[["potencial", "Potencial €"], ["cercania", "Cercanía"], ["ultvisita", "Últ. Visita"]].map(([k, l]) => (
              <button key={k} className={priority === k ? "btn" : "btn-secondary"} onClick={() => setPriority(k)} style={{ padding: "6px 12px", fontSize: 12.5 }}>{l}</button>
            ))}
          </div>
        </div>

        <div className="card">
          <h3>Clientes en la Zona</h3>
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {clientsInZone.map((c, i) => (
              <div key={c.code} onClick={() => setSelected(selected.includes(i) ? selected.filter(j => j !== i) : [...selected, i])}
                style={{ cursor: "pointer", padding: "10px 12px", border: `1px solid ${selected.includes(i) ? "var(--accent)" : "var(--border)"}`, background: selected.includes(i) ? "var(--accent-soft)" : "var(--surface)", borderRadius: 8, display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                  <div style={{ width: 24, height: 24, background: "var(--accent)", color: "#fff", borderRadius: 99, display: "grid", placeItems: "center", fontSize: 11, fontWeight: 600 }}>{i + 1}</div>
                  <div>
                    <div style={{ fontWeight: 500, fontSize: 13 }}>{c.name}</div>
                    <div style={{ fontSize: 11, color: "var(--ink-muted)" }}>Clase {c.class} · {c.volume}</div>
                  </div>
                </div>
                <Badge variant={c.class === "A" ? "ok" : c.class === "B" ? "info" : "neutral"}>{c.class}</Badge>
              </div>
            ))}
          </div>
        </div>

        <div className="card" style={{ background: "linear-gradient(135deg, var(--accent), oklch(0.55 0.17 35))", color: "#fff", border: "none" }}>
          <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.05em", fontWeight: 600, opacity: 0.9 }}>Ruta Optimizada</div>
          <div style={{ fontSize: 14, opacity: 0.95, marginTop: 2 }}>{selected.length} clientes seleccionados</div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 10, margin: "16px 0" }}>
            <RouteStat v="12 km" l="distancia" />
            <RouteStat v="24 min" l="tiempo" />
            <RouteStat v="232K" l="potencial €" />
          </div>
          <button style={{ width: "100%", padding: 10, background: "#fff", color: "var(--accent)", border: "none", borderRadius: 6, fontWeight: 600, cursor: "pointer", display: "flex", justifyContent: "center", alignItems: "center", gap: 6 }}>
            <div style={{ width: 14, height: 14 }}><Icon.Arrow /></div> Iniciar Navegación
          </button>
        </div>
      </div>
    </div>
  );
}
function RouteStat({ v, l }) {
  return <div style={{ textAlign: "center" }}><div style={{ fontSize: 17, fontWeight: 600 }}>{v}</div><div style={{ fontSize: 10, textTransform: "uppercase", letterSpacing: "0.05em", opacity: 0.85, marginTop: 2 }}>{l}</div></div>;
}

function MapMock({ zone }) {
  // Mapa estilizado con rejilla + pines
  return (
    <div style={{ height: 320, background: "oklch(0.95 0.02 120)", position: "relative", overflow: "hidden" }}>
      <svg viewBox="0 0 400 320" style={{ position: "absolute", inset: 0, width: "100%", height: "100%" }}>
        <defs>
          <pattern id="grid" width="20" height="20" patternUnits="userSpaceOnUse">
            <path d="M 20 0 L 0 0 0 20" fill="none" stroke="oklch(0.88 0.02 120)" strokeWidth="0.5" />
          </pattern>
        </defs>
        <rect width="400" height="320" fill="url(#grid)" />
        {/* Carreteras */}
        <path d="M 0 140 Q 100 120 200 160 T 400 130" stroke="oklch(0.82 0.02 80)" strokeWidth="6" fill="none" strokeLinecap="round" />
        <path d="M 180 0 Q 220 100 160 200 T 200 320" stroke="oklch(0.82 0.02 80)" strokeWidth="5" fill="none" strokeLinecap="round" />
        <path d="M 60 40 L 340 280" stroke="oklch(0.85 0.02 80)" strokeWidth="3" fill="none" strokeDasharray="4 4" />
        {/* Zonas verdes */}
        <ellipse cx="80" cy="240" rx="40" ry="22" fill="oklch(0.88 0.08 130)" opacity="0.7" />
        <ellipse cx="310" cy="70" rx="35" ry="25" fill="oklch(0.88 0.08 130)" opacity="0.7" />
        {/* Pines clientes */}
        {[
          { x: 150, y: 130, label: "1", active: true },
          { x: 240, y: 180, label: "2", active: true },
          { x: 110, y: 200, label: "3" },
          { x: 290, y: 220, label: "4" },
        ].map(p => (
          <g key={p.label}>
            <circle cx={p.x} cy={p.y} r="14" fill={p.active ? "var(--accent)" : "#fff"} stroke={p.active ? "#fff" : "var(--accent)"} strokeWidth="2" />
            <text x={p.x} y={p.y + 4} textAnchor="middle" fontSize="12" fontWeight="600" fill={p.active ? "#fff" : "var(--accent)"}>{p.label}</text>
          </g>
        ))}
        {/* Ruta entre 1-2 */}
        <path d="M 150 130 Q 200 140 240 180" stroke="var(--accent)" strokeWidth="3" fill="none" strokeDasharray="6 3" opacity="0.8" />
      </svg>
      <div style={{ position: "absolute", top: 12, left: 12, background: "#fff", padding: "6px 12px", borderRadius: 6, fontSize: 12, boxShadow: "var(--shadow-sm)", border: "1px solid var(--border)" }}>
        <b>{zone}</b><span style={{ color: "var(--ink-muted)", marginLeft: 6 }}>Madrid, España</span>
      </div>
    </div>
  );
}

Object.assign(window, { RutasProspeccion });
