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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
// Import the component loader and page utilities
import { importComponent } from "/js/components.js";
import { callJsExtensions } from "/js/extensions.js";

// Modal functionality
const modalStack = [];
const RESTORABLE_MODAL_STACK_KEY = "a0.modalStack.restorable";
let restoringModalSession = false;
let restoredModalSession = false;

function sameModalPath(left = "", right = "") {
  return String(left || "").replace(/^\/+/, "") === String(right || "").replace(/^\/+/, "");
}

function isReloadNavigation() {
  const navigation = performance.getEntriesByType?.("navigation")?.[0];
  if (navigation?.type) return navigation.type === "reload";
  if (!performance.navigation) return false;
  return performance.navigation?.type === performance.navigation?.TYPE_RELOAD;
}

function modalHasClass(modalOrElement, className) {
  const element = modalOrElement?.element || modalOrElement;
  return Boolean(
    element?.classList?.contains(className)
      || element?.querySelector?.(".modal-inner")?.classList?.contains(className)
  );
}

function modalDatasetFlag(modalOrElement, name) {
  const element = modalOrElement?.element || modalOrElement;
  const inner = element?.querySelector?.(".modal-inner");
  const value = element?.dataset?.[name] ?? inner?.dataset?.[name] ?? "";
  return ["1", "true", "yes", "on"].includes(String(value).trim().toLowerCase());
}

function modalRequiresExplicitClose(modalOrElement) {
  return modalHasClass(modalOrElement, "modal-explicit-close")
    || modalDatasetFlag(modalOrElement, "modalExplicitClose");
}

function modalSuppressesBackdrop(modalOrElement) {
  return modalHasClass(modalOrElement, "modal-no-backdrop")
    || modalDatasetFlag(modalOrElement, "modalNoBackdrop");
}

function modalRestoreMode(modalOrElement) {
  const element = modalOrElement?.element || modalOrElement;
  const inner = element?.querySelector?.(".modal-inner");
  return String(element?.dataset?.modalRestore || inner?.dataset?.modalRestore || "").trim();
}

function modalCanRestore(modalOrElement) {
  return modalRestoreMode(modalOrElement) === "surface";
}

function restorableModalSnapshot() {
  return modalStack
    .filter((modal) => modalCanRestore(modal))
    .map((modal) => ({ path: modal.path }));
}

export function persistRestorableModalStack(options = {}) {
  if (restoringModalSession && options.force !== true) return;
  try {
    const modals = restorableModalSnapshot();
    if (modals.length === 0) {
      sessionStorage.removeItem(RESTORABLE_MODAL_STACK_KEY);
      return;
    }
    sessionStorage.setItem(
      RESTORABLE_MODAL_STACK_KEY,
      JSON.stringify({
        version: 1,
        modals,
      }),
    );
  } catch (error) {
    console.warn("Could not persist restorable modals", error);
  }
}

function dispatchModalEvent(name, modal, detail = {}) {
  document.dispatchEvent(
    new CustomEvent(name, {
      detail: {
        modalPath: modal?.path ?? null,
        modal,
        modalStack: getModalStack(),
        ...detail,
      },
    }),
  );
}

function activateModal(modal) {
  if (!modal) return;
  updateModalZIndexes();
  restoreModalScrollSnapshot(modal);
  dispatchModalEvent("modal-activated", modal);
  persistRestorableModalStack();
}

function findModalIndexByPath(modalPath) {
  return modalStack.findIndex((modal) => sameModalPath(modal.path, modalPath));
}

function focusModal(modalPath) {
  const modalIndex = findModalIndexByPath(modalPath);
  if (modalIndex === -1) return false;
  const currentTopModal = modalStack[modalStack.length - 1];
  if (currentTopModal) {
    currentTopModal.savedScrollSnapshot = captureModalScrollSnapshot(currentTopModal);
  }
  const [modal] = modalStack.splice(modalIndex, 1);
  modalStack.push(modal);
  activateModal(modal);
  return true;
}

function getModalScrollElement(modal) {
  return modal?.element?.querySelector(".modal-scroll");
}

function captureModalScrollSnapshot(modal) {
  const modalScroll = getModalScrollElement(modal);
  if (!modalScroll) return null;
  return {
    scrollTop: modalScroll.scrollTop,
    scrollLeft: modalScroll.scrollLeft,
  };
}

function restoreModalScrollSnapshot(modal) {
  const snapshot = modal?.savedScrollSnapshot;
  if (!snapshot) return;

  requestAnimationFrame(() => {
    const modalScroll = getModalScrollElement(modal);
    if (!modalScroll) return;
    modalScroll.scrollTop = snapshot.scrollTop;
    modalScroll.scrollLeft = snapshot.scrollLeft;
    modal.savedScrollSnapshot = null;
  });
}

