let mosaicoActual = null; // Referencia al mosaico activo

// Selectores de UI
const deskContent = document.querySelector('.desk-content');
const items = document.querySelectorAll('.desk-content-item');
const toolLeft = document.querySelector('.desk-tools-left');
const toolRight = document.querySelector('.desk-tools-right');
const toolLpLeft = document.querySelector('.desk-tools-lp-left');
const toolLpRight = document.querySelector('.desk-tools-lp-right');
const btnNext = document.querySelector('.desk-tools-control-page-right');
const btnPrev = document.querySelector('.desk-tools-control-page-left');

const modalAct = document.getElementById('modal-actividad');
const titleModal = document.getElementsByClassName('modal-actividad-title')[0];
const iframe = document.getElementById('iframe-actividad');
const closeBtn = document.getElementById('close-modal');

const botonMenuPrincipal = document.getElementById('botonMenu');
const menuPrincipal = document.getElementById('menuLista');
const btnCloseMenu = document.getElementById('btnCloseMenu');

const botonMenuAudio = document.getElementById('botonAudio');
const menuAudios = document.getElementById('menuAudios');
const btnCloseAudios = document.getElementById('btnCloseAudios');

const botonMenuFlashcards = document.getElementById('botonFlashcards');
const menuFlashcards = document.getElementById('menuFlashcards');
const btnCloseFlashcards = document.getElementById('btnCloseFlashcards');

const botonMenuRecursosExtras = document.getElementById('botonRecursosExtras');
const menuRecursosExtras = document.getElementById('menuRecursosExtras');
const btnCloseRecursosExtras = document.getElementById('btnCloseRecursosExtras');

const botonMenuVideos = document.getElementById('botonVideos');
const menuVideos = document.getElementById('menuVideos');
const btnCloseVideos = document.getElementById('btnCloseVideos');

const btnDownloadWord = document.querySelector('.btn-download-word');

// Herrmientas
// const botonHerramienta1 = document.getElementById('botonHerramienta1');
// const menuHerramienta1 = document.getElementById('menuHerramienta1');

// const botonHerramienta2 = document.getElementById('botonHerramienta2');
// const menuHerramienta2 = document.getElementById('menuHerramienta2');

// const botonHerramienta3 = document.getElementById('botonHerramienta3');
// const menuHerramienta3 = document.getElementById('menuHerramienta3');

// const botonHerramienta4 = document.getElementById('botonHerramienta4');
// const menuHerramienta4 = document.getElementById('menuHerramienta4');
// -----------

const btnMosaico = document.getElementById('btnMosaico');
const bodyMosaico = document.querySelector('.mosaicos-pg');
const templateMosaico = document.getElementById('templateMosaico');

const contenedorResource = document.querySelector('.contenedor-resource');

// const btnFullscreen = document.getElementById('btnFullscreen');


const zoomSlider = document.getElementById('custom_zoom_slider');

const btnActiveTools = document.getElementById('btn-active-tools');
const colorPicker = document.getElementById('colorPicker');
const toolLapiz = document.getElementById('tool-lapiz');
const toolMarcador = document.getElementById('tool-marcador');
const toolTrazo = document.getElementById('tool-trazo');
const toolText = document.getElementById('tool-text');
const toolEraser = document.getElementById('tool-eraser');

let activeNote = false;
const toolNote = document.getElementById('btn-active-note');

const drawingState = {
  mode: 'pencil',
  width: 3,
  color: colorPicker?.value || '#ff0000'
};

function hexToRGBA(hex, alpha) {
  const cleaned = hex.replace('#', '');
  const hexValue = cleaned.length === 3
    ? cleaned.split('').map(c => c + c).join('')
    : cleaned;
  const numeric = parseInt(hexValue, 16);
  const r = (numeric >> 16) & 255;
  const g = (numeric >> 8) & 255;
  const b = numeric & 255;
  return `rgba(${r}, ${g}, ${b}, ${alpha})`;
}

function storageKeyForPage(page) {
  const prefix = componentId ? `iSolutions-${componentId}` : 'iSolutions';
  return `${prefix}-page-${page}`;
}

function getVisiblePageInfo() {
  const visiblePages = [];
  const total = componentData ? Object.keys(componentData).length : 0;
  const canvasLeft = items[0]?.querySelector('canvas');
  const canvasRight = items[1]?.querySelector('canvas');

  if (!isDoublePage) {
    if (canvasRight) {
      visiblePages.push({ page: currentIndex, canvas: canvasRight });
    }
    return visiblePages;
  }

  const isCover = currentIndex === 1;
  const hasSingleBackCover = total % 2 === 0;
  const isBackCover = hasSingleBackCover && currentIndex === total;

  if (isCover) {
    if (canvasRight) visiblePages.push({ page: 1, canvas: canvasRight });
  } else if (isBackCover) {
    if (canvasLeft) visiblePages.push({ page: total, canvas: canvasLeft });
  } else {
    if (canvasLeft) visiblePages.push({ page: currentIndex, canvas: canvasLeft });
    const nextPage = currentIndex + 1;
    if (canvasRight && nextPage <= total) {
      visiblePages.push({ page: nextPage, canvas: canvasRight });
    }
  }

  return visiblePages;
}

function getCanvasByPage(page) {
  return getVisiblePageInfo().find(item => item.page === page)?.canvas || null;
}

function getVisiblePageElements() {
  const visiblePages = [];
  const total = componentData ? Object.keys(componentData).length : 0;
  const itemLeft = items[0];
  const itemRight = items[1];
  const canvasLeft = itemLeft?.querySelector('canvas');
  const canvasRight = itemRight?.querySelector('canvas');

  if (!isDoublePage) {
    if (itemRight) {
      visiblePages.push({ page: currentIndex, item: itemRight, canvas: canvasRight });
    }
    return visiblePages;
  }

  const isCover = currentIndex === 1;
  const hasSingleBackCover = total % 2 === 0;
  const isBackCover = hasSingleBackCover && currentIndex === total;

  if (isCover) {
    if (itemRight) visiblePages.push({ page: 1, item: itemRight, canvas: canvasRight });
  } else if (isBackCover) {
    if (itemLeft) visiblePages.push({ page: total, item: itemLeft, canvas: canvasLeft });
  } else {
    if (itemLeft) visiblePages.push({ page: currentIndex, item: itemLeft, canvas: canvasLeft });
    const nextPage = currentIndex + 1;
    if (itemRight && nextPage <= total) {
      visiblePages.push({ page: nextPage, item: itemRight, canvas: canvasRight });
    }
  }

  return visiblePages;
}

function getVisiblePageInfo() {
  return getVisiblePageElements().map(info => ({ page: info.page, canvas: info.canvas }));
}

function setCanvasPageDatasets() {
  getVisiblePageElements().forEach(info => {
    if (info.canvas) {
      info.canvas.dataset.page = info.page;
    }
    if (info.item) {
      info.item.dataset.page = info.page;
    }
  });
}

function storageKeyForPageNotes(page) {
  const prefix = componentId ? `iSolutions-${componentId}` : 'iSolutions';
  return `${prefix}-page-${page}-notes`;
}

function getPageNotesFromLocalStorage(page) {
  if (!page) return [];
  try {
    const raw = localStorage.getItem(storageKeyForPageNotes(page));
    return raw ? JSON.parse(raw) : [];
  } catch (error) {
    console.warn('Leer notas desde localStorage falló:', error);
    return [];
  }
}

function savePageNotesToLocalStorage(page, notes) {
  if (!page) return;
  try {
    localStorage.setItem(storageKeyForPageNotes(page), JSON.stringify(notes));
  } catch (error) {
    console.warn('Guardar notas en localStorage falló:', error);
  }
}

function clearNotesFromItems() {
  items.forEach(item => {
    item.querySelectorAll('.dynamic-note').forEach(note => note.remove());
  });
}

