/* ============================================================
   Robotia Cotizador · Vista VENTA del resumen
   Oferta + matriz escalabilidad + gráfico escalonado.
   ============================================================ */
const Sr = window.RBSales;

/* ---------- Gráfico escalonado (SVG) ---------- */
function StepChart({ escData, fmt }) {
  const segs = escData.segs;
  const steps = escData.steps;
  if (steps.length < 2) {
    return <div className="hint" style={{ padding: "30px 0", textAlign: "center" }}>Agregue al menos un escalón para ver el gráfico.</div>;
  }
  const W = 720, H = 380, padL = 70, padR = 28, padT = 26, padB = 46;
  const plotW = W - padL - padR, plotH = H - padT - padB;
  const xMin = steps[0], xMax = steps[steps.length - 1];
  const rates = segs.map((s) => s.ratePP);
  const yMax = Math.max.apply(null, rates) * 1.06;
  const yMin = Math.min.apply(null, rates) * 0.86;
  const xS = (p) => padL + (xMax === xMin ? 0 : (p - xMin) / (xMax - xMin)) * plotW;
  const yS = (v) => padT + (1 - (v - yMin) / (yMax - yMin)) * plotH;

  // staircase points: (s0,r0)->(s0,r1)->(s1,r1)->(s1,r2)->(s2,r2)...
  const pts = [];
  pts.push([steps[0], segs[0].ratePP]);
  for (let k = 1; k < segs.length; k++) {
    pts.push([steps[k - 1], segs[k].ratePP]);
    pts.push([steps[k], segs[k].ratePP]);
  }
  const lineD = pts.map((p, i) => (i === 0 ? "M" : "L") + xS(p[0]).toFixed(1) + " " + yS(p[1]).toFixed(1)).join(" ");
  const fillD = lineD + " L" + xS(pts[pts.length - 1][0]).toFixed(1) + " " + yS(yMin).toFixed(1) +
    " L" + xS(pts[0][0]).toFixed(1) + " " + yS(yMin).toFixed(1) + " Z";

  // y gridlines (4)
  const yticks = [];
  for (let g = 0; g <= 4; g++) { const v = yMin + (yMax - yMin) * g / 4; yticks.push(v); }

  return (
    <svg viewBox={"0 0 " + W + " " + H} style={{ width: "100%", height: "auto", display: "block" }}>
      {yticks.map((v, i) => (
        <g key={i}>
          <line className="chart-grid" x1={padL} y1={yS(v)} x2={W - padR} y2={yS(v)} />
          <text className="chart-axis-txt" x={padL - 10} y={yS(v) + 4} textAnchor="end">{fmt(v)}</text>
        </g>
      ))}
      {/* base reference dashed line */}
      <line className="chart-base-line" x1={padL} y1={yS(segs[0].ratePP)} x2={W - padR} y2={yS(segs[0].ratePP)} />
      <path className="chart-step-fill" d={fillD} />
      <path className="chart-step-line" d={lineD} />
      {/* drop guides + dots + labels at each step */}
      {segs.map((s, k) => {
        const x = xS(steps[k]), y = yS(s.ratePP);
        return (
          <g key={k}>
            <line className="chart-drop" x1={x} y1={y} x2={x} y2={yS(yMin)} />
            <circle className="chart-dot" cx={x} cy={y} r="5" />
            <text className="chart-step-lbl" x={x} y={y - 12} textAnchor={k === 0 ? "start" : "middle"}>{fmt(s.ratePP)}</text>
            <text className="chart-axis-txt" x={x} y={H - padB + 20} textAnchor="middle">{steps[k]} pts</text>
          </g>
        );
      })}
      <text className="chart-axis-txt" x={padL} y={H - 8} textAnchor="start" style={{ fontWeight: 600 }}>Puntos de monitoreo →</text>
      <text className="chart-axis-txt" x={padL - 10} y={padT - 10} textAnchor="end" transform={"rotate(0)"}>M$/pto·año</text>
    </svg>
  );
}