// Create a single backdrop for all modals
const backdrop = document.createElement("div");
backdrop.className = "modal-backdrop";
backdrop.style.display = "none";
backdrop.style.backdropFilter = "blur(8px) saturate(112%)";
document.body.appendChild(backdrop);

// Function to update z-index for all modals and backdrop
function updateModalZIndexes() {
  // Base z-index for modals
  const baseZIndex = 5000;

  // Update z-index for all modals
  modalStack.forEach((modal, index) => {
    // For first modal, z-index is baseZIndex
    // For second modal, z-index is baseZIndex + 20
    // This leaves room for the backdrop between them
    modal.element.style.zIndex = baseZIndex + index * 20;
  });

  const backdropModalStack = modalStack.filter((modal) => !modalSuppressesBackdrop(modal));

  if (backdropModalStack.length === 0) {
    backdrop.style.display = "none";
    return;
  }

  backdrop.style.display = "block";
  backdrop.style.backdropFilter = "blur(8px) saturate(112%)";
  backdrop.style.backgroundColor = "";

  if (backdropModalStack.length === modalStack.length && modalStack.length > 1) {
    const topModalIndex = modalStack.length - 1;
    backdrop.style.zIndex = baseZIndex + (topModalIndex - 1) * 20 + 10;
  } else {
    const topBackdropModal = backdropModalStack[backdropModalStack.length - 1];
    const topBackdropModalIndex = modalStack.indexOf(topBackdropModal);
    backdrop.style.zIndex = topBackdropModalIndex > 0
      ? baseZIndex + (topBackdropModalIndex - 1) * 20 + 10
      : baseZIndex - 1;
  }
}

// Function to create a new modal element
function createModalElement(path) {
  // Create modal element
  const newModal = document.createElement("div");
  newModal.className = "modal";
  newModal.path = path; // save name to the object
  newModal.dataset.modalPath = path;

  // Add click handlers to only close modal if both mousedown and mouseup are on the modal container
  let mouseDownTarget = null;
  newModal.addEventListener("mousedown", (event) => {
    mouseDownTarget = event.target;
  });
  newModal.addEventListener("mouseup", (event) => {
    if (
      event.target === newModal
      && mouseDownTarget === newModal
      && !modalRequiresExplicitClose(newModal)
    ) {
      closeModal();
    }
    mouseDownTarget = null;
  });


  // Create modal structure
  newModal.innerHTML = `
    <div class="modal-inner" x-data>
      <x-extension id="modal-shell-start"></x-extension>
      <div class="modal-header">
        <h2 class="modal-title"></h2>
        <button class="modal-close">&times;</button>
      </div>
      <div class="modal-scroll">
        <div class="modal-bd"></div>
      </div>
      <div class="modal-footer-slot" style="display: none;"></div>
      <x-extension id="modal-shell-end"></x-extension>
    </div>
  `;

  // Setup close button handler for this specific modal
  const close_button = newModal.querySelector(".modal-close");
  close_button.addEventListener("click", () => closeModal());


  // Add modal to DOM
  document.body.appendChild(newModal);

  // Show the modal
  newModal.classList.add("show");

  // Update modal z-indexes
  updateModalZIndexes();

  return {
    path: path,
    element: newModal,
    title: newModal.querySelector(".modal-title"),
    header: newModal.querySelector(".modal-header"),
    body: newModal.querySelector(".modal-bd"),
    close: close_button,
    footerSlot: newModal.querySelector(".modal-footer-slot"),
    inner: newModal.querySelector(".modal-inner"),
    styles: [],
    scripts: [],
    beforeClose: null,
    savedScrollSnapshot: null,
  };
}