function createFloatingNoteElement(noteData) {
  const newNote = document.createElement('div');
  newNote.className = 'dynamic-note';
  newNote.style.left = `${noteData.left}%`;
  newNote.style.top = `${noteData.top}%`;
  newNote.setAttribute('data-title', noteData.text);
  newNote.dataset.url = noteData.isUrl ? 'true' : 'false';
  newNote.title = noteData.text;

  if (noteData.isUrl) {
    newNote.addEventListener('click', () => {
      window.open(noteData.text, '_blank');
    });
  }

  newNote.innerHTML = `
    <svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<g filter="url(#filter0_d_35_4120)">
<circle cx="20" cy="16" r="16" fill="#6ECD60"/>
<rect x="11" y="8" width="18" height="18" fill="url(#pattern0_35_4120)"/>
</g>
<defs>
<filter id="filter0_d_35_4120" x="0" y="0" width="40" height="40" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
<feFlood flood-opacity="0" result="BackgroundImageFix"/>
<feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/>
<feOffset dy="4"/>
<feGaussianBlur stdDeviation="2"/>
<feComposite in2="hardAlpha" operator="out"/>
<feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.25 0"/>
<feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_35_4120"/>
<feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_35_4120" result="shape"/>
</filter>
<pattern id="pattern0_35_4120" patternContentUnits="objectBoundingBox" width="1" height="1">
<use xlink:href="#image0_35_4120" transform="scale(0.0078125)"/>
</pattern>
<image id="image0_35_4120" width="128" height="128" preserveAspectRatio="none" xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACA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4Bm1uMnfAMy05KdL7hVAROYCHwG3xDzlb4IFpM3ZReUveVeAZcD3xE/+VwSLOpb8jMhbAHOJV3XOA8tVdYGqdmUck9c4Mw3sRyfB9O5w0YH4QOHTwH5cAl4G5lny88OVCvArsERV9xQdiG+4UAHWAbdb8ouhyArQDTyuql8UGIP3FFUBthBM7yz5BZO3AHoIXiVbrKqncr62UYU8h4BdwFK19widIo8K0Ac8B7RZ8t0j6wpge/aOk1UFUOBNbM/eebKoAMeB+aq6IwPfRsqE/n8Aww9cWAk0CsQE4DkmAM8xAXiOCcBzTACeYwLwHBOA5/wH2O/ouZdinqMAAAAASUVORK5CYII="/>
</defs>
</svg>

      
  `;

  return newNote;
}

function restoreVisiblePageNotes() {
  clearNotesFromItems();
  getVisiblePageElements().forEach(info => {
    if (!info.page || !info.item) return;
    const notes = getPageNotesFromLocalStorage(info.page);
    notes.forEach(noteData => {
      info.item.prepend(createFloatingNoteElement(noteData));
    });
  });
}

function saveNoteForPage(page, noteData) {
  if (!page || !noteData) return;
  const notes = getPageNotesFromLocalStorage(page);
  notes.push(noteData);
  savePageNotesToLocalStorage(page, notes);
}

function getPageNotesFromItem(item) {
  const page = parseInt(item.dataset.page, 10);
  return page ? getPageNotesFromLocalStorage(page) : [];
}

function getPageForItem(item) {
  if (item.dataset.page) return parseInt(item.dataset.page, 10);
  const index = Array.from(items).indexOf(item);
  if (!isDoublePage) return currentIndex;
  if (index === 0) return currentIndex;
  if (index === 1) return currentIndex + 1;
  return currentIndex;
}

function updateVisibleNoteVisibility() {
  const notas = Array.from(document.querySelectorAll('.dynamic-note'));
  if (btnActiveTools?.querySelector('img')?.src.includes('33.svg')) {
    notas.forEach(n => n.classList.remove('d-none'));
  } else {
    notas.forEach(n => n.classList.add('d-none'));
  }
}

function getPageDrawingFromLocalStorage(page) {
  if (!page) return null;
  return localStorage.getItem(storageKeyForPage(page));
}

function savePageDrawingToLocalStorage(page, canvas) {
  if (!page || !canvas) return;
  try {
    const dataUrl = canvas.toDataURL('image/png');
    localStorage.setItem(storageKeyForPage(page), dataUrl);
  } catch (error) {
    console.warn('Guardar dibujo en localStorage falló:', error);
  }
}

function openDrawingDB() {
  return new Promise((resolve, reject) => {
    if (!window.indexedDB) {
      reject(new Error('IndexedDB no disponible'));
      return;
    }
    const request = indexedDB.open('iSolutionsDrawingDB', 1);
    request.onupgradeneeded = (event) => {
      const db = event.target.result;
      if (!db.objectStoreNames.contains('drawings')) {
        db.createObjectStore('drawings');
      }
    };
    request.onsuccess = (event) => resolve(event.target.result);
    request.onerror = (event) => reject(event.target.error);
  });
}

function savePageDrawingToIndexedDB(page, dataUrl) {
  if (!page || !dataUrl) return Promise.resolve();
  return openDrawingDB().then((db) => {
    return new Promise((resolve, reject) => {
      const transaction = db.transaction('drawings', 'readwrite');
      const store = transaction.objectStore('drawings');
      const request = store.put(dataUrl, storageKeyForPage(page));
      request.onsuccess = () => resolve();
      request.onerror = (event) => reject(event.target.error);
    });
  });
}

function getPageDrawingFromIndexedDB(page) {
  if (!page) return Promise.resolve(null);
  return openDrawingDB().then((db) => {
    return new Promise((resolve, reject) => {
      const transaction = db.transaction('drawings', 'readonly');
      const store = transaction.objectStore('drawings');
      const request = store.get(storageKeyForPage(page));
      request.onsuccess = (event) => resolve(event.target.result || null);
      request.onerror = (event) => reject(event.target.error);
    });
  });
}

async function savePageDrawing(page, canvas) {
  if (!pizaraActiva || !page || !canvas) return;
  const dataUrl = canvas.toDataURL('image/png');

  savePageDrawingToLocalStorage(page, canvas);

  try {
    await savePageDrawingToIndexedDB(page, dataUrl);
  } catch (error) {
    console.warn('Guardar dibujo en IndexedDB falló:', error);
  }
}



async function loadDrawingDataForPage(page) {
  if (!pizaraActiva || !page) return null;
  const localData = getPageDrawingFromLocalStorage(page);
  if (localData) return localData;

  try {
    const indexedData = await getPageDrawingFromIndexedDB(page);
    return indexedData;
  } catch (error) {
    console.warn('Leer dibujo desde IndexedDB falló:', error);
    return null;
  }
}

function restoreCanvasFromDataUrl(canvas, dataUrl) {
  return new Promise((resolve) => {
    if (!canvas || !dataUrl) { resolve(false); return; }
    const ctx = canvas.getContext('2d');
    const image = new Image();
    image.onload = () => {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
      resolve(true);
    };
    image.onerror = () => resolve(false);
    image.src = dataUrl;
  });
}

async function restoreCanvasForPage(page) {
  const canvas = getCanvasByPage(page);
  if (!canvas) return false;
  const dataUrl = await loadDrawingDataForPage(page);
  if (!dataUrl) return false;
  return restoreCanvasFromDataUrl(canvas, dataUrl);
}

async function restoreCurrentPageDrawings() {
  if (!pizaraActiva) return;
  setCanvasPageDatasets();
  const promises = getVisiblePageInfo().map(info => restoreCanvasForPage(info.page));
  await Promise.all(promises);
}

async function saveVisiblePages() {
  if (!pizaraActiva) return;
  const promises = getVisiblePageInfo().map(info => {
    if (info.page && info.canvas) {
      return savePageDrawing(info.page, info.canvas);
    }
    return Promise.resolve();
  });
  await Promise.all(promises);
}

async function restoreAndSetCurrentPages() {
  if (!pizaraActiva) return;
  setCanvasPageDatasets();
  await restoreCurrentPageDrawings();
}

// function applyDrawSettings(ctx) {
//   ctx.lineJoin = 'round';
//   ctx.lineCap = 'round';
//   if (drawingState.mode === 'highlighter') {
//     ctx.strokeStyle = hexToRGBA(drawingState.color, 0.2);
//     ctx.lineWidth = Math.max(1, drawingState.width || 12);
//   } else {
//     ctx.strokeStyle = drawingState.color;
//     ctx.lineWidth = drawingState.width;
//   }
//   ctx.fillStyle = drawingState.color;
//   ctx.globalAlpha = 1;
// }

