// Lalaluxe booking — booking/screens/design.jsx
// Page: "design" — THE LOOK screen: the shape of the nail, then the art on it.
// Nail art is priced by tier. Every piece the studio offers sits in a tier (cfg.art → cfg.tier), and
// she picks the whole tier her design falls in, not a piece, charged once at that tier's set price
// (artTier). So the tiers are drawn as a ladder (WholeSet below) and each rung is one tap: each
// carries what its tier adds to her set ("+$20"), the rung she picks is marked and the rungs under it
// are covered. A plain set lives on the first rung (a solid color, a french tip), so one pick is
// required. Tiers, their prices and what sits in each are the studio's, edited in the console under
// Menu → Nail art.
// Where the studio turns Build your own on (cfg.buildOwn, Menu → Nail art), a switch at the top also
// lets her build her set nail by nail (s.perNail, NailByNail below), each nail at its tier's price a
// nail (nailLines). With it off, a set built before is taken back to her picks, priced by tier.
// One screen per file. Load before app.jsx (see docs/architecture.md, "The no-build multi-file Babel contract").
function DesignStep({ cfg, s, set }) {
	const tiers = orderedKeys(cfg.content.order?.tier, cfg.tier);
	const pieces = orderedKeys(cfg.content.order?.art, cfg.art);
	const offered = cfg.buildOwn === true;
	const byNail = offered && Array.isArray(s.perNail);
	const notes = s.contact?.notes || "";
	const setNotes = (v) => set({ contact: { ...s.contact, notes: v } });
	// the shapes are the studio's, edited in the console under Menu → Shapes, and one can add to the price
	const shapes = orderedKeys(cfg.content.order?.shape, cfg.labels.shape || {});
	// One shape for the set is kept as s.shape, which the bill prices, and as one "Shape: …" line at the
	// top of the note the artist reads.
	const shapeLine = /^Shape: [^\n]*\n?/;
	const pickShape = (k) => {
		const rest = notes.replace(shapeLine, "");
		const on = s.shape !== k;
		set({ shape: on ? k : null, contact: { ...s.contact, notes: on ? `Shape: ${cfg.labels.shape[k]}\n${rest}` : rest } });
	};
	// Built nail by nail, the nails are kept as s.perNail and the pieces on them as s.art, and any nail
	// cut differently from the set as s.perShape. The artist reads which nail gets what from a "Nails: …"
	// line and a "Shapes: …" line in the note, under any shape line. Back to the whole set (perNail null),
	// those lines go and her picks are art (the pieces that were on her nails, unless she had others).
	const nailsLine = /^Nails: [^\n]*\n?/m;
	const shapesLine = /^Shapes: [^\n]*\n?/m;
	const paint = (perNail, perShape = perNail ? s.perShape : null, art = s.art) => {
		const rest = notes.replace(nailsLine, "").replace(shapesLine, "");
		const own = perShape && perShape.some(Boolean) ? perShape : null;
		const lines = [perNail && nailsNote(perNail, cfg.labels.art, "Nails", FINGER_NAMES), own && nailsNote(own, cfg.labels.shape || {}, "Shapes", FINGER_NAMES)].filter(Boolean).map((l) => l + "\n").join("");
		const shape = rest.match(shapeLine)?.[0] || "";
		set({
			perNail,
			perShape: own,
			art: perNail ? pieces.filter((a) => perNail.includes(a)) : art,
			contact: { ...s.contact, notes: shape + lines + rest.slice(shape.length) },
		});
	};
	// a set built nail by nail while the studio no longer offers it goes back to her picks, by tier
	const stale = !offered && (Array.isArray(s.perNail) || Array.isArray(s.perShape));
	useEffect(() => {
		if (stale) paint(null);
	}, [stale]);
	// what she leaves on one side of the switch comes back as she left it
	const kept = useRef({});
	// built nail by nail, what a tap on a nail puts on: a look ({ art }) or a shape ({ shape }). The one
	// look she had picked for the whole set, if just one, is picked up ready to tap onto nails.
	const [brush, setBrush] = useState(null);
	const buildOwn = (on) => {
		setBrush(null);
		if (!on) {
			kept.current.nails = { nails: s.perNail, cuts: s.perShape };
			return paint(null, null, kept.current.whole || []);
		}
		kept.current.whole = s.art;
		const back = kept.current.nails;
		if (back) return paint(back.nails, back.cuts);
		if (s.art.length === 1) setBrush({ art: s.art[0] });
		paint(Array(NAILS).fill(null));
	};
	return (
		<div className="screen">
			<ScreenHead cfg={cfg} screen="design" sub={shapes.length ? undefined : byNail ? "Choose designs for each nail." : "Choose the highest tier your design needs."}>
				What’s Your <em>Look?</em>
			</ScreenHead>

			<div className="body">
				{/* where the studio offers it, the first choice: one tier for the whole set, or a set built nail by nail */}
				{offered && (
					<section className="block">
						<div className="art-mode" role="radiogroup" aria-label="How your set is priced">
							<button role="radio" aria-checked={!byNail} className={byNail ? "" : "sel"} onClick={() => byNail && buildOwn(false)}>
								Whole Set
								<small>One Tier for the Set</small>
							</button>
							<button role="radio" aria-checked={byNail} className={byNail ? "sel" : ""} onClick={() => byNail || buildOwn(true)}>
								Build Your Own
								<small>Priced by the Nail</small>
							</button>
						</div>
					</section>
				)}

				{byNail ? (
					<NailByNail cfg={cfg} s={s} tiers={tiers} pieces={pieces} shapes={shapes} paint={paint} brush={brush} setBrush={setBrush} />
				) : (
					<WholeSet cfg={cfg} s={s} set={set} tiers={tiers} pieces={pieces} shapes={shapes} pickShape={pickShape} offered={offered} />
				)}

				{s.art.length > 0 && (
					<section className="block">
						<h3 className="co-section">Describe Your Look</h3>
						{byNail && <p className="custom-hint">Your nail choices are saved here. Add colors or other details.</p>}
						<textarea
							aria-label="Describe your look"
							className="look-note"
							rows={3}
							placeholder="Colors, details to include or avoid."
							value={notes}
							onChange={(e) => setNotes(e.target.value)}
						/>
					</section>
				)}

				{s.art.length > 0 && (
					<section className="block">
						<h3 className="co-section">Inspiration Photos <small>Optional</small></h3>
						<p className="custom-hint">
							Add photos and note what to keep or change.
						</p>
						<InspoUpload s={s} set={set} />
					</section>
				)}
			</div>
		</div>
	);
}

