// ============================================================
// floating-dropdown.jsx — Dropdown panel via React Portal (s130)
// ------------------------------------------------------------
// Risolve il bug "tendina clippata sotto altri blocchi": il pannello
// dell'Autocomplete (o di qualsiasi altro popover) finiva dietro a
// .card { overflow: hidden } o sotto un Modal a z-index alto perché
// usava position:absolute dentro l'ancestor del trigger. Fix:
// renderizziamo il pannello come figlio di document.body via
// ReactDOM.createPortal, con position:fixed allineato al trigger via
// getBoundingClientRect(); così esce da qualunque clipping ancestor e
// vive in cima a tutto.
//
// Caratteristiche:
//  - Auto-flip up se non c'è abbastanza spazio sotto al trigger
//  - Riallinea su scroll (capture per intercettare anche scroll su
//    contenitori interni) + resize della finestra
//  - z-index 10000 (Modal del prototipo sta a ~1000)
//  - Niente "...rest" / spread JSX (vincolo Babel-in-browser, pattern
//    babel-in-browser-no-spread)
//
// Props:
//  - anchorRef: React.useRef puntato all'elemento ancora (input/button)
//  - open: boolean — quando false renderizza nulla
//  - children: contenuto del pannello (lista, messaggi, …)
//  - maxHeight?: number = 280 — altezza massima del pannello
//  - matchWidth?: boolean = true — larghezza = larghezza dell'ancora
//  - style?: object — merge sullo style del pannello (override
//    parziale; passa solo proprietà semplici, niente spread interno)
// ============================================================

function FloatingDropdown({
  anchorRef,
  open,
  children,
  maxHeight = 280,
  matchWidth = true,
  style,
}) {
  const [pos, setPos] = React.useState({ top: 0, left: 0, width: 0, flipUp: false, ready: false });

  React.useEffect(() => {
    if (!open) return undefined;
    function updatePos() {
      const el = anchorRef && anchorRef.current;
      if (!el) return;
      const rect = el.getBoundingClientRect();
      const vh = window.innerHeight || document.documentElement.clientHeight;
      const spaceBelow = vh - rect.bottom;
      const spaceAbove = rect.top;
      // se sotto non c'è spazio per almeno 180px del pannello, prova a flippare
      // sopra (solo se sopra c'è effettivamente più spazio).
      const wantFlip = spaceBelow < Math.min(maxHeight, 180) && spaceAbove > spaceBelow;
      setPos({
        top: wantFlip ? Math.max(8, rect.top - 4 - Math.min(maxHeight, spaceAbove - 8)) : rect.bottom + 2,
        left: rect.left,
        width: rect.width,
        flipUp: wantFlip,
        // se siamo in flip mode, l'altezza utile è ridotta dallo spazio sopra
        capHeight: wantFlip ? Math.min(maxHeight, spaceAbove - 12) : Math.min(maxHeight, spaceBelow - 8),
        ready: true,
      });
    }
    updatePos();
    // capture=true così intercettiamo scroll anche di contenitori intermedi
    // (es. <div class="main" style="overflow:auto">)
    window.addEventListener('scroll', updatePos, true);
    window.addEventListener('resize', updatePos);
    return () => {
      window.removeEventListener('scroll', updatePos, true);
      window.removeEventListener('resize', updatePos);
    };
  }, [open, anchorRef, maxHeight]);

  if (!open || !pos.ready) return null;

  // costruiamo lo style senza spread; eventuali override arrivano via prop
  // 'style' (oggetto piano).
  const baseStyle = {
    position: 'fixed',
    top: pos.top,
    left: pos.left,
    width: matchWidth ? pos.width : undefined,
    minWidth: matchWidth ? pos.width : undefined,
    maxHeight: pos.capHeight || maxHeight,
    overflowY: 'auto',
    background: 'var(--bg-1)',
    border: '1px solid var(--line)',
    borderRadius: 4,
    boxShadow: '0 8px 24px rgba(0,0,0,0.18)',
    zIndex: 10000,
  };
  if (style) {
    for (const k in style) {
      if (Object.prototype.hasOwnProperty.call(style, k) && style[k] !== undefined) {
        baseStyle[k] = style[k];
      }
    }
  }

  return ReactDOM.createPortal(
    React.createElement('div', { style: baseStyle, 'data-floating-dropdown': true }, children),
    document.body,
  );
}

Object.assign(window, { FloatingDropdown });