function applyDrawSettings(ctx) {
  ctx.lineJoin = 'round';
  ctx.lineCap = 'round';

  if (drawingState.mode === 'highlighter') {
    ctx.strokeStyle = hexToRGBA(drawingState.color, 0.55);
    ctx.fillStyle = hexToRGBA(drawingState.color, 0.25);
    ctx.lineWidth = drawingState.width || 22;
    ctx.shadowBlur = 0;
    ctx.globalAlpha = 1;
    ctx.globalCompositeOperation = 'source-over';
  } else if (drawingState.mode === 'eraser') {
    ctx.strokeStyle = 'rgba(0,0,0,1)';
    ctx.fillStyle = 'rgba(0,0,0,1)';
    ctx.lineWidth = drawingState.width || 24;
    ctx.shadowBlur = 0;
    ctx.globalAlpha = 1;
    ctx.globalCompositeOperation = 'destination-out';
  } else {
    ctx.strokeStyle = drawingState.color;
    ctx.fillStyle = drawingState.color;
    ctx.lineWidth = drawingState.width;
    ctx.globalAlpha = 1;
    ctx.globalCompositeOperation = 'source-over';
  }
}

function updateToolSelectionClasses() {
  toolLapiz?.classList.toggle('tool-selected', drawingState.mode === 'pencil');
  toolMarcador?.classList.toggle('tool-selected', drawingState.mode === 'highlighter');
  toolTrazo?.classList.toggle('tool-selected', ['rectangle', 'circle', 'line'].includes(drawingState.mode));
  toolText?.classList.toggle('tool-selected', drawingState.mode === 'text');
  toolEraser?.classList.toggle('tool-selected', drawingState.mode === 'eraser');

  toolLapiz?.querySelectorAll('.icon-sub').forEach((btn, idx) => {
    const expectedWidth = idx === 0 ? 3 : 6;
    btn.classList.toggle('subtool-selected', drawingState.mode === 'pencil' && drawingState.width === expectedWidth);
  });

  toolMarcador?.querySelectorAll('.icon-sub').forEach((btn, idx) => {
    const expectedWidth = idx === 0 ? 12 : 18;
    btn.classList.toggle('subtool-selected', drawingState.mode === 'highlighter' && drawingState.width === expectedWidth);
  });

  if (toolTrazo) {
    const [circleBtn, lineBtn] = Array.from(toolTrazo.querySelectorAll('.icon-sub'));
    circleBtn?.classList.toggle('subtool-selected', drawingState.mode === 'circle');
    lineBtn?.classList.toggle('subtool-selected', drawingState.mode === 'line');
  }
}

function updateCursorForTool() {
  const eraserActive = drawingState.mode === 'eraser';
  document.body.classList.toggle('eraser-active', eraserActive);
  allCanvas.forEach(canvas => {
    canvas.style.cursor = eraserActive ? 'not-allowed' : '';
  });
}

function setDrawingMode(mode, width) {
  drawingState.mode = mode;
  if (width) drawingState.width = width;
  updateToolSelectionClasses();
  updateCursorForTool();
}

function setStrokeColor(color) {
  drawingState.color = color;
}

updateToolSelectionClasses();

/*Importante camvas de dibujo*/
/**
 * CONFIGURACIÓN DE PIZARRA DUAL
 */
// const btnPizara = document.getElementById('btnPizaraLapiz');
const allCanvas = document.querySelectorAll('.canvas-pauta');
let pizaraActiva = false;

// Estado global del ratón (presionado o no)
let isMouseDownGlobal = false;
window.addEventListener('mousedown', () => isMouseDownGlobal = true);
window.addEventListener('mouseup', () => isMouseDownGlobal = false);

// Estado del lápiz
const pencilConfig = {
  color: '#ff0000',
  width: 3
};

async function buscarPagina(pagina) {
  try {
    const respuesta = await fetch(`componentes/${componentId}/item_${pagina}.json`);

    if (!respuesta.ok) {
      throw new Error(`Error en la petición: ${respuesta.status}`);
    }

    // 3. Parseamos el JSON y lo retornamos
    const datos = await respuesta.json();
    return datos;

  } catch (error) {
    console.error("Hubo un fallo al recuperar los datos:", error);
    throw error; // Re-lanzamos para que quien llame a la función pueda manejarlo
  }
};

/**
 * Carga una imagen y devuelve una promesa cuando está lista.
 */
function loadImage(container, src) {
  return new Promise((resolve) => {
    let img = container.querySelector('img');
    if (!img) {
      img = document.createElement('img');
      container.appendChild(img);
    }
    container.classList.add('is-loading');

    img.onload = () => {
      container.classList.remove('is-loading');
      resolve();
    };
    img.src = src;
  });
}

/**
 * Pre-carga las siguientes páginas en la caché del navegador.
 */
async function prefetchNext() {
  const nextIdx = (currentIndex === 1) ? 2 : currentIndex + 2;
  if (nextIdx < Object.keys(componentData).length) {
    const dataPagina = await buscarPagina(nextIdx);

    new Image().src = dataPagina.full;
    if (componentData[nextIdx + 1]) {
      const dataPagina = await buscarPagina(nextIdx + 1);
      new Image().src = dataPagina.full;
    };
  }
}

/**
 * Actualiza la vista del libro con lógica de paridad y animaciones.
 */
