pages/ValuePartnership/PartnershipsPage/SlideView.jsxjavascript
import { useEffect, useRef, useState } from "react";
import PropTypes from "prop-types";
import { useTracking } from "../../../services/tracking/useTracking";
import { UIMCButton } from "@ui-marcom/react/button";
import { UIMCControlButton } from "@ui-marcom/react/control-button";
import { UIMCPagination } from "@ui-marcom/react/pagination";
// ui-marcom-pagination's own "compact" template renders a <ui-marcom-dropdown>
// for the page counter but never imports @ui-marcom/dropdown itself (likely a
// packaging oversight) - register it ourselves or the dropdown just sits
// inert/undefined (same fix as GlobeBottomNav.jsx; route-level code
// splitting means that page's own registration can't be relied on here).
import "@ui-marcom/dropdown";
import { QrCodeCanvas } from "./QrCodeCanvas";
import { resolveWebLink } from "./qrCodeLink";
import "./SlideView.scss";
import { useConfig } from "../../../services/config/config";

/**
 * Fullscreen presentation-deck viewer, ported from value-slideview.js
 * (minus the QR/congress-app "save highlights" checkbox mode, which lives in
 * PresentationBrowser, and the manual `<link rel=preload>` injection, replaced
 * by the browser's own image decoding/caching). Mount with `key={ppt.id}` so
 * opening a different deck resets `page` cleanly instead of syncing it via effect.
 *
 * @param {Object} props
 * @param {{id: string, content: string, pictures: string[]}} props.ppt
 * @param {number} [props.initialPage=1]
 * @param {Object} props.labels
 * @param {function(): void} props.onClose
 */
// ported verbatim from value-slideview.js's __disclaimer block, which hard-
// codes this the same way (not content/labels-driven there either)
const COPYRIGHT_NOTICE = "Unrestricted © Siemens Healthineers";

