/* ============================================================
   INside One — Pipeline CRM (Módulo Comercial)
   Colección Firestore: qg_pipeline
   ============================================================ */

// ── Constantes ──────────────────────────────────────────────
const PIPELINE_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 LOSS_REASONS = [
  "Precio muy alto",
  "Competencia seleccionada",
  "Proyecto cancelado",
  "Sin respuesta del cliente",
  "Presupuesto insuficiente",
  "Otro",
];

const STAGE_MAP = Object.fromEntries(PIPELINE_STAGES.map(s => [s.key, s]));

// ── Helpers ──────────────────────────────────────────────────
function oppStage(opp) { return STAGE_MAP[opp.stage] || PIPELINE_STAGES[0]; }
function fmtK(n) { return n >= 1000 ? "$" + (n / 1000).toFixed(1) + "k" : window.fmtMoney(n); }

// ── OppModal ─────────────────────────────────────────────────
function OppModal({ opp, onClose, onSave, onRemove }) {
  const { clients = [] } = React.useContext(window.AppCtx);
  const isNew = !opp.id;
  const [form, setForm] = React.useState({
    name: opp.name || "",
    client_id: opp.client_id || "",
    client_name: opp.client_name || "",
    client_company: opp.client_company || "",
    stage: opp.stage || "prospecto",
    value: opp.value || "",
    quote_number: opp.quote_number || "",
    contact_date: opp.contact_date || new Date().toISOString().slice(0, 10),
    expected_close: opp.expected_close || "",
    notes: opp.notes || "",
    loss_reason: opp.loss_reason || "",
  });
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const isLost = form.stage === "no_adjudicado";

  const pickClient = (id) => {
    if (!id) { set("client_id",""); set("client_name",""); set("client_company",""); return; }
    const c = clients.find(x=>x.id===id);
    if (c) setForm(f=>({...f, client_id:id, client_name:c.name||"", client_company:c.company||""}));
  };

  const handleSave = () => {
    if (!form.name.trim()) { alert("El nombre del proyecto es requerido."); return; }
    onSave({ ...opp, ...form, value: parseFloat(form.value) || 0 });
  };

  return (
    <div style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,.45)", zIndex: 1000,
      display: "flex", alignItems: "center", justifyContent: "center", padding: 16 }}>
      <div style={{ background: "var(--surface)", borderRadius: 14, padding: 28, width: "100%",
        maxWidth: 520, maxHeight: "90vh", overflowY: "auto", boxShadow: "0 20px 60px rgba(0,0,0,.25)" }}>

        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 22 }}>
          <h2 style={{ margin: 0, fontSize: 18 }}>{isNew ? "Nueva oportunidad" : "Editar oportunidad"}</h2>
          <button className="iconbtn" onClick={onClose}><window.Icon name="close" size={18} /></button>
        </div>

        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          <label style={{ fontSize: 12, fontWeight: 600, color: "var(--muted)" }}>
            Proyecto / oportunidad *
            <input className="inp" style={{ marginTop: 4, display: "block", width: "100%" }}
              value={form.name} onChange={e => set("name", e.target.value)} placeholder="Nombre del proyecto" />
          </label>

          <label style={{ fontSize: 12, fontWeight: 600, color: "var(--muted)" }}>
            Cliente
            {clients.length > 0 ? (
              <select className="inp" style={{ marginTop: 4, display: "block", width: "100%" }}
                value={form.client_id} onChange={e => pickClient(e.target.value)}>
                <option value="">— Seleccionar cliente —</option>
                {clients.map(c=>(
                  <option key={c.id} value={c.id}>{c.name}{c.company?" · "+c.company:""}</option>
                ))}
                <option value="__nuevo__">+ Nuevo (escribir manualmente)</option>
              </select>
            ) : (
              <input className="inp" style={{ marginTop: 4, display: "block", width: "100%" }}
                value={form.client_name} onChange={e => set("client_name", e.target.value)} placeholder="Nombre" />
            )}
          </label>
          {(form.client_id === "__nuevo__" || !form.client_id) && (
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
              <label style={{ fontSize: 12, fontWeight: 600, color: "var(--muted)" }}>
                Nombre del contacto
                <input className="inp" style={{ marginTop: 4, display: "block", width: "100%" }}
                  value={form.client_name} onChange={e => set("client_name", e.target.value)} placeholder="Nombre" />
              </label>
              <label style={{ fontSize: 12, fontWeight: 600, color: "var(--muted)" }}>
                Empresa
                <input className="inp" style={{ marginTop: 4, display: "block", width: "100%" }}
                  value={form.client_company} onChange={e => set("client_company", e.target.value)} placeholder="Empresa" />
              </label>
            </div>
          )}

          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
            <label style={{ fontSize: 12, fontWeight: 600, color: "var(--muted)" }}>
              Etapa
              <select className="inp" style={{ marginTop: 4, display: "block", width: "100%" }}
                value={form.stage} onChange={e => set("stage", e.target.value)}>
                {PIPELINE_STAGES.map(s => <option key={s.key} value={s.key}>{s.label}</option>)}
              </select>
            </label>
            <label style={{ fontSize: 12, fontWeight: 600, color: "var(--muted)" }}>
              Valor estimado ($)
              <input className="inp" style={{ marginTop: 4, display: "block", width: "100%" }}
                type="number" min="0" step="100"
                value={form.value} onChange={e => set("value", e.target.value)} placeholder="0.00" />
            </label>
          </div>

          {isLost && (
            <label style={{ fontSize: 12, fontWeight: 600, color: "var(--muted)" }}>
              Razón de pérdida
              <select className="inp" style={{ marginTop: 4, display: "block", width: "100%" }}
                value={form.loss_reason} onChange={e => set("loss_reason", e.target.value)}>
                <option value="">Seleccionar...</option>
                {LOSS_REASONS.map(r => <option key={r} value={r}>{r}</option>)}
              </select>
            </label>
          )}

          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
            <label style={{ fontSize: 12, fontWeight: 600, color: "var(--muted)" }}>
              Cotización vinculada
              <input className="inp" style={{ marginTop: 4, display: "block", width: "100%" }}
                value={form.quote_number} onChange={e => set("quote_number", e.target.value)} placeholder="IN065" />
            </label>
            <label style={{ fontSize: 12, fontWeight: 600, color: "var(--muted)" }}>
              Fecha de contacto
              <input className="inp" type="date" style={{ marginTop: 4, display: "block", width: "100%" }}
                value={form.contact_date} onChange={e => set("contact_date", e.target.value)} />
            </label>
          </div>

          <label style={{ fontSize: 12, fontWeight: 600, color: "var(--muted)" }}>
            Cierre estimado
            <input className="inp" type="date" style={{ marginTop: 4, display: "block", width: "100%" }}
              value={form.expected_close} onChange={e => set("expected_close", e.target.value)} />
          </label>

          <label style={{ fontSize: 12, fontWeight: 600, color: "var(--muted)" }}>
            Notas
            <textarea className="inp" rows={3} style={{ marginTop: 4, display: "block", width: "100%", resize: "vertical", fontFamily: "inherit" }}
              value={form.notes} onChange={e => set("notes", e.target.value)} placeholder="Detalles de la reunión, próximos pasos..." />
          </label>
        </div>

        <div style={{ display: "flex", justifyContent: "space-between", marginTop: 22, gap: 10 }}>
          <div>
            {!isNew && (
              <window.Btn variant="ghost" size="sm" icon="trash"
                onClick={() => { if (confirm("¿Eliminar esta oportunidad?")) onRemove(opp.id); }}>
                Eliminar
              </window.Btn>
            )}
          </div>
          <div style={{ display: "flex", gap: 8 }}>
            <window.Btn variant="outline" size="sm" onClick={onClose}>Cancelar</window.Btn>
            <window.Btn variant="primary" size="sm" icon="check" onClick={handleSave}>
              {isNew ? "Crear" : "Guardar"}
            </window.Btn>
          </div>
        </div>
      </div>
    </div>
  );
}

