// Contabilidad — ingresos, costos y margen neto, derivados de las órdenes pagadas

function ordenesPagadasMes(ordenes, mesKey) {
  return ordenes.filter(o => o.estado === "pagados" && (o.fechaPagado || "").slice(0, 7) === mesKey);
}

function sumaLineas(arr, campo) {
  return (arr || []).reduce((s, l) => s + (Number(l[campo]) || 0), 0);
}

function ingresosMes(ordenes, mesKey) {
  const pagadas = ordenesPagadasMes(ordenes, mesKey);
  const mantenimiento = pagadas.reduce((s, o) => s + sumaLineas(o.mantenimiento, "importe"), 0);
  const reparacion    = pagadas.reduce((s, o) => s + sumaLineas(o.reparaciones, "importe"), 0);
  const repuestos     = pagadas.reduce((s, o) => s + sumaLineas(o.repuestosItems, "venta"), 0);
  return { mantenimiento, reparacion, repuestos, total: mantenimiento + reparacion + repuestos, ordenes: pagadas };
}

function costoRepuestosMes(ordenes, mesKey) {
  return ordenesPagadasMes(ordenes, mesKey).reduce((s, o) => s + sumaLineas(o.repuestosItems, "compra"), 0);
}

function costosFijosMesTotal(data, mesKey) {
  return (data.costosFijos || []).filter(c => c.activo).reduce((s, c) => s + costoEquivMensual(c, mesKey), 0);
}

function bonoTecnicoContable(data, tecnicoId, mesKey) {
  return Number((data.bonosContables || {})[mesKey]?.[tecnicoId]) || 0;
}

function bonosMesTotal(data, mesKey) {
  const mesObj = (data.bonosContables || {})[mesKey] || {};
  return Object.values(mesObj).reduce((s, v) => s + (Number(v) || 0), 0);
}

function porTecnicoMes(data, mesKey) {
  const pagadas = ordenesPagadasMes(data.ordenes, mesKey);
  return (data.tecnicos || []).map(t => {
    const ords   = pagadas.filter(o => o.tecnicoId === t.id);
    const moMant = ords.reduce((s, o) => s + sumaLineas(o.mantenimiento, "importe"), 0);
    const moRep  = ords.reduce((s, o) => s + sumaLineas(o.reparaciones, "importe"), 0);
    const bono   = bonoTecnicoContable(data, t.id, mesKey);
    return { t, moMant, moRep, bono, total: moMant + moRep };
  });
}

function deudaProveedoresTotal(data) {
  return (data.cuentasCorrientes || []).reduce((s, c) => {
    const sal = calcSaldo(c.registros);
    return s + (sal > 0 ? sal : 0);
  }, 0);
}

function costosVariablesMesTotal(data, mesKey) {
  return (data.costosVariables || [])
    .filter(c => (c.fecha || "").slice(0, 7) === mesKey)
    .reduce((s, c) => s + (Number(c.importe) || 0), 0);
}

function resultadoMes(data, mesKey) {
  const ingresos          = ingresosMes(data.ordenes, mesKey);
  const costoRepuestos    = costoRepuestosMes(data.ordenes, mesKey);
  const costosFijos       = costosFijosMesTotal(data, mesKey);
  const costosVariables   = costosVariablesMesTotal(data, mesKey);
  const bonos             = bonosMesTotal(data, mesKey);
  const gananciaRepuestos = ingresos.repuestos - costoRepuestos;
  const margenNeto = ingresos.total - (costoRepuestos + costosFijos + costosVariables + bonos);
  const margenPct  = ingresos.total > 0 ? (margenNeto / ingresos.total) * 100 : 0;
  return { ingresos, costoRepuestos, costosFijos, costosVariables, bonos, gananciaRepuestos, margenNeto, margenPct };
}

