---
// Centre - HAUT : Carte O mindmap (V1.3-D : onglet Chatbot retire, bandeau "Sommaire editorial" + legende).
//          MILIEU : preview article (V1.2-P) - inseree au clic journal-item-click.
//          BAS  : iframe carte AEP (toujours visible).
// V1.3-D : ChatbotV2 retire du DOM (backlog V2). Pour reactivation -> reintroduire le tab + panel.
// V1.4-C : cadre Carte O + bouton toggle desktop + drag fix (window listeners) + preview hydration (client:load) + transitions.
import CarteOWrapper from '../vue/CarteOWrapper.vue';
import EmbedDynamique from '../vue/EmbedDynamique.vue';
import PreviewArticle from '../vue/PreviewArticle.vue';
---
<!--
  V1.2-P : Col centre = flex column container.
  - Default : Carte O (1/3) + iframe AEP (2/3), pas de scroll vertical (h-full).
  - Preview ouverte : Carte O (33vh fixe) + Preview (auto) + iframe AEP (67vh fixe), overflow-y-auto.
  Flex-basis dynamique pilote via JS.
-->
<div
  id="col-centre-grid"
  class="flex flex-col gap-2 p-2"
  data-preview-open="false"
  style="height: 100%; overflow-y: hidden;"
>
  <!-- HAUT (default flex-1 base 33%) : V1.3-D bandeau "Sommaire editorial" + legende + Carte O plein espace
       V1.4-C1 : cadre 1px renforce (border-neutral-300) + transition height pour toggle collapse desktop -->
  <section
    id="col-centre-haut"
    class="rounded flex flex-col overflow-hidden bg-white"
    style="min-height: 0; flex: 1 1 33%; border: 1px solid #CBD5E1; border-radius: 6px; transition: flex-basis 0.3s ease, min-height 0.3s ease;"
    data-collapsed="false"
  >
    <!-- V1.3-D : bandeau header (titre gauche + legende droite) -->
    <header
      class="flex items-center justify-between gap-3 px-3 py-2 border-b border-neutral-200 shrink-0"
      style="font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;"
    >
      <span class="text-xs truncate" style="color: #475569;">
        Sommaire éditorial d'architecture d'écologie politique
      </span>
      <div class="flex items-center gap-3 shrink-0">
        <ul class="flex items-center gap-3 shrink-0 text-xs" style="color: #475569;" aria-label="Légende">
          <li class="flex items-center gap-1.5">
            <span
              aria-hidden="true"
              style="width: 8px; height: 8px; border-radius: 999px; background: #0F172A; display: inline-block;"
            ></span>
            <span>publié</span>
          </li>
          <li class="flex items-center gap-1.5">
            <span
              aria-hidden="true"
              style="width: 8px; height: 8px; border-radius: 999px; background: transparent; border: 1px solid #0F172A; display: inline-block;"
            ></span>
            <span>à venir</span>
          </li>
          <li class="flex items-center gap-1.5">
            <span
              aria-hidden="true"
              style="width: 8px; height: 8px; border-radius: 999px; background: #B45309; display: inline-block;"
            ></span>
            <span>projet</span>
          </li>
        </ul>
        <!-- V1.4-C2 : bouton toggle Carte O desktop (replier/deployer la zone HAUT) -->
        <button
          id="col-centre-haut-toggle-desktop"
          type="button"
          aria-label="Replier la Carte O"
          class="hidden md:inline-flex items-center justify-center w-5 h-5 text-neutral-500 hover:text-neutral-900 cursor-pointer transition-colors"
          style="font-size: 10px; line-height: 1;"
          title="Replier la Carte O"
        >
          <span id="col-centre-haut-toggle-icon">▼</span>
        </button>
      </div>
    </header>

    <div id="col-centre-haut-body" class="flex-1 overflow-hidden relative" style="transition: opacity 0.25s ease;">
      <div id="panel-mindmap" class="absolute inset-0">
        <CarteOWrapper client:visible />
      </div>
    </div>
  </section>

  <!-- Drag handle desktop - redimensionnement vertical md+ -->
  <div
    id="col-centre-drag-handle"
    class="hidden md:flex items-center justify-center h-2 cursor-row-resize hover:bg-neutral-200 transition-colors w-full -mt-1 -mb-1 shrink-0"
    aria-hidden="true"
  >
    <span class="block w-10 h-0.5 bg-neutral-300 rounded-full"></span>
  </div>

  <!-- Poignee repli zone HAUT - mobile only -->
  <button
    id="col-centre-poignee"
    type="button"
    aria-label="Replier ou deployer la Carte O"
    class="md:hidden flex items-center justify-center h-6 bg-neutral-100 border-y border-neutral-200 cursor-pointer w-full -mt-2 -mb-2 hover:bg-neutral-200 transition-colors shrink-0"
  >
    <span class="block w-8 h-0.5 bg-neutral-400 rounded-full"></span>
  </button>

  <!-- MILIEU (V1.2-P) : preview article inseree entre Carte O et iframe AEP.
       Pas de border ici - PreviewArticle.vue gere son propre conteneur.
       shrink-0 pour preserver sa taille auto, sinon flex pourrait l'ecraser.
       V1.4-E1 : client:load (vs client:visible) pour garantir hydration immediate des listeners
                  'preview-open' / 'journal-item-click' (le v-if rendait l'observer aveugle).
       V1.4-bis FIX 3 : le wrapper en display:contents masquait l'astro-island au flex layout.
       On passe en flex container explicite (column) + l'astro-island prend display:block.
       Quand mode=null, PreviewArticle renvoie rien → le slot ne prend pas de hauteur.
       Quand mode=manifeste/article, le slot grandit pour contenir la preview. -->
  <div id="col-centre-preview-slot" class="shrink-0 flex flex-col">
    <PreviewArticle client:load />
  </div>

  <!-- BAS (default flex-1 base 67%) : iframe carte AEP toujours visible
       V1.4-E2 : transition flex-basis 0.3s ease (smooth quand preview ouvre/ferme) -->
  <section
    id="col-centre-bas"
    class="border border-neutral-200 rounded overflow-hidden bg-white"
    style="min-height: 0; flex: 1 1 67%; transition: flex-basis 0.3s ease;"
  >
    <div class="h-full min-h-[60vh] md:min-h-[400px]">
      <EmbedDynamique client:visible />
    </div>
  </section>
</div>

<style>
  /* V1.4-bis FIX 3 : force l'astro-island a se comporter comme block dans le slot preview,
     sinon le default inline empeche le contenu Vue (border + bg) de se rendre correctement
     dans le flex column de la col centre. */
  #col-centre-preview-slot > astro-island {
    display: block;
    width: 100%;
  }
  /* V1.4-bis FIX 4 : scrollbar visible sur la col centre quand preview ouverte
     (overflow:auto au lieu de natif fin qui se cache). Style WebKit + Firefox. */
  #col-centre-grid[data-preview-open="true"] {
    scrollbar-width: thin;
    scrollbar-color: #94A3B8 #FAFAF7;
  }
  #col-centre-grid[data-preview-open="true"]::-webkit-scrollbar {
    width: 10px;
  }
  #col-centre-grid[data-preview-open="true"]::-webkit-scrollbar-track {
    background: #FAFAF7;
  }
  #col-centre-grid[data-preview-open="true"]::-webkit-scrollbar-thumb {
    background: #94A3B8;
    border-radius: 5px;
    border: 2px solid #FAFAF7;
  }
  #col-centre-grid[data-preview-open="true"]::-webkit-scrollbar-thumb:hover {
    background: #64748B;
  }
