/* global window, React */
// =====================================================================
// Action runner: bridges dashboard buttons → /api/actions/* endpoints
// with a confirmation modal and audit-trail awareness.
// =====================================================================

(function () {
  // --------- payload builders per action_kind ---------
  const buildPayload = {
    budget_increase: ({ ad_id, campaign_id, alert_id, percent = 50 }) => ({
      path: "/api/actions/budget",
      body: { ad_id, campaign_id, alert_id, direction: "up", percent },
    }),
    budget_decrease: ({ ad_id, campaign_id, alert_id, percent = 30 }) => ({
      path: "/api/actions/budget",
      body: { ad_id, campaign_id, alert_id, direction: "down", percent },
    }),
    pause: ({ ad_id, campaign_id, alert_id }) => ({
      path: "/api/actions/pause",
      body: { ad_id, campaign_id, alert_id },
    }),
    resume: ({ ad_id, campaign_id, alert_id }) => ({
      path: "/api/actions/resume",
      body: { ad_id, campaign_id, alert_id },
    }),
    duplicate: ({ ad_id, alert_id, target_adset_id }) => ({
      path: "/api/actions/duplicate",
      body: { ad_id, alert_id, target_adset_id },
    }),
    creative_swap: ({ ad_id, alert_id, message }) => ({
      path: "/api/actions/note",
      body: { ad_id, alert_id, message: message || "Marked for creative swap" },
    }),
    note: ({ ad_id, campaign_id, alert_id, message }) => ({
      path: "/api/actions/note",
      body: { ad_id, campaign_id, alert_id, message },
    }),
  };

  const confirmCopy = {
    budget_increase: (p) => `¿Subir budget de la campaña +${p.percent || 50}%? Se ejecuta en Meta inmediatamente.`,
    budget_decrease: (p) => `¿Bajar budget de la campaña -${p.percent || 30}%? Se ejecuta en Meta inmediatamente.`,
    pause: () => `¿Pausar este elemento en Meta? Se puede reactivar después.`,
    resume: () => `¿Reactivar este elemento en Meta?`,
    duplicate: () => `¿Duplicar este ad? La copia queda PAUSED para que la edites antes de activar.`,
    creative_swap: () => `¿Marcar este creativo para cambio? Sólo log, no toca Meta.`,
    note: () => `¿Marcar esta alerta como atendida (sin acción en Meta)?`,
  };

  // --------- The modal (singleton, rendered once into a portal) ---------
  let modalState = {
    open: false,
    title: "",
    body: "",
    confirmLabel: "Confirmar",
    onConfirm: null,
    onCancel: null,
    busy: false,
    error: null,
    success: null,
  };
  let subscribers = [];
  const subscribe = (fn) => { subscribers.push(fn); return () => { subscribers = subscribers.filter(s => s !== fn); }; };
  const notify = () => subscribers.forEach((f) => f(modalState));
  function setState(patch) { modalState = { ...modalState, ...patch }; notify(); }

  function ActionModal() {
    const [s, setS] = React.useState(modalState);
    React.useEffect(() => subscribe(setS), []);
    if (!s.open) return null;
    return (
      <div className="sheet-overlay" style={{ alignItems: "center", justifyContent: "center" }} onClick={() => !s.busy && setState({ open: false, error: null, success: null })}>
        <div className="card" style={{ maxWidth: 460, width: "92vw", padding: 0 }} onClick={(e) => e.stopPropagation()}>
          <div style={{ padding: "16px 20px", borderBottom: "1px solid var(--op-chrome-line)" }}>
            <div style={{ fontSize: 16, fontWeight: 900, color: "var(--wm-blue)" }}>{s.title}</div>
          </div>
          <div style={{ padding: "16px 20px", fontSize: 13, color: "var(--wm-fg)", lineHeight: 1.5 }}>
            {s.body}
            {s.error && (
              <div style={{ marginTop: 12, padding: 10, background: "var(--op-red-50)", color: "var(--op-red)", borderRadius: 6, fontSize: 12 }}>
                {s.error}
              </div>
            )}
            {s.success && (
              <div style={{ marginTop: 12, padding: 10, background: "var(--op-green-50)", color: "var(--op-green)", borderRadius: 6, fontSize: 12, fontWeight: 700 }}>
                ✓ {s.success}
              </div>
            )}
          </div>
          <div style={{ padding: "12px 20px", borderTop: "1px solid var(--op-chrome-line)", display: "flex", gap: 8, justifyContent: "flex-end" }}>
            {!s.success ? (
              <>
                <button className="btn btn-ghost btn-sm" disabled={s.busy} onClick={() => { setState({ open: false, error: null }); s.onCancel && s.onCancel(); }}>Cancelar</button>
                <button className="btn btn-primary btn-sm" disabled={s.busy} onClick={() => s.onConfirm && s.onConfirm()}>
                  {s.busy ? "Ejecutando…" : s.confirmLabel}
                </button>
              </>
            ) : (
              <button className="btn btn-primary btn-sm" onClick={() => setState({ open: false, error: null, success: null })}>Cerrar</button>
            )}
          </div>
        </div>
      </div>
    );
  }
  window.ActionModal = ActionModal;

  // --------- Public API: runAction(kind, payload) ---------
  async function runAction(kind, payload = {}) {
    const builder = buildPayload[kind];
    if (!builder) {
      console.error("[action-runner] Unknown kind:", kind);
      return { error: "unknown_kind" };
    }
    const { path, body } = builder(payload);
    const title = ({
      budget_increase: "Subir budget",
      budget_decrease: "Bajar budget",
      pause: "Pausar",
      resume: "Reactivar",
      duplicate: "Duplicar ad",
      creative_swap: "Cambiar creativo",
      note: "Marcar como atendido",
    })[kind] || kind;
    const message = confirmCopy[kind](payload);

    return new Promise((resolve) => {
      setState({
        open: true,
        title,
        body: message,
        confirmLabel: title,
        busy: false,
        error: null,
        success: null,
        onCancel: () => resolve({ cancelled: true }),
        onConfirm: async () => {
          setState({ busy: true, error: null });
          try {
            const r = await fetch(path, {
              method: "POST",
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify(body),
            });
            const data = await r.json();
            if (!r.ok) {
              setState({ busy: false, error: data.error || `HTTP ${r.status}` });
              resolve({ error: data.error, status: r.status });
              return;
            }
            const msg = data.message || (data.status === "pending"
              ? "Acción registrada (queue). Se ejecutará cuando META_ACCESS_TOKEN esté configurado."
              : "Acción ejecutada correctamente.");
            setState({ busy: false, success: msg });
            // Trigger dashboard refresh after a brief moment — preserve scope
            setTimeout(() => {
              if (typeof window.fetchFromSupabase === "function") {
                const s = window.__currentScope || {};
                const r = window.__currentRange || {};
                window.fetchFromSupabase(
                  // Custom range object or preset string
                  r.from && r.to ? { from: r.from, to: r.to } : "30d",
                  s.dashboardKey || "general",
                  s.accountFilter || "all"
                );
              }
            }, 600);
            resolve(data);
          } catch (e) {
            console.error("[action-runner] Failed:", e);
            setState({ busy: false, error: String(e.message || e) });
            resolve({ error: String(e) });
          }
        },
      });
    });
  }

  window.runAction = runAction;
})();
