// Lalaluxe booking — booking/screens/tbase.jsx
// Page: "tbase" — all of the toes on ONE screen: the base (acrylic, gel, or acrylic on the big toes and
// gel on the rest) on top, then the toe art.
// Toe art is the same menu as nail art (cfg.art), every tier of it; she selects one whole tier,
// charged once (artTier), on a line of its own, at the tier's toe price (toeTierPriceOf: the studio's toe set
// price, ten toes at its toe price, or the nail price where it set neither). A plain set lives on the
// first tier (a solid color, a french tip), so toes need one pick, as nails do (WholeToes below).
// Where the studio turns Build your own on (cfg.buildOwn), a switch at the top also lets her build her
// toes toe by toe (s.perToe, ToeByToe below): a look on each toe, and acrylic or gel on each
// (s.perToeBase), each toe priced on its own (toeLines, toeBaseLines).
// One screen per file. Load before app.jsx (see docs/architecture.md, "The no-build multi-file Babel contract").
function TBaseStep({ 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 byToe = offered && Array.isArray(s.perToe);

	// Built toe by toe, the toes are kept as s.perToe and the pieces on them as s.tart, and any toe on a
	// base other than the set's as s.perToeBase. The artist reads which toe gets what from a "Toes: …"
	// line and a "Toe base: …" line in the note, under any lines the look screen wrote. Back to the
	// whole set (perToe null), those lines go and her picks are toe art.
	const notes = s.contact?.notes || "";
	const toesLine = /^Toes: [^\n]*\n?/m;
	const basesLine = /^Toe base: [^\n]*\n?/m;
	const paint = (perToe, perBase = perToe ? s.perToeBase : null, tart = s.tart) => {
		const rest = notes.replace(toesLine, "").replace(basesLine, "");
		const own = perBase && perBase.some(Boolean) ? perBase : null;
		const bases = own && own.map((k) => k || s.tbase);
		const lines = [perToe && nailsNote(perToe, cfg.labels.art, "Toes", TOE_NAMES), bases && nailsNote(bases, cfg.labels.toesBase, "Toe base", TOE_NAMES)].filter(Boolean).map((l) => l + "\n").join("");
		const head = rest.match(/^(?:(?:Shape|Nails|Shapes): [^\n]*\n)*/)[0];
		set({
			perToe,
			perToeBase: own,
			tart: perToe ? pieces.filter((a) => perToe.includes(a)) : tart,
			contact: { ...s.contact, notes: head + lines + rest.slice(head.length) },
		});
	};
	// toes built toe by toe while the studio no longer offers it go back to her picks, by tier
	const stale = !offered && (Array.isArray(s.perToe) || Array.isArray(s.perToeBase));
	useEffect(() => {
		if (stale) paint(null);
	}, [stale]);
	// One toe is acrylic or gel. Acrylic on the big toes and gel on the rest is a base for the whole set,
	// so built toe by toe it is put on each toe as it reads: acrylic on both big toes, gel on the others.
	const split = (bases) => (s.tbase === "bigtoe" ? Array.from({ length: NAILS }, (_, i) => (bases || [])[i] || (i % 5 === 0 ? "acrylic" : "gel")) : bases);
	const unsplit = byToe && s.tbase === "bigtoe" && !(Array.isArray(s.perToeBase) && s.perToeBase.every(Boolean));
	useEffect(() => {
		if (unsplit) paint(s.perToe, split(s.perToeBase));
	}, [unsplit]);
	// what she leaves on one side of the switch comes back as she left it
	const kept = useRef({});
	// built toe by toe, what a tap on a toe puts on: a look ({ art }) or a base ({ base }). The one look
	// she had picked for the whole set, if just one, is picked up ready to tap onto toes.
	const [brush, setBrush] = useState(null);
	const buildOwn = (on) => {
		setBrush(null);
		if (!on) {
			kept.current.toes = { toes: s.perToe, bases: s.perToeBase };
			return paint(null, null, kept.current.whole || []);
		}
		kept.current.whole = s.tart;
		const back = kept.current.toes;
		if (back) return paint(back.toes, split(back.bases));
		if (s.tart.length === 1) setBrush({ art: s.tart[0] });
		paint(Array(NAILS).fill(null), split(null));
	};

	return (
		<div className="screen">
			<ScreenHead cfg={cfg} screen="tbase">
				Choose Your <em>Toes</em>
			</ScreenHead>
			<div className="body">
				{/* where the studio offers it, the first choice: one tier for all ten toes, or toes built toe by toe */}
				{offered && tiers.length > 0 && (
					<section className="block">
						<div className="art-mode" role="radiogroup" aria-label="How your toes are priced">
							<button role="radio" aria-checked={!byToe} className={byToe ? "" : "sel"} onClick={() => byToe && buildOwn(false)}>
								Whole Set
								<small>One Tier for Your Toes</small>
							</button>
							<button role="radio" aria-checked={byToe} className={byToe ? "sel" : ""} onClick={() => byToe || buildOwn(true)}>
								Build Your Own
								<small>Priced by the Toe</small>
							</button>
						</div>
					</section>
				)}

				{byToe ? (
					<ToeByToe cfg={cfg} s={s} tiers={tiers} pieces={pieces} paint={paint} brush={brush} setBrush={setBrush} />
				) : (
					<WholeToes cfg={cfg} s={s} set={set} tiers={tiers} pieces={pieces} offered={offered} />
				)}
			</div>
		</div>
	);
}

// All ten toes alike: a base, then the toe art ladder. As on the look screen she selects a whole tier,
// one button a rung, kept as its pieces (s.tart); she pays it once, at its toe price, and it covers
// everything in it and in the tiers below.
function WholeToes({ cfg, s, set, tiers, pieces, offered }) {
	const TDESC = {
		acrylic: "Sculpted acrylic on your toes",
		gel: "Gel polish on natural toenails",
		bigtoe: "Acrylic on your big toes, gel on the rest",
	};
	const bases = ["acrylic", "gel", "bigtoe"].filter((k) => cfg.toesBase[k] != null);
	const paying = artTier({ art: s.tart });
	const rank = paying ? tiers.indexOf(paying.id) : -1;
	return (
		<>
			<section className="block">
				<h3 className="co-section">Base</h3>
				<div className="opt-list">
					{bases.map((k) => (
						<button key={k} className={"opt " + (s.tbase === k ? "sel" : "")} aria-pressed={s.tbase === k} onClick={() => set({ tbase: k })}>
							<ToeIcon kind={k === "bigtoe" ? "acrylic" : k} />
							<div className="meta">
								<div className="name">{cfg.labels.toesBase[k]}</div>
								<div className="desc">{TDESC[k]}</div>
							</div>
							<div className="price">{priceTag(cfg.toesBase[k], "flat")}</div>
						</button>
					))}
				</div>
			</section>

			{tiers.length > 0 && (
				<section className="block">
					<h3 className="co-section">Toe Art</h3>
					<p className="custom-hint">
						Choose the highest tier your design needs. Lower tiers are included in the price.{offered ? " To choose each toe 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" : "";
							const price = toeTierPriceOf(t);
							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({ tart: 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> : (price > 0 ? <b>{priceTag(price)}</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">
													<ToeIcon art={cfg.content.artIcon?.[a] || "plain"} />
													<span className="art-name">{cfg.labels.art[a]}</span>
												</span>
											))}
										</span>
									</button>
								</li>
							);
						})}
					</ol>
				</section>
			)}
		</>
	);
}