</style>

<script>
  // Poignee repli zone HAUT (mobile only) + toggle desktop V1.4-C2
  const grid = document.getElementById('col-centre-grid');
  const haut = document.getElementById('col-centre-haut');
  const bas = document.getElementById('col-centre-bas');
  const poignee = document.getElementById('col-centre-poignee');
  const toggleDesktop = document.getElementById('col-centre-haut-toggle-desktop');
  const toggleDesktopIcon = document.getElementById('col-centre-haut-toggle-icon');
  const hautBody = document.getElementById('col-centre-haut-body');

  // Sauvegarde flex-basis defaults pour restaure apres fermeture preview
  let defaultHautFlex = '1 1 33%';
  let defaultBasFlex = '1 1 67%';

  const applyRepliState = (replie: boolean) => {
    if (!grid || !haut) return;
    if (grid.dataset.previewOpen === 'true') return; // skip si preview ouverte
    if (replie) {
      haut.style.flex = '0 0 0%';
      haut.style.overflow = 'hidden';
      haut.style.minHeight = '0';
      poignee?.setAttribute('aria-label', 'Deployer la Carte O');
    } else {
      haut.style.flex = defaultHautFlex;
      haut.style.overflow = '';
      haut.style.minHeight = '0';
      poignee?.setAttribute('aria-label', 'Replier la Carte O');
    }
  };

  const savedRepli = sessionStorage.getItem('tf-haut-replie');
  applyRepliState(savedRepli === 'true');

  poignee?.addEventListener('click', () => {
    const current = sessionStorage.getItem('tf-haut-replie') === 'true';
    const next = !current;
    sessionStorage.setItem('tf-haut-replie', String(next));
    applyRepliState(next);
  });

  // V1.4-C2 : bouton toggle Carte O desktop (replier/deployer la zone HAUT).
  // Etat distinct de l'etat mobile (clef differente) pour permettre persistance par device.
  // Replie : flex 0 0 36px (juste le bandeau header reste visible), body masque.
  // Deploye : restaure flex-basis precedent (default 33% ou drag-resize sauvegarde).
  const applyDesktopCollapseState = (collapsed: boolean) => {
    if (!haut) return;
    if (grid && grid.dataset.previewOpen === 'true') return; // skip si preview ouverte (preview pilote la mise en page)
    if (collapsed) {
      haut.style.flex = '0 0 36px';
      haut.dataset.collapsed = 'true';
      if (hautBody) hautBody.style.opacity = '0';
      if (toggleDesktopIcon) toggleDesktopIcon.textContent = '▶';
      toggleDesktop?.setAttribute('aria-label', 'Deployer la Carte O');
      toggleDesktop?.setAttribute('title', 'Deployer la Carte O');
    } else {
      // Restaure flex-basis precedent (drag-resize ou default)
      haut.style.flex = defaultHautFlex;
      haut.dataset.collapsed = 'false';
      if (hautBody) hautBody.style.opacity = '1';
      if (toggleDesktopIcon) toggleDesktopIcon.textContent = '▼';
      toggleDesktop?.setAttribute('aria-label', 'Replier la Carte O');
      toggleDesktop?.setAttribute('title', 'Replier la Carte O');
    }
  };

  const savedDesktopCollapsed = sessionStorage.getItem('tf-carte-o-collapsed') === 'true';
  if (savedDesktopCollapsed) {
    // applique apres que defaultHautFlex soit defini (deja le cas)
    applyDesktopCollapseState(true);
  }

  toggleDesktop?.addEventListener('click', () => {
    const current = sessionStorage.getItem('tf-carte-o-collapsed') === 'true';
    const next = !current;
    sessionStorage.setItem('tf-carte-o-collapsed', String(next));
    applyDesktopCollapseState(next);
  });

  // V1.2-P : preview ouverte = container scrollable, Carte O et iframe AEP figes en vh.
  const applyPreviewState = (open: boolean) => {
    if (!grid || !haut || !bas) return;
    grid.dataset.previewOpen = String(open);
    if (open) {
      // Memorise les flex actuels avant override (au cas ou l'user a drag-resize)
      const curHautFlex = haut.style.flex;
      const curBasFlex = bas.style.flex;
      if (curHautFlex && !curHautFlex.startsWith('0 0')) defaultHautFlex = curHautFlex;
      if (curBasFlex) defaultBasFlex = curBasFlex;

      // Figer hauteurs : Carte O 33vh, iframe AEP 67vh - on perd le flex
      haut.style.flex = '0 0 33vh';
      bas.style.flex = '0 0 67vh';
      // Le container reste a 100% du parent (overflow-hidden de <main>),
      // mais on active le scroll interne pour passer Carte O -> Preview -> iframe AEP.
      grid.style.height = '100%';
      grid.style.minHeight = '';
      grid.style.overflowY = 'auto';
    } else {
      haut.style.flex = defaultHautFlex;
      bas.style.flex = defaultBasFlex;
      grid.style.height = '100%';
      grid.style.minHeight = '';
      grid.style.overflowY = 'hidden';
    }
  };

  // V1.2-P : ouverture preview article via journal-item-click
  // V1.3-E : ouverture preview unifiee via preview-open (article OU manifeste)
  const openPreview = () => {
    applyPreviewState(true);
    // Scroll vers la preview apres mount
    requestAnimationFrame(() => {
      const preview = document.querySelector('.preview-article');
      if (preview && grid) {
        const previewTop = (preview as HTMLElement).offsetTop;
        grid.scrollTo({ top: Math.max(0, previewTop - 8), behavior: 'smooth' });
      }
    });
  };
  window.addEventListener('journal-item-click', openPreview);
  window.addEventListener('preview-open', openPreview);
  window.addEventListener('preview-close', () => {
    applyPreviewState(false);
  });

  // Drag-resize desktop (>=768px) - desactive quand preview ouverte
  const dragHandle = document.getElementById('col-centre-drag-handle');

  if (dragHandle && grid && haut && bas) {
    let isDragging = false;
    let startY = 0;
    let startHautH = 0;
    let containerH = 0;

    // V1.4-bis FIX 1 : overlay full-screen pendant drag.
    // ROOT CAUSE : l'iframe AEP (EmbedDynamique) capture les pointer events des qu'on
    // depasse sa zone — mouseup tombe dans l'iframe et n'arrive jamais au parent window.
    // SOLUTION : creer un <div fixed inset-0 z-9998> AU MOMENT DU mousedown, qui
    // intercepte tous les events (mousemove + mouseup) pendant le drag. Au mouseup,
    // on retire l'overlay. Garantie : peu importe ce qu'il y a en dessous (iframe,
    // Vue island, browser chrome), l'overlay capte la fin du drag.
    const overlayDuringDrag = document.createElement('div');
    overlayDuringDrag.style.cssText = 'position:fixed;inset:0;z-index:9998;cursor:row-resize;display:none;background:transparent;';
    overlayDuringDrag.setAttribute('aria-hidden', 'true');
    document.body.appendChild(overlayDuringDrag);

    dragHandle.addEventListener('mousedown', (e: MouseEvent) => {
      if (grid.dataset.previewOpen === 'true') return;
      if (sessionStorage.getItem('tf-haut-replie') === 'true') return;
      if (sessionStorage.getItem('tf-carte-o-collapsed') === 'true') return;
      isDragging = true;
      startY = e.clientY;
      startHautH = haut.getBoundingClientRect().height;
      containerH = grid.getBoundingClientRect().height;
      document.body.style.cursor = 'row-resize';
      document.body.style.userSelect = 'none';
      // Suspend transitions pendant drag pour responsivite
      haut.style.transition = 'none';
      bas.style.transition = 'none';
      // Active l'overlay : capture tous les events tant qu'on draggue
      overlayDuringDrag.style.display = 'block';
      e.preventDefault();
    });

    const onMouseMove = (e: MouseEvent) => {
      if (!isDragging) return;
      const delta = e.clientY - startY;
      const newHautH = Math.min(Math.max(startHautH + delta, containerH * 0.2), containerH * 0.8);
      const hautPct = (newHautH / containerH) * 100;
      const basPct = 100 - hautPct;
      haut.style.flex = `1 1 ${hautPct.toFixed(1)}%`;
      bas.style.flex = `1 1 ${basPct.toFixed(1)}%`;
    };

    const stopDrag = () => {
      if (!isDragging) return;
      isDragging = false;
      // Retire l'overlay (rend le reste de la page de nouveau interactif)
      overlayDuringDrag.style.display = 'none';
      document.body.style.cursor = '';
      document.body.style.userSelect = '';
      // Restaure transitions
      haut.style.transition = 'flex-basis 0.3s ease, min-height 0.3s ease';
      bas.style.transition = 'flex-basis 0.3s ease';
      const hf = haut.style.flex;
      const bf = bas.style.flex;
      if (hf) {
        sessionStorage.setItem('tf-centre-haut-flex', hf);
        defaultHautFlex = hf;
      }
      if (bf) {
        sessionStorage.setItem('tf-centre-bas-flex', bf);
        defaultBasFlex = bf;
      }
    };

    // V1.4-bis : ecoute mousemove + mouseup SUR L'OVERLAY (le plus haut z-index garantit capture).
    overlayDuringDrag.addEventListener('mousemove', onMouseMove);
    overlayDuringDrag.addEventListener('mouseup', stopDrag);
    overlayDuringDrag.addEventListener('pointerup', stopDrag);
    overlayDuringDrag.addEventListener('mouseleave', stopDrag);
    // Backup window listeners (pour le cas tres rare ou l'overlay n'aurait pas pris le focus)
    window.addEventListener('mouseup', stopDrag);
    window.addEventListener('pointerup', stopDrag);
    window.addEventListener('blur', stopDrag);
    // Si la souris revient dans la fenetre sans bouton enfonce, on stoppe
    window.addEventListener('mouseenter', (e: MouseEvent) => {
      if (isDragging && e.buttons === 0) stopDrag();
    });

    // Restaurer position depuis sessionStorage
    const savedHF = sessionStorage.getItem('tf-centre-haut-flex');
    const savedBF = sessionStorage.getItem('tf-centre-bas-flex');
    if (savedHF && savedBF && sessionStorage.getItem('tf-haut-replie') !== 'true') {
      haut.style.flex = savedHF;
      bas.style.flex = savedBF;
      defaultHautFlex = savedHF;
      defaultBasFlex = savedBF;
    }

    // Double-click sur drag handle = reset default 1/3 + 2/3
    dragHandle.addEventListener('dblclick', () => {
      haut.style.flex = '1 1 33%';
      bas.style.flex = '1 1 67%';
      sessionStorage.removeItem('tf-centre-haut-flex');
      sessionStorage.removeItem('tf-centre-bas-flex');
      defaultHautFlex = '1 1 33%';
      defaultBasFlex = '1 1 67%';
    });
  }

  // V1.3-D : tabs Chatbot retires, plus de toggle a gerer (un seul panel Carte O).
</script>
