// TermTooltip.jsx — Composant tooltip moderne pour les termes immobiliers
// Convention du projet : NO import/export, React global, Babel in-browser.
//
// Usage :
//   <TermTooltip term="cap_rate">Cap rate</TermTooltip>
//   <TermTooltip term="dom" badge={false}>Jours sur marché</TermTooltip>
//
// Props :
//   term      {string}   — clé dans window.GLOSSARY
//   children  {node}     — label affiché (avec soulignement pointillé)
//   badge     {boolean}  — affiche le petit « ? » à côté (défaut : true)
//   placement {string}   — 'top' | 'bottom' | 'auto' (défaut : 'auto')

(function () {
  const { useState: useTT, useRef: useRefTT, useEffect: useEffTT, useCallback: useCBTT } = React;

  // ─── CSS injecté une seule fois ──────────────────────────────────────────────
  const STYLE_ID = 'term-tooltip-styles';
  if (!document.getElementById(STYLE_ID)) {
    const style = document.createElement('style');
    style.id = STYLE_ID;
    style.textContent = `
/* ── TermTooltip ─────────────────────────────────────────────────────── */

.ttooltip-anchor {
  display: inline-flex;
  align-items: baseline;
  gap: 3px;
  position: relative;
}

/* Soulignement pointillé sur le label */
.ttooltip-label {
  border-bottom: 1.5px dashed rgba(59, 130, 246, 0.55);
  cursor: help;
  text-decoration: none;
  transition: border-color 0.15s;
}

.ttooltip-anchor:hover .ttooltip-label,
.ttooltip-anchor:focus-within .ttooltip-label {
  border-bottom-color: rgba(59, 130, 246, 0.9);
}

/* Petit badge ? */
.ttooltip-badge {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 14px;
  height: 14px;
  border-radius: 50%;
  background: rgba(59, 130, 246, 0.12);
  color: rgba(59, 130, 246, 0.75);
  font-size: 9px;
  font-weight: 700;
  line-height: 1;
  cursor: help;
  flex-shrink: 0;
  transition: background 0.15s, color 0.15s;
  vertical-align: middle;
  margin-bottom: 1px;
}

.ttooltip-anchor:hover .ttooltip-badge,
.ttooltip-anchor:focus-within .ttooltip-badge {
  background: rgba(59, 130, 246, 0.22);
  color: #1d4ed8;
}

/* Popover flottant — rendu via ReactDOM.createPortal dans <body> */
.ttooltip-popover {
  position: fixed;
  z-index: 99999;   /* au-dessus de Leaflet (z=1000) et des modals (z=1200) */
  max-width: 280px;
  min-width: 200px;
  background: rgba(17, 24, 39, 0.96);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  color: #f9fafb;
  border-radius: 10px;
  padding: 12px 14px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.35), 0 2px 8px rgba(0, 0, 0, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.08);
  pointer-events: none;
  animation: ttooltip-in 0.15s ease-out both;
  font-family: var(--sans, "Inter", system-ui, sans-serif);
}

@keyframes ttooltip-in {
  from {
    opacity: 0;
    transform: translateY(4px) scale(0.97);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.ttooltip-term-label {
  font-size: 11px;
  font-weight: 700;
  text-transform: uppercase;
  letter-spacing: 0.07em;
  color: rgba(147, 197, 253, 0.9);  /* bleu clair */
  margin: 0 0 6px;
}

.ttooltip-def {
  font-size: 12.5px;
  line-height: 1.55;
  color: rgba(249, 250, 251, 0.95);
  margin: 0;
}

.ttooltip-example {
  font-size: 11.5px;
  color: rgba(156, 163, 175, 0.9);
  margin: 6px 0 0;
  font-style: italic;
  line-height: 1.4;
  border-top: 1px solid rgba(255, 255, 255, 0.08);
  padding-top: 6px;
}

/* Flèche du popover */
.ttooltip-arrow {
  position: absolute;
  width: 10px;
  height: 10px;
  background: rgba(17, 24, 39, 0.96);
  border: 1px solid rgba(255, 255, 255, 0.08);
  transform: rotate(45deg);
  pointer-events: none;
}

/* focus-visible pour accessibilité clavier */
.ttooltip-trigger:focus-visible {
  outline: 2px solid rgba(59, 130, 246, 0.7);
  outline-offset: 2px;
  border-radius: 3px;
}
    `;
    document.head.appendChild(style);
  }

  // ─── Composant Popover (rendu dans <body> via portal) ────────────────────────
  function TooltipPopover({ entry, anchorRect, placement }) {
    const OFFSET = 10; // px entre l'ancre et le popover
    const ARROW_SIZE = 10;

    if (!anchorRect) return null;

    const vw = window.innerWidth;
    const vh = window.innerHeight;

    // Largeur estimée du popover (max-width dans CSS)
    const POPOVER_W = 280;
    const POPOVER_H = 120; // estimation minimale

    // Décide si on affiche au-dessus ou en dessous
    let showAbove = placement === 'top';
    if (placement === 'auto') {
      const spaceBelow = vh - anchorRect.bottom;
      const spaceAbove = anchorRect.top;
      showAbove = spaceAbove > 150 && (spaceBelow < 160 || spaceAbove > spaceBelow);
    }

    // Position horizontale : centré sur l'ancre, clamped dans la fenêtre
    let left = anchorRect.left + anchorRect.width / 2 - POPOVER_W / 2;
    left = Math.max(8, Math.min(left, vw - POPOVER_W - 8));

    // Position verticale
    let top;
    let arrowTop;
    let arrowBottom;
    if (showAbove) {
      top = anchorRect.top - POPOVER_H - OFFSET;
      arrowBottom = -(ARROW_SIZE / 2);
      arrowTop = undefined;
    } else {
      top = anchorRect.bottom + OFFSET;
      arrowTop = -(ARROW_SIZE / 2);
      arrowBottom = undefined;
    }

    // Position horizontale de la flèche : pointe vers le centre de l'ancre
    const anchorCenterX = anchorRect.left + anchorRect.width / 2;
    const arrowLeft = Math.max(10, Math.min(anchorCenterX - left - ARROW_SIZE / 2, POPOVER_W - 20));

    const popoverStyle = {
      left: Math.round(left),
      top: Math.round(top),
    };

    const arrowStyle = {
      left: Math.round(arrowLeft),
      ...(arrowTop !== undefined ? { top: arrowTop } : { bottom: arrowBottom }),
    };

    return ReactDOM.createPortal(
      <div
        className="ttooltip-popover"
        style={popoverStyle}
        role="tooltip"
        id={`ttooltip-${entry.id}`}
      >
        {/* Flèche */}
        <div className="ttooltip-arrow" style={arrowStyle} aria-hidden="true" />

        {/* Contenu */}
        <p className="ttooltip-term-label">{entry.label}</p>
        <p className="ttooltip-def">{entry.short_def}</p>
        {entry.example && (
          <p className="ttooltip-example">{entry.example}</p>
        )}
      </div>,
      document.body
    );
  }

  // ─── Composant principal TermTooltip ────────────────────────────────────────
  function TermTooltip({ term, children, badge = true, placement = 'auto' }) {
    const [visible, setVisible] = useTT(false);
    const [anchorRect, setAnchorRect] = useTT(null);
    const anchorRef = useRefTT(null);

    const entry = window.GLOSSARY && window.GLOSSARY[term];

    // Si le terme n'existe pas dans le glossaire, rendu simple sans tooltip
    if (!entry) {
      return <span>{children}</span>;
    }

    function updateRect() {
      if (anchorRef.current) {
        setAnchorRect(anchorRef.current.getBoundingClientRect());
      }
    }

    function handleShow() {
      updateRect();
      setVisible(true);
    }

    function handleHide() {
      setVisible(false);
    }

    // Ferme le tooltip si la fenêtre défile (évite le décalage)
    useEffTT(() => {
      if (!visible) return;
      const onScroll = () => setVisible(false);
      window.addEventListener('scroll', onScroll, { passive: true, capture: true });
      return () => window.removeEventListener('scroll', onScroll, { capture: true });
    }, [visible]);

    return (
      <span
        className="ttooltip-anchor"
        ref={anchorRef}
        onMouseEnter={handleShow}
        onMouseLeave={handleHide}
        onFocus={handleShow}
        onBlur={handleHide}
        onTouchStart={(e) => {
          // Tap mobile : toggle
          if (visible) {
            handleHide();
          } else {
            e.preventDefault();
            handleShow();
          }
        }}
        aria-describedby={visible ? `ttooltip-${entry.id}` : undefined}
      >
        {/* Label avec soulignement pointillé */}
        <span className="ttooltip-label ttooltip-trigger" tabIndex={0}>
          {children}
        </span>

        {/* Badge ? optionnel */}
        {badge && (
          <span className="ttooltip-badge" aria-hidden="true">?</span>
        )}

        {/* Popover flottant */}
        {visible && (
          <TooltipPopover
            entry={entry}
            anchorRect={anchorRect}
            placement={placement}
          />
        )}
      </span>
    );
  }

  // Expose en global
  window.TermTooltip = TermTooltip;

})();