// ─── Fila de bono por técnico (tabla) ────────────────────────────────────────
function TechBonoRow({ nombre, moMant, moRep, savedBono, isConfirmado, onSaveBono, onSetConfirmado }) {
  const [draft, setDraft] = React.useState(savedBono > 0 ? String(savedBono) : "");
  const hasDraft = Number(draft) > 0;

  const handleBlur = () => {
    const v = Number(draft);
    onSaveBono(v > 0 ? v : 0);
  };

  const handleConfirmar = () => {
    const v = Number(draft);
    if (!v || v <= 0) return;
    onSaveBono(v);
    onSetConfirmado(true);
  };

  const chipBase = {
    display: "inline-flex", alignItems: "center", gap: 4,
    fontSize: 10, fontWeight: 700, textTransform: "uppercase", letterSpacing: ".8px",
    padding: "3px 9px", borderRadius: 20,
  };

  let chip;
  if (isConfirmado) {
    chip = <span style={{ ...chipBase, background: "rgba(63,178,127,0.12)", color: "var(--ok)", border: "1px solid rgba(63,178,127,0.2)" }}>✓ Confirmado</span>;
  } else if (hasDraft) {
    chip = <span style={{ ...chipBase, background: "rgba(245,158,11,0.1)", color: "#f59e0b", border: "1px solid rgba(245,158,11,0.22)" }}>Pendiente</span>;
  } else {
    chip = <span style={{ ...chipBase, background: "rgba(255,255,255,0.03)", color: "var(--text-mute)", border: "1px solid var(--border)" }}>Sin bono</span>;
  }

  return (
    <tr>
      <td><b>{nombre}</b></td>
      <td className="num mono">{moMant > 0 ? fmtMoney(moMant) : <span className="muted">—</span>}</td>
      <td className="num mono">{moRep  > 0 ? fmtMoney(moRep)  : <span className="muted">—</span>}</td>
      <td className="num mono" style={{ fontWeight: 700 }}>{fmtMoney(moMant + moRep)}</td>
      <td style={{ width: 170 }}>
        <input
          type="number" min="0"
          value={draft}
          disabled={isConfirmado}
          onChange={e => setDraft(e.target.value)}
          onWheel={e => e.target.blur()}
          onBlur={handleBlur}
          placeholder="—"
          className="mono"
          style={{
            width: "100%", textAlign: "right",
            background: isConfirmado ? "rgba(255,255,255,0.02)" : "rgba(255,255,255,0.04)",
            border: `1px solid ${isConfirmado ? "var(--border)" : hasDraft ? "rgba(245,212,22,0.3)" : "var(--border)"}`,
            borderRadius: "var(--radius-sm)", padding: "6px 10px",
            color: isConfirmado ? "var(--text-mute)" : "var(--text)",
            fontSize: 13, fontWeight: 600, outline: "none",
          }}
        />
      </td>
      <td>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          {chip}
          {isConfirmado ? (
            <button className="btn btn--ghost btn--sm" onClick={() => onSetConfirmado(false)}>Editar</button>
          ) : hasDraft ? (
            <button className="btn btn--sm"
              style={{ background: "var(--brand)", color: "#000", fontWeight: 700 }}
              onClick={handleConfirmar}>
              ✓ Confirmar
            </button>
          ) : null}
        </div>
      </td>
    </tr>
  );
}