/* ---------- Vista venta completa ---------- */
function VentaResumen({ cot }) {
  const Eg = window.RBEngine;
  const venta = cot.venta;
  const vb = Sr.ventaBase(cot, venta);
  const esc = venta.escalabilidad;
  const [metric, setMetric] = useState("ratePP"); // ratePP | tcv
  const mtz = esc.activo ? Sr.matrizEscalabilidad(cot, venta) : null;
  const [yrIdx, setYrIdx] = useState(mtz ? mtz.Tmax - 1 : 0);
  const ti = mtz ? Math.min(yrIdx, mtz.Tmax - 1) : 0;
  const escData = esc.activo && mtz ? Sr.escalera(cot, venta, ti) : null;

  const cell = (c) => metric === "ratePP" ? Eg.fmtMiles(c.ratePP) : Eg.fmtMiles(c.tcv);

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 24, marginTop: 4 }}>
      {/* Oferta principal */}
      <div className="totalcard">
        <div className="lbl">— Propuesta al cliente · valor anual</div>
        <div className="big">{Eg.fmtMiles(vb.pvTotal)}<span className="unit">M$ / año</span></div>
        <div className="sub">Para <b>{cot.cliente.nombre || "el cliente"}</b> · {MODALIDADES[cot.modalidad].label} · {cot.inputs.nPuntos} puntos · año {cot.anioCotizacion}</div>
        <div className="metricrow">
          <div className="metric"><div className="l">— Valor por punto/año</div><div className="v">{Eg.fmtMiles(vb.pvTotal / cot.inputs.nPuntos)}</div></div>
          <div className="metric"><div className="l">— Utilidad anual</div><div className="v">{Eg.fmtMiles(vb.utilidadTotal)}</div></div>
          <div className="metric"><div className="l">— Margen proyecto</div><div className="v">{Eg.fmtDec(vb.margenProyecto * 100, 0)}<small>%</small></div></div>
        </div>
      </div>

      {/* Detalle de la oferta (precios cliente) */}
      <div className="panel">
        <h3 className="ph">Detalle de la <em>oferta</em></h3>
        <table className="recap">
          <tbody>
            {vb.items.map((it) => (
              <tr key={it.key}><td>{it.label}</td><td>{Eg.fmtMS(it.precio * vb.factor)}</td></tr>
            ))}
            <tr style={{ fontWeight: 600 }}><td style={{ color: "var(--ink)" }}>Total anual</td><td style={{ color: "var(--acc-soft)", fontSize: 16 }}>{Eg.fmtMS(vb.pvTotal)}</td></tr>
          </tbody>
        </table>
      </div>

      {/* Plan de escalabilidad */}
      {esc.activo && mtz ? (
        <React.Fragment>
          <div className="panel">
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", flexWrap: "wrap", gap: 14, marginBottom: 18 }}>
              <h3 className="ph" style={{ margin: 0 }}>Plan de <em>escalabilidad</em></h3>
              <div className="viewtoggle">
                <button className={metric === "ratePP" ? "on" : ""} onClick={() => setMetric("ratePP")}>Valor por punto/año</button>
                <button className={metric === "tcv" ? "on" : ""} onClick={() => setMetric("tcv")}>Valor total contrato</button>
              </div>
            </div>
            <div className="matwrap">
              <table className="matrix">
                <thead>
                  <tr>
                    <th>Años \ Puntos</th>
                    {mtz.steps.map((P, k) => <th key={k}>{P} pts{k === 0 ? " · base" : ""}</th>)}
                  </tr>
                </thead>
                <tbody>
                  {mtz.rows.map((row, rti) => (
                    <tr key={rti}>
                      <th>{rti + 1} {rti === 0 ? "año" : "años"}</th>
                      {row.map((c, k) => {
                        const isBest = rti === mtz.Tmax - 1 && k === mtz.K && mtz.K > 0;
                        const isBase = rti === 0 && k === 0;
                        return (
                          <td key={k} className={isBest ? "best" : (isBase ? "basecell" : "")}>
                            {cell(c)}
                            <span className="sub">margen {Eg.fmtDec(c.margen * 100, 0)}%</span>
                          </td>
                        );
                      })}
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            <div className="matlabel">
              <i style={{ background: "var(--acc)" }}></i> Mejor tarifa — máximo compromiso (margen mínimo {Eg.fmtDec(mtz.mf * 100, 0)}%)
              &nbsp;·&nbsp; valores en M$ {metric === "ratePP" ? "por punto / año" : "totales del contrato"}, año de inicio {cot.anioCotizacion}.
            </div>
          </div>

          <div className="chartcard">
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", flexWrap: "wrap", gap: 14, marginBottom: 8 }}>
              <h3 className="ph" style={{ margin: 0 }}>Tarifa escalonada por <em>volumen</em></h3>
              <div className="yrchips">
                {mtz.rows.map((_, rti) => (
                  <button key={rti} className={rti === ti ? "on" : ""} onClick={() => setYrIdx(rti)}>{rti + 1} {rti === 0 ? "año" : "años"}</button>
                ))}
              </div>
            </div>
            <p className="hint" style={{ marginTop: 0, marginBottom: 14 }}>
              Cada tramo se cobra a la tarifa por punto del escalón que lo cierra. A más puntos comprometidos, menor es el valor por punto: contratar un punto adicional cuesta marginalmente menos.
            </p>
            <StepChart escData={escData} fmt={(v) => Eg.fmtMiles(v)} />
          </div>
        </React.Fragment>
      ) : (
        <div className="empty">El plan de escalabilidad está desactivado. Actívelo en el paso “Precio de venta” para incluir la matriz y el gráfico.</div>
      )}

      <div className="footnote">
        Propuesta referencial en M$ (millones de pesos chilenos). Los valores de escalabilidad asumen compromiso de puntos y años; la inflación se acumula de forma compuesta sobre los años contratados. La oferta definitiva queda sujeta a visita técnica<span className="u">_</span>
      </div>
    </div>
  );
}

Object.assign(window, { VentaResumen, StepChart });