// The whole set: a shape for the set, then the nail art ladder. She selects a whole tier, not a piece
// (the owner's ask: fewer taps, and a nail can carry more than one design): each rung is one button
// listing what is in that tier, and the tier she picks is kept as its pieces (s.art), so the bill and
// checkout price it as before (artTier), once, at the tier's set price. It covers everything in it
// and in the tiers below, so those rungs read "Covered". What her design is goes in the note below.
function WholeSet({ cfg, s, set, tiers, pieces, shapes, pickShape, offered }) {
	const paying = artTier(s);
	const rank = paying ? tiers.indexOf(paying.id) : -1;
	const picked = shapes.includes(s.shape) ? s.shape : null;
	// a fill-in keeps the set's shape, so no shape adds to it unless the studio turned that off (shapeFree)
	const shapesFree = shapeFree(s);
	// a price line on every tile once any shape has a price, so the names stay level
	const priced = !shapesFree && shapes.some((k) => Number(cfg.shapePrice?.[k]) > 0);
	// the art is shown on a nail cut the way she chose hers
	const cut = picked && cfg.content.shapeIcon?.[picked];
	return (
		<>
			{shapes.length > 0 && (
				<section className="block">
					<h3 className="co-section">Shape <small>Optional</small></h3>
					<ShapeStrip role="group" aria-label="Nail shape">
						{shapes.map((k) => {
							const add = shapesFree ? 0 : Number(cfg.shapePrice?.[k]) || 0;
							return (
								<button key={k} className={"shape " + (picked === k ? "sel" : "")} aria-pressed={picked === k} onClick={() => pickShape(k)}>
									<ShapeIcon cut={cfg.content.shapeIcon?.[k]} />
									<span className="shape-name">{cfg.labels.shape[k]}</span>
									{priced && <small className="shape-price">{add > 0 ? priceTag(add) : "\u00a0"}</small>}
								</button>
							);
						})}
					</ShapeStrip>
				</section>
			)}

			<section className="block">
				<h3 className="co-section">Nail Art</h3>
				<p className="custom-hint">
					Choose the highest tier your design needs. Lower tiers are included in the price.{offered ? " To choose each nail separately, select Build Your Own." : ""}
				</p>
				<ol className="tiers">
					{tiers.map((t, i) => {
						const mine = pieces.filter((a) => cfg.art[a] === t);
						if (!mine.length) return null;
						const state = i === rank ? "on" : i < rank ? "under" : "";
						return (
							<li key={t} className={("tier " + state).trim()}>
								<span className="tier-no" aria-hidden="true">{i + 1}</span>
								<button className="tier-body" aria-pressed={state === "on"} onClick={() => set({ art: mine })}>
									<span className="tier-head">
										<span className="tier-name">{cfg.labels.tier[t]}</span>
										<span className="tier-price">
											{state === "on" && <small>Your Tier</small>}
											{state === "under" ? <small>Covered</small> : (Number(cfg.tier[t]) > 0 ? <b>{priceTag(cfg.tier[t])}</b> : <small>Included</small>)}
										</span>
										{cfg.content.tierDesc?.[t] && <span className="tier-desc">{cfg.content.tierDesc[t]}</span>}
									</span>
									<span className="art-grid">
										{mine.map((a) => (
											<span key={a} className="art">
												<ArtIcon kind={cfg.content.artIcon?.[a]} shape={cut} />
												<span className="art-name">{cfg.labels.art[a]}</span>
											</span>
										))}
									</span>
								</button>
							</li>
						);
					})}
				</ol>
			</section>
		</>
	);
}

