// Lalaluxe booking — booking/screens/intro.jsx: home (step "intro"), the lookbook with the headline on it.
// The home screen's lookbook: the studio's recent sets, each photo filling the screen in turn. It
// works like a story: a bar per photo runs along the top, a tap on the right goes on, a tap on the
// left goes back, holding a finger down pauses, and left alone the page turns itself. The headline
// (passed as children) sits on the photo. A page can be a video clip instead: it plays silent over
// its own first frame and holds the page for as long as it runs. Photos, clips, labels and their
// order come from Look → Photos in the console. Intro, at the end of the file, is the screen.

// how long a photo holds before the page turns on its own
const LOOK_DWELL = 6000;
// a press longer than this was a hold to pause, not a tap to move on
const LOOK_HOLD = 350;

// A clip, laid over the photo of its own first frame. It runs while its page is in view, stops for
// a held finger and rewinds when the page turns. `onAt` is told how far through it is (0 to 1) for
// the bar. Where it cannot play — an unsupported file, a phone saving power — the frame stays, and
// under reduced motion the clip is not put on the page at all.
function LookClip({ src, shown, near, run, loop, onAt, onStart, onEnd }) {
	const ref = useRef(null);
	const [live, setLive] = useState(false);
	useEffect(() => {
		const v = ref.current;
		if (!v) return;
		if (!shown) {
			v.pause();
			if (v.currentTime) v.currentTime = 0;
			return setLive(false);
		}
		if (!run) return v.pause();
		v.muted = true; // set by hand as well: a phone will not start a clip it thinks has sound
		const started = v.play();
		if (started) started.catch(() => {});
	}, [shown, run]);
	// the bar is read off the clip itself, so a slow connection or a held finger stops both together
	useEffect(() => {
		if (!shown) return;
		let frame = requestAnimationFrame(function tick() {
			const v = ref.current;
			if (v && v.duration > 0 && v.duration < Infinity) onAt(v.currentTime / v.duration);
			frame = requestAnimationFrame(tick);
		});
		return () => cancelAnimationFrame(frame);
	}, [shown, onAt]);
	return (
		<video
			ref={ref}
			className={"rw-img rw-clip" + (live ? " live" : "")}
			src={mediaUrl(src)}
			muted
			playsInline
			loop={loop}
			preload={shown ? "auto" : near ? "metadata" : "none"}
			disablePictureInPicture
			disableRemotePlayback
			tabIndex={-1}
			aria-hidden="true"
			onPlaying={() => { setLive(true); onStart(); }}
			onEnded={onEnd}
		/>
	);
}

function RecentWorkCard({ item, idx, warm, shown, near, clip }) {
	const name = item.label || `Portfolio photo ${idx + 1}`;
	// the seeded photos ship a 400px cut beside the full one; console uploads are a single file
	const cuts = item.sm && item.src && item.sm !== item.src ? `${mediaUrl(item.sm)} 400w, ${mediaUrl(item.src)} 1000w` : undefined;
	return (
		<div className="rw-card" aria-hidden={shown ? undefined : true}>
			<img
				className="rw-img"
				src={mediaUrl(item.src || item.sm)}
				srcSet={cuts}
				sizes={cuts && "(max-width: 640px) 100vw, 36vw"}
				alt={name}
				loading={idx < 2 || warm ? "eager" : "lazy"}
				fetchPriority={idx === 0 ? "high" : undefined}
				draggable={false}
			/>
			{item.video && clip && <LookClip src={item.video} shown={shown} near={near} {...clip} />}
		</div>
	);
}