async function updateView() {
  const total = Object.keys(componentData).length;
  const isCover = isDoublePage ? (currentIndex === 1) : false;
  const hasSingleBackCover = total % 2 === 0;
  const isBackCover = isDoublePage ? (hasSingleBackCover && currentIndex === total) : false;

  // 1. Iniciar animación de salida
  deskContent.classList.remove('page-transition');
  void deskContent.offsetWidth;
  deskContent.classList.add('page-transition');

  // 2. Punto medio de la animación (Cambiamos el layout aquí)
  setTimeout(async () => {
    // Antes de cargar las nuevas, ocultamos las viejas para que no se estiren
    items.forEach(item => {
      const img = item.querySelector('img');
      if (img) img.style.opacity = '0';
    });

    // Aplicamos las reglas de visibilidad (Aquí es donde el ancho del div empezará a transicionar)
    items.forEach(el => el.classList.remove('d-none'));
    [toolLeft, toolRight].forEach(el => el?.classList.add('d-none'));
    [toolLpLeft, toolLpRight].forEach(el => el?.classList.add('v-none'));

    const promises = [];

    if (!isDoublePage) {
      const dataPaginaDouble = await buscarPagina(currentIndex);

      // MODO PÁGINA SIMPLE
      items[0].classList.add('d-none');

      if (currentIndex === 1) {
        toolRight.classList.remove('d-none');
        // toolLpRight.classList.add('v-none');
      } else if (currentIndex === total) {
        toolLeft.classList.remove('d-none');
        // toolLpLeft.classList.add('v-none');
      } else {
        // toolLpLeft.classList.add('v-none');
        [toolLeft, toolRight].forEach(el => el?.classList.remove('d-none'));
      }

      items[1].setAttribute('data-page', dataPaginaDouble.page);

      promises.push(loadImage(items[1], dataPaginaDouble.full));
      marcarPaginaActual(dataPaginaDouble.page);
    } else if (isCover) {
      // MODO DOBLE - PORTADA
      items[0].classList.add('d-none');
      toolRight.classList.remove('d-none');
      // toolLpRight.classList.add('v-none');

      const dataPaginaCover = await buscarPagina(1);

      items[1].setAttribute('data-page', dataPaginaCover.page);

      promises.push(loadImage(items[1], dataPaginaCover.full));
      marcarPaginaActual(dataPaginaCover.page);
    } else if (isBackCover) {
      // MODO DOBLE - CONTRA PORTADA
      items[1].classList.add('d-none');
      toolLeft.classList.remove('d-none');
      // toolLpLeft.classList.add('v-none');

      const dataPaginaDobleBack = await buscarPagina(total);

      items[0].setAttribute('data-page', dataPaginaDobleBack.page);

      promises.push(loadImage(items[0], dataPaginaDobleBack.full));
      marcarPaginaActual(dataPaginaDobleBack.page);
    } else {
      // MODO DOBLE - PLIEGO NORMAL

      const dataPagina = await buscarPagina(currentIndex);
      let pageActive = currentIndex;

      items[0].setAttribute('data-page', dataPagina.page);

      promises.push(loadImage(items[0], dataPagina.full));
      toolLeft.classList.remove('d-none');
      if (componentData[currentIndex + 1]) {
        pageActive = currentIndex + 1;
        const dataPaginaNext = await buscarPagina(currentIndex + 1);

        items[1].setAttribute('data-page', dataPaginaNext.page);

        promises.push(loadImage(items[1], dataPaginaNext.full));
        toolRight.classList.remove('d-none');
      }

      marcarPaginaActual(pageActive);
    }

    await Promise.all(promises);
    await restoreAndSetCurrentPages();
    restoreVisiblePageNotes();

    // Pequeño delay para asegurar que el navegador procesó el nuevo ancho
    setTimeout(async () => {
      items.forEach(item => {
        const img = item.querySelector('img');
        if (img) img.style.opacity = '1';
      });
      prefetchNext();

      let bookContent = document.querySelector('.desk-content');
      let pages = bookContent.querySelectorAll('.desk-content-item:not(.d-none)');

      for (const [idx, page] of pages.entries()) {

        // Aquí el bucle SE DETIENE hasta que buscarPagina termine
        const dataPagina = await buscarPagina(currentIndex + idx);
        const currentHotspots = dataPagina.config.hotspot || [];
        const currentLearningPath = dataPagina.config.learningPath || [];

        // Limpiamos hotspots viejos
        page.querySelectorAll('.hotspot').forEach(hs => hs.remove());

        // Dibujamos los nuevos
        currentHotspots.forEach(hs => {
          let hotspot = document.createElement('div');

          const baseWidth = hs.coordinates.originalWidth || 1824;
          const baseHeight = hs.coordinates.originalHeight || 2428;

          hotspot.style.width = (hs.coordinates.width / baseWidth * 100) + '%';
          hotspot.style.height = (hs.coordinates.height / baseHeight * 100) + '%';
          hotspot.style.left = (hs.coordinates.x / baseWidth * 100) + '%';
          hotspot.style.top = (hs.coordinates.y / baseHeight * 100) + '%';

          hotspot.setAttribute('data-activity', hs.activity);
          hotspot.classList.add('hotspot');

          page.appendChild(hotspot);
        });

        let lista;

        if (idx == 0) {
          lista = document.querySelector('#menu-left ul');
          if (currentLearningPath.length > 0)
            toolLpLeft.classList.remove('v-none');
        } else {
          lista = document.querySelector('#menu-right ul');
          if (currentLearningPath.length > 0)
            toolLpRight.classList.remove('v-none');
        }

        lista.innerHTML = '';
        currentLearningPath.forEach(lp => {
          let action = '';

          if (lp.type == 'reference') {
            const info = lp.link.split('|');
            const index = iSolutionsData.components.findIndex(item => item.componentId === info[0]);

            action = `javaScript:abrirComponente(${index}, ${info[1]})`;
          } else {
            if (lp.format == 'audios') {
              action = `javaScript:abrirModal('audio', 'recursos/extra/audios/${lp.rsc}', '${lp.label}');`;
            } else if (lp.format == 'documentos') {
              action = `javascript:abrirModal('docs', 'recursos/extra/documents/${lp.rsc}', '${lp.label}');`;
            } else if (lp.format == 'imagenes') {
              action = `javascript:abrirModal('images', 'recursos/extra/images/${lp.rsc}', '${lp.label}');`;
            } else if (lp.format == 'videos') {
              action = `javascript:abrirModal('video', 'recursos/extra/videos/${lp.rsc}', '${lp.label}');`;
            } else if (lp.format == 'platform_resource') {
              action = `javascript:abrirModal('extra_rsc', 'images/rlp_reference/rlp_${lp.link}.jpg', '${lp.label}');`;
            } else {
              action = `javascript:abrirModal('stand', 'recursos/extra/${lp.format}/${lp.rsc}', '${lp.label}');`;
            }
          }

          // action = `javaScript:abrirModal('extra', ${lp.link})`;


          const li = `
            <li class="${lp.colorSpan}" onClick="${action}">
              ${lp.icon}
              <span>${lp.label}</span>
            </li>
          `
          lista.insertAdjacentHTML('beforeend', li);
        });
      }

      hideLoader();
    }, 50);

    currentReference = -1; // Reseteamos la referencia para que no afecte a futuras navegaciones

  }, 300);
}

/**
 * Renderiza los mosaicos de las páginas del libro.
 */
function renderizarMosaicos() {
  Object.keys(componentData).forEach((page, idx) => {

    const mosaico = templateMosaico.cloneNode(true);
    const pageNum = componentData[page].folio;

    mosaico.removeAttribute('id');
    mosaico.classList.remove('d-none');

    mosaico.dataset.pageno = page;
    mosaico.querySelector('img').src = componentData[page].thumb;
    mosaico.querySelector('span').textContent = pageNum;
    mosaico.querySelector('span').setAttribute('title', pageNum);

    bodyMosaico.appendChild(mosaico);
  });
}

/**
 * Borra los mosaicos existentes antes de renderizar nuevos.
 */
function limpiarMosaicos() {
  document.querySelectorAll('.mosaicos-pg .mosaico:not(#templateMosaico)')
    .forEach(el => el.remove());
}

function marcarPaginaActual(paginaActiva) {
  // 1. Limpiamos cualquier clase 'active' previa para no tener duplicados
  const previo = document.querySelector('.mosaico.active');
  if (previo) previo.classList.remove('active');

  // 2. Buscamos el mosaico que tenga el data-pageno exacto
  // Usamos el selector de atributo [data-pageno="X"]
  mosaicoActual = document.querySelector(`.mosaicos-pg .mosaico[data-pageno="${paginaActiva}"]`);

  if (mosaicoActual) {
    mosaicoActual.classList.add('active');
  }
}

/**
 * 2. AJUSTE DE RESOLUCIÓN (Crucial para que el trazo no se desfase)
 */
function ajustarResolucionCanvas(canvas) {
  const rect = canvas.getBoundingClientRect();
  const ctx = canvas.getContext('2d');

  // Solo actuamos si el tamaño físico del elemento ha cambiado
  if (canvas.width !== Math.floor(rect.width) || canvas.height !== Math.floor(rect.height)) {

    // --- PASO A: PERSISTENCIA ---
    // Guardamos el dibujo actual como una "foto" instantánea
    const contenidoPrevio = canvas.toDataURL();

    // --- PASO B: REDIMENSIONAMIENTO ---
    // Esto limpia automáticamente el canvas y resetea el contexto (ctx)
    canvas.width = rect.width;
    canvas.height = rect.height;

    // --- PASO C: RESTAURAR CONTEXTO ---
    // Al cambiar width/height se pierden los estilos, hay que re-aplicarlos
    ctx.lineJoin = 'round';
    ctx.lineCap = 'round';
    ctx.strokeStyle = pencilConfig.color;
    ctx.lineWidth = pencilConfig.width;

    // --- PASO D: DIBUJAR LO QUE HABÍA ---
    const img = new Image();
    img.src = contenidoPrevio;
    img.onload = function () {
      // Dibujamos la imagen vieja estirándola para que encaje perfectamente 
      // en las nuevas dimensiones (útil para Fullscreen)
      ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
    };
  }
}

// --- Eventos ---
btnNext.addEventListener('click', async () => {
  if (pizaraActiva) btnActiveTools.click();

  const total = Object.keys(componentData).length;

  await saveVisiblePages();

  if (isDoublePage) {
    const hasSingleBackCover = total % 2 === 0;
    if (currentIndex === 1) {
      currentIndex = 2;
    } else {
      if (hasSingleBackCover && currentIndex + 2 === total) {
        currentIndex += 2;
      } else if (currentIndex + 2 < total) {
        currentIndex += 2;
      }
    }
  } else {
    if (currentIndex + 1 < total) {
      currentIndex += 1;
    } else if (currentIndex + 1 === total) {
      currentIndex = total;
    }
  }

  updateView();
});

btnPrev.addEventListener('click', async () => {
  if (pizaraActiva) btnActiveTools.click();

  await saveVisiblePages();

  if (isDoublePage) {
    if (currentIndex === 2) {
      currentIndex = 1;
    } else if (currentIndex > 1) {
      currentIndex -= 2;
      if (currentIndex < 1) currentIndex = 1;
    }
  } else {
    if (currentIndex > 1) {
      currentIndex -= 1;
    }
  }

  updateView();
});