// Her ten nails, drawn as two hands, and the looks to put on them. Nothing is put on for her: she picks
// a look (or a shape) and taps, or swipes across, the nails it goes on. A tap always puts the picked
// look on a nail, so a second tap never takes it off; a mistake is painted over or undone (the Undo
// arrow). With bare nails, "All 10" puts the picked look on every nail, a matching set; once some
// nails wear something, "Remaining N" puts it on the ones still bare. Each tier says what one nail
// from it costs and what all ten do, and the hands, with what her nail art costs so far, stay in view
// while she scrolls the looks.
function NailByNail({ cfg, s, tiers, pieces, shapes, paint, brush, setBrush }) {
	const nails = s.perNail;
	const cuts = s.perShape || Array(NAILS).fill(null);
	// what a nail is cut to: its own shape (a set from before had one shape for all ten, s.shape)
	const cutOf = (i) => cfg.content.shapeIcon?.[cuts[i] || s.shape];
	const blank = nails.filter((a) => !a).length;
	// a nail given the old set's shape simply keeps it
	const cutTo = (k) => (k === s.shape ? null : k);
	// a nail under the brush
	const brushed = (n, c, i) => (brush.art ? [n.map((a, j) => (j === i ? brush.art : a)), c] : [n, c.map((k, j) => (j === i ? cutTo(brush.shape) : k))]);
	// a tap or a swipe across the nails puts the brush on; a tap with nothing picked shakes the line
	// that says what to do
	const { past, nudge, commit, tap, press, swipe, lift, undo } = usePaintTen(nails, cuts, brush, brushed, paint);
	// the picked look on every nail still bare (all ten, when all are bare); the picked shape on all ten
	const fill = () => commit(nails.map((a) => a || brush.art), s.perShape);
	const fillShape = () => commit(nails, Array(NAILS).fill(cutTo(brush.shape)));
	const allCut = brush?.shape && cuts.every((k) => (k || s.shape) === brush.shape);
	// what her nail art costs so far, each nail at its tier's price
	const artCost = (nailLines(s) || []).reduce((sum, line) => sum + line.amt, 0);
	const say = shapes.length ? "Choose a shape or design, then tap the nails to apply it." : "Choose a design, then tap the nails to apply it.";
	// the hands as she sees them, palms down: the left runs pinky to thumb, the right thumb to pinky,
	// so the two thumbs meet in the middle. The fingertips rise and fall the way a hand's do, and a
	// thumb is drawn broader, the way a thumbnail is.
	const hand = (side, from) => (
		<div className="byn-hand" role="group" aria-label={side + " hand"}>
			<span className="byn-side" aria-hidden="true">{side}</span>
			{(side === "Left" ? [4, 3, 2, 1, 0] : [0, 1, 2, 3, 4]).map((k) => {
				const i = from + k, a = nails[i], cut = cuts[i] || s.shape;
				const said = (a ? cfg.labels.art[a] : "no design selected") + (cut && cfg.labels.shape?.[cut] ? ", " + cfg.labels.shape[cut] : "");
				return (
					<button key={k} data-i={i} style={{ "--lift": FINGER_LIFT[k] }} className={"byn-nail" + (a ? "" : " empty") + (k === 0 ? " thumb" : "")} aria-label={`${side} ${FINGERS[k]}: ${said}`} onClick={() => tap(i)}>
						<ArtIcon key={(a || "") + "|" + (cut || "")} kind={a ? cfg.content.artIcon?.[a] : "bare"} shape={cutOf(i)} />
					</button>
				);
			})}
		</div>
	);
	return (
		<section className="block byn">
			<div className="byn-hands" onPointerDown={press} onPointerMove={swipe} onPointerUp={lift} onPointerCancel={lift}>
				<p className="byn-meter" aria-live="polite">Nail Art <b>{money(artCost)}</b></p>
				{hand("Left", 0)}
				{hand("Right", 5)}
				<div className="byn-bar">
					{brush ? (
						<div className="byn-brush">
							{brush.art ? <ArtIcon kind={cfg.content.artIcon?.[brush.art]} shape={cfg.content.shapeIcon?.[s.shape]} /> : <ShapeIcon cut={cfg.content.shapeIcon?.[brush.shape]} />}
							<span>
								<b>{brush.art ? cfg.labels.art[brush.art] : cfg.labels.shape[brush.shape]}</b>
								<small>{brush.art ? "Tap or swipe nails to apply" : "Tap nails to apply"}</small>
							</span>
						</div>
					) : (
						<p key={nudge} className={"byn-say" + (nudge ? " nudge" : "")} aria-live="polite">
							<Ico name="down" />
							{say}
						</p>
					)}
					<div className="byn-acts">
						{past.length > 0 && (
							<button className="byn-act byn-act--icon" aria-label="Undo" title="Undo" onClick={undo}>
								<Ico name="undo" />
							</button>
						)}
						{brush?.art && blank === NAILS && <button className="byn-act" onClick={fill}>All 10</button>}
						{brush?.art && blank > 0 && blank < NAILS && <button className="byn-act" onClick={fill}>Remaining {blank}</button>}
						{brush?.shape && !allCut && <button className="byn-act" onClick={fillShape}>All 10</button>}
					</div>
				</div>
			</div>
			{shapes.length > 0 && (
				<div className="byn-part">
					<h3 className="co-section">Shape <small>Optional</small></h3>
					<ShapeStrip role="radiogroup" aria-label="Shapes">
						{shapes.map((k) => {
							// a tenth of the shape's price a nail, to the cent, so a cheap shape still shows what it costs
						const each = s.service === "fillin" && cfg.shapeFreeOnFill !== false ? 0 : (Number(cfg.shapePrice?.[k]) || 0) / NAILS;
							const count = cuts.filter((x) => (x || s.shape) === k).length;
							const held = brush?.shape === k;
							return (
								<button key={k} role="radio" aria-checked={held} className={"shape " + (held ? "sel" : "")} onClick={() => setBrush({ shape: k })}>
									<ShapeIcon cut={cfg.content.shapeIcon?.[k]} />
									<span className="shape-name">{cfg.labels.shape[k]}</span>
									<small className="shape-price">{each > 0 ? `${priceTag(each)} per nail` : "\u00a0"}</small>
									<span className="art-on">{count > 0 ? `${count} ${count === 1 ? "nail" : "nails"}` : "\u00a0"}</span>
								</button>
							);
						})}
					</ShapeStrip>
				</div>
			)}
			<div className="byn-part">
			<h3 className="co-section">Nail Art</h3>
			<ol className="tiers">
				{tiers.map((t, i) => {
					const mine = pieces.filter((a) => cfg.art[a] === t);
					if (!mine.length) return null;
					const each = nailPriceOf(t);
					return (
						<li key={t} className="tier">
							<span className="tier-no" aria-hidden="true">{i + 1}</span>
							<div className="tier-head">
								<span className="tier-name">{cfg.labels.tier[t]}</span>
								<span className="tier-price">
									{each > 0 ? <b>{money(each)}</b> : <small>Included</small>}
									{each > 0 && <small className="tier-unit">per nail</small>}
									{each > 0 && <small className="tier-all">All 10: {money(each * NAILS)}</small>}
								</span>
								{cfg.content.tierDesc?.[t] && <span className="tier-desc">{cfg.content.tierDesc[t]}</span>}
							</div>
							<div className="art-grid" role="radiogroup" aria-label={cfg.labels.tier[t]}>
								{mine.map((a) => {
									const count = nails.filter((x) => x === a).length;
									const held = brush?.art === a;
									return (
										<button key={a} role="radio" aria-checked={held} className={"art " + (held ? "sel" : "")} onClick={() => setBrush({ art: a })}>
											<ArtIcon kind={cfg.content.artIcon?.[a]} shape={cfg.content.shapeIcon?.[s.shape]} />
											<span className="art-name">{cfg.labels.art[a]}</span>
											{count > 0 && <span className="art-on">On {count} {count === 1 ? "nail" : "nails"}</span>}
										</button>
									);
								})}
							</div>
						</li>
					);
				})}
			</ol>
			</div>
		</section>
	);
}

const FINGERS = ["thumb", "index", "middle", "ring", "pinky"];
// each finger as the artist's note names one and both ("the left ring", "both rings")
const FINGER_NAMES = [["thumb", "thumbs"], ["index", "index fingers"], ["middle", "middle fingers"], ["ring", "rings"], ["pinky", "pinkies"]];
// how far each fingertip rises above the thumb's, in em, the way the tips of a hand laid flat do
const FINGER_LIFT = [0, 0.55, 0.8, 0.6, 0.2];

// The shapes in one row she scrolls sideways. When she comes back to the screen with a shape picked
// that sits out of view, the row opens on it.
function ShapeStrip({ children, ...rest }) {
	const row = useRef(null);
	useEffect(() => {
		const el = row.current,
			on = el && el.querySelector(".sel");
		if (!on) return;
		const box = el.getBoundingClientRect(),
			tile = on.getBoundingClientRect();
		if (tile.left >= box.left && tile.right <= box.right) return;
		el.scrollLeft += tile.left - box.left - parseFloat(getComputedStyle(el).paddingLeft);
	}, []);
	return (
		<div ref={row} className="shape-row" {...rest}>
			{children}
		</div>
	);
}
