(function (global) {
  const app = (global.EpicrisisApp = global.EpicrisisApp || {});
  const data = global.EPICRISIS_PDF_DATA || {};

  app.state = app.state || {
    data,
    toastProcessIds: {
      pdf: null,
      qx: null,
      soat: null,
    },
    pdfSelectionData: global.__pdfSelectionData || {
      diagnosticos: [],
      procedimientos: [],
      medicamentos: [],
      ayudas_diagnosticas: [],
      imagenes_diagnosticas: [],
    },
    manualSoatResults: Array.isArray(global.__manualSoatResults)
      ? [...global.__manualSoatResults]
      : (Array.isArray(data.manualSoatResults) ? [...data.manualSoatResults] : []),
    qxAgentResults: Array.isArray(global.__qxAgentResults)
      ? [...global.__qxAgentResults]
      : (Array.isArray(data.qxAgentResults) ? [...data.qxAgentResults] : []),
    draftSaveTimer: global.__draftSaveTimer || null,
    draftSaveErrorShown: Boolean(global.__draftSaveErrorShown),
    latestPdfCacheId: global.__ultimoPdfCacheId || null,
    pdfPrintState: global.__epicrisisPdfPrintState || {
      isGenerating: false,
      activeFrame: null,
      printRequested: false,
      cleanupTimerId: null,
      focusFallbackTimerId: null,
      releaseListeners: null,
    },
  };

  app.state.syncGlobals = function syncGlobals() {
    global.__pdfSelectionData = this.pdfSelectionData;
    global.__manualSoatResults = this.manualSoatResults;
    global.__qxAgentResults = this.qxAgentResults;
    global.__draftSaveTimer = this.draftSaveTimer;
    global.__draftSaveErrorShown = this.draftSaveErrorShown;
    global.__ultimoPdfCacheId = this.latestPdfCacheId;
    global.__epicrisisPdfPrintState = this.pdfPrintState;
  };

  app.state.syncGlobals();

  app.toast = app.toast || {
    actions: {
      verHistorial: () => {
        global.location.href = "/ver_historia";
      },
      reintentarPdf: () => global.generarPdfEpicrisis?.(),
      reintentarQx: () => global.ejecutarAgenteHallazgosQx?.(),
    },
  };
})(globalThis);