document.addEventListener('click', (e) => {
  // Verificamos si lo que se clickeó es un hotspot
  if (e.target.classList.contains('hotspot')) {
    const actividad = e.target.getAttribute('data-activity');

    if (actividad) {
      if (actividad !== 'nothing') {
        abrirModal(actividad);
      }
    }
  }

  // Si el click no fue dentro del menú ni en el botón, cerramos el menú principal
  if (!menuPrincipal.contains(e.target) && e.target !== botonMenuPrincipal) {
    menuPrincipal.classList.remove('show');
  }

  // Si el click no fue dentro del menú ni en el botón, cerramos el menú de audios
  if (!menuAudios.contains(e.target) && e.target !== botonMenuAudio) {
    menuAudios.classList.remove('show');
  }

  // Si el click no fue dentro del menú ni en el botón, cerramos el menú de flashcards
  if (!menuFlashcards.contains(e.target) && e.target !== botonMenuFlashcards) {
    menuFlashcards.classList.remove('show');
  }

  // Si el click no fue dentro del menú ni en el botón, cerramos el menú de recursos extras
  if (!menuRecursosExtras.contains(e.target) && e.target !== botonMenuRecursosExtras) {
    menuRecursosExtras.classList.remove('show');
  }

  // Si el click no fue dentro del menú ni en el botón, cerramos el menú de videos
  if (!menuVideos.contains(e.target) && e.target !== botonMenuVideos) {
    menuVideos.classList.remove('show');
  }

  // // Si el click no fue dentro del menú ni en el botón, cerramos el menú de herramienta
  // if (!menuHerramienta1.contains(e.target) && e.target !== botonHerramienta1) {
  //   menuHerramienta1.classList.remove('show');
  // }

  // // Si el click no fue dentro del menú ni en el botón, cerramos el menú de herramienta
  // if (!menuHerramienta2.contains(e.target) && e.target !== botonHerramienta2) {
  //   menuHerramienta2.classList.remove('show');
  // }

  // // Si el click no fue dentro del menú ni en el botón, cerramos el menú de herramienta
  // if (!menuHerramienta3.contains(e.target) && e.target !== botonHerramienta3) {
  //   menuHerramienta3.classList.remove('show');
  // }

  //   // Si el click no fue dentro del menú ni en el botón, cerramos el menú de herramienta
  // if (!menuHerramienta4.contains(e.target) && e.target !== botonHerramienta4) {
  //   menuHerramienta4.classList.remove('show');
  // }
});

function abrirModal(nombreAct, link = 0, customTitle = '') {
  if (nombreAct === 'mosaico') {
    titleModal.textContent = "Book Overview";
    bodyMosaico.classList.remove('d-none');

    const tieneMosaicos = document.querySelectorAll('.mosaicos-pg .mosaico:not(#templateMosaico)').length > 0;

    if (!tieneMosaicos) {
      renderizarMosaicos();
    }

    if (mosaicoActual) {
      setTimeout(() => {
        mosaicoActual.scrollIntoView({ behavior: 'smooth', block: 'center' });
      }, 500);
    }
  } else if (nombreAct === 'extra_rsc') {
    titleModal.textContent = "Extra Resources: " + customTitle;
    contenedorResource.classList.remove('d-none');

    const imagen = contenedorResource.querySelector('img');
    imagen.src = link;
  } else if (nombreAct === 'fc') {
    titleModal.textContent = `FlashCards - ${customTitle}`;
    iframe.classList.remove('d-none');
    iframe.src = link;
  } else if (nombreAct === 'vd') {
    titleModal.textContent = `Videos`;
    iframe.classList.remove('d-none');
    iframe.src = `${link}/index.html`;
  } else if (nombreAct === 'gvd') {
    titleModal.textContent = `Grammar Videos`;
    iframe.classList.remove('d-none');
    iframe.src = link;
  } else if (nombreAct === 'usg') {
    titleModal.textContent = `UN Sustainable Goal`;
    iframe.classList.remove('d-none');
    iframe.src = link;
  } else if (nombreAct === 'cg') {
    titleModal.textContent = `Classroom Games`;
    iframe.classList.remove('d-none');
    iframe.src = link;
  } else if (nombreAct === 'tc') {
    titleModal.textContent = `Language Log Transcripts`;
    iframe.classList.remove('d-none');
    iframe.src = link;
  } else if (nombreAct === 'gtc') {
    titleModal.textContent = `Grammar and Skills Log Transcripts`;
    iframe.classList.remove('d-none');
    iframe.src = link;
  } else if (nombreAct === 'stand') {
    titleModal.textContent = customTitle;
    iframe.classList.remove('d-none');
    iframe.src = link;
  } else if (nombreAct === 'audio') {
    titleModal.textContent = customTitle;
    iframe.classList.remove('d-none');
    iframe.src = link;
  } else if (nombreAct === 'docs') {
    const url = new URL(link, window.location.origin);
    const isDoc = url.pathname.toLowerCase().endsWith('.docx');

    if (isDoc) {
      document.getElementById("custom-w-viewer").classList.remove('d-none');
      btnDownloadWord.classList.remove('d-none');
      btnDownloadWord.setAttribute('href', link);

      fetch(link)
        .then(res => {
          if (!res.ok) {
            throw new Error(`HTTP ${res.status}`);
          }
          return res.blob();
        })
        .then(blob => {

          const options = {
            className: "docx",
            inWrapper: true,
            hideWrapperOnPrint: false,

            ignoreWidth: false,
            ignoreHeight: false,
            ignoreFonts: false,

            breakPages: true,
            ignoreLastRenderedPageBreak: true,

            experimental: true,

            trimXmlDeclaration: true,
            useBase64URL: false,

            renderHeaders: true,
            renderFooters: true,
            renderFootnotes: true,
            renderEndnotes: true,
            renderComments: true,
            renderChanges: true,
            renderAltChunks: true,

            debug: false
          };
          return docx.renderAsync(
            blob,
            document.getElementById("custom-w-viewer"),
            false,
            options
          );
        })
        .catch(err => {
          console.error(err);
        });
    } else {
      iframe.classList.remove('d-none');
      iframe.src = link;
    }

    titleModal.textContent = customTitle;
  } else if (nombreAct === 'video') {
    titleModal.textContent = customTitle;
    iframe.classList.remove('d-none');

    // const subtitleUrl = link.replace(/\.[^/.]+$/, `.srt`);

    const htmlContent = `
      <!DOCTYPE html>
      <html>
      <head>
        <style>
          body { margin: 0; background: #000; display: flex; justify-content: center; align-items: center; height: 100vh; }
          video { width: 100%; height: 100%; max-height: 100vh; }
        </style>
      </head>
      <body>
        <video controls autoplay>
          <source src="${link}" type="video/mp4">
        </video>
      </body>
      </html>
    `;

    iframe.srcdoc = htmlContent;
  } else if (nombreAct === 'images') {
    titleModal.textContent = customTitle;
    contenedorResource.classList.remove('d-none');

    const imagen = contenedorResource.querySelector('img');
    imagen.src = link;
  } else {
    titleModal.textContent = `Activity`;
    iframe.classList.remove('d-none');
    iframe.src = `recursos/${componentId}/actividades/${nombreAct}/index.html`;
  }

  document.body.style.overflow = 'hidden';
  modalAct.classList.add('is-visible');
}

function abrirComponente(idComponente, idPagina) {
  currentReference = idPagina;
  document.querySelector(`[data-indexcomponente="${idComponente}"]`)?.click();
}

closeBtn.addEventListener('click', cerrarModal);

modalAct.addEventListener('click', (e) => {
  if (e.target === modalAct) cerrarModal();
});

function cerrarModal() {
  modalAct.classList.remove('is-visible');

  setTimeout(() => {
    btnDownloadWord.classList.add('d-none');
    btnDownloadWord.removeAttribute('href');

    iframe.removeAttribute('src');
    iframe.removeAttribute('srcdoc');

    document.getElementById("custom-w-viewer").innerHTML = "";
    document.getElementById("custom-w-viewer").classList.add('d-none');

    iframe.classList.add('d-none');

    bodyMosaico.classList.add('d-none');

    contenedorResource.classList.add('d-none');

    document.body.style.overflow = 'auto';
  }, 400);
}