// ── KPI card ─────────────────────────────────────────────────
function KpiCard({ label, value, sub, color }) {
  return (
    <div style={{ background: "var(--surface)", border: "1px solid var(--border)", borderRadius: 12,
      padding: "18px 20px", display: "flex", flexDirection: "column", gap: 4 }}>
      <div style={{ fontSize: 11, fontWeight: 600, color: "var(--muted)", textTransform: "uppercase", letterSpacing: ".06em" }}>{label}</div>
      <div style={{ fontSize: 26, fontWeight: 800, color: color || "var(--text)", lineHeight: 1.15 }}>{value}</div>
      {sub && <div style={{ fontSize: 12, color: "var(--muted)" }}>{sub}</div>}
    </div>
  );
}

// ── Stage badge ───────────────────────────────────────────────
function StageBadge({ stage }) {
  const s = STAGE_MAP[stage] || PIPELINE_STAGES[0];
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 11,
      fontWeight: 600, padding: "3px 9px", borderRadius: 99, color: s.color,
      background: s.color + "1a", border: "1px solid " + s.color + "44" }}>
      {s.label}
    </span>
  );
}

// ── PipelineView ──────────────────────────────────────────────
function PipelineView() {
  const ctx = React.useContext(window.AppCtx);
  const { opps = [], addOpp, updateOpp, removeOpp, adminMode } = ctx;

  const [stageFilter, setStageFilter] = React.useState("all");
  const [search, setSearch] = React.useState("");
  const [modal, setModal] = React.useState(null); // null | opp object (new={} or existing)

  const filtered = React.useMemo(() => {
    let list = [...opps].sort((a, b) => (b.created_at || 0) - (a.created_at || 0));
    if (stageFilter !== "all") list = list.filter(o => o.stage === stageFilter);
    if (search.trim()) {
      const q = search.trim().toLowerCase();
      list = list.filter(o =>
        (o.name || "").toLowerCase().includes(q) ||
        (o.client_name || "").toLowerCase().includes(q) ||
        (o.client_company || "").toLowerCase().includes(q)
      );
    }
    return list;
  }, [opps, stageFilter, search]);

  // KPIs
  const active = opps.filter(o => o.stage !== "adjudicado" && o.stage !== "no_adjudicado");
  const won    = opps.filter(o => o.stage === "adjudicado");
  const lost   = opps.filter(o => o.stage === "no_adjudicado");
  const closed = won.length + lost.length;
  const winRate = closed > 0 ? Math.round((won.length / closed) * 100) : 0;
  const pipelineValue = active.reduce((s, o) => s + (o.value || 0), 0);

  const handleSave = async (data) => {
    if (data.id) {
      await updateOpp(data.id, data);
    } else {
      await addOpp({ ...data, created_at: Date.now() });
    }
    setModal(null);
  };

  const handleRemove = async (id) => {
    await removeOpp(id);
    setModal(null);
  };

  return (
    <div style={{ padding: "28px 28px 60px" }}>
      {/* Header */}
      <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", marginBottom: 24, gap: 16, flexWrap: "wrap" }}>
        <div>
          <h1 style={{ margin: 0, fontSize: 22, fontWeight: 800 }}>Pipeline comercial</h1>
          <div style={{ fontSize: 13, color: "var(--muted)", marginTop: 4 }}>
            Seguimiento de oportunidades y proyectos
          </div>
        </div>
        <window.Btn variant="primary" size="sm" icon="plus" onClick={() => setModal({})}>
          Nueva oportunidad
        </window.Btn>
      </div>

      {/* KPIs */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(160px,1fr))", gap: 12, marginBottom: 28 }}>
        <KpiCard label="Pipeline activo" value={fmtK(pipelineValue)} sub={`${active.length} oportunidades`} color="var(--gold,#c9a84c)" />
        <KpiCard label="Adjudicadas" value={won.length} sub={won.length > 0 ? fmtK(won.reduce((s,o) => s+(o.value||0),0)) : "—"} color="#22c55e" />
        <KpiCard label="No adjudicadas" value={lost.length} color="#ef4444" />
        <KpiCard label="Tasa de cierre" value={winRate + "%"} sub={`${closed} cerradas`} color={winRate >= 40 ? "#22c55e" : winRate >= 20 ? "#f59e0b" : "#ef4444"} />
      </div>

      {/* Filters */}
      <div style={{ display: "flex", gap: 10, marginBottom: 16, flexWrap: "wrap", alignItems: "center" }}>
        <input className="inp" style={{ width: 220 }} placeholder="Buscar proyecto o cliente..."
          value={search} onChange={e => setSearch(e.target.value)} />
        <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
          {[{ key: "all", label: "Todas" }, ...PIPELINE_STAGES].map(s => (
            <button key={s.key} onClick={() => setStageFilter(s.key)}
              style={{ fontSize: 12, padding: "5px 12px", borderRadius: 99, fontWeight: 600, cursor: "pointer", border: "1px solid",
                borderColor: stageFilter === s.key ? (s.color || "var(--gold)") : "var(--border)",
                background: stageFilter === s.key ? ((s.color || "var(--gold)") + "18") : "transparent",
                color: stageFilter === s.key ? (s.color || "var(--gold)") : "var(--muted)" }}>
              {s.label}
            </button>
          ))}
        </div>
      </div>

      {/* Table */}
      {filtered.length === 0 ? (
        <div style={{ textAlign: "center", padding: "60px 20px", color: "var(--muted)" }}>
          <window.Icon name="layers" size={32} />
          <div style={{ marginTop: 12, fontSize: 15, fontWeight: 600, color: "var(--text)" }}>
            {opps.length === 0 ? "Sin oportunidades aún" : "Sin resultados"}
          </div>
          <div style={{ fontSize: 13, marginTop: 6 }}>
            {opps.length === 0 ? "Crea tu primera oportunidad para comenzar el seguimiento." : "Prueba con otro filtro o búsqueda."}
          </div>
          {opps.length === 0 && (
            <window.Btn variant="primary" size="sm" icon="plus" style={{ marginTop: 16 }} onClick={() => setModal({})}>
              Nueva oportunidad
            </window.Btn>
          )}
        </div>
      ) : (
        <div style={{ background: "var(--surface)", border: "1px solid var(--border)", borderRadius: 12, overflow: "hidden" }}>
          <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13 }}>
            <thead>
              <tr style={{ borderBottom: "1px solid var(--border)", background: "var(--bg2)" }}>
                <th style={{ padding: "11px 16px", textAlign: "left", fontWeight: 600, color: "var(--muted)", fontSize: 11, textTransform: "uppercase", letterSpacing: ".05em" }}>Proyecto</th>
                <th style={{ padding: "11px 16px", textAlign: "left", fontWeight: 600, color: "var(--muted)", fontSize: 11, textTransform: "uppercase", letterSpacing: ".05em" }}>Cliente</th>
                <th style={{ padding: "11px 16px", textAlign: "left", fontWeight: 600, color: "var(--muted)", fontSize: 11, textTransform: "uppercase", letterSpacing: ".05em" }}>Etapa</th>
                <th style={{ padding: "11px 16px", textAlign: "right", fontWeight: 600, color: "var(--muted)", fontSize: 11, textTransform: "uppercase", letterSpacing: ".05em" }}>Valor</th>
                <th style={{ padding: "11px 16px", textAlign: "left", fontWeight: 600, color: "var(--muted)", fontSize: 11, textTransform: "uppercase", letterSpacing: ".05em" }}>Cotización</th>
                <th style={{ padding: "11px 16px", textAlign: "left", fontWeight: 600, color: "var(--muted)", fontSize: 11, textTransform: "uppercase", letterSpacing: ".05em" }}>Cierre est.</th>
                <th style={{ padding: "11px 4px" }}></th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((opp, i) => (
                <tr key={opp.id} style={{ borderBottom: i < filtered.length - 1 ? "1px solid var(--border)" : "none",
                  cursor: "pointer", transition: "background .12s" }}
                  onClick={() => setModal(opp)}
                  onMouseEnter={e => e.currentTarget.style.background = "var(--bg)"}
                  onMouseLeave={e => e.currentTarget.style.background = ""}>
                  <td style={{ padding: "13px 16px" }}>
                    <div style={{ fontWeight: 600 }}>{opp.name || "—"}</div>
                    {opp.notes && <div style={{ fontSize: 11, color: "var(--muted)", marginTop: 2, maxWidth: 240, overflow: "hidden", whiteSpace: "nowrap", textOverflow: "ellipsis" }}>{opp.notes}</div>}
                  </td>
                  <td style={{ padding: "13px 16px" }}>
                    <div>{opp.client_name || "—"}</div>
                    {opp.client_company && <div style={{ fontSize: 11, color: "var(--muted)" }}>{opp.client_company}</div>}
                  </td>
                  <td style={{ padding: "13px 16px" }}>
                    <StageBadge stage={opp.stage} />
                    {opp.stage === "no_adjudicado" && opp.loss_reason && (
                      <div style={{ fontSize: 11, color: "var(--muted)", marginTop: 3 }}>{opp.loss_reason}</div>
                    )}
                  </td>
                  <td style={{ padding: "13px 16px", textAlign: "right", fontFamily: "var(--mono)", fontWeight: 600 }}>
                    {opp.value ? window.fmtMoney(opp.value) : "—"}
                  </td>
                  <td style={{ padding: "13px 16px", color: "var(--muted)" }}>
                    {opp.quote_number || "—"}
                  </td>
                  <td style={{ padding: "13px 16px", color: "var(--muted)" }}>
                    {opp.expected_close || "—"}
                  </td>
                  <td style={{ padding: "13px 8px", textAlign: "right" }}>
                    <button className="iconbtn" onClick={e => { e.stopPropagation(); setModal(opp); }} title="Editar">
                      <window.Icon name="settings" size={14} />
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {modal !== null && (
        <OppModal
          opp={modal}
          onClose={() => setModal(null)}
          onSave={handleSave}
          onRemove={handleRemove}
        />
      )}
    </div>
  );
}

window.PipelineView = PipelineView;