// Function to open modal with content from URL
export async function openModal(modalPath, beforeClose = null) {
  const openCtx = { modalPath, modal: null, cancel: false };
  await callJsExtensions("open_modal_before", openCtx);
  if (openCtx.cancel) return;
  modalPath = openCtx.modalPath;

  return new Promise((resolve) => {
    try {
      const currentTopModal = modalStack[modalStack.length - 1];
      if (currentTopModal) {
        currentTopModal.savedScrollSnapshot = captureModalScrollSnapshot(currentTopModal);
      }

      const returnFocus = document.activeElement;
      // Create new modal instance
      const modal = createModalElement(modalPath);
      modal.beforeClose = beforeClose;
      modal.returnFocus = returnFocus;
      openCtx.modal = modal;

      new MutationObserver(
        (_, o) =>
          !document.contains(modal.element) && (o.disconnect(), resolve())
      ).observe(document.body, { childList: true, subtree: true });

      // Set a loading state
      modal.body.innerHTML = '<div class="loading">Loading...</div>';

      // Already added to stack above

      // Use importComponent to load the modal content
      // This handles all HTML, styles, scripts and nested components
      // Updated path to use the new folder structure with modal.html
      const componentPath = modalPath; // `modals/${modalPath}/modal.html`;

      // Use importComponent which now returns the parsed document
      importComponent(componentPath, modal.body)
        .then(async (doc) => {
          // Set the title from the document
          modal.title.innerHTML = doc.title || modalPath;
          const htmlElement = doc.documentElement;
          if (htmlElement && htmlElement.classList) {
            const inner = modal.element.querySelector(".modal-inner");
            if (inner) inner.classList.add(...htmlElement.classList);
          }
          if (doc.body && doc.body.classList) {
            modal.body.classList.add(...doc.body.classList);
          }
          await callJsExtensions("modal_content_loaded", {
            modalPath,
            modal,
            doc,
          });
          dispatchModalEvent("modal-content-loaded", modal, { doc });
          refreshModalStack();
          
          // Some modals have a footer. Check if it exists and move it to footer slot
          // Use requestAnimationFrame to let Alpine mount the component first
          requestAnimationFrame(() => {
            const componentFooter = modal.body.querySelector('[data-modal-footer]');
            if (componentFooter && modal.footerSlot) {
              // Move footer outside modal-scroll scrollable area
              modal.footerSlot.appendChild(componentFooter);
              modal.footerSlot.style.display = 'block';
              modal.inner.classList.add('modal-with-footer');
            }
          });
        })
        .catch((error) => {
          console.error("Error loading modal content:", error);
          modal.body.innerHTML = `<div class="error">Failed to load modal content: ${error.message}</div>`;
        });

      // Add modal to stack and show it
      // Add modal to stack
      modal.path = modalPath;
      modalStack.push(modal);
      document.body.style.overflow = "hidden";

      activateModal(modal);
    } catch (error) {
      console.error("Error loading modal content:", error);
      resolve();
    }
  });
}

export function isModalOpen(modalPath) {
  return findModalIndexByPath(modalPath) !== -1;
}

export function getModalStack() {
  return modalStack.slice();
}

export function refreshModalStack() {
  if (modalStack.length === 0) {
    updateModalZIndexes();
    persistRestorableModalStack();
    return;
  }
  activateModal(modalStack[modalStack.length - 1]);
}

export function restoreRestorableModalStack() {
  if (restoredModalSession) return;
  if (!isReloadNavigation()) {
    sessionStorage.removeItem(RESTORABLE_MODAL_STACK_KEY);
    return;
  }
  restoredModalSession = true;

  let saved;
  try {
    saved = JSON.parse(sessionStorage.getItem(RESTORABLE_MODAL_STACK_KEY) || "{}");
  } catch (error) {
    console.warn("Could not restore restorable modals", error);
    sessionStorage.removeItem(RESTORABLE_MODAL_STACK_KEY);
    return;
  }

  const paths = Array.isArray(saved?.modals)
    ? saved.modals
      .map((entry) => String(entry?.path || "").trim())
      .filter(Boolean)
    : [];
  if (paths.length === 0) return;

  restoringModalSession = true;
  for (const path of paths) {
    try {
      const openPromise = ensureModalOpen(path);
      openPromise?.catch?.((error) => console.error(`Failed to restore modal ${path}`, error));
    } catch (error) {
      console.error(`Failed to restore modal ${path}`, error);
    }
  }

  globalThis.setTimeout?.(() => {
    restoringModalSession = false;
    persistRestorableModalStack({ force: true });
  }, 1500);
}

export async function ensureModalOpen(modalPath, beforeClose = null) {
  if (focusModal(modalPath)) return null;
  return openModal(modalPath, beforeClose);
}

export async function toggleModal(modalPath, beforeClose = null) {
  if (!isModalOpen(modalPath)) {
    return openModal(modalPath, beforeClose);
  }
  while (isModalOpen(modalPath)) {
    const closed = await closeModal(modalPath);
    if (closed === false) return false;
  }
  return true;
}