botonMenuPrincipal.addEventListener('click', (e) => {
  e.stopPropagation(); // Evita que el click se propague al 'window' inmediatamente
  menuPrincipal.classList.toggle('show');

  menuAudios.classList.remove('show');
  menuFlashcards.classList.remove('show');
  menuVideos.classList.remove('show');
  menuRecursosExtras.classList.remove('show');
});

btnCloseMenu.addEventListener('click', () => {
  menuPrincipal.classList.remove('show');
});

botonMenuAudio.addEventListener('click', (e) => {
  e.stopPropagation(); // Evita que el click se propague al 'window' inmediatamente
  menuAudios.classList.toggle('show');

  menuPrincipal.classList.remove('show');
  menuFlashcards.classList.remove('show');
  menuVideos.classList.remove('show');
  menuRecursosExtras.classList.remove('show');
});

btnCloseAudios.addEventListener('click', () => {
  menuAudios.classList.remove('show');
});

botonMenuFlashcards.addEventListener('click', (e) => {
  e.stopPropagation(); // Evita que el click se propague al 'window' inmediatamente
  menuFlashcards.classList.toggle('show');

  menuPrincipal.classList.remove('show');
  menuAudios.classList.remove('show');
  menuVideos.classList.remove('show');
  menuRecursosExtras.classList.remove('show');
});

btnCloseFlashcards.addEventListener('click', () => {
  menuFlashcards.classList.remove('show');
});

botonMenuVideos.addEventListener('click', (e) => {
  e.stopPropagation(); // Evita que el click se propague al 'window' inmediatamente
  menuVideos.classList.toggle('show');

  menuPrincipal.classList.remove('show');
  menuAudios.classList.remove('show');
  menuFlashcards.classList.remove('show');
  menuRecursosExtras.classList.remove('show');
});

btnCloseVideos.addEventListener('click', () => {
  menuVideos.classList.remove('show');
});

botonMenuRecursosExtras.addEventListener('click', (e) => {
  e.stopPropagation(); // Evita que el click se propague al 'window' inmediatamente
  menuRecursosExtras.classList.toggle('show');

  menuPrincipal.classList.remove('show');
  menuAudios.classList.remove('show');
  menuFlashcards.classList.remove('show');
  menuVideos.classList.remove('show');
});

// Acciones herramientas
// botonHerramienta1.addEventListener('click', (e) => {
//   e.stopPropagation(); // Evita que el click se propague al 'window' inmediatamente
//   menuHerramienta1.classList.toggle('show');
// });

// botonHerramienta2.addEventListener('click', (e) => {
//   e.stopPropagation(); // Evita que el click se propague al 'window' inmediatamente
//   menuHerramienta2.classList.toggle('show');
// });

// botonHerramienta3.addEventListener('click', (e) => {
//   e.stopPropagation(); // Evita que el click se propague al 'window' inmediatamente
//   menuHerramienta3.classList.toggle('show');
// });

// botonHerramienta4.addEventListener('click', (e) => {
//   e.stopPropagation(); // Evita que el click se propague al 'window' inmediatamente
//   menuHerramienta4.classList.toggle('show');
// });
//----------------------

btnCloseRecursosExtras.addEventListener('click', () => {
  menuRecursosExtras.classList.remove('show');
});

btnMosaico.addEventListener('click', abrirModal.bind(null, 'mosaico'));

bodyMosaico.addEventListener('click', async (e) => {
  const clickedMosaico = e.target.closest('.mosaico');

  if (clickedMosaico && clickedMosaico.id !== 'templateMosaico') {
    const targetIndex = parseInt(clickedMosaico.dataset.pageno);
    const total = Object.keys(componentData).length;

    await saveVisiblePages();

    if (isDoublePage) {
      if (targetIndex === 1) {
        currentIndex = 1;
      } else if (targetIndex >= total) {
        currentIndex = total;
      } else {
        currentIndex = (targetIndex % 2 !== 0) ? targetIndex - 1 : targetIndex;
        if (currentIndex < 1) currentIndex = 1;
      }
    } else {
      currentIndex = targetIndex;
    }

    updateView();
    cerrarModal();
  }
});

btnSwitch.addEventListener('click', async function () {
  if (pizaraActiva) btnActiveTools.click();

  await saveVisiblePages();

  if (isDoublePage) {
    isDoublePage = false;
    iconImg.src = "icons/17.svg";
  } else {
    isDoublePage = true;
    iconImg.src = "icons/34.svg";

    if (currentIndex % 2 === 1 && currentIndex !== 1) {
      currentIndex -= 1;
    }
  }

  updateView();
});

// btnFullscreen.addEventListener('click', () => {
//   if (!document.fullscreenElement) {
//     // Intentar entrar en pantalla completa
//     const requestMethod = deskContent.requestFullscreen ||
//       deskContent.webkitRequestFullscreen ||
//       deskContent.msRequestFullscreen;
//     if (requestMethod) requestMethod.call(deskContent);
//   } else {
//     // Salir de pantalla completa
//     if (document.exitFullscreen) document.exitFullscreen();
//   }
// });

document.addEventListener('fullscreenchange', () => {
  // Buscamos todos los hotspots actuales en el DOM
  const hotspots = document.querySelectorAll('.hotspot');

  if (document.fullscreenElement) {
    hotspots.forEach(hs => hs.classList.add('d-none'));
  } else {
    hotspots.forEach(hs => hs.classList.remove('d-none'));
  }

  setTimeout(() => {
    allCanvas.forEach(canvas => ajustarResolucionCanvas(canvas));
  }, 500);
});

/**
 * 1. ACTIVAR / DESACTIVAR MODO DIBUJO
 */
function toglePizara() {
  pizaraActiva = !pizaraActiva;
  // this.classList.toggle('active', pizaraActiva);

  allCanvas.forEach(canvas => {
    canvas.classList.toggle('active', pizaraActiva);
    if (pizaraActiva) {
      ajustarResolucionCanvas(canvas);
    }
  });

  if (pizaraActiva) {
    restoreAndSetCurrentPages();
  } else {
    limpiarPizarras();
  }
};

/**
 * 3. LÓGICA DE DIBUJO DELEGADA
 */