// ─── Vista principal ──────────────────────────────────────────────────────────
function ContabilidadView({ data, setData, mes }) {
  const mesKey = mes;

  const r          = resultadoMes(data, mesKey);
  const porTec     = porTecnicoMes(data, mesKey);
  const deuda      = deudaProveedoresTotal(data);
  const costosTotal = r.costoRepuestos + r.costosFijos + r.costosVariables + r.bonos;

  const setBono = (tecnicoId, v) => {
    setData(d => {
      const bc     = { ...(d.bonosContables || {}) };
      const delMes = { ...(bc[mesKey] || {}) };
      if (v > 0) delMes[tecnicoId] = v;
      else delete delMes[tecnicoId];
      bc[mesKey] = delMes;
      return { ...d, bonosContables: bc };
    });
  };

  const bonoConfirmado = (tecnicoId) => !!(data.bonosConfirmados || {})[mesKey]?.[tecnicoId];

  const setBonoConfirmado = (tecnicoId, confirmado) => {
    setData(d => {
      const bc     = { ...(d.bonosConfirmados || {}) };
      const delMes = { ...(bc[mesKey] || {}) };
      if (confirmado) delMes[tecnicoId] = true;
      else delete delMes[tecnicoId];
      bc[mesKey] = delMes;
      return { ...d, bonosConfirmados: bc };
    });
  };

  // Resumen de bonos para el chip del header
  const mesBonosContables   = (data.bonosContables   || {})[mesKey] || {};
  const mesBonosConfirmados = (data.bonosConfirmados  || {})[mesKey] || {};
  const withBonoCount  = Object.values(mesBonosContables).filter(v => Number(v) > 0).length;
  const confirmedCount = Object.entries(mesBonosContables)
    .filter(([id, v]) => Number(v) > 0 && mesBonosConfirmados[id]).length;

  // Ring SVG: circunferencia 2π×66 ≈ 414.69
  const CIRC     = 414.69;
  const ringPct  = Math.max(0, Math.min(100, r.margenPct));
  const ringFill = (ringPct / 100) * CIRC;
  const ringColor = r.margenNeto >= 0 ? "#f5d416" : "#e63946";

  // Anchos de barras proporcionales (evitar /0)
  const iT  = r.ingresos.total || 1;
  const cT  = costosTotal      || 1;
  const pMant  = +(r.ingresos.mantenimiento / iT * 100).toFixed(1);
  const pRep   = +(r.ingresos.reparacion   / iT * 100).toFixed(1);
  const pParts = +(r.ingresos.repuestos    / iT * 100).toFixed(1);
  const pCRep  = +(r.costoRepuestos   / cT * 100).toFixed(1);
  const pCFij  = +(r.costosFijos      / cT * 100).toFixed(1);
  const pCVar  = +(r.costosVariables  / cT * 100).toFixed(1);
  const pCBon  = +(r.bonos            / cT * 100).toFixed(1);

  const StackedBar = ({ segments }) => (
    <div style={{ display: "flex", height: 7, borderRadius: 4, overflow: "hidden", marginBottom: 16, gap: 2 }}>
      {segments.map(([color, pct], i) => (
        <div key={i} style={{ width: `${pct}%`, background: color, borderRadius: 2, minWidth: pct > 0 ? 2 : 0 }} />
      ))}
    </div>
  );

  const BkdItem = ({ color, label, pct, val, valColor }) => (
    <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 11 }}>
      <div style={{ width: 8, height: 8, borderRadius: 2, background: color, flexShrink: 0 }} />
      <div style={{ flex: 1, fontSize: 12, color: "var(--text-mute)" }}>{label}</div>
      <div className="mono" style={{ fontSize: 11, color: "var(--text-mute)", minWidth: 36, textAlign: "right" }}>{pct}%</div>
      <div className="mono" style={{ fontSize: 12, fontWeight: 600, color: valColor || "var(--text)", minWidth: 90, textAlign: "right" }}>
        {fmtMoney(val)}
      </div>
    </div>
  );

  return (
    <>
      {/* ── HERO: ring + KPI stack ── */}
      <div className="contab-hero" style={{ display: "grid", gridTemplateColumns: "220px 1fr", gap: 14, marginBottom: 14 }}>

        {/* Ring */}
        <div className="card" style={{ background: "radial-gradient(ellipse at 40% 30%, rgba(245,212,22,0.09) 0%, transparent 65%), var(--panel)", borderColor: "rgba(245,212,22,0.14)" }}>
          <div className="card__body" style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 10 }}>
            <div className="muted" style={{ fontSize: 10, textTransform: "uppercase", letterSpacing: 1.5, alignSelf: "flex-start" }}>
              Margen neto
            </div>
            <svg viewBox="0 0 160 160" style={{ width: 148, height: 148 }}>
              <circle cx="80" cy="80" r="66" fill="none" stroke="rgba(245,212,22,0.06)" strokeWidth="22"/>
              <circle cx="80" cy="80" r="66" fill="none" stroke="rgba(255,255,255,0.05)" strokeWidth="12"/>
              <circle cx="80" cy="80" r="66" fill="none"
                stroke={ringColor} strokeWidth="12" strokeLinecap="round"
                strokeDasharray={`${ringFill} ${CIRC - ringFill}`}
                transform="rotate(-90 80 80)"
              />
              <text x="80" y="73" textAnchor="middle" fill={ringColor}
                fontSize="34" fontWeight="700" fontFamily="DM Mono, JetBrains Mono, monospace">
                {Math.round(ringPct)}%
              </text>
              <text x="80" y="93" textAnchor="middle" fill="rgba(230,230,224,0.3)"
                fontSize="9" letterSpacing="1">
                MARGEN NETO
              </text>
            </svg>
            <div style={{ textAlign: "center" }}>
              <div className="mono" style={{ fontSize: 20, fontWeight: 700, color: r.margenNeto >= 0 ? "var(--ok)" : "var(--accent)" }}>
                {fmtMoney(r.margenNeto)}
              </div>
              <div className="muted" style={{ fontSize: 11, marginTop: 2 }}>
                sobre {fmtMoney(r.ingresos.total)} ingresados
              </div>
            </div>
          </div>
        </div>

        {/* KPI stack */}
        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>

          {/* Ingresos */}
          <div className="card" style={{ flex: 1 }}>
            <div className="card__body" style={{ display: "flex", alignItems: "center", gap: 14 }}>
              <div style={{ flex: 1 }}>
                <div className="muted" style={{ fontSize: 10, textTransform: "uppercase", letterSpacing: ".8px" }}>Ingresos del mes</div>
                <div className="mono" style={{ fontSize: 20, fontWeight: 700, color: "var(--ok)", marginTop: 1 }}>{fmtMoney(r.ingresos.total)}</div>
                <div className="muted" style={{ fontSize: 10, marginTop: 1 }}>{r.ingresos.ordenes.length} órdenes cobradas</div>
              </div>
              <span className="mono" style={{ fontSize: 11, fontWeight: 700, padding: "3px 8px", borderRadius: 5, background: "rgba(63,178,127,0.1)", color: "var(--ok)" }}>
                M.O. + REP.
              </span>
            </div>
          </div>

          {/* Costos */}
          <div className="card" style={{ flex: 1 }}>
            <div className="card__body" style={{ display: "flex", alignItems: "center", gap: 14 }}>
              <div style={{ flex: 1 }}>
                <div className="muted" style={{ fontSize: 10, textTransform: "uppercase", letterSpacing: ".8px" }}>Costos totales</div>
                <div className="mono" style={{ fontSize: 20, fontWeight: 700, color: "var(--accent)", marginTop: 1 }}>{fmtMoney(costosTotal)}</div>
                <div className="muted" style={{ fontSize: 10, marginTop: 1 }}>repuestos · fijos · variables · bonos</div>
              </div>
              <span className="mono" style={{ fontSize: 11, fontWeight: 700, padding: "3px 8px", borderRadius: 5, background: "rgba(230,57,70,0.1)", color: "var(--accent)" }}>
                {r.ingresos.total > 0 ? Math.round(costosTotal / r.ingresos.total * 100) : 0}%
              </span>
            </div>
          </div>

          {/* Ganancia repuestos */}
          <div className="card" style={{ flex: 1 }}>
            <div className="card__body" style={{ display: "flex", alignItems: "center", gap: 14 }}>
              <div style={{ flex: 1 }}>
                <div className="muted" style={{ fontSize: 10, textTransform: "uppercase", letterSpacing: ".8px" }}>Ganancia en repuestos</div>
                <div className="mono" style={{ fontSize: 20, fontWeight: 700, color: "var(--info)", marginTop: 1 }}>{fmtMoney(r.gananciaRepuestos)}</div>
                <div className="muted" style={{ fontSize: 10, marginTop: 1 }}>venta {fmtMoneyShort(r.ingresos.repuestos)} − costo {fmtMoneyShort(r.costoRepuestos)}</div>
              </div>
              {r.ingresos.repuestos > 0 && (
                <span className="mono" style={{ fontSize: 11, fontWeight: 700, padding: "3px 8px", borderRadius: 5, background: "rgba(107,168,255,0.1)", color: "var(--info)" }}>
                  +{Math.round(r.gananciaRepuestos / r.ingresos.repuestos * 100)}%
                </span>
              )}
            </div>
          </div>

          {/* Proveedores */}
          <div className="card" style={{ flex: 1 }}>
            <div className="card__body" style={{ display: "flex", alignItems: "center", gap: 14 }}>
              <div style={{ flex: 1 }}>
                <div className="muted" style={{ fontSize: 10, textTransform: "uppercase", letterSpacing: ".8px" }}>Deuda con proveedores</div>
                <div className="mono" style={{ fontSize: 20, fontWeight: 700, color: deuda > 0 ? "var(--accent)" : "var(--ok)", marginTop: 1 }}>
                  {deuda > 0 ? fmtMoney(deuda) : "Al día"}
                </div>
                <div className="muted" style={{ fontSize: 10, marginTop: 1 }}>cuentas corrientes pendientes</div>
              </div>
              <span className="mono" style={{
                fontSize: 11, fontWeight: 700, padding: "3px 8px", borderRadius: 5,
                background: deuda > 0 ? "rgba(230,57,70,0.08)" : "rgba(63,178,127,0.08)",
                color: deuda > 0 ? "rgba(230,57,70,0.6)" : "rgba(63,178,127,0.7)",
              }}>
                {deuda > 0 ? "PENDIENTE" : "OK"}
              </span>
            </div>
          </div>

        </div>
      </div>

      {/* ── BREAKDOWN ── */}
      <div className="contab-breakdown" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginBottom: 22 }}>

        {/* Ingresos */}
        <div className="card">
          <div className="card__body">
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 14 }}>
              <span className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: 1 }}>Composición de ingresos</span>
              <span className="mono" style={{ fontSize: 17, fontWeight: 700, color: "var(--ok)" }}>{fmtMoney(r.ingresos.total)}</span>
            </div>
            {r.ingresos.total > 0 ? (
              <>
                <StackedBar segments={[["#f5d416", pMant], ["#4b8bf5", pRep], ["rgba(230,230,224,0.22)", pParts]]} />
                <BkdItem color="#f5d416" label="M.O. Mantenimiento"            pct={pMant}  val={r.ingresos.mantenimiento} valColor="var(--brand)" />
                <BkdItem color="#4b8bf5" label="M.O. Reparación"               pct={pRep}   val={r.ingresos.reparacion}    valColor="var(--info)" />
                <BkdItem color="rgba(230,230,224,0.3)" label="Repuestos (precio venta)" pct={pParts} val={r.ingresos.repuestos} />
              </>
            ) : (
              <div className="muted" style={{ fontSize: 12, textAlign: "center", padding: "16px 0" }}>Sin ingresos registrados este mes</div>
            )}
          </div>
        </div>

        {/* Costos */}
        <div className="card">
          <div className="card__body">
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 14 }}>
              <span className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: 1 }}>Composición de costos</span>
              <span className="mono" style={{ fontSize: 17, fontWeight: 700, color: "var(--accent)" }}>{fmtMoney(costosTotal)}</span>
            </div>
            {costosTotal > 0 ? (
              <>
                <StackedBar segments={[["#e63946", pCRep], ["#f59e0b", pCFij], ["#4b8bf5", pCVar], ["#4ec994", pCBon]]} />
                <BkdItem color="#e63946" label="Repuestos (costo proveedor)" pct={pCRep} val={r.costoRepuestos} />
                <BkdItem color="#f59e0b" label="Costos fijos"                pct={pCFij} val={r.costosFijos} />
                <BkdItem color="#4b8bf5" label="Costos variables"             pct={pCVar} val={r.costosVariables} />
                <BkdItem color="#4ec994" label="Bonos técnicos"               pct={pCBon} val={r.bonos} valColor="var(--ok)" />
              </>
            ) : (
              <div className="muted" style={{ fontSize: 12, textAlign: "center", padding: "16px 0" }}>Sin costos registrados este mes</div>
            )}
          </div>
        </div>

      </div>

      {/* ── TÉCNICOS + BONOS ── */}
      {porTec.length > 0 && (
        <>
          <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 12 }}>
            <span className="muted" style={{ fontSize: 10, textTransform: "uppercase", letterSpacing: 1.5 }}>
              Técnicos — {labelDeMes(mesKey)}
            </span>
            {withBonoCount > 0 && (
              <div style={{
                display: "flex", alignItems: "center", gap: 8, marginLeft: "auto",
                background: "rgba(245,212,22,0.07)", border: "1px solid rgba(245,212,22,0.14)",
                borderRadius: 20, padding: "4px 12px",
                fontSize: 11, color: "var(--brand)", fontFamily: "var(--mono)",
              }}>
                <div style={{ display: "flex", gap: 3 }}>
                  {porTec.filter(({ bono }) => bono > 0).map(({ t }) => (
                    <div key={t.id} style={{
                      width: 6, height: 6, borderRadius: "50%",
                      background: bonoConfirmado(t.id) ? "var(--brand)" : "rgba(245,212,22,0.25)",
                    }} />
                  ))}
                </div>
                {confirmedCount} de {withBonoCount} bonos confirmados
              </div>
            )}
          </div>

          <div className="card contab-tec-card">
            <table className="table">
              <thead>
                <tr>
                  <th>Técnico</th>
                  <th className="num">M.O. mantenimiento</th>
                  <th className="num">M.O. reparación</th>
                  <th className="num">Total M.O.</th>
                  <th className="num">Bono del mes</th>
                  <th>Estado</th>
                </tr>
              </thead>
              <tbody>
                {porTec.map(({ t, moMant, moRep, bono }) => (
                  <TechBonoRow
                    key={`${t.id}-${mesKey}`}
                    nombre={t.nombre}
                    moMant={moMant}
                    moRep={moRep}
                    savedBono={bono}
                    isConfirmado={bonoConfirmado(t.id)}
                    onSaveBono={(v) => setBono(t.id, v)}
                    onSetConfirmado={(c) => setBonoConfirmado(t.id, c)}
                  />
                ))}
              </tbody>
            </table>
          </div>
        </>
      )}
    </>
  );
}

window.ContabilidadView = ContabilidadView;
