/* global React */
// HoverPreview — hover ≥250ms 浮出大張預覽 popover，自動避邊，src=null 不觸發

const { useState, useRef, useCallback } = React;

const HoverPreview = ({ src, children }) => {
  const [pos, setPos]     = useState(null); // { x, y } or null
  const timerRef          = useRef(null);
  const triggerRef        = useRef(null);

  const show = useCallback((e) => {
    if (!src) return;
    const rect   = e.currentTarget.getBoundingClientRect();
    timerRef.current = setTimeout(() => {
      // compute best position (prefer right of element, fallback left)
      const PW = 284, PH = 284;
      const vw = window.innerWidth, vh = window.innerHeight;
      let x = rect.right + 8;
      if (x + PW > vw - 8) x = rect.left - PW - 8;
      let y = rect.top;
      if (y + PH > vh - 8) y = vh - PH - 8;
      if (y < 8) y = 8;
      setPos({ x, y });
    }, 250);
  }, [src]);

  const hide = useCallback(() => {
    clearTimeout(timerRef.current);
    setPos(null);
  }, []);

  return (
    <span
      ref={triggerRef}
      style={{ display: "inline-block", lineHeight: 0 }}
      onMouseEnter={show}
      onMouseLeave={hide}
      onClick={hide}
    >
      {children}
      {pos && src && ReactDOM.createPortal(
        <div
          className="hover-preview-portal"
          style={{ left: pos.x, top: pos.y }}
        >
          <img
            src={src}
            alt=""
            onError={(e) => { e.currentTarget.style.display = "none"; }}
          />
        </div>,
        document.body
      )}
    </span>
  );
};

Object.assign(window, { HoverPreview });
