// Promo carousel — a fanned deck of product banners.
// Auto-flips through cards; clicking a card brings it to the top of the stack;
// clicking the front (active) card opens its product.

const { useState: useStateC, useEffect: useEffectC, useRef: useRefC, useCallback: useCallbackC } = React;

// Banner → product mapping. `route` is consumed by Dashboard's promo handler.
const PROMO_SLIDES = [
  {
    id: "person-check",
    img: "assets/promos/person-check.jpg",
    label: "Person Check",
    cta: "Open Person Check",
    route: "scan/new-person",
    badge: "Most popular",
    accent: "#3B5BF5"
  },
  {
    id: "face",
    img: "assets/promos/face.jpg",
    label: "Face Scan",
    cta: "Open Face Scan",
    route: "scan/face",
    badge: "New",
    accent: "#7C3AED"
  },
  {
    id: "dating-app",
    img: "assets/promos/dating-app.jpg",
    label: "Dating App Scan",
    cta: "Open Dating App Scan",
    route: "scan/dating-app",
    badge: "Hot",
    accent: "#EC4899"
  },
  {
    id: "tinder-sonar",
    img: "assets/promos/sonar.jpg",
    label: "Tinder Sonar",
    cta: "Open Tinder Sonar",
    route: "scan/tinder-sonar",
    badge: "Trending",
    accent: "#FF4458"
  }
];

const PROMO_INTERVAL = 5000;

function PromoCarousel({ onOpen }) {
  const n = PROMO_SLIDES.length;
  const [active, setActive] = useStateC(0);
  const [paused, setPaused] = useStateC(false);
  const timer = useRefC(null);

  const advance = useCallbackC(() => setActive(a => (a + 1) % n), [n]);
  const goPrev = useCallbackC(() => setActive(a => (a - 1 + n) % n), [n]);

  // Swipe / drag to navigate
  const swipe = useRefC({ x: 0, t: 0, dragged: false });
  const onSwipeStart = useCallbackC((e) => {
    const x = e.touches ? e.touches[0].clientX : e.clientX;
    swipe.current = { x, t: Date.now(), dragged: false };
  }, []);
  const onSwipeEnd = useCallbackC((e) => {
    const x = e.changedTouches ? e.changedTouches[0].clientX : e.clientX;
    const dx = x - swipe.current.x;
    if (Math.abs(dx) > 40) {
      swipe.current.dragged = true;
      dx < 0 ? advance() : goPrev();
    }
  }, [advance, goPrev]);

  // Auto-flip
  useEffectC(() => {
    if (paused) return;
    timer.current = setInterval(advance, PROMO_INTERVAL);
    return () => clearInterval(timer.current);
  }, [paused, advance]);

  const activeSlide = PROMO_SLIDES[active];

  return (
    <section
      className="promo"
      aria-roledescription="carousel"
      aria-label="Featured Sweepify products"
      onMouseEnter={() => setPaused(true)}
      onMouseLeave={() => setPaused(false)}
    >
      <div className="section__head">
        <div className="promo__headrow">
          <div className="section__title">Featured</div>
          <span className="promo__badge promo__badge--mobile" style={{ ['--badge-accent']: activeSlide.accent }}>
            {activeSlide.badge}
          </span>
        </div>
      </div>

      <div className="promo__viewport">
        <button className="promo__arrow promo__arrow--prev" aria-label="Previous" onClick={goPrev}>
          <span style={{ transform: "rotate(180deg)", display: "inline-flex" }}><IconArrowRight size={18} /></span>
        </button>
        <button className="promo__arrow promo__arrow--next" aria-label="Next" onClick={advance}>
          <IconArrowRight size={18} />
        </button>

        <div
          className="promo__stage"
          onTouchStart={onSwipeStart}
          onTouchEnd={onSwipeEnd}
          onPointerDown={onSwipeStart}
          onPointerUp={onSwipeEnd}
        >
          {PROMO_SLIDES.map((slide, i) => {
            // slot 0 = front; higher = further back in the fan
            const slot = (i - active + n) % n;
            const isFront = slot === 0;
            const style = {
              transform: `translate(${slot * 34}px, ${slot * 18}px) rotate(${slot * 1.6}deg) scale(${1 - slot * 0.045})`,
              zIndex: n - slot,
              opacity: slot > 3 ? 0 : 1 - slot * 0.06,
              pointerEvents: slot > 3 ? "none" : "auto"
            };
            return (
              <button
                key={slide.id}
                className={"promo__card" + (isFront ? " is-front" : "")}
                style={style}
                aria-hidden={!isFront}
                aria-label={isFront ? slide.cta : `Bring ${slide.label} to front`}
                onClick={() => {
                  if (swipe.current.dragged) { swipe.current.dragged = false; return; }
                  isFront ? onOpen(slide.route) : setActive(i);
                }}
              >
                <img className="promo__img" src={slide.img} alt={slide.label} draggable="false" />
                <span className="promo__badge" style={{ ['--badge-accent']: slide.accent }}>{slide.badge}</span>
                {isFront && (
                  <span className="promo__cta">
                    {slide.cta}
                    <IconArrowRight size={15} />
                  </span>
                )}
              </button>
            );
          })}
        </div>
      </div>

      <button
        className="promo__cta promo__cta--mobile"
        onClick={() => onOpen(activeSlide.route)}
      >
        {activeSlide.cta}
        <IconArrowRight size={15} />
      </button>

      <div className="promo__dockbar">
        <button className="promo__navbtn promo__navbtn--prev" aria-label="Previous" onClick={goPrev}>
          <span style={{ transform: "rotate(180deg)", display: "inline-flex" }}><IconArrowRight size={16} /></span>
        </button>
        <div className="promo__dots" role="tablist" aria-label="Choose featured product">
        {PROMO_SLIDES.map((slide, i) => (
          <button
            key={slide.id}
            role="tab"
            aria-selected={i === active}
            aria-label={slide.label}
            className={"promo__dot" + (i === active ? " is-active" : "")}
            onClick={() => setActive(i)}
          >
            {i === active && (
              <span
                key={active}
                className="promo__dot-fill"
                style={{
                  animationDuration: PROMO_INTERVAL + "ms",
                  animationPlayState: paused ? "paused" : "running"
                }}
              />
            )}
          </button>
        ))}
        </div>
        <button className="promo__navbtn promo__navbtn--next" aria-label="Next" onClick={advance}>
          <IconArrowRight size={16} />
        </button>
      </div>
    </section>
  );
}

Object.assign(window, { PromoCarousel, PROMO_SLIDES });

// ============================================================
// Scan image grid — the carousel banners as clickable tiles
// (replaces the boxed scan cards on the dashboard)
// ============================================================
function ScanImageGrid({ onOpen }) {
  return (
    <section>
      <div className="section__head">
        <div>
          <div className="section__title">Run a New Scan</div>
          <div className="section__sub">Pick a product to get started · results in under 2 minutes</div>
        </div>
      </div>
      <div className="scan-tiles">
        {PROMO_SLIDES.map(slide => (
          <button
            key={slide.id}
            className="scan-tile"
            aria-label={slide.cta}
            onClick={() => onOpen(slide.route)}
          >
            <img className="scan-tile__img" src={slide.img} alt={slide.label} draggable="false" />
            <span className="scan-tile__cta">
              {slide.cta}
              <IconArrowRight size={14} />
            </span>
          </button>
        ))}
      </div>
    </section>
  );
}

Object.assign(window, { ScanImageGrid });