function RecentWork({ gallery, children }) {
	const trackRef = useRef(null);
	const count = gallery ? gallery.length : 0;
	// the photo in view
	const [at, setAt] = useState(0);
	// The first two photos load with the page. The rest are fetched once it has settled, so they
	// are already there when the page turns instead of arriving as empty frames.
	const [warm, setWarm] = useState(false);
	useEffect(() => {
		const id = setTimeout(() => setWarm(true), 1200);
		return () => clearTimeout(id);
	}, []);

	const measure = useCallback(() => {
		const t = trackRef.current;
		if (!t || !t.clientWidth) return;
		setAt(Math.max(0, Math.min(t.children.length - 1, Math.round(t.scrollLeft / t.clientWidth))));
	}, []);

	useEffect(() => {
		const t = trackRef.current;
		if (!t) return;
		measure();
		t.addEventListener("scroll", measure, { passive: true });
		window.addEventListener("resize", measure);
		return () => {
			t.removeEventListener("scroll", measure);
			window.removeEventListener("resize", measure);
		};
	}, [gallery, measure]);

	const still = () => window.matchMedia("(prefers-reduced-motion: reduce)").matches;
	const show = useCallback((i, glide) => {
		const t = trackRef.current;
		if (!t) return;
		t.scrollTo({ left: i * t.clientWidth, behavior: glide && !still() ? "smooth" : "instant" });
	}, []);

	// The page turns itself. A finger or pointer held on the photo pauses it; letting go starts the
	// wait again (`turn` restarts both the timer and the bar). Reduced motion: nothing moves on its own.
	const [holding, setHolding] = useState(false);
	const [turn, setTurn] = useState(0);
	const pressed = useRef(0);
	const auto = count > 1 && !holding && !still();
	const next = () => {
		// from the last photo it starts over without the long rewind
		if (at + 1 >= count) show(0, false);
		else show(at + 1, true);
	};
	// A clip holds its page for as long as it runs and turns it when it ends, so once the clip in
	// view has started the photo's wait is off. A clip that never starts is left as its photo.
	const [rolling, setRolling] = useState(-1);
	useEffect(() => setRolling(-1), [at]);
	useEffect(() => {
		if (!auto || rolling === at) return;
		const id = setTimeout(() => {
			if (document.hidden) return setTurn((n) => n + 1);
			next();
		}, LOOK_DWELL);
		return () => clearTimeout(id);
	}, [auto, at, count, turn, show, rolling]);
	// the bar of the page in view; a clip fills it as it plays
	const bar = useRef(null);
	const fill = useCallback((part) => { if (bar.current) bar.current.style.setProperty("--at", part); }, []);
	const hold = () => { pressed.current = performance.now(); setHolding(true); };
	const release = () => { setHolding(false); setTurn((n) => n + 1); };

	// A tap cuts straight to the next photo, as a story does; after the last it starts over.
	const step = (dir) => {
		const i = Math.min(at, count - 1);
		if (dir > 0) show(i + 1 >= count ? 0 : i + 1, false);
		else if (i > 0) show(i - 1, false);
		setTurn((n) => n + 1);
	};
	const onTap = (e) => {
		if (performance.now() - pressed.current > LOOK_HOLD) return;
		const box = e.currentTarget.getBoundingClientRect();
		step(e.clientX - box.left < box.width * 0.3 ? -1 : 1);
	};
	const onKey = (e) => {
		if (e.key !== "ArrowRight" && e.key !== "ArrowLeft") return;
		e.preventDefault();
		step(e.key === "ArrowRight" ? 1 : -1);
	};

	if (!count) return null;
	const i = Math.min(at, count - 1);
	const two = (n) => String(n).padStart(2, "0");

	return (
		<section className="rw" style={{ "--dwell": LOOK_DWELL + "ms" }}>
			<div
				className="rw-track"
				ref={trackRef}
				role="group"
				aria-roledescription="carousel"
				aria-label="Recent sets. Tap the right side or press Right Arrow for the next photo; tap the left side or press Left Arrow for the previous photo."
				tabIndex={0}
				onClick={onTap}
				onKeyDown={onKey}
				onPointerDown={hold}
				onPointerUp={release}
				onPointerCancel={release}
				onPointerLeave={holding ? release : undefined}
			>
				{gallery.map((g, n) => (
					<RecentWorkCard key={(g.src || "") + n} item={g} idx={n} warm={warm} shown={n === i} near={warm && n === (i + 1) % count}
						clip={still() ? null : { run: !holding, loop: count === 1, onAt: fill, onStart: () => setRolling(n), onEnd: auto ? next : undefined }} />
				))}
			</div>

			<div className="rw-bars" aria-hidden="true">
				{gallery.map((g, n) => {
					const clip = n === i && g.video && !still();
					return <i key={n === i && !clip ? `${n}-${turn}` : n} ref={n === i ? bar : undefined} className={n < i ? "done" : clip ? "cur clip" : n === i ? (auto ? "cur run" : "cur") : undefined} />;
				})}
			</div>

			{/* with a mouse there is no thumb to guess with: show which side does what */}
			<span className="rw-hint rw-hint--back" aria-hidden="true"><Ico name="back" /></span>
			<span className="rw-hint rw-hint--next" aria-hidden="true"><Ico name="next" /></span>

			<div className="rw-foot">
				<p className="rw-plate" aria-live="polite">
					<span>{two(i + 1)} / {two(count)}</span>
					<span key={i}>{gallery[i].label || "Recent Set"}</span>
				</p>
				{children}
			</div>
		</section>
	);
}

// Home: the lookbook. The studio's photos are the screen; the headline rides on them.
function Intro({ cfg }) {
	const GALLERY = getGallery(cfg);
	// the studio writes both lines under Look → Titles; the second is set in italic over the brush
	const { lead = "", accent = "" } = cfg?.content?.headline || {};
	const headline = (lead || accent) ? <h1 className="hero__headline">{lead}{lead && accent && <br />}{accent && <em>{accent}</em>}</h1> : null;

	return (
		<div className="screen hero-screen" data-screen-label="Landing">
			{/* with no photos set in the console, the painting stands in */}
			{GALLERY.length ? (
				<RecentWork gallery={GALLERY}>{headline}</RecentWork>
			) : (
				<section className="rw">
					<div className="hero__art"><HandStage ext={62} label="" /></div>
					<div className="rw-foot">{headline}</div>
				</section>
			)}
		</div>
	);
}
