"use client";
import { useState } from "react";
import NuevaActividad from "./NuevaActividad";
import { hoyManagua, addDays, objetivoSugerido } from "../../lib/plan";
import { localDeIso, OBJETIVOS_LIBRES } from "../../lib/agendador";
// Botón «+ Actividad» de las tablas de oportunidades. Reemplaza a los tres enlaces (Cita / Tarea / Llamada) que
// abrían el formulario de Dynamics: ahora se abre la ventana de la app, ya ligada a la oportunidad, con el
// objetivo sugerido según su etapa. La actividad queda a nombre del propietario de la oportunidad.
// `opp`: { id, nombre | name, cliente, ownerId, forecast, tipoCodigo }
export default function AgendarBoton({ opp }) {
const [abierto, setAbierto] = useState(false);
const [preset, setPreset] = useState(null);
function abrir() {
const hoy = hoyManagua();
const ahora = localDeIso(new Date().toISOString()).min;
// Próxima hora en punto dentro del horario (8:00–17:00); si ya pasó, mañana a las 9:00.
const sig = Math.ceil((ahora + 1) / 60) * 60;
const hoyOk = sig >= 480 && sig <= 1020;
const dia = hoyOk ? hoy : addDays(hoy, sig < 480 ? 0 : 1);
const min = hoyOk ? sig : 540;
const sug = objetivoSugerido(opp);
const nombre = opp.nombre || opp.name || "";
setPreset({
referente: { tipo: "opportunity", id: opp.id, nombre: opp.cliente ? `${opp.cliente} — ${nombre}` : nombre },
dia,
hora: `${String(Math.floor(min / 60)).padStart(2, "0")}:${String(min % 60).padStart(2, "0")}`,
objetivo: sug && OBJETIVOS_LIBRES.includes(sug) ? sug : "",
enNombreDe: true, // queda a nombre del propietario de la oportunidad (el servidor valida el permiso)
});
setAbierto(true);
}
return (
<>
{abierto && preset && setAbierto(false)} />}
>
);
}