// Function to close modal
export async function closeModal(modalPath = null) {
  if (modalStack.length === 0) return;

  let modalIndex = modalStack.length - 1; // Default to last modal
  let modal;

  if (modalPath) {
    // Find the modal with the specified name in the stack
    modalIndex = findModalIndexByPath(modalPath);
    if (modalIndex === -1) return; // Modal not found in stack

    // Get the modal from stack at the found index
    modal = modalStack[modalIndex];
  } else {
    // Just get the last modal (removal happens after beforeClose)
    modal = modalStack[modalStack.length - 1];
  }
  const wasTop = modalIndex === modalStack.length - 1;

  const closeCtx = { modalPath: modalPath ?? null, modal, cancel: false };
  await callJsExtensions("close_modal_before", closeCtx);
  if (closeCtx.cancel) return false;

  const canClose = async () => {
    if (!modal.beforeClose) return true;
    try {
      const result = await Promise.resolve(modal.beforeClose());
      return result !== false;
    } catch (error) {
      console.error("Error in beforeClose handler:", error);
      return true;
    }
  };

  return Promise.resolve(canClose()).then((shouldClose) => {
    if (!shouldClose) return false;

    if (modalPath) {
      // Remove the modal from stack after beforeClose check
      modalStack.splice(modalIndex, 1);
    } else {
      modalStack.pop();
    }

    // Remove modal-specific styles and scripts immediately
    modal.styles.forEach((styleId) => {
      document.querySelector(`[data-modal-style="${styleId}"]`)?.remove();
    });
    modal.scripts.forEach((scriptId) => {
      document.querySelector(`[data-modal-script="${scriptId}"]`)?.remove();
    });

    // First remove the show class to trigger the transition
    modal.element.classList.remove("show");

  // commented out to prevent race conditions

  // // Remove the modal element from DOM after animation
  // modal.element.addEventListener(
  //   "transitionend",
  //   () => {
  //     // Make sure the modal is completely removed from the DOM
  //     if (modal.element.parentNode) {
  //       modal.element.parentNode.removeChild(modal.element);
  //     }
  //   },
  //   { once: true }
  // );

  // // Fallback in case the transition event doesn't fire
  // setTimeout(() => {
  //   if (modal.element.parentNode) {
  //     modal.element.parentNode.removeChild(modal.element);
  //   }
  // }, 500); // 500ms should be enough for the transition to complete

    // remove immediately
    if (modal.element.parentNode) {
      modal.element.parentNode.removeChild(modal.element);
    }


    // Handle backdrop visibility and body overflow
    if (modalStack.length === 0) {
      // Hide backdrop when no modals are left
      backdrop.style.display = "none";
      document.body.style.overflow = "";
    } else {
      activateModal(modalStack[modalStack.length - 1]);
    }
    if (wasTop && modal.returnFocus?.isConnected) modal.returnFocus.focus();

    document.dispatchEvent(
      new CustomEvent("modal-closed", {
        detail: {
          modalPath: modal.path ?? null,
          remainingModalCount: modalStack.length,
        },
      }),
    );
    persistRestorableModalStack();

    return true;
  });
}

// Function to scroll to element by ID within the last modal
export function scrollModal(id) {
  if (!id) return;

  // Get the last modal in the stack
  const lastModal = modalStack[modalStack.length - 1].element;
  if (!lastModal) return;

  // Find the modal container and target element
  const modalContainer = lastModal.querySelector(".modal-scroll");
  const targetElement = lastModal.querySelector(`#${id}`);

  if (modalContainer && targetElement) {
    modalContainer.scrollTo({
      top: targetElement.offsetTop - 20, // 20px padding from top
      behavior: "smooth",
    });
  }
}

// Make scrollModal globally available
globalThis.scrollModal = scrollModal;

// Handle modal content loading from clicks
document.addEventListener("click", async (e) => {
  const modalTrigger = e.target.closest("[data-modal-content]");
  if (modalTrigger) {
    e.preventDefault();
    if (
      modalTrigger.hasAttribute("disabled") ||
      modalTrigger.classList.contains("disabled")
    ) {
      return;
    }
    const modalPath = modalTrigger.getAttribute("href");
    await openModal(modalPath);
  }
});

// Close modal on escape key (closes only the top modal)
document.addEventListener("keydown", (e) => {
  if (e.key === "Escape" && modalStack.length > 0) {
    if (modalRequiresExplicitClose(modalStack[modalStack.length - 1])) return;
    closeModal();
  }
});

// also export as global function
globalThis.openModal = openModal;
globalThis.closeModal = closeModal;
globalThis.scrollModal = scrollModal;
globalThis.isModalOpen = isModalOpen;
globalThis.ensureModalOpen = ensureModalOpen;
globalThis.toggleModal = toggleModal;