allCanvas.forEach(canvas => {
  const ctx = canvas.getContext('2d');
  let isDrawingOnThisCanvas = false;
  let startPoint = null;
  let savedImage = null;

  // Función auxiliar para obtener coordenadas exactas
  function getMousePos(e, canvasEl) {
    const rect = canvasEl.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;

    return {
      x: x * (canvasEl.width / rect.width),
      y: y * (canvasEl.height / rect.height)
    };
  }

  function drawShape(ctx, from, to, mode) {
    const x = Math.min(from.x, to.x);
    const y = Math.min(from.y, to.y);
    const width = Math.abs(to.x - from.x);
    const height = Math.abs(to.y - from.y);

    ctx.beginPath();
    if (mode === 'rectangle') {
      ctx.fillStyle = 'rgba(255,255,255,0.5)';
      ctx.fillRect(x, y, width, height);
      ctx.strokeStyle = drawingState.color;
      ctx.strokeRect(x, y, width, height);
    } else if (mode === 'circle') {
      const centerX = (from.x + to.x) / 2;
      const centerY = (from.y + to.y) / 2;
      const radius = Math.max(width, height) / 2;
      ctx.fillStyle = 'rgba(255,255,255,0.5)';
      ctx.ellipse(centerX, centerY, radius, radius, 0, 0, Math.PI * 2);
      ctx.fill();
      ctx.strokeStyle = drawingState.color;
      ctx.stroke();
    } else if (mode === 'line') {
      ctx.moveTo(from.x, from.y);
      ctx.lineTo(to.x, to.y);
      ctx.stroke();
    }
  }

  // --- A. Empieza el trazo ---
  canvas.addEventListener('mousedown', (e) => {
    if (!pizaraActiva) return;

    const pos = getMousePos(e, canvas);
    const mode = drawingState.mode;

    if (mode === 'text') {
      const text = prompt('Escribe el texto:');
      if (text) {
        applyDrawSettings(ctx);
        ctx.globalAlpha = 1;
        ctx.font = `${drawingState.width * 8}px sans-serif`;
        ctx.fillStyle = drawingState.color;
        ctx.fillText(text, pos.x, pos.y);
      }
      return;
    }

    isDrawingOnThisCanvas = true;
    applyDrawSettings(ctx);

    if (mode === 'pencil' || mode === 'highlighter' || mode === 'eraser') {
      ctx.beginPath();
      ctx.moveTo(pos.x, pos.y);
    } else {
      startPoint = pos;
      savedImage = ctx.getImageData(0, 0, canvas.width, canvas.height);
    }
  });

  // --- B. Dibujar (Sigue el trazo) ---
  canvas.addEventListener('mousemove', (e) => {
    if (!isDrawingOnThisCanvas || !pizaraActiva) return;

    const pos = getMousePos(e, canvas);
    applyDrawSettings(ctx);

    // if (drawingState.mode === 'pencil' || drawingState.mode === 'highlighter') {
    //   ctx.lineTo(pos.x, pos.y);
    //   ctx.stroke();
    //   return;
    // }

    if (drawingState.mode === 'pencil') {
      ctx.lineTo(pos.x, pos.y);
      ctx.stroke();
      return;
    }

    if (drawingState.mode === 'highlighter' || drawingState.mode === 'eraser') {
      ctx.lineTo(pos.x, pos.y);
      ctx.stroke();
      ctx.beginPath();
      ctx.arc(pos.x, pos.y, ctx.lineWidth / 2, 0, Math.PI * 2);
      ctx.fill();
      ctx.beginPath();
      ctx.moveTo(pos.x, pos.y);
      return;
    }

    if (!startPoint || !savedImage) return;

    ctx.putImageData(savedImage, 0, 0);
    drawShape(ctx, startPoint, pos, drawingState.mode);
  });

  // --- C. Detiene el trazo si se suelta dentro del canvas ---
  canvas.addEventListener('mouseup', async (e) => {
    if (!isDrawingOnThisCanvas) return;

    if (drawingState.mode !== 'pencil' && drawingState.mode !== 'highlighter') {
      const pos = getMousePos(e, canvas);
      if (startPoint && savedImage) {
        ctx.putImageData(savedImage, 0, 0);
        applyDrawSettings(ctx);
        drawShape(ctx, startPoint, pos, drawingState.mode);
      }
    }

    isDrawingOnThisCanvas = false;
    startPoint = null;
    savedImage = null;

    const page = parseInt(canvas.dataset.page, 10);
    if (page) {
      await savePageDrawing(page, canvas);
    }
  });

  /**
   * --- SOLUCIÓN AL PROBLEMA DE LA IMAGEN (Eventos de Borde) ---
   */

  // D. Cuando el puntero SALE del canvas
  canvas.addEventListener('mouseleave', () => {
    if (!isDrawingOnThisCanvas) return;

    isDrawingOnThisCanvas = false;
    startPoint = null;
    savedImage = null;
  });

  // E. Cuando el puntero RE-ENTRA al canvas
  canvas.addEventListener('mouseenter', (e) => {
    if (!pizaraActiva) return;

    if (isMouseDownGlobal) {
      isDrawingOnThisCanvas = true;
      const pos = getMousePos(e, canvas);
      if (drawingState.mode === 'pencil' || drawingState.mode === 'highlighter' || drawingState.mode === 'eraser') {
        applyDrawSettings(ctx);
        ctx.beginPath();
        ctx.moveTo(pos.x, pos.y);
      } else {
        startPoint = pos;
        savedImage = ctx.getImageData(0, 0, canvas.width, canvas.height);
      }
    }
  });
});

/**
 * 4. INTEGRACIÓN CON TU NAVEGACIÓN (UpdateView)
 */
function limpiarPizarras() {
  allCanvas.forEach(canvas => {
    const ctx = canvas.getContext('2d');
    ctx.clearRect(0, 0, canvas.width, canvas.height);
  });
}

window.addEventListener('resize', () => {
  allCanvas.forEach(canvas => ajustarResolucionCanvas(canvas));
});

async function irPagina(pagina) {
  const total = Object.keys(componentData).length;

  await saveVisiblePages();

  if (isDoublePage) {
    if (pagina === 1) {
      currentIndex = 1;
    } else if (pagina >= total) {
      currentIndex = total;
    } else {
      currentIndex = (pagina % 2 !== 0) ? pagina - 1 : pagina;
      if (currentIndex < 1) currentIndex = 1;
    }
  } else {
    currentIndex = pagina;
  }

  updateView();
}

const zoomInner = document.getElementById('zoom_inner');

zoomSlider.addEventListener('input', () => {
  const sliderValue = parseInt(zoomSlider.value);
  const newScale = sliderValue / 100;

  // const element = document.querySelector('.desk-content.page-transition');
  // element.style.transform = `scale(${newScale})`;

  zoomInner.style.transform = `scale(${newScale})`;

  zoomInner.style.width = `${100 * newScale}%`;
  zoomInner.style.height = `${100 * newScale}%`;

  if (sliderValue > 0) {
    containerZoom.style.cursor = 'grab';
  } else {
    containerZoom.style.cursor = 'default';
  }

  centerIfNeeded();

});

const containerZoom = document.getElementById('zoom_container');

let isDown = false;
let startX, startY;
let scrollLeft, scrollTop;

containerZoom.addEventListener('mousedown', (e) => {
  if (pizaraActiva) return;

  isDown = true;
  containerZoom.style.cursor = 'grabbing';

  startX = e.pageX;
  startY = e.pageY;

  scrollLeft = containerZoom.scrollLeft;
  scrollTop = containerZoom.scrollTop;
});

containerZoom.addEventListener('mouseup', () => {
  isDown = false;
  containerZoom.style.cursor = 'grab';
});

containerZoom.addEventListener('mouseleave', () => {
  isDown = false;
});

containerZoom.addEventListener('mousemove', (e) => {
  if (pizaraActiva) return;

  if (!isDown) return;

  const dx = e.pageX - startX;
  const dy = e.pageY - startY;

  // containerZoom.scrollLeft = scrollLeft - dx;
  // containerZoom.scrollTop = scrollTop - dy;

  const maxScrollLeft = Math.max(0, containerZoom.scrollWidth - containerZoom.clientWidth);
  const maxScrollTop = Math.max(0, containerZoom.scrollHeight - containerZoom.clientHeight);

  let newScrollLeft = scrollLeft - dx;
  let newScrollTop = scrollTop - dy;

  // clamp
  newScrollLeft = Math.max(0, Math.min(newScrollLeft, maxScrollLeft));
  newScrollTop = Math.max(0, Math.min(newScrollTop, maxScrollTop));

  containerZoom.scrollLeft = newScrollLeft;
  containerZoom.scrollTop = newScrollTop;
});

function centerIfNeeded() {
  const hasHorizontalScroll = containerZoom.scrollWidth > containerZoom.clientWidth;
  const hasVerticalScroll = containerZoom.scrollHeight > containerZoom.clientHeight;

  containerZoom.style.justifyContent = hasHorizontalScroll ? 'flex-start' : 'center';
  containerZoom.style.alignItems = hasVerticalScroll ? 'flex-start' : 'center';
}

function toggleMenu(containerId) {
  const allMenus = document.querySelectorAll('.menu-item-container');
  const target = document.getElementById(containerId);

  allMenus.forEach(menu => {
    if (menu === target) {
      menu.classList.toggle('active');
    } else {
      menu.classList.remove('active');
    }
  });
}

// Opcional: Cerrar si haces clic fuera de la barra
document.addEventListener('click', (e) => {
  if (!e.target.closest('.menu-item-container')) {
    document.querySelectorAll('.menu-item-container').forEach(m => m.classList.remove('active'));
  }
});

colorPicker?.addEventListener('input', (e) => {
  setStrokeColor(e.target.value);
});

if (toolLapiz) {
  const [smallBtn, largeBtn] = Array.from(toolLapiz.querySelectorAll('.icon-sub'));
  toolLapiz.querySelector('.icon-main')?.addEventListener('click', () => setDrawingMode('pencil'));
  smallBtn?.addEventListener('click', (e) => { e.stopPropagation(); setDrawingMode('pencil', 3); });
  largeBtn?.addEventListener('click', (e) => { e.stopPropagation(); setDrawingMode('pencil', 6); });
}

