// Mobile detail slide-up — reuses desktop <DetailPanel/> verbatim.
//
// Per user pref (memory: feedback_mobile_reuse_detail_panel) we don't fork
// DetailPanel. This wrapper:
//   1. Returns null when there's no selected product AND we're not playing
//      the close animation.
//   2. Adds .r-detail-mobile .is-closed on mount, then swaps to .is-open on
//      the next animation frame so the panel slides up from the bottom.
//   3. On close, swaps back to .is-closed and waits for the CSS transition
//      to finish before telling the parent to unmount.

function MobileDetailSheet({ product, onClose, t, lang, dark, profile, allProducts, onSelectProduct }) {
  // We render DetailPanel while either (a) a product is selected, or
  // (b) the closing animation is still playing on the prior product.
  const [renderProduct, setRenderProduct] = React.useState(product);
  const closeTimerRef = React.useRef(null);

  // Keep the rendered product in sync when a new one is selected, or when
  // it goes null without a controlled close (e.g. parent reset).
  React.useEffect(() => {
    if (product) setRenderProduct(product);
  }, [product]);

  // Open animation: add r-detail-mobile + is-closed synchronously before
  // paint, force a style flush, then swap to is-open on the next animation
  // frame so the browser actually paints the off-screen state once before
  // transitioning back. Without the void-offsetHeight reflow + double-rAF,
  // the browser coalesces both class changes into a single paint and the
  // CSS transition never fires.
  React.useLayoutEffect(() => {
    if (!renderProduct) return;
    const panel = document.querySelector(".r-detail");
    if (!panel) return;
    panel.classList.add("r-detail-mobile", "is-closed");
    panel.classList.remove("is-open");
    // Force layout/style flush so is-closed is committed to a paint.
    void panel.offsetHeight;
    let raf2 = 0;
    const raf1 = requestAnimationFrame(() => {
      raf2 = requestAnimationFrame(() => {
        const p = document.querySelector(".r-detail");
        if (!p) return;
        p.classList.remove("is-closed");
        p.classList.add("is-open");
      });
    });
    return () => {
      cancelAnimationFrame(raf1);
      if (raf2) cancelAnimationFrame(raf2);
    };
  }, [renderProduct]);

  const handleClose = React.useCallback(() => {
    const panel = document.querySelector(".r-detail");
    if (!panel) {
      onClose();
      setRenderProduct(null);
      return;
    }
    // Replay the slide-down, then unmount.
    panel.classList.remove("is-open");
    panel.classList.add("is-closed");
    const finalize = () => {
      panel.removeEventListener("transitionend", onTransitionEnd);
      if (closeTimerRef.current) {
        clearTimeout(closeTimerRef.current);
        closeTimerRef.current = null;
      }
      onClose();
      setRenderProduct(null);
    };
    const onTransitionEnd = (e) => {
      // Only react to the transform transition (other props on .r-detail
      // also animate, e.g. background — ignore those).
      if (e.propertyName !== "transform") return;
      finalize();
    };
    panel.addEventListener("transitionend", onTransitionEnd);
    // Safety: if transitionend never fires (e.g. element detached), still
    // unmount after a bit more than the 320ms CSS transition.
    closeTimerRef.current = setTimeout(finalize, 400);
  }, [onClose]);

  // When product becomes null externally (e.g. parent clears it without
  // calling onClose), still play the close animation if we had one mounted.
  React.useEffect(() => {
    if (!product && renderProduct) {
      handleClose();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [product]);

  if (!renderProduct) return null;
  if (!window.DetailPanel) return null;

  return (
    <window.DetailPanel
      product={renderProduct}
      onClose={handleClose}
      t={t}
      lang={lang}
      dark={dark}
      profile={profile}
      allProducts={allProducts}
      onSelectProduct={onSelectProduct}
    />
  );
}

Object.assign(window, { MobileDetailSheet });