export const SlideView = ({ ppt, initialPage = 1, labels, onClose }) => {
  const [page, setPage] = useState(initialPage);
  const [qrOpen, setQrOpen] = useState(false);
  const total = ppt.pictures.length;
  const webLink = resolveWebLink(ppt.webLink);
  const { trackEvent, trackSlideOrStory } = useTracking();
  const { stageDevice } = useConfig();

  const isIpad = stageDevice == "ipad";

  // ppt_close on unmount, so every way out counts: the close buttons
  // ("button"), opening another deck, switching app/tab or the screensaver
  // reset ("left"). The deferred mounted-check skips StrictMode's simulated
  // unmount in dev.
  const openedAtRef = useRef(Date.now());
  const visitedPagesRef = useRef(new Set([initialPage]));
  const pageRef = useRef(page);
  pageRef.current = page;
  const closeReasonRef = useRef("left");
  const mountedRef = useRef(false);
  useEffect(() => {
    mountedRef.current = true;
    const openedAt = openedAtRef.current;
    const visitedPages = visitedPagesRef.current;
    return () => {
      mountedRef.current = false;
      setTimeout(() => {
        if (mountedRef.current) return;
        trackEvent?.("ppt_close", {
          element: ppt.content || ppt.id,
          payload: {
            pptId: ppt.id || ppt.content,
            reason: closeReasonRef.current,
            durationMs: Date.now() - openedAt,
            pagesViewed: visitedPages.size,
            lastPage: pageRef.current,
            totalPages: total,
          },
        });
      }, 0);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps -- the deck is fixed per mount (key={ppt.id})
  }, []);
  const handleClose = () => {
    closeReasonRef.current = "button";
    onClose();
  };
  // console.log(isIpad);

  // opening the deck is already tracked by PartnershipsPage (same story_view
  // event and storyId), so only page turns are tracked here. The same-page
  // guard drops the echo the pagination may emit when `page` changes through
  // a thumbnail click.
  const goToPage = (newPage, source) => {
    if (newPage === page) return;
    setPage(newPage);
    visitedPagesRef.current.add(newPage);
    trackSlideOrStory?.(ppt.id || ppt.content, newPage, { title: ppt.content || ppt.id, source });
  };

  // keeps the active thumbnail visible as `page` changes (Prev/Next,
  // thumbnail click, or a deep initialPage on mount) - .slide-view__thumbnails
  // scrolls independently of the rest of the bar, and nothing else keeps the
  // highlighted thumbnail (see --active in SlideView.scss) in view otherwise.
  // Scrolls only the strip itself, deliberately not scrollIntoView(): that
  // also scrolls every scrollable ancestor (overflow: hidden included) - near
  // the deck's end, where the strip is already maxed out and can't center the
  // thumbnail, it pushed the leftover offset onto Stage's .stage-outer and
  // shifted the whole app left. offsetLeft (strip is position: relative)
  // instead of getBoundingClientRect, which Stage's transform scale distorts.
  // Side navigation besides the slide (customer request: "navigate left/right
  // of the slide"). Kiosk: the slide is inset by Figma's 400px side padding
  // (SlideView.scss), so those otherwise dead gutters become prev/next tap
  // zones with a visible arrow. iPad: the slide spans the full width (no
  // gutters), so a horizontal swipe on the slide turns the page instead.
  const goPrev = (source) => page > 1 && goToPage(page - 1, source);
  const goNext = (source) => page < total && goToPage(page + 1, source);

  // horizontal swipe = a pointer drag that moved mostly sideways and far
  // enough. Real (unscaled) screen pixels - Stage's transform scale doesn't
  // matter for a threshold like this. Needs `touch-action: pan-y` on the
  // slide (SlideView.scss), else the browser claims the horizontal pan
  // itself and cancels the pointer stream before pointerup.
  const SWIPE_MIN_PX = 60;
  const swipeStartRef = useRef(null);
  const swipeHandlers = isIpad
    ? {
        onPointerDown: (e) => {
          swipeStartRef.current = { x: e.clientX, y: e.clientY };
        },
        onPointerUp: (e) => {
          const start = swipeStartRef.current;
          swipeStartRef.current = null;
          if (!start) return;
          const dx = e.clientX - start.x;
          const dy = e.clientY - start.y;
          if (Math.abs(dx) < SWIPE_MIN_PX || Math.abs(dx) < Math.abs(dy)) return;
          if (dx < 0) goNext("swipe");
          else goPrev("swipe");
        },
        onPointerCancel: () => {
          swipeStartRef.current = null;
        },
      }
    : {};

  const activeThumbRef = useRef(null);
  useEffect(() => {
    const thumb = activeThumbRef.current;
    const strip = thumb?.parentElement;
    if (!thumb || !strip) return;
    strip.scrollTo({
      left: thumb.offsetLeft + thumb.offsetWidth / 2 - strip.clientWidth / 2,
      behavior: "smooth",
    });
  }, [page]);

  return (
    <div className="slide-view">
      <div className="slide-view__slide" {...swipeHandlers}>
        <img src={ppt.pictures[page - 1]} alt="" draggable={false} />

        {!isIpad && page > 1 && (
          <div
            className="slide-view__side-nav slide-view__side-nav--prev"
            onClick={() => goPrev("side_nav")}>
            <UIMCControlButton icon="arrow-left-large" title={labels.previous} />
          </div>
        )}
        {!isIpad && page < total && (
          <div
            className="slide-view__side-nav slide-view__side-nav--next"
            onClick={() => goNext("side_nav")}>
            <UIMCControlButton icon="arrow-right-large" title={labels.next} />
          </div>
        )}

        {labels.showQRCode && webLink && (
          <UIMCButton
            className="slide-view__qr-trigger"
            variant="primary-cta"
            title={labels.showQRCode}
            onClick={() => {
              trackEvent?.("qr_code_open", {
                element: ppt.content || ppt.id,
                payload: { pptId: ppt.id },
              });
              setQrOpen(true);
            }}>
            <ui-marcom-icon slot="prefix" icon="arrow-right-medium"></ui-marcom-icon>
            {labels.showQRCode}
          </UIMCButton>
        )}
      </div>

      <div className="slide-view__nav">
        <div className="slide-view__nav-buttons">
          <UIMCControlButton
            icon="home"
            title="Home"
            onClick={handleClose}
            className="slide-view__nav-button--home"
          />
          <UIMCButton
            variant="standard"
            title={labels.backToOverview}
            onClick={handleClose}
            className="slide-view__nav-button--back">
            <ui-marcom-icon slot="prefix" icon="arrow-long-left"></ui-marcom-icon>
            {labels.backToOverview}
          </UIMCButton>
          {isIpad ? (
            <UIMCPagination
              className="slide-view__pagination"
              variant="compact"
              totalItems={total}
              itemsPerPage={1}
              currentPage={page}
              onChange={(newPage) => goToPage(newPage, "pagination")}
            />
          ) : (
            <UIMCPagination
              className="slide-view__pagination"
              variant="compact"
              totalItems={total}
              itemsPerPage={1}
              currentPage={page}
              i18n={{
                prev: labels.previous,
                next: labels.next,
                prevLabel: labels.previous,
                nextLabel: labels.next,
                separatorLabel: "of",
              }}
              onChange={(newPage) => goToPage(newPage, "pagination")}
            />
          )}
        </div>

        <div className="slide-view__thumbnails">
          {ppt.pictures.map((src, index) => {
            const isActive = index === page - 1;
            return (
              <div
                key={src}
                ref={isActive ? activeThumbRef : undefined}
                className={
                  isActive
                    ? "slide-view__thumbnail slide-view__thumbnail--active"
                    : "slide-view__thumbnail"
                }
                onClick={() => goToPage(index + 1, "thumbnail")}>
                <img src={src} alt="" loading="lazy" />
                <span>Slide {index + 1}</span>
              </div>
            );
          })}
        </div>

        <div className="slide-view__nav-meta">
          <span className="slide-view__copyright">{COPYRIGHT_NOTICE}</span>
        </div>
      </div>

      {qrOpen && (
        <div className="slide-view__qr-overlay" onClick={() => setQrOpen(false)}>
          <div className="slide-view__qr-card" onClick={(e) => e.stopPropagation()}>
            <div className="slide-view__qr-card-header">
              <h5 className="slide-view__qr-card-title">Scan your assets to read them later</h5>
              <UIMCControlButton
                className="slide-view__qr-card-close"
                icon="close"
                title="Schließen"
                onClick={() => setQrOpen(false)}
              />
            </div>
            <div className="slide-view__qr-card-content">
              <QrCodeCanvas url={webLink} size={440} />
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

SlideView.propTypes = {
  ppt: PropTypes.shape({
    id: PropTypes.string,
    content: PropTypes.string,
    pictures: PropTypes.arrayOf(PropTypes.string).isRequired,
  }).isRequired,
  initialPage: PropTypes.number,
  labels: PropTypes.object.isRequired,
  onClose: PropTypes.func.isRequired,
};