// Her ten toes, drawn as two feet, and the bases and looks to put on them. As on the nails, nothing is
// put on for her: she picks a base or a look and taps, or swipes across, the toes it goes on; a tap
// never takes anything off, a mistake is painted over or undone (the Undo arrow). With no toe holding
// one yet, "All 10" puts the picked base or look on every toe; once some toes have one, "Remaining N"
// puts it on the ones still without. Each base and each tier says what one toe costs, and the feet,
// with what her toes cost so far, stay in view while she scrolls the looks.
function ToeByToe({ cfg, s, tiers, pieces, paint, brush, setBrush }) {
	const toes = s.perToe;
	const own = s.perToeBase || Array(NAILS).fill(null);
	// what a toe is done in: its own base, or the set's
	const baseOf = (i) => own[i] || s.tbase;
	// a toe given the set's own base simply keeps the set's base
	const baseTo = (k) => (k === s.tbase ? null : k);
	// a toe 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 ? baseTo(brush.base) : k))]);
	const { past, nudge, commit, tap, press, swipe, lift, undo } = usePaintTen(toes, own, brush, brushed, paint);
	// one toe is acrylic or gel (the big toe set is put on toe by toe as those two)
	const bases = ["acrylic", "gel"].filter((k) => cfg.toesBase[k] != null);
	// how many toes the picked base or look could still go on: the toes still without one
	const left = brush?.art ? toes.filter((a) => !a).length : brush?.base ? toes.filter((_, i) => !baseOf(i)).length : 0;
	// what her toes cost so far: each toe's base and its look
	const cost = [...(toeBaseLines(s) || []), ...(toeLines(s) || [])].reduce((sum, line) => sum + line.amt, 0);
	// the picked look (or base) on every toe still without one (all ten, when none has one)
	const fill = () => (brush.art ? commit(toes.map((a) => a || brush.art), own) : commit(toes, own.map((k, i) => (baseOf(i) ? k : baseTo(brush.base)))));
	// the feet as she looks down at them: the left runs little toe to big toe, the right big toe to
	// little toe, so the two big toes meet in the middle. The big toe is drawn largest and each toe
	// after it a little smaller, their tips stepping down to the little toe.
	const foot = (side, from) => (
		<div className="byn-hand byn-foot" role="group" aria-label={side + " foot"}>
			<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 = toes[i], b = baseOf(i);
				const said = !a && !b ? "no design or base selected" : (a ? cfg.labels.art[a] : "no design selected") + (b ? ", " + cfg.labels.toesBase[b] : ", no base selected");
				return (
					<button key={k} data-i={i} style={{ "--lift": TOE_LIFT[k], "--toe": TOE_SIZE[k] }} className={"byn-nail toe" + (a && b ? "" : " empty")} aria-label={`${side} ${TOE_NAMES[k][0]}: ${said}`} onClick={() => tap(i)}>
						<ToeIcon key={(a || "") + "|" + (b || "")} art={a ? cfg.content.artIcon?.[a] || "plain" : "bare"} base={b || undefined} />
						<span className="toe-tag">{b ? TOE_TAG[b] : "\u00a0"}</span>
					</button>
				);
			})}
		</div>
	);
	return (
		<section className="block byn">
			<div className="byn-hands byn-feet" onPointerDown={press} onPointerMove={swipe} onPointerUp={lift} onPointerCancel={lift}>
				<p className="byn-meter" aria-live="polite">Toes <b>{money(cost)}</b></p>
				{foot("Left", 0)}
				{foot("Right", 5)}
				<div className="byn-bar">
					{brush ? (
						<div className="byn-brush">
							{brush.art ? <ToeIcon art={cfg.content.artIcon?.[brush.art] || "plain"} /> : <ToeIcon kind={brush.base} />}
							<span>
								<b>{brush.art ? cfg.labels.art[brush.art] : cfg.labels.toesBase[brush.base]}</b>
								<small>Tap or swipe toes to apply</small>
							</span>
						</div>
					) : (
						<p key={nudge} className={"byn-say" + (nudge ? " nudge" : "")} aria-live="polite">
							<Ico name="down" />
							Choose a base or design, then tap the toes to apply it.
						</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>
						)}
						{left === NAILS && <button className="byn-act" onClick={fill}>All 10</button>}
						{left > 0 && left < NAILS && <button className="byn-act" onClick={fill}>Remaining {left}</button>}
					</div>
				</div>
			</div>
			<div className="byn-part">
				<h3 className="co-section">Base</h3>
				<div className="shape-row" role="radiogroup" aria-label="Bases">
					{bases.map((k) => {
						const each = Math.round((Number(cfg.toesBase[k]) || 0) / NAILS);
						const count = toes.filter((_, i) => baseOf(i) === k).length;
						const held = brush?.base === k;
						return (
							<button key={k} role="radio" aria-checked={held} className={"shape " + (held ? "sel" : "")} onClick={() => setBrush({ base: k })}>
								<ToeIcon kind={k} />
								<span className="shape-name">{cfg.labels.toesBase[k]}</span>
								<small className="shape-price">{each > 0 ? `${priceTag(each)} per toe` : " "}</small>
								<span className="art-on">{count > 0 ? `${count} ${count === 1 ? "toe" : "toes"}` : " "}</span>
							</button>
						);
					})}
				</div>
			</div>
			<div className="byn-part">
				<h3 className="co-section">Toe 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 = toePriceOf(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 toe</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={"Toe art, " + cfg.labels.tier[t]}>
									{mine.map((a) => {
										const count = toes.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 })}>
												<ToeIcon art={cfg.content.artIcon?.[a] || "plain"} />
												<span className="art-name">{cfg.labels.art[a]}</span>
												{count > 0 && <span className="art-on">On {count} {count === 1 ? "toe" : "toes"}</span>}
											</button>
										);
									})}
								</div>
							</li>
						);
					})}
				</ol>
			</div>
		</section>
	);
}

// each toe as the artist's note names one and both ("the left big toe", "both big toes"), big toe first
const TOE_NAMES = [["big toe", "big toes"], ["second toe", "second toes"], ["middle toe", "middle toes"], ["fourth toe", "fourth toes"], ["little toe", "little toes"]];
// a toe's base, said under it: a picture alone does not tell acrylic from gel at this size
const TOE_TAG = { acrylic: "Acrylic", gel: "Gel" };
// how big each toe is drawn against the big toe's box, and how far its tip rises, in em: the big
// toe largest, each toe after it smaller and lower
const TOE_SIZE = [1, 0.84, 0.76, 0.7, 0.62];
const TOE_LIFT = [0, 0.35, 0.3, 0.15, 0];
