/**
 * Multi-step spotlight coach — dim scrim with cutout, title/body card, Next / Skip.
 * Copy via getSysMessage keys on each step; English fallbacks in callers.
 */
(function () {
  'use strict';

  const { useState, useEffect, useCallback, useRef } = React;

  const PAD = 8;
  /** Estimated coach card height for placement (px). */
  const CARD_EST_HEIGHT = 300;
  /** Tall cutouts (e.g. Flow Profile TV) — place coach centered, not on top of in-hole copy. */
  const HOLE_TALL_PX = 200;
  const DEFAULT_FALLBACK = {
    skip: 'Skip',
    next: 'Next',
    done: 'Done',
    dontShowAgain: "Don't show this again"
  };

  function clampRect(rect) {
    if (!rect || rect.width < 1 || rect.height < 1) return null;
    const vw = window.innerWidth || 390;
    const vh = window.innerHeight || 844;
    const top = Math.max(0, rect.top - PAD);
    const left = Math.max(0, rect.left - PAD);
    const right = Math.min(vw, rect.right + PAD);
    const bottom = Math.min(vh, rect.bottom + PAD);
    return {
      top,
      left,
      width: Math.max(24, right - left),
      height: Math.max(24, bottom - top)
    };
  }

  function SpotlightTour({
    open,
    steps,
    labels,
    showDontShowAgain,
    dontShowAgain,
    onDontShowAgainChange,
    onComplete,
    onSkip
  }) {
    const [stepIndex, setStepIndex] = useState(0);
    const [hole, setHole] = useState(null);
    const rafRef = useRef(null);

    const L = { ...DEFAULT_FALLBACK, ...(labels || {}) };
    const total = Array.isArray(steps) ? steps.length : 0;
    const step = total > 0 && stepIndex >= 0 && stepIndex < total ? steps[stepIndex] : null;
    const isLast = stepIndex >= total - 1;

    const measure = useCallback(() => {
      if (!open || !step || typeof step.resolveTarget !== 'function') {
        setHole(null);
        return;
      }
      try {
        const el = step.resolveTarget();
        if (!el || typeof el.getBoundingClientRect !== 'function') {
          setHole(null);
          return;
        }
        setHole(clampRect(el.getBoundingClientRect()));
      } catch (_) {
        setHole(null);
      }
    }, [open, step]);

    useEffect(() => {
      if (!open) {
        setStepIndex(0);
        setHole(null);
        return undefined;
      }
      measure();
      const onResize = () => {
        if (rafRef.current) cancelAnimationFrame(rafRef.current);
        rafRef.current = requestAnimationFrame(measure);
      };
      window.addEventListener('resize', onResize);
      window.addEventListener('scroll', onResize, true);
      const t = window.setTimeout(measure, 120);
      const retry =
        hole == null
          ? window.setInterval(() => {
              measure();
            }, 200)
          : null;
      const retryStop = retry ? window.setTimeout(() => window.clearInterval(retry), 3200) : null;
      return () => {
        window.removeEventListener('resize', onResize);
        window.removeEventListener('scroll', onResize, true);
        window.clearTimeout(t);
        if (retry) window.clearInterval(retry);
        if (retryStop) window.clearTimeout(retryStop);
        if (rafRef.current) cancelAnimationFrame(rafRef.current);
      };
    }, [open, stepIndex, measure, hole]);

    if (!open || !step) return null;

    const cardStyle = (() => {
      const maxWidth = 'min(92vw, 22rem)';
      const center = {
        top: '50%',
        left: '50%',
        transform: 'translate(-50%, -50%)',
        maxWidth
      };
      if (!hole) return center;

      const vh = window.innerHeight || 844;
      let safeTop = 12;
      try {
        safeTop = Math.max(12, parseInt(getComputedStyle(document.documentElement).getPropertyValue('--sat') || '0', 10) || 0);
      } catch (_) {}
      safeTop = Math.max(safeTop, 52);
      const safeBottom = 20;
      const belowTop = hole.top + hole.height + 12;

      if (hole.height >= HOLE_TALL_PX) {
        const centeredTop = Math.max(
          safeTop,
          Math.min(vh - safeBottom - CARD_EST_HEIGHT, (vh - CARD_EST_HEIGHT) * 0.38)
        );
        return {
          top: centeredTop,
          left: '50%',
          transform: 'translateX(-50%)',
          maxWidth
        };
      }

      if (belowTop + CARD_EST_HEIGHT <= vh - safeBottom) {
        return {
          top: belowTop,
          left: '50%',
          transform: 'translateX(-50%)',
          maxWidth
        };
      }

      const aboveAnchor = hole.top - 12;
      if (aboveAnchor - CARD_EST_HEIGHT >= safeTop) {
        return {
          top: aboveAnchor,
          left: '50%',
          transform: 'translate(-50%, -100%)',
          maxWidth
        };
      }

      const centeredTop = Math.max(safeTop, Math.min(vh - safeBottom - CARD_EST_HEIGHT, (vh - CARD_EST_HEIGHT) * 0.42));
      return {
        top: centeredTop,
        left: '50%',
        transform: 'translateX(-50%)',
        maxWidth
      };
    })();

    const handleNext = () => {
      if (isLast) {
        if (typeof onComplete === 'function') onComplete({ dontShowAgain: !!dontShowAgain });
      } else {
        setStepIndex((i) => Math.min(total - 1, i + 1));
      }
    };

    return (
      <div
        className="fixed inset-0 z-[270] [touch-action:manipulation]"
        role="dialog"
        aria-modal="true"
        aria-labelledby="sf-spotlight-tour-title"
        aria-describedby="sf-spotlight-tour-body"
      >
        {hole ? (
          <div
            className="pointer-events-none fixed rounded-2xl ring-2 ring-[#2DE2C5]/55"
            style={{
              top: hole.top,
              left: hole.left,
              width: hole.width,
              height: hole.height,
              boxShadow: '0 0 0 9999px rgba(0,0,0,0.78)'
            }}
            aria-hidden
          />
        ) : (
          <div className="pointer-events-none fixed inset-0 bg-black/78" aria-hidden />
        )}

        <div
          className="pointer-events-auto fixed z-[1] w-full px-4"
          style={cardStyle}
        >
          <div className="max-h-[min(70vh,22rem)] overflow-y-auto overscroll-y-contain rounded-2xl border border-[#2DE2C5]/35 bg-[#0c1018] px-5 py-5 shadow-[0_0_48px_-12px_rgba(45,226,197,0.45)] backdrop-blur-md">
            <p className="mb-2 font-mono text-[10px] uppercase tracking-[0.28em] text-[#2DE2C5]/80">
              {stepIndex + 1} / {total}
            </p>
            <h2 id="sf-spotlight-tour-title" className="text-base font-semibold leading-snug text-white">
              {step.title}
            </h2>
            <p id="sf-spotlight-tour-body" className="mt-3 text-sm leading-relaxed text-slate-300">
              {step.body}
            </p>
            {showDontShowAgain ? (
              <label className="mt-4 flex cursor-pointer items-start gap-2.5 text-left">
                <input
                  type="checkbox"
                  className="mt-0.5 h-4 w-4 shrink-0 rounded border-[#2DE2C5]/40 bg-black/40 accent-[#2DE2C5]"
                  checked={!!dontShowAgain}
                  onChange={(e) => {
                    if (typeof onDontShowAgainChange === 'function') {
                      onDontShowAgainChange(e.target.checked);
                    }
                  }}
                />
                <span className="text-xs leading-snug text-slate-400">{L.dontShowAgain}</span>
              </label>
            ) : null}
            <div className="mt-5 flex gap-2">
              <button
                type="button"
                className="min-h-[44px] flex-1 rounded-xl border border-white/15 bg-white/5 px-3 text-sm font-semibold text-slate-200"
                onClick={() => {
                  if (typeof onSkip === 'function') onSkip({ dontShowAgain: !!dontShowAgain });
                }}
              >
                {L.skip}
              </button>
              <button
                type="button"
                className="min-h-[44px] flex-[1.2] rounded-xl bg-gradient-to-r from-teal-400 to-teal-300 px-3 text-sm font-semibold text-black shadow-[0_0_22px_-6px_rgba(45,226,197,0.55)]"
                onClick={handleNext}
              >
                {isLast ? L.done : L.next}
              </button>
            </div>
          </div>
        </div>
      </div>
    );
  }

  window.SpotlightTour = SpotlightTour;
})();