if (toolMarcador) {
  const [smallBtn, largeBtn] = Array.from(toolMarcador.querySelectorAll('.icon-sub'));
  toolMarcador.querySelector('.icon-main')?.addEventListener('click', () => setDrawingMode('highlighter', 12));
  smallBtn?.addEventListener('click', (e) => { e.stopPropagation(); setDrawingMode('highlighter', 16); });
  largeBtn?.addEventListener('click', (e) => { e.stopPropagation(); setDrawingMode('highlighter', 28); });
}

if (toolTrazo) {
  const [circleBtn, lineBtn] = Array.from(toolTrazo.querySelectorAll('.icon-sub'));
  toolTrazo.querySelector('.icon-main')?.addEventListener('click', () => setDrawingMode('rectangle', 4));
  circleBtn?.addEventListener('click', (e) => { e.stopPropagation(); setDrawingMode('circle', 4); });
  lineBtn?.addEventListener('click', (e) => { e.stopPropagation(); setDrawingMode('line', 4); });
}

if (toolText) {
  toolText.querySelector('.icon-main')?.addEventListener('click', () => setDrawingMode('text', 3));
}

if (toolEraser) {
  toolEraser.querySelector('.icon-main')?.addEventListener('click', () => setDrawingMode('eraser', 24));
}

toolNote.addEventListener('click', () => {
  document.getElementById('zoom_container').style.cursor = 'crosshair'
  activeNote = !activeNote;
});

btnActiveTools.addEventListener('click', function () {
  const imagen = btnActiveTools.querySelector('img');
  const items = Array.from(document.querySelectorAll('.menu-item-container'));
  const notas = Array.from(document.querySelectorAll('.dynamic-note'));

  toglePizara();

  if (imagen.src.includes('33.svg')) {
    imagen.src = 'icons/close_tools.svg';

    items.slice(1, -1).forEach(m => { m.classList.remove('btn-disabled'); m.classList.add('btn-enabled'); });

    notas.forEach(n => n.classList.add('d-none'));

    document.getElementById('colorPicker').classList.remove('btn-disabled');
    document.getElementById('colorPicker').classList.add('btn-enabled');
  } else {
    imagen.src = 'icons/33.svg';

    items.slice(1, -1).forEach(m => { m.classList.remove('btn-enabled'); m.classList.add('btn-disabled'); });

    notas.forEach(n => n.classList.remove('d-none'));

    document.getElementById('colorPicker').classList.remove('btn-enabled');
    document.getElementById('colorPicker').classList.add('btn-disabled');
  }

});

items.forEach(item => {
  item.addEventListener('click', function (e) {
    if (!activeNote) return;

    const nota = prompt('Escribe la nota que deseas fijar:');

    if (nota) {
      // Obtener las dimensiones del contenedor
      const rect = item.getBoundingClientRect();

      // Calcular la posición relativa al contenedor en píxeles
      const x = e.clientX - rect.left;
      const y = e.clientY - rect.top;

      // Convertir a porcentajes para mantener la posición relativa si el contenedor escala
      const xPercent = (x / rect.width) * 100;
      const yPercent = (y / rect.height) * 100;

      // Crear el nuevo elemento
      const newNote = document.createElement('div');
      newNote.className = 'dynamic-note';
      newNote.style.left = `${xPercent}%`;
      newNote.style.top = `${yPercent}%`;
      newNote.setAttribute('data-title', nota);

      if (esURL(nota)) {
        newNote.addEventListener('click', () => {
          window.open(nota, '_blank');
        });
      }

      newNote.innerHTML = `
        <svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<g filter="url(#filter0_d_35_4120)">
<circle cx="20" cy="16" r="16" fill="#6ECD60"/>
<rect x="11" y="8" width="18" height="18" fill="url(#pattern0_35_4120)"/>
</g>
<defs>
<filter id="filter0_d_35_4120" x="0" y="0" width="40" height="40" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
<feFlood flood-opacity="0" result="BackgroundImageFix"/>
<feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/>
<feOffset dy="4"/>
<feGaussianBlur stdDeviation="2"/>
<feComposite in2="hardAlpha" operator="out"/>
<feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.25 0"/>
<feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_35_4120"/>
<feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_35_4120" result="shape"/>
</filter>
<pattern id="pattern0_35_4120" patternContentUnits="objectBoundingBox" width="1" height="1">
<use xlink:href="#image0_35_4120" transform="scale(0.0078125)"/>
</pattern>
<image id="image0_35_4120" width="128" height="128" preserveAspectRatio="none" xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAACFAAAAhQByJdEOwAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAAbwSURBVHic7Z1diFVVFMd/Kz8aTUsx1BRkSipQxyn8CB+qAYvEiMSHeknDiOhBCokgkpI+CAcqsMDypawkUiGDKaMQtSzJmgc1FSzCj2qcUNKcUGb8WD2cK8zce8+559x7Pnaz1w/Wyz37rLPuXv9Z++y9z5krqorhL1cVHYBRLCYAzzEBeI4JwHNMAJ5jAvAcE4DnDE3DiYiMBSaXbDwwJA2/RgUXgG6gC/hDVXsadSj1LgSJyBxgUcmmNRqIURedwGfAFlU9VJcHVU1kwN3AbkDNnLKtQGvifCZI/Hjgcwe+qFm4XQbWA9ekKgCgBTjqwBc0i2d7gSlxclvzHkBE2oAOYFRkQ8M1/gLmq+rBqEaRAhCRm4E9wNh0YzNy4ghwh6qeDGsQKgARGQP8ANwa82IK/AIcAC4mi9OISRPQCjQnOGcXQSW4UPVoxLi/hng3He8AbcC1Se9AzeozYBxwH7AxRo4UWJHoHkBEmoHDwPAIZR0DHlPV7XFkaGSDiDwErCUQRRingKmqerb8QNhS8Cqik78NaLHkF4+qbgKmA/sjml0PrKh2oKICiMgIAsWMDHF2GpiuqicSR2tkhojMBH4i/A/3iKreVP5htQpwL+HJB1huyXcPVd0PvBTR5MaSSAZQTQCLIpx8o6ofJw3OyI124LeI4xW5rSaAGREOdiYMyMgRVb0EfBfRpCK31QQwKcJBZ9KgjNyJylFFbgcIQESG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JHIvyW2wlgYdrfbTCa04+EichwEWknuO9ojnnap0CLqm7NKq7BhHNvBl1BRGYAG6i9zHmFs8DTqro+s6AGIc5VAAl4hmBZOW7yvwVaLfnJcaoCiMgUgs2Ntpin9AEvAK+r6uWs4hrMOCMAEVkCvE38/w90AHhEVfdlF9Xgp/AhQETGichm4EPiJV+BN4DZlvzGKbQCiMgC4D3ghpinHCfY3dqZWVCeUUgFEJGRIrKW4Bm1uMnfAMy05KdL7hVAROYCHwG3xDzlb4IFpM3ZReUveVeAZcD3xE/+VwSLOpb8jMhbAHOJV3XOA8tVdYGqdmUck9c4Mw3sRyfB9O5w0YH4QOHTwH5cAl4G5lny88OVCvArsERV9xQdiG+4UAHWAbdb8ouhyArQDTyuql8UGIP3FFUBthBM7yz5BZO3AHoIXiVbrKqncr62UYU8h4BdwFK19widIo8K0Ac8B7RZ8t0j6wpge/aOk1UFUOBNbM/eebKoAMeB+aq6IwPfRsqE/n8Aww9cWAk0CsQE4DkmAM8xAXiOCcBzTACeYwLwHBOA5/wH2O/ouZdinqMAAAAASUVORK5CYII="/>
</defs>
</svg>

      `;

      item.prepend(newNote);
      const page = getPageForItem(item);
      saveNoteForPage(page, {
        left: xPercent,
        top: yPercent,
        text: nota,
        isUrl: esURL(nota)
      });
    }

    activeNote = false;


  });
});


function esURL(texto) {
  try {
    const url = new URL(texto);
    // Verificamos protocolos comunes para evitar "javascript:" o "data:" si no los quieres
    return url.protocol === "http:" || url.protocol === "https:";
  } catch (_) {
    return false;
  }
}