/* global React */
const { useState: useFlipState, useEffect: useFlipEffect } = React;

// A two-faced outfit card that flips on Y axis every few seconds.
// On each flip, the now-hidden face updates to the next outfit, so when
// it rotates back into view it shows a new image.
function FlipOutfitCard({
  outfits = [1,2,3,4,5,6,7,8,9,10,11,12],   // outfit indices to cycle through
  width = 240,
  intervalMs = 3800,                          // pause between flips
  flipMs = 700,                               // duration of the flip itself
}) {
  const N = outfits.length;
  const [tick, setTick] = useFlipState(0);
  const [frontIdx, setFrontIdx] = useFlipState(outfits[0]);
  const [backIdx, setBackIdx]   = useFlipState(outfits[1 % N]);

  // Drive the flip on an interval.
  useFlipEffect(() => {
    const id = setInterval(() => setTick((t) => t + 1), intervalMs);
    return () => clearInterval(id);
  }, [intervalMs]);

  // After each flip lands, swap the now-hidden face to the next outfit.
  useFlipEffect(() => {
    if (tick === 0) return;
    const next = outfits[(tick + 1) % N];
    const t = setTimeout(() => {
      if (tick % 2 === 1) setFrontIdx(next);
      else setBackIdx(next);
    }, flipMs);
    return () => clearTimeout(t);
  }, [tick, outfits, N, flipMs]);

  return (
    <div className="cc-flip-card" style={{ width }}>
      <div
        className="cc-flip-inner"
        style={{
          transform: `rotateY(${tick * 180}deg)`,
          transition: `transform ${flipMs}ms cubic-bezier(0.22, 0.61, 0.36, 1)`,
        }}
      >
        <FlipFace outfit={frontIdx} />
        <FlipFace outfit={backIdx} back />
      </div>
    </div>
  );
}

function FlipFace({ outfit, back = false }) {
  return (
    <div className={`cc-flip-face ${back ? 'cc-flip-face-back' : ''}`}>
      <div className="cc-outfit-figure">
        <img src={`assets/outfits/outfit-${String(outfit).padStart(2, '0')}.png`} alt="" />
      </div>
    </div>
  );
}

window.FlipOutfitCard = FlipOutfitCard;
