App · project 13 of 37

Look Blueprint.

Set who you are today, pick beard, hair or brow goals and mix styles, then follow a month-by-month plan in a lit barber's mirror: it counts your days, shows your barber what to do and puts every visit in your calendar.

Open the project ↗Get the skill and the code
After: A month-by-month plan in a lit barber's mirror with a cleanup template on the face, a day count, a card to show your barber, every visit in your calendar and a prompt that keeps your face. Before: AI pictures of "my future beard" that show someone else's face, and a barber who takes two inches off every visit.

BeforeAI pictures of "my future beard" that show someone else's face, and a barber who takes two inches off every visit.

AfterA month-by-month plan in a lit barber's mirror with a cleanup template on the face, a day count, a card to show your barber, every visit in your calendar and a prompt that keeps your face.

What it is worthA plan from today to the goal that tells you when to book, a barber card that protects your length, and a prompt that says when it cannot keep your face. Instead of guessing for months, and AI images that quietly change your face.

More like this: small apps for everyday life ›

How to use it

  1. Now: pick who you are today (gender, skin tone) and tap your hair and brows as they are, plus your beard for Man or Neutral. Turn the sound up; it plays even on an iPhone set to silent.
  2. Goal: tap what you want to change (one or more), then mix and match the styles and watch them grow in the mirror.
  3. Pick how long you can give it and your top 3 priorities. Your plan opens by itself.
  4. How: watch it play month by month. Read the jobs under the picture, tap Before and After to see what this month's cleanup removes, and tap a color to see only that zone. Tap the picture to pause.
  5. Tap I start today (or enter the day you started). From then on the plan opens on your month and tells you when to book the next visit. Tap Add visits to my calendar to save every visit, with what to say, to your phone calendar.
  6. At the visit, tap Show my barber (or Show on any checkpoint card) and hold the card up in the chair. Then tap Get my AI prompt, take a front and a side photo and send them with the prompt to an image AI. Every 3 months, take new photos and run it again.

Where it helps most

  • Growing out a beard or long hair without a barber or stylist taking the length back at every visit.
  • Knowing exactly what to trim, and what to leave alone, in the awkward months.
  • Seeing a realistic end look and timeline before committing months to it, for any gender and any mix of hair, brows and beard.
  • Anyone whose AI pictures keep turning into someone else: the prompt locks the face and says when it cannot.
  • Sticking to a plan over months: it counts your days, tells you when to book, and the barber card says exactly what to cut and what to keep.

The idea

I wanted to grow a long beard and asked AI to show me how it would look. Every picture changed my face: different eyes, younger, someone else. So I wrote a long prompt that locks the face, analyzes what is really there, compares styles and checks its own work before showing anything. It worked, but nobody else would write a prompt that long. Look Blueprint turns it into five taps for any goal, for men and women, and hands back the plan and the prompt for free.

The build

Claude built it as one page that works as one app: a stage on top that keeps the same character on every step, a panel underneath, and one button at the bottom that always moves you on. One drawing function makes any gender and skin tone and mixes 8 hairstyles, 4 brow shapes and, for men and neutral, 9 beard shapes, with length in centimeters deciding the shape; beards and mustaches are fitted to each face by its eyes and mouth, and women get no beard or mustache options. Growth follows the usual averages: scalp and beard hair about 1.25 cm (half an inch) a month and brows 3 to 4 months to fill in, so a short timeframe honestly says when the full look will arrive. Each month gets a phase per area (awkward early months, first shape check, shaping, keeping), and the phase decides that month's jobs, the zones drawn on the face, the regrowth shown in Before, what After removes, and what to say at the checkpoint. The Now and Goal steps are narrated in one voice (Kokoro, af_heart) through Web Audio and play on an iPhone set to silent. Everything was checked across hundreds of combinations of gender, goals, styles and timeframes, then reviewed twice by a separate checker that had not seen the build. Answers stay in your browser. Limits: the pictures are cartoons, not you; hair grows at different rates for different people; and many image AIs still drift a face, which is why the prompt falls back to marking up your real photos instead of faking a likeness. The look is a barbershop station so it does not read like a template app: a brass mirror frame with bulbs around the stage, a mint tile wall (bottle green at night, with a neon glow on the title), a pinstriped barber cape, a barber-pole progress bar and a magenta accent chosen to stay clear of the four zone colors; type is Big Shoulders Display for headings and Figtree for text, both stored on the site. The tracker keeps only the start day in this browser (nothing is sent anywhere); the calendar file is a standard .ics with one all-day event per checkpoint visit (script, jobs and a reminder three days before) and a weekly tidy reminder.

Free to take

Build your own.

Copy the skill, paste it into your own AI, and say what you want different. How to use a skill, step by step ›

Get the skillThe instructions your AI follows. Works in Claude, ChatGPT, Gemini or any other

# Master prompt: Look Blueprint

You are a product designer, a front-end developer and a grooming consultant (master barber, senior stylist, brow specialist). Build "Look Blueprint": a free, phone-first web app where anyone sets who they are today, picks beard, hair or brow goals and mixes styles, then watches a month-by-month plan play on a cartoon of themselves with a color template of what to do each month, and finally copies a master prompt that makes an image AI keep their real face.

DELIVERABLE
One page (index.html, one CSS file, one JS file), no libraries or CDN, no inline scripts or style attributes, so it runs under a strict Content-Security-Policy (markup built in script may carry style="..."; apply those through element.style.cssText). Local woff2 fonts (Big Shoulders Display, Figtree). Light and dark themes from one set of tokens (prefers-color-scheme and data-theme on <html>); redraw on theme change. Dark mode must read well: a slightly lighter stage, and a thin light rim on dark hair silhouettes and regrowth marks.

JOURNEY: NOW, GOAL, HOW
- Header: name, voice on/off, a 3-part progress bar: 1 Now, 2 Goal, 3 How. How unlocks once a plan exists. No separate tutorial: each step has one short line under its title saying why it matters.
- A persistent SVG stage (360x320) shows the same character on every step; one action bar (Back + one main button) always moves forward.
- NOW, one screen, "Who are you today?": Man / Woman / Neutral, 4 skin tones, Hair today (Bald, Buzz, Short, Curly, Chin-length, Shoulder, Long), Beard today (None, Stubble, Short, Medium, Long), Brows today (Thin, Sparse, Medium, Full). The picture shows exactly what is picked. Women get no beard or mustache anywhere (no Beard today row, no Beard goal, no beard in mix and match or in a "Something else" goal); switching to Woman drops any beard picks.
- GOAL 1, what to change: Hair, Brows, Beard for men and neutral (any combination) or Something else (area text, goal sentence, how far along). Anything not picked stays as it is today.
- GOAL 2, mix and match: tiles for 9 beard shapes (clean-shaven, stubble, short boxed, goatee, mustache, tapered, rounded-square, ducktail, natural wide), 8 hairstyles (shaved, buzz, short crop, curly volume, chin bob, shoulder U, long layers, long blunt) and 4 brow shapes (straight, soft arch, high arch, feathered). Goal areas grow from today to the pick on the stage; non-goal areas can be restyled to see the whole look.
- GOAL 3, timeframe 3/6/12/18/24 months (auto-advance). GOAL 4, priorities: tap 3 in order, taken in turn from each goal area (cut-down goals get their own list); keeping the face is always #1. Drop priorities that no longer fit when goals change; open the plan only when the third is added.

LOOK: A BARBERSHOP STATION, NOT A TEMPLATE APP
- The stage is a lit vanity mirror: brass gradient frame with round bulbs down both sides (they flicker on once when the app opens; glow at night), behind the glass a tile wall with a soft spotlight and a diagonal glass sheen. The character wears a pinstriped barber cape (SVG pattern), never a plain shirt.
- Colors: mint tile wall and white cards by day (#D2F0E4 paper, #FFFFFF cards, #0F2E2A ink), deep teal at night (#04201F, #0B3532) with a neon glow on the title and the day count; one magenta accent (#C2185B day, #FF5FA2 night) for labels, selections and the tracker, so it never clashes with the zone colors (green #22A84A, yellow #F2B705, red #E8382E, blue #2370F0); hot brass (#FFDC78 to #E8991A) for the frame and the main button; barber red #E3263A and royal blue #1F4FD1 only on the barber poles.
- A small spinning barber pole next to the title; the 3-part progress bar is a barber-pole stripe that moves on the current step. Selected tiles get a magenta ring and a check badge. Month cards hang on a timeline rail like an appointment book; the month's jobs under the mirror sit on a notched slip.
- Type: Big Shoulders Display (700/800) for headings and big numbers, Figtree (400-800) for everything else; no monospace, no all-caps labels, no arrows on buttons, no middle-dot separators. Buttons say what happens (Next: my goal, See my plan, Get my AI prompt).

DRAWING
One person() function draws any gender and skin tone, with beard (drawn in a man-sized frame, then fitted to each face by its eyes, mouth and width, so the mustache sits just above the lips), hair (in a woman-sized frame scaled to the head) and brows. Length is in centimeters and decides the shape: hair under 2 cm is a buzz shadow, under 9 cm a short cap, then lengths with a hem that follows the style; curly is a rounded cloud that sits high so the face stays clear; beards under 1 cm are stubble shadow; the mustache style draws only the mustache. Natural curl texture inside longer beards.

NATURAL GROWTH
Scalp and beard hair about 1.25 cm (half an inch) a month; brows fill in over 3 to 4 months. Each goal area: amount at month m = min(target, start + rate x m); if start is longer than the target it is cut on day one and then kept. Phase per area from progress: now, early (up to 30%), mid (to 65%), late, goal (reached). If the timeframe is too short, say when the full look arrives (plan and prompt).

HOW: THE MONTH-BY-MONTH PLAN
- Auto-plays month by month on the stage (about 3 s per month, growth tweened between months; reduced motion steps without tweening). Tap the picture or the button to pause/resume; resume keeps the current month; ‹ › step months.
- Directly under the picture, never over it: the month, the growth so far, and that month's jobs with color dots (one line per goal area when there are several).
- The color template drawn on the face for that month: green = let grow / leave alone, yellow = shape lightly (with a dashed target line in late months), red = clean up, blue = detail. Zones that have no job this month stay faint. Geometry follows each style (cheek patches, neckline, outline curls, lip line; side lines and ear rings for short hair; hem and face-framing for long hair; ring and front curls for curly; brow body, ticks on top, between and below, tail).
- Before / After scissors and cleanup: Before draws a month of regrowth (curls past the outline, flyaways, cheek and neck strays, lip hairs, split ends, brow strays); After removes only what this month's jobs remove and leaves what is not due yet (for example outline curls stay through the awkward phase). Picking a month in After snips the removed marks away.
- Legend that explains each color for that month per area, with "This month" / "Not yet" tags; On/Off; tap a color to isolate it; All/area tabs for several goals (start on one area when there are three).
- A card for every month (face with its template, growth, jobs); checkpoint months add a script for the barber, stylist or brow artist, with Copy. Weekly rules. Copy my whole plan as text.

FOLLOW IT: DAY TRACKER, BARBER CARD, CALENDAR
- Tracker card at the top of How: I start today, or a date picker for the day you started (kept only in this browser, with try/catch). Then: Day N of the plan's total days (30.4375 days a month), a barber-pole progress bar, which month's jobs you are on, and the next checkpoint visit with its date and days left. Buttons: See this month, Show my barber (Show at my visit when the pro is more than one), Add visits to my calendar, Change start day. With a start day the plan opens on today's month instead of playing from the start; past the end it says to take new photos and set the next goal.
- Barber card: a full-screen bright sheet (bright even in dark mode, large type) to hold up in the chair: the face with that visit's template, the visit and date, what to say in big text, and what to let grow, clean up, shape and detail; Earlier visit / Later visit; Esc and Close return focus; focus stays inside. Open it from the tracker or from Show on any checkpoint card.
- Calendar file (.ics, CRLF, lines folded at 75 bytes, text escaped): one all-day event per upcoming checkpoint (summary like "Barber visit, month 6", the script, that month's jobs and the expected length, an alarm 3 days before to book) plus a weekly tidy event (RRULE weekly for the plan's length) with the clean-up, leave-alone and never rules. On the web it is a normal download; inside Claude it goes through the page's downloads capability.

THE AI PROMPT (last step of How)
Photo checklist (front, side, daylight, no filters), the master prompt with the visitor's answers highlighted, Copy, three fixes (face changed, too thick, keeps failing), adjustable fields, and why it works. The prompt: role; objective and ranked priorities (face first) plus the realistic end-of-plan look when the timeframe is short; identity lock (only the goal areas may change; do not preserve brows when brows are the goal); analysis labeled observed vs assumed; forced comparison of four styles per area; target and timeline visuals; color zone map on the visitor's own photos; tools; maintenance; quality control with an honest fallback (mark up real photos instead of faking a likeness).

VOICE
Short Kokoro af_heart clips for the Now and Goal steps through Web Audio; on the first tap set navigator.audioSession.type='playback' and fall back to a silent looping <audio> on older iPhones, so it plays on silent. Show "No sound? Turn the volume up and tap once" on the Now screen.

STRESS TEST BEFORE SHIPPING
Every gender x goal set x style x timeframe (hundreds of combinations) through every month: no errors, no NaN/undefined/[placeholder] in anything visible. Check the template sits on the right part of the face for every style and gender, the explanation strip never covers the face, priorities follow the goals, playback pause/resume/end, reduced motion, 320 to 420 px wide, landscape, light and dark, restore after reload and with storage blocked; tracker at day 1, mid-plan and past the end, the calendar file against the standard, and the barber card by keyboard. Then hand it to a fresh reviewer who has not seen the build.
Get the code4 files, exactly as they run on this site · free under the MIT license

The first three files are exactly what runs at sghadimi.com/look, with six font files in fonts/ (Big Shoulders Display and Figtree, SIL Open Font License) and 14 voice clips in audio/ (Kokoro af_heart, plus a 1-second silent file for older iPhones). kit/site.py builds them from the single-file preview.

index.html132 lines

Raw file

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>Look Blueprint: your grooming plan and AI prompt</title>
<meta name="description" content="Free: set your look today, pick beard, hair or brow goals, watch a month-by-month plan on the face and get an AI prompt that keeps your own face. No sign-up.">
<link rel="icon" href="/favicon.svg">
<link rel="stylesheet" href="./look.css">
</head>
<body>
<svg width="0" height="0" class="defs" aria-hidden="true"><defs><pattern id="tex" width="7" height="9" patternUnits="userSpaceOnUse"><path d="M1.5 0 q2.5 4.5 0 9" stroke="rgba(255,255,255,.09)" fill="none"/><path d="M5 0 q-2 4.5 0 9" stroke="rgba(0,0,0,.25)" fill="none"/></pattern><filter id="rim" x="-15%" y="-15%" width="130%" height="130%"><feMorphology in="SourceAlpha" operator="dilate" radius="1.1" result="d"/><feFlood flood-color="#fff" flood-opacity=".38"/><feComposite in2="d" operator="in" result="o"/><feMerge><feMergeNode in="o"/><feMergeNode in="SourceGraphic"/></feMerge></filter><pattern id="cape" width="9" height="9" patternUnits="userSpaceOnUse"><rect width="9" height="9" fill="#F3F1EA"/><path d="M4.5 0v9" stroke="#C9D3DA" stroke-width="1.2"/></pattern><clipPath id="tileclip"><rect x="6" y="6" width="348" height="308" rx="18"/></clipPath><filter id="sh" x="-20%" y="-20%" width="140%" height="140%"><feDropShadow dx="0" dy="2" stdDeviation="2.5" flood-opacity=".18"/></filter></defs></svg>

<div class="app">
  <header class="top">
    <div class="toprow">
      <b><span class="pole" aria-hidden="true"></span>Look Blueprint</b><a class="home" href="/all/">Free tools ›</a>
      <button class="iconbtn" id="voiceBtn" aria-pressed="true" aria-label="Voice-over"><svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 9v6h4l5 4V5L8 9z" fill="currentColor"/><path class="won" d="M16.5 8.5a5 5 0 0 1 0 7M19 6a8.5 8.5 0 0 1 0 12"/><path class="woff" d="M17 9l5 6M22 9l-5 6"/></svg><span id="voiceLbl">Voice on</span></button>
    </div>
    <nav class="phases" id="phases" aria-label="Your journey">
      <button data-ph="now"><i></i><span>1 Now</span></button>
      <button data-ph="goal"><i></i><span>2 Goal</span></button>
      <button data-ph="plan"><i></i><span>3 How</span></button>
    </nav>
  </header>

  <div class="stagewrap">
    <div class="stagebar"><div class="storybar" id="storybar"></div><span class="sblabel" id="sbLabel"></span><button class="stagebtn" id="stageBtn" aria-label="Pause"></button></div>
    <div class="mirror"><div class="stage" id="stage" aria-hidden="true">
      <svg id="svg" viewBox="0 0 360 320" preserveAspectRatio="xMidYMid meet"></svg>
      <div class="stagecap" id="stageCap" hidden></div>
    </div></div>
    <div class="explain" id="explain" hidden aria-live="polite"></div>
  </div>

  <div class="panel" id="panel" role="main">

    <!-- 2 GOAL -->
    <section class="screen" id="sc-goal" hidden>
      <span class="k" id="gK">Now</span>
      <h2 id="gQ"></h2>
      <p class="why0" id="gWhy"></p>
      <p class="why0" id="gWhyPh" hidden></p>
      <label class="field" for="wzLook" id="gLook" hidden><span>Describe the look you want</span><textarea id="wzLook" rows="3" placeholder="One detail per line"></textarea></label>
      <div id="gBody" class="gbody"></div>
      <div id="gCustom" class="card" hidden>
        <label class="field" for="wzArea"><span>Which area?</span><input type="text" id="wzArea" placeholder="e.g. mustache, gray blending, grow-out after a pixie cut"></label>
        <label class="field" for="wzGoalTxt"><span>Your goal in one sentence</span><textarea id="wzGoalTxt" rows="2" placeholder="e.g. grow a full, neat mustache that suits my face"></textarea></label>
        <div class="field"><span>How far along are you?</span><div class="seg wrap" id="wzLv" role="group" aria-label="How far along"></div></div>
      </div>
      <button class="linkbtn" id="gRestart">Start over</button>
    </section>

    <!-- 3 PLAN -->
    <section class="screen" id="sc-plan" hidden>
      <span class="k">How</span>
      <h2>Month by month</h2>
      <p class="why0">It plays month by month on the picture, with that month's jobs right under it. Last step: an AI prompt for pictures of you.</p>
      <div class="trk" id="pToday"></div>
      <div class="card" id="pTpl">
        <div class="lghead"><h3 id="tplTitle">Template for now</h3><div class="seg" role="group" aria-label="Show template on the face"><button type="button" id="tplOn" aria-pressed="true">On</button><button type="button" id="tplOff" aria-pressed="false">Off</button></div></div>
        <div class="row"><div class="seg" role="group" aria-label="Before or after this month's scissors and cleanup"><button type="button" id="baBefore" aria-pressed="false">Before</button><button type="button" id="baAfter" aria-pressed="true">After scissors &amp; cleanup</button></div></div>
        <p class="help up">Before: a month of regrowth. After: what this month's jobs remove; the rest stays for now.</p>
        <div class="scrub"><button type="button" class="stepb" id="mPrev" aria-label="Previous month">‹</button><div class="scrubmid"><span id="mLbl" class="k">Now</span><span class="muted sm">Plays month by month on the picture. Tap it to pause.</span></div><button type="button" class="stepb" id="mNext" aria-label="Next month">›</button></div>
        <div class="seg areaseg" id="tplAreas" role="group" aria-label="Which area to show" hidden></div>
        <div class="growl" id="pGrow"></div>
        <p class="muted note" id="tplNote"></p>
        <div class="legend" id="pLegend"></div>
        <p class="help" id="pReach" hidden></p>
      </div>
      <div class="card sum" id="pSum"></div>
      <div class="card">
        <h3>Month by month</h3>
        <p class="muted note">Every month has its own template and jobs, based on natural growth. Checkpoints add what to say to your barber or stylist. Tap a month to see it on the face.</p>
        <div class="cps" id="pCps"></div>
      </div>
      <div class="card"><h3>Rules every week</h3><div class="rules" id="pRules"></div></div>
      <p class="help" id="pBasis"></p>
      <button class="btn" id="pCopyPlan">Copy my whole plan</button>
    </section>

    <!-- 4 PROMPT -->
    <section class="screen" id="sc-prompt" hidden>
      <span class="k">How, last step</span>
      <h2>Your AI prompt</h2>
      <p class="muted">Send it with two photos to an AI that can edit images. It turns your plan into pictures of you.</p>
      <div class="card"><h3>1. Take two photos</h3><div id="rPhotos"></div></div>
      <div class="card"><h3>2. Copy and paste</h3><p class="muted note">Highlighted parts come from your answers.</p><div class="preview" id="rPrev"><pre id="rPrompt"></pre></div><button class="btn small" id="rExpand">Show full prompt</button></div>
      <div class="card"><h3>3. If something looks off</h3><p class="muted note">Copy a fix and send it as your reply.</p><div id="rFixes" class="fixes"></div></div>
      <details class="acc"><summary>Adjust details</summary><div class="inner" id="rFields">
        <label class="field" for="f-goal"><span>Your goal</span><textarea id="f-goal" rows="2"></textarea></label>
        <label class="field" for="f-style"><span>The look you want</span><small>One detail per line.</small><textarea id="f-style" rows="4"></textarea></label>
        <label class="field" for="f-options"><span>Styles to compare</span><small>Four, one per line.</small><textarea id="f-options" rows="4"></textarea></label>
        <label class="field" for="f-priorities"><span>Priorities after keeping your face</span><textarea id="f-priorities"></textarea></label>
        <div class="zone"><i class="z-g"></i><label class="field" for="f-green"><span>Green: leave alone</span><textarea id="f-green" rows="2" class="short"></textarea></label></div>
        <div class="zone"><i class="z-y"></i><label class="field" for="f-yellow"><span>Yellow: shape lightly</span><textarea id="f-yellow" rows="2" class="short"></textarea></label></div>
        <div class="zone"><i class="z-r"></i><label class="field" for="f-red"><span>Red: clean up</span><textarea id="f-red" rows="2" class="short"></textarea></label></div>
        <div class="zone"><i class="z-b"></i><label class="field" for="f-blue"><span>Blue: detail zone</span><textarea id="f-blue" rows="2" class="short"></textarea></label></div>
        <label class="field" for="f-tools"><span>Tools you already own</span><input type="text" id="f-tools"></label>
        <label class="field" for="f-detail"><span>Area that needs a close-up</span><textarea id="f-detail" rows="2" class="short"></textarea></label>
        <label class="field" for="f-risk"><span>Biggest mistake to avoid</span><textarea id="f-risk" rows="2" class="short"></textarea></label>
        <label class="field" for="f-milestones"><span>Checkpoints</span><input type="text" id="f-milestones"></label>
        <label class="field" for="f-area"><span>Area name</span><input type="text" id="f-area"></label>
        <label class="field" for="f-pro"><span>Expert the AI acts as</span><input type="text" id="f-pro"></label>
        <label class="field" for="f-proName"><span>Who gets the script</span><input type="text" id="f-proName"></label>
      </div></details>
      <details class="acc"><summary>Why the prompt works</summary><div class="inner" id="rWhy"></div></details>
      <p class="help">Every 3 months: take new photos and send the same prompt. Your plan updates to how you've actually grown.</p>
    </section>
  </div>

  <footer class="actions">
    <button class="btn" id="actBack">‹ Back</button>
    <button class="btn accent" id="actMain"></button>
  </footer>
</div>
<div class="toast" id="toast" role="status">Copied</div>
<div class="bcard" id="bCard" role="dialog" aria-modal="true" aria-labelledby="bTitle" hidden>
  <div class="bsheet">
    <div class="bhead"><span class="pole" aria-hidden="true"></span><h2 id="bTitle">For my barber</h2><button type="button" class="iconbtn" id="bClose">Close</button></div>
    <div class="bpic"><svg id="bSvg" viewBox="64 26 232 294" preserveAspectRatio="xMidYMid meet" aria-hidden="true"></svg></div>
    <p class="bwhen" id="bWhen"></p>
    <blockquote class="bsay" id="bSay"></blockquote>
    <ul class="acts" id="bActs"></ul>
    <div class="bnav"><button type="button" class="btn" id="bPrev">Earlier visit</button><button type="button" class="btn" id="bNext">Later visit</button></div>
  </div>
</div>

<script src="./look.js" defer></script>
</body>
</html>
look.js (the whole app: drawings, steps, plan, prompt, voice)1,298 lines

Raw file


(function(){
/* Strict-CSP safe: markup strings may carry style="…"; apply those through CSSOM instead of as attributes. */
(function(){ const d=Object.getOwnPropertyDescriptor(Element.prototype,'innerHTML'); if(!d||!d.set) return;
  Object.defineProperty(Element.prototype,'innerHTML',{configurable:true,enumerable:d.enumerable,get:d.get,set(v){ const s=String(v); if(s.indexOf(' style="')<0){ d.set.call(this,s); return; }
    d.set.call(this,s.replace(/ style="/g,' data-st="')); this.querySelectorAll('[data-st]').forEach(n=>{ n.style.cssText=n.getAttribute('data-st'); n.removeAttribute('data-st'); }); }}); })();
const RM = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
const C={g:'#22A84A',y:'#F2B705',r:'#E8382E',b:'#2370F0',acc:'#C2185B',ink:'#0F2E2A',pill:'#0F2E2A',panel:'rgba(255,255,255,.92)',dot:'#fff',tile:'rgba(255,255,255,.35)'};
function isDark(){ const t=document.documentElement.getAttribute('data-theme'); if(t==='dark') return true; if(t==='light') return false; return !!(window.matchMedia&&matchMedia('(prefers-color-scheme: dark)').matches); }
function applyPalette(){ const d=isDark(); C.dark=d; Object.assign(C, d?{ink:'#F6F1E4',pill:'#145049',panel:'rgba(4,32,31,.84)',dot:'#0B3532',tile:'rgba(255,255,255,.05)',acc:'#FF5FA2',b:'#4D93FF',g:'#36C463'}:{ink:'#0F2E2A',pill:'#0F2E2A',panel:'rgba(255,255,255,.92)',dot:'#fff',tile:'rgba(255,255,255,.35)',acc:'#C2185B',b:'#2370F0',g:'#22A84A'}); }
applyPalette();
/* ---------- characters: one universal person (any gender, any skin tone, any beard + hair + brows) ---------- */
let SK='#D9A57F', SKD='#B9845E';
const SKINS={light:['#F2CDAE','#D6A889'],medium:['#D9A57F','#B9845E'],tan:['#B67E55','#93603D'],deep:['#7B4F34','#5C3925']};
const HAIRCOL={man:'#2A221E',woman:'#4E3024',neutral:'#2F2520'};
const SHIRT={man:'url(#cape)',woman:'url(#cape)',neutral:'url(#cape)'};
const GEO={man:{rx:66,ry:82,cy:125,eye:128,ex:156,ew:9,er:3.6,mouth:186,nose:160},
 woman:{rx:58,ry:74,cy:128,eye:127,ex:157,ew:8.5,er:3.4,mouth:180,nose:155},
 neutral:{rx:62,ry:78,cy:126,eye:128,ex:156,ew:8.8,er:3.5,mouth:183,nose:158}};
const esc=s=>String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
const tr=(s,n)=>{s=String(s).trim();return s.length>n?s.slice(0,n-1).trim()+'…':s;};
const f3=n=>(+n).toFixed(3);
/* beard frame: drawn for the man's face, then fitted to any face by its eyes (y 128) and mouth (y 186), and its width */
function bT(g){ const G=GEO[g]||GEO.man; if(g==='man') return 'translate(0 0)'; const sx=G.rx/66, ay=(G.mouth-G.eye)/(186-128), by=G.eye-ay*128;
  return `matrix(${f3(sx)} 0 0 ${f3(ay)} ${f3(180-180*sx)} ${f3(by)})`; }
function hT(g){ const G=GEO[g]||GEO.man; return `translate(180 ${G.cy}) scale(${f3(G.rx/58)} ${f3(G.ry/74)}) translate(-180 -128)`; }
const MIR=p=>`${p}<g transform="translate(360 0) scale(-1 1)">${p}</g>`;

/* beard (drawn in the man frame, scaled to any face) */
const MV={taper:{k:16,tip:18,w:6},square:{k:30,tip:5,w:9},duck:{k:6,tip:28,w:2},natural:{k:36,tip:2,w:22},boxed:{k:30,tip:2,w:4},stubble:{k:30,tip:0,w:0},none:{k:30,tip:0,w:0},goatee:{k:14,tip:8,w:0},mustache:{k:30,tip:0,w:0}};
function beardOuter(L,v){const b=205+100*L,w=v.w*L,t=v.tip*L,k=v.k;return `M116 114 C${112-w} 170 ${118-w} ${b-38} ${180-k-8} ${b-6} Q180 ${b+6+t} ${180+k+8} ${b-6} C${248+w} ${b-38} ${244+w} 170 244 114`;}
function beardPath(L,v){return beardOuter(L,v)+` L234 114 C234 148 226 160 212 165 Q196 160 180 163 Q164 160 148 165 C134 160 126 148 126 114 Z`;}
function goateeOuter(L){const b=196+100*L;return `M158 186 C156 ${b-10} 168 ${b} 180 ${b+5} C192 ${b} 204 ${b-10} 202 186`;}
function goateePath(L){return goateeOuter(L)+` Q191 192 180 193 Q169 192 158 186 Z`;}
const beardL=cm=>Math.max(.02,Math.min(1.15,cm/13));
const MUST='M153 182 C155 173 165 166 180 169.5 C195 166 205 173 207 182 C200 179.2 191 179.6 180 180.6 C169 179.6 160 179.2 153 182 Z';
function beardSVG(cm,sh,hc,gray){
  if(cm<=.05) return {u:'',m:''};
  if(sh==='mustache'){ const k=Math.min(cm,5), m=`<g transform="translate(180 181) scale(${(1+k*.05).toFixed(3)} ${(1+k*.1).toFixed(3)}) translate(-180 -181)"><path d="${MUST}" fill="${hc}"/><path d="${MUST}" fill="url(#tex)"/></g>`;
    return {u:'',m:cm<1?`<g opacity="${(.2+cm*.5).toFixed(2)}">${m}</g>`:m}; }
  const L=beardL(cm), v=MV[sh]||MV.square, path=sh==='goatee'?goateePath(L):beardPath(L,v);
  if(cm<1){ const op=(.16+cm*.4).toFixed(2); return {u:`<path d="${path}" fill="${hc}" opacity="${op}"/>`,m:`<path d="${MUST}" fill="${hc}" opacity="${op}"/>`}; }
  const b=205+100*L;
  let u=`<path d="${path}" fill="${hc}"/><path d="${path}" fill="url(#tex)"/>`;
  if(gray&&cm>=3&&sh!=='goatee') u+=`<path d="M172 ${b-34} q3 8 1 15 M186 ${b-28} q-3 9 0 15 M164 ${b-18} q2 6 0 11 M196 ${b-40} q2 7 0 12 M178 ${b-12} q2 5 0 9" stroke="#D8D1C8" stroke-width="1.3" fill="none" opacity=".85" stroke-linecap="round"/>`;
  if(cm>=3&&sh!=='goatee'){ const R=rng(11); let c=''; const n=Math.min(22,Math.round(cm*1.6));
    for(let i=0;i<n;i++){ const x=138+R()*84, y=166+R()*Math.max(8,b-180); if(x>158&&x<202&&y<196) continue; c+=`<path d="M${F1(x)} ${F1(y)} a3 3 0 1 1 ${F1(3+R()*2)} ${F1(2+R()*2)}" stroke="${i%3?'rgba(0,0,0,.28)':'rgba(255,255,255,.14)'}" stroke-width="1.2" fill="none" stroke-linecap="round"/>`; }
    u+=c; }
  return {u,m:`<path d="${MUST}" fill="${hc}"/>`};
}

/* brows (absolute coordinates) */
const BA={straight:2,soft:7,high:13,feather:6};
function browD(v){const a=BA[v]||7;return `M172 113 C165 ${110-a*.5} 152 ${107-a} 140 ${117}`;}
function brows(L,v,col){
  const w=2.5+6*L, d=browD(v);
  let s=`<path d="${d}" stroke="${col}" stroke-width="${w}" stroke-linecap="round" fill="none"/><path d="M172 113 C168 111 164 ${110-(BA[v]||7)*.4} 160 ${109-(BA[v]||7)*.6}" stroke="${col}" stroke-width="${w*1.25}" stroke-linecap="round" fill="none"/>`;
  if(v==='feather'){for(let k=0;k<6;k++){const x=146+k*4.5;s+=`<path d="M${x} ${113-k*.6} l2 -${4+L*3}" stroke="${col}" stroke-width="1.4" stroke-linecap="round"/>`;}}
  return `<g>${s}</g><g transform="translate(360 0) scale(-1 1)">${s}</g>`;
}

/* hair (drawn in the woman frame, scaled to any head). Length in cm decides the shape. */
const hairB=cm=>cm<22?120+(cm-9)*(82/13):202+(cm-22)*3.6;
function hemPath(b,st){ if(st==='blunt'||st==='bob') return `L242 ${b}`; return `Q180 ${b+(st==='u'?26:16)} 242 ${b}`; }
function hairBackPath(b,st){ const c1=Math.min(160,b-8); return `M112 104 C98 ${c1} 104 ${b-20} 118 ${b} ${hemPath(b,st)} C256 ${b-20} 262 ${c1} 248 104 C268 18 92 18 112 104 Z`; }
function curtainB(b,st){ const cs=st==='layers'?Math.min(44,Math.max(8,(b-170)*.4)):8, e=b-cs;
  const end=(st==='blunt'||st==='bob')?`L140 ${e}`:st==='u'?`Q118 ${e+16} 140 ${e-14}`:`Q120 ${e+10} 140 ${e-6}`;
  return `M128 76 C100 104 98 ${Math.max(110,b-60)} 104 ${e} ${end} C132 ${Math.max(140,b-78)} 126 180 128 128 Z`; }
const CAP='M108 128 C92 22 268 22 252 128 C244 92 218 68 190 68 C168 80 142 90 108 128 Z';
const capT=cm=>1.5+cm*1.9;
function shortCap(t){ const rxo=58+t*.45, ryo=74+t, dx=rxo*Math.sqrt(1-Math.pow(10/ryo,2)), hl=72;
  return `M${(180-dx).toFixed(1)} 118 A${rxo.toFixed(1)} ${ryo.toFixed(1)} 0 0 1 ${(180+dx).toFixed(1)} 118 L236 118 C232 92 214 ${hl+4} 180 ${hl} C146 ${hl+4} 128 92 124 118 Z`; }
const curlyDims=cm=>({rx:60+cm*2.6,ry:62+cm*1.5,cy:104+cm*.2,r:9+cm*.55});
function curlyBack(cm,hc){ const d=curlyDims(cm); let s=`<ellipse cx="180" cy="${d.cy}" rx="${d.rx}" ry="${d.ry}"/>`;
  for(let i=0;i<20;i++){ const t=i/20*Math.PI*2; s+=`<circle cx="${(180+Math.cos(t)*d.rx).toFixed(1)}" cy="${(d.cy+Math.sin(t)*d.ry).toFixed(1)}" r="${d.r.toFixed(1)}"/>`; }
  return `<g fill="${hc}">${s}</g>`; }
function curlyFront(cm,hc){ let s=''; const r=7+cm*.35;
  for(let i=0;i<=8;i++){ const t=Math.PI+i/8*Math.PI; s+=`<circle cx="${(180+Math.cos(t)*56).toFixed(1)}" cy="${(100+Math.sin(t)*36).toFixed(1)}" r="${r.toFixed(1)}"/>`; }
  return `<g fill="${hc}">${s}</g><g fill="url(#tex)">${s}</g>`; }

function person(st,o){
  o=o||{}; const sk=SKINS[st.skin||S.skin]||SKINS.medium; SK=sk[0]; SKD=sk[1];
  const g=st.g||'man', G=GEO[g]||GEO.man, hc=HAIRCOL[g], drift=o.drift;
  const rx=drift?G.rx*.88:G.rx, ry=drift?G.ry*1.04:G.ry, er=drift?G.er*1.35:G.er, ew=drift?G.ew*1.22:G.ew;
  const H=st.hair||{s:'shaved',a:0}, B=st.beard||{s:'none',a:0}, W=st.brows||{s:'soft',a:.3};
  const hs=H.s, ha=H.a, curly=hs==='curly'&&ha>=2, long=!curly&&ha>=9;
  let s='<g>';
  if(curly) s+=`<g transform="${hT(g)}"${C.dark?' filter="url(#rim)"':''}>${curlyBack(ha,hc)}</g>`;
  else if(long) s+=`<g transform="${hT(g)}"${C.dark?' filter="url(#rim)"':''}><path d="${hairBackPath(hairB(ha),hs)}" fill="${hc}"/></g>`;
  s+= g==='woman'
    ? `<path d="M74 320 C84 278 128 264 180 264 C232 264 276 278 286 320 Z" fill="${SHIRT[g]}"/><rect x="160" y="180" width="40" height="88" fill="${SKD}"/><path d="M160 262 Q180 274 200 262" stroke="#C9D3DA" stroke-width="5" fill="none" stroke-linecap="round"/>`
    : `<path d="M70 320 C80 272 130 258 180 258 C230 258 280 272 290 320 Z" fill="${SHIRT[g]}"/><rect x="${g==='man'?152:156}" y="${g==='man'?190:186}" width="${g==='man'?56:48}" height="80" fill="${SKD}"/>`;
  s+=`<ellipse cx="${180-rx-2}" cy="${G.cy+15}" rx="10" ry="16" fill="${SKD}"/><ellipse cx="${180+rx+2}" cy="${G.cy+15}" rx="10" ry="16" fill="${SKD}"/>`;
  s+=`<ellipse cx="180" cy="${G.cy}" rx="${rx}" ry="${ry}" fill="${SK}"/>`;
  if(ha<2&&!curly) s+=`<ellipse cx="160" cy="${G.cy-55}" rx="20" ry="10" fill="#fff" opacity=".22" transform="rotate(-20 160 ${G.cy-55})"/>`;
  s+=brows(W.a,W.s,hc);
  const ey=G.eye, ex=G.ex, ex2=360-ex;
  s+=`<ellipse cx="${ex}" cy="${ey}" rx="${ew}" ry="5" fill="#fff"/><ellipse cx="${ex2}" cy="${ey}" rx="${ew}" ry="5" fill="#fff"/><circle cx="${ex}" cy="${ey}" r="${er}" fill="#3B2A20"/><circle cx="${ex2}" cy="${ey}" r="${er}" fill="#3B2A20"/>`;
  s+= g==='woman'
    ? `<path d="M${ex-10} ${ey-5} Q${ex} ${ey-10} ${ex+10} ${ey-5} M${ex2-10} ${ey-5} Q${ex2} ${ey-10} ${ex2+10} ${ey-5} M${ex-10} ${ey-5} l-3 -3 M${ex2+10} ${ey-5} l3 -3" stroke="#2A1D17" stroke-width="1.8" fill="none" stroke-linecap="round"/>`
    : `<path d="M${ex-10} ${ey-5} Q${ex} ${ey-9} ${ex+10} ${ey-5} M${ex2-10} ${ey-5} Q${ex2} ${ey-9} ${ex2+10} ${ey-5}" stroke="${SKD}" stroke-width="2" fill="none"/>`;
  const nb=G.nose; s+=`<path d="M180 ${ey+3} C176 ${nb-12} 170 ${nb-4} 174 ${nb} Q180 ${nb+4} 186 ${nb}" stroke="${SKD}" stroke-width="2.4" fill="none" stroke-linecap="round"/>`;
  if(g!=='man'&&!drift){ const op=g==='woman'?.35:.2; s+=`<ellipse cx="146" cy="${ey+25}" rx="9" ry="5" fill="#E08A7C" opacity="${op}"/><ellipse cx="214" cy="${ey+25}" rx="9" ry="5" fill="#E08A7C" opacity="${op}"/>`; }
  const bd=g==='woman'?{u:'',m:''}:beardSVG(B.a,B.s,hc,g==='man');
  if(bd.u) s+=`<g transform="${bT(g)}">${bd.u}</g>`;
  const my=G.mouth;
  s+= g==='woman' ? `<path d="M166 ${my-1} Q173 ${my-6} 180 ${my-3} Q187 ${my-6} 194 ${my-1} Q180 ${my+9} 166 ${my-1} Z" fill="#B9505A"/>`
                  : `<ellipse cx="180" cy="${my}" rx="${g==='man'?13:12}" ry="4.5" fill="${g==='man'?'#B5675A':'#B25E5E'}"/>`;
  if(bd.m) s+=`<g transform="${bT(g)}">${bd.m}</g>`;
  if(curly) s+=`<g transform="${hT(g)}">${curlyFront(ha,hc)}</g>`;
  else if(long){ const b=hairB(ha); let f='';
    if(b>=165){ const c=curtainB(b,hs); f+=MIR(`<path d="${c}" fill="${hc}"/><path d="${c}" fill="url(#tex)"/>`); }
    f+=`<path d="${CAP}" fill="${hc}"/><path d="${CAP}" fill="url(#tex)"/>`; s+=`<g transform="${hT(g)}">${f}</g>`; }
  else if(ha>=.2){ const p=shortCap(capT(ha)); s+=`<g transform="${hT(g)}" opacity="${ha<2?(.45+ha*.2).toFixed(2):1}"><path d="${p}" fill="${hc}"/><path d="${p}" fill="url(#tex)"/></g>`; }
  return s+'</g>';
}
function pill(x,y,text,color,cls,delay,anchor){
  text=esc(text); const w=text.length*6.1+16; const xx=anchor==='end'?x-w:anchor==='middle'?x-w/2:x;
  return `<g class="${cls||'a-fade'}" style="animation-delay:${delay||0}s"><rect x="${xx}" y="${y-11}" width="${w}" height="19" rx="9.5" fill="${color}" filter="url(#sh)"/><text x="${xx+w/2}" y="${y+2.5}" text-anchor="middle" font-family="Figtree,sans-serif" font-size="11" font-weight="700" fill="#fff" >${text}</text></g>`;
}

/* ---------- goals, looks and natural growth ---------- */
var rmReady=false;
var SRC=null;
const AREAS=['beard','hair','brows'];
const GN={man:'Man',woman:'Woman',neutral:'Neutral'};
const STY={beard:[['none','Clean-shaven'],['stubble','Stubble'],['boxed','Short boxed'],['goatee','Goatee'],['mustache','Mustache'],['taper','Tapered'],['square','Rounded-square'],['duck','Ducktail'],['natural','Natural wide']],
 hair:[['shaved','Shaved'],['buzz','Buzz cut'],['crop','Short crop'],['curly','Curly volume'],['bob','Chin bob'],['u','Shoulder U'],['layers','Long layers'],['blunt','Long blunt']],
 brows:[['straight','Straight'],['soft','Soft arch'],['high','High arch'],['feather','Feathered']]};
const AMT={beard:{none:0,stubble:.3,boxed:2.5,goatee:4,mustache:2.5,taper:12,square:12,duck:10,natural:15},hair:{shaved:0,buzz:1,crop:5,curly:15,bob:22,u:35,layers:55,blunt:55}};
const LV={beard:[['Clean-shaven',0],['Stubble',.3],['Short',1.5],['Medium',4],['Long',8]],
 hair:[['Shaved',0],['Buzz',1],['Short',6],['Chin-length',22],['Shoulder-length',35],['Long',50]],
 brows:[['Thin',.05],['Sparse',.2],['Medium',.45],['Full',.7]]};
const GENLV=[['Just starting',.1],['Some growth',.35],['Halfway',.6],['Nearly there',.85]];
const KEEP={man:{beard:'boxed',hair:'crop',brows:'straight'},woman:{beard:'none',hair:'u',brows:'soft'},neutral:{beard:'none',hair:'crop',brows:'soft'}};
const GOALDEF={beard:'square',hair:'layers',brows:'soft'};
const RATE=1.25;
const basis=()=>noBeard()?BASIS_T.replace('scalp and beard hair grow','scalp hair grows'):BASIS_T; /* cm a month, scalp and beard hair (about half an inch) */
const BASIS_T='Growth uses averages: scalp and beard hair grow about 1.25 cm (½ inch) a month, and brows take about 3 to 4 months to grow back. Yours may be faster or slower, so take new photos every 3 months and adjust.';
const S={g:'man',skin:'medium',goals:['beard'],custom:false,look:{beard:'square',hair:'crop',brows:'straight'},lvl:{},picked:{},ready:false,prio:[],goal:'beard',who:'him'};
const noBeard=()=>S.g==='woman';
function sync(){ if(noBeard()){ S.goals=S.goals.filter(a=>a!=='beard'); S.look.beard='none'; S.picked.beard=false; S.base=S.base||{}; S.base.beard='none'; S.lvl.beard=0; }
  S.goal=S.custom?'custom':(S.goals[0]||(noBeard()?'hair':'beard')); S.who=S.g==='woman'?'her':'him'; }
const areasFor=()=>AREAS.filter(a=>!(a==='beard'&&noBeard()));
const GOALS=[['beard','Beard','Grow it or reshape it'],['hair','Hair','Grow out or change the cut'],['brows','Brows','Fuller, natural shape'],['custom','Something else','Start from blank']];
function customArea(){ const t=(raw('area')||'').toLowerCase();
  if(/brow/.test(t)) return 'brows'; if(!noBeard()&&/must|beard|goatee|stubble|sideburn|chin|jaw|neck/.test(t)) return 'beard';
  if(/hair|bang|fringe|bob|pixie|curl|crop|fade|gray|grey|scalp|part/.test(t)) return 'hair'; return S.g==='man'?'beard':'hair'; }
function kind(){ if(S.custom) return customArea(); return S.goals[0]||(noBeard()?'hair':'beard'); }
function isGoal(a){ return S.custom? a===kind() : S.goals.includes(a); }
function goalAreas(){ return S.custom?[kind()]:AREAS.filter(a=>S.goals.includes(a)); }
function zoomOn(){ return (!S.custom&&S.goals.length===1&&S.goals[0]==='brows')||(phase==='plan'&&tplArea==='brows'); }
const cap1=s=>String(s).replace(/^./,c=>c.toUpperCase());
const areaWord=a=>a;
function goalDef(a){ if(a==='hair'&&S.base&&S.base.hair==='curly') return 'curly'; if(a==='beard'&&S.g!=='man') return 'boxed'; return a==='brows'?(S.g==='man'?'straight':'soft'):GOALDEF[a]; }
const TODAY={hair:[['shaved','Bald',0],['buzz','Buzz',1],['crop','Short',2],['curly','Curly',2],['bob','Chin-length',3],['u','Shoulder',4],['layers','Long',5]],beard:[['none','None',0],['stubble','Stubble',1],['boxed','Short',2],['square','Medium',3],['square','Long',4]],brows:[[null,'Thin',0],[null,'Sparse',1],[null,'Medium',2],[null,'Full',3]]};
function todayAmt(a,st,lv){ return LV[a][lv][1]; }
function baseAmt(a,s){ return S.base&&S.base[a]===s&&S.lvl[a]!=null?LV[a][S.lvl[a]][1]:targetAmt(a,s); }
function todayAmts(){ const o={}; AREAS.forEach(a=>{ if(S.base&&S.base[a]!=null&&S.lvl[a]!=null) o[a]=LV[a][S.lvl[a]][1]; }); return o; }
function todayLbl(){ const b=S.base||{}; const p=[]; if(b.hair!=null&&S.lvl.hair!=null) { const n=((TODAY.hair.find(x=>x[0]===b.hair&&x[2]===S.lvl.hair)||[])[1]||'').toLowerCase(); p.push(n==='bald'?'bald':n+' hair'); } if(!noBeard()&&b.beard!=null&&S.lvl.beard!=null) p.push(S.lvl.beard===0?'no beard':(LV.beard[S.lvl.beard][0]).toLowerCase()+' beard'); if(b.brows!=null&&S.lvl.brows!=null) p.push(LV.brows[S.lvl.brows][0].toLowerCase()+' brows'); return p.length?p.join(', ').replace(/^./,c=>c.toUpperCase()):'tap what you have'; }
function baseLook(a){ return (S.base&&S.base[a])||KEEP[S.g][a]; }
function styleName(a,st){ const x=(STY[a]||[]).find(y=>y[0]===(st||S.look[a])); return x?x[1]:''; }
function targetAmt(a,st){ st=st||S.look[a]; return a==='brows'?.9:(AMT[a][st]||0); }
function lvIdx(a){ if(S.lvl[a]!=null) return S.lvl[a]; return a==='beard'?2:a==='hair'?(S.g==='man'?2:4):1; }
function startAmt(a){ if(S.custom){ const f=GENLV[S.lvl.custom!=null?S.lvl.custom:1][1]; return Math.max(a==='brows'?.05:.3,targetAmt(a)*f); } return LV[a][lvIdx(a)][1]; }
function growMonths(a){ const s=startAmt(a), t=targetAmt(a); if(s>=t) return 0; if(S.custom) return totalMo(); return a==='brows'?Math.min(4,3+(t-s)*1.2):(t-s)/RATE; }
function totalMo(){ const ms=milestones(); return ms[ms.length-1].mo; }
function amountAt(a,mo){ const t=targetAmt(a); if(!isGoal(a)) return t; const s=startAmt(a);
  if(s>t) return mo<=1e-6?s:t; if(Math.abs(s-t)<1e-6) return t;
  return Math.min(t, s+(t-s)*Math.min(1,mo/Math.max(.01,growMonths(a)))); }
function progressAt(a,mo){ const s=startAmt(a), t=targetAmt(a); if(Math.abs(t-s)<1e-6) return 1; if(s>t) return mo<=1e-6?0:1; return Math.max(0,Math.min(1,(amountAt(a,mo)-s)/(t-s))); }
function phaseAt(a,mo){ if(mo<=1e-6) return 'now'; const q=progressAt(a,mo); if(q>=.999) return 'goal'; return q<=.3?'early':q<=.65?'mid':'late'; }
function fam(a){ if(S.custom) return 'custom'; const st=S.look[a];
  if(a==='beard') return st==='none'?'beardNone':st==='goatee'?'goatee':st==='mustache'?'mustache':(st==='boxed'||st==='stubble')?'beardShort':'beardLong';
  if(a==='hair'){ if(st==='shaved') return 'hairShaved'; if(st==='curly') return 'hairCurly'; if(st==='crop'||st==='buzz') return 'hairShort'; return startAmt('hair')<9?'hairGrowout':'hairLong'; }
  return 'brows'; }
function stOf(fn,o){ o=o||{}; const st={g:o.g||S.g,skin:o.skin||S.skin}; AREAS.forEach(a=>{ const s=(o.look&&o.look[a])||S.look[a]; st[a]={s,a:fn(a,s)}; }); if(o.amt) Object.keys(o.amt).forEach(a=>{ st[a].a=o.amt[a]; }); return st; }
function stateAt(mo,o){ return stOf((a,s)=>isGoal(a)?amountAt(a,mo):baseAmt(a,s),o); }
function stateQ(q,o){ o=o||{}; const lk={...(o.look||{})}; if(o.v) lk[kind()]=o.v;
  return stOf((a,s)=>{ const t=targetAmt(a,s); if(!isGoal(a)) return baseAmt(a,s); const st=startAmt(a); return st+(t-st)*Math.max(0,Math.min(1,q)); },{...o,look:lk}); }
function face(q,o){ return person(stateQ(q,o),o); }
function personAt(mo,o){ return person(stateAt(mo,o),o); }
const K={
  beard:{variants:['taper','square','duck','natural'],
    obs:'Dense chin, lighter upper cheeks, curls at the jaw corners. The cheek density is flagged as a guess to confirm.',
    scan:[[180,214,1,'dense chin',8,262],[134,148,0,'lighter cheek?',8,92],[238,196,1,'curls at jaw',262,250],[121,112,1,'sideburns join',8,46]]},
  hair:{variants:['blunt','u','curly','layers'],
    obs:'Dense crown, thinner ends, shorter face-framing pieces. Split ends are flagged as a guess to confirm.',
    scan:[[180,62,1,'dense crown',8,40],[108,222,1,'thinner ends',8,262],[132,150,1,'short framing',8,150],[238,246,0,'split ends?',262,290]]},
  brows:{variants:['straight','soft','high','feather'],
    obs:'Full at the center, sparse tails, a few strays between the brows. Sparse tails are flagged as a guess to confirm.',
    scan:[[160,108,1,'full center',8,40],[142,117,0,'sparse tail?',8,214],[180,116,1,'strays between',244,40],[218,117,0,'uneven arch?',262,214]]}
};
const VNAMES={beard:['Tapered','Rounded-square','Ducktail','Natural wide'],hair:['Long blunt','Shoulder U','Curly volume','Long layers'],brows:['Straight','Soft arch','High arch','Feathered']};
function curV(){ return S.look[kind()]; }
function winIdx(){ return K[kind()].variants.indexOf(curV()); }
function startLbl(){ if(S.custom) return GENLV[S.lvl.custom!=null?S.lvl.custom:1][0]; return cap1(goalAreas().map(a=>`${a==='hair'&&S.base&&S.base.hair==='curly'?'curly':LV[a][lvIdx(a)][0].toLowerCase()} ${areaWord(a)}`).join(' + ')); }
function targetLbl(){ if(S.custom) return 'your look'; const A=goalAreas(); return A.map(a=>styleName(a)+(A.length>1?' '+areaWord(a):'')).join(' + '); }
function nowL(){ return 0; }
const ZS=1.9, ZX=180, ZY=128;
function Z(content){ return zoomOn() ? `<g transform="translate(${ZX} ${ZY}) scale(${ZS}) translate(${-ZX} ${-ZY})">${content}</g>` : content; }
function zp(x,y){ return zoomOn() ? [ZX+(x-ZX)*ZS, ZY+(y-ZY)*ZS] : [x,y]; }
const cmTxt=cm=>cm<1?`${Math.round(cm*10)} mm`:`${cm.toFixed(cm<10?1:0)} cm (${(cm/2.54).toFixed(1)}″)`;
const moTxt=m=>+(+m).toFixed(1);

/* ---------- user values ---------- */
const LABEL={area:'area',pro:'expert role',proName:'barber or stylist',goal:'your goal',timeframe:'timeframe',milestones:'checkpoints',priorities:'priority',style:'look detail',options:'style option',green:'what to leave alone',yellow:'what to shape lightly',red:'what to clean up',blue:'detail zone',detail:'close-up area',tools:'tools you own',risk:'biggest mistake'};
const KEYS=Object.keys(LABEL);
let tf='12 months';
function val(k){ if(SRC){ if(k==='timeframe') return SRC.timeframe||tf; const v=(SRC[k]||'').trim(); return v||('['+LABEL[k]+']'); } if(k==='timeframe') return tf; const el=document.getElementById('f-'+k); const v=el?el.value.trim():''; return v||('['+LABEL[k]+']'); }
function raw(k){ if(SRC) return (SRC[k]||'').trim(); const el=document.getElementById('f-'+k); return el?el.value.trim():''; }
function lines(k){ return raw(k).split('\n').map(x=>x.trim()).filter(Boolean); }
function milestones(){
  let toks=raw('milestones').replace(/\band\b/gi,',').split(',').map(x=>x.trim()).filter(Boolean);
  const lastUnit=/week|wk/i.test(toks[toks.length-1]||'')?'wk':'mo';
  let pts=toks.map(t=>{ if(/now|today|start/i.test(t)) return {l:'Now',m:0}; const n=t.match(/\d+(\.\d+)?/); if(!n) return {l:tr(t,6),m:null};
    const u=/week|wk/i.test(t)?'wk':/month|mo/i.test(t)?'mo':lastUnit; const v=+n[0]; return {l:v+' '+u,m:u==='wk'?v/4.3:v}; });
  if(pts.length<2) pts=[{l:'Now',m:0},{l:tr(tf,8),m:parseInt(tf,10)||1}];
  pts=pts.slice(0,7);
  return pts.map((p,j)=>({l:p.l,mo:p.m==null?j:+p.m.toFixed(2)}));
}
function monthEntries(){
  const ms=milestones(), T=ms[ms.length-1].mo, map=new Map();
  for(let m=0;m<=Math.floor(T+1e-6);m++) map.set(m.toFixed(2),{mo:m});
  ms.forEach(x=>{ const k=x.mo.toFixed(2), e=map.get(k)||{mo:x.mo}; e.cp=x.l; map.set(k,e); });
  return [...map.values()].sort((a,b)=>a.mo-b.mo).map(e=>({...e,l:e.mo===0?'Now':(e.cp&&/wk/.test(e.cp)?e.cp:'Month '+moTxt(e.mo))}));
}
const ZONEKEYS=['green','yellow','red','blue'];
const ZONECOL={get green(){return C.g},get yellow(){return C.y},get red(){return C.r},get blue(){return C.b}};

/* ---------- scenes ---------- */
const STEPS=[
 ['Set the objective','State the goal, the timeframe and ranked priorities. Keeping your face always ranks first.'],
 ['Lock your identity','Your own photos are the only source for your face. Only the target area may change.'],
 ['Analyze what is there','Density, boundaries, texture and asymmetry, region by region. Each finding is labeled seen or guessed.'],
 ['Choose the style','Your four styles are compared against your actual face. One wins, with a reason.'],
 ['Visualize the growth','A target look, then a timeline at your checkpoints with the same face, angle and light.'],
 ['Map the zones','Colors show exactly where to grow, shape lightly, clean up and detail, drawn on your photo.'],
 ['Check and correct','Every image is compared with your photo. A face that drifted gets redone, not shipped.'],
 ['Your roadmap','From today to the goal, checkpoint by checkpoint, as a plan you can copy. Your turn next.']
];
function capLine(i){
  const k=kind(), opts=lines('options');
  switch(i){
    case 0: return `${val('goal').replace(/^./,c=>c.toUpperCase())}, in ${tf}.`;
    case 1: return `Only your ${val('area')} may change. Eyes, nose, skin and age stay as photographed.`;
    case 2: return S.goal==='custom'?'Each region gets a note: seen in your photo, or a guess to confirm.':K[k].obs;
    case 3: return opts.length?`Comparing ${opts.slice(0,4).join(', ')}.`:'Add four styles in Build to compare them here.';
    case 4: return `Checkpoints: ${val('milestones')}.`;
    case 5: return `Close-up map of ${val('detail')}.`;
    case 6: return `Then it checks that only your ${val('area')} changed, across every stage.`;
    case 7: return `${startLbl()} → ${targetLbl()} in ${tf}. Your plan is ready below.`;
  }
}
/* ---------- zone templates drawn on the face ---------- */
function geoKind(a,amt){ const st=S.look[a];
  if(a==='beard') return st==='none'?'none':st==='goatee'?'goatee':st==='mustache'?'mustache':(st==='boxed'||st==='stubble')?'short':'long';
  if(a==='hair'){ if(st==='shaved') return 'shaved'; if(st==='curly'&&amt>=2) return 'curly'; return amt<9?'short':'long'; }
  return 'brows'; }
const LIP='M158 184 Q180 178 202 184';
const CHEEK='M126 112 C126 146 134 158 148 164 L156 156 C142 150 136 140 136 112 Z';
const GCHEEK='M116 114 C112 160 128 196 156 196 L158 188 Q148 182 146 166 C134 156 126 140 126 114 Z';
function zoneGeo(a,amt,ph,g){
  g=g||S.g; const st=S.look[a], k=geoKind(a,amt), Zn={};
  if(a==='beard'){ const v=MV[st]||MV.square, L=beardL(amt), b=205+100*L, w=x=>x?`<g transform="${bT(g)}">${x}</g>`:'';
    const lip=w(`<path d="${LIP}" stroke="${C.b}" stroke-width="5" fill="none" stroke-linecap="round"/>`);
    if(k==='none'){ Zn.red=w(`<path d="${beardPath(.08,MV.square)}" fill="${C.r}" opacity=".45"/>`); Zn.blue=lip; return Zn; }
    if(k==='mustache'){ const kk=Math.min(amt,5), T=`translate(180 181) scale(${(1+kk*.05).toFixed(3)} ${(1+kk*.1).toFixed(3)}) translate(-180 -181)`;
      Zn.green=w(`<path transform="${T}" d="${MUST}" fill="${C.g}" opacity=".55"/>`);
      Zn.yellow=w(`<path transform="${T}" d="${MUST}" fill="none" stroke="${C.y}" stroke-width="2.5"/>`);
      Zn.red=w(MIR(`<path d="${GCHEEK}" fill="${C.r}" opacity=".42"/>`)+`<path d="${goateePath(.12)}" fill="${C.r}" opacity=".42"/>`);
      Zn.blue=w(`<path d="M160 186 Q180 181 200 186" stroke="${C.b}" stroke-width="3.5" fill="none" stroke-linecap="round"/>`); return Zn; }
    if(k==='goatee'){
      Zn.green=w(`<path d="${goateePath(L)}" fill="${C.g}" opacity=".5"/>`);
      Zn.yellow=w(`<path d="${goateeOuter(L)}" fill="none" stroke="${C.y}" stroke-width="4.5" stroke-linecap="round"/>`+(ph==='late'?`<path d="${goateeOuter(beardL(targetAmt(a)))}" fill="none" stroke="${C.y}" stroke-width="2.5" stroke-dasharray="5 5"/>`:''));
      Zn.red=w(MIR(`<path d="${GCHEEK}" fill="${C.r}" opacity=".45"/>`)); Zn.blue=lip; return Zn; }
    Zn.green=w(`<path d="${beardPath(L,v)}" fill="${C.g}" opacity=".5"/>`);
    Zn.yellow=w(`<path d="${beardOuter(L,v)}" fill="none" stroke="${C.y}" stroke-width="5" stroke-linecap="round"/>`+(ph==='late'?`<path d="${beardOuter(beardL(targetAmt(a)),v)}" fill="none" stroke="${C.y}" stroke-width="2.5" stroke-dasharray="6 6"/>`:''));
    Zn.red=w(MIR(`<path d="${CHEEK}" fill="${C.r}" opacity=".75"/>`)+`<circle cx="110" cy="124" r="7" fill="${C.r}" opacity=".7"/><circle cx="250" cy="124" r="7" fill="${C.r}" opacity=".7"/>`+(b<262?`<path d="M148 ${b+10} Q180 ${b+20} 212 ${b+10}" stroke="${C.r}" stroke-width="5" fill="none" stroke-linecap="round" opacity=".85"/>`:''));
    Zn.blue=lip; return Zn; }
  if(a==='hair'){ const w=x=>x?`<g transform="${hT(g)}">${x}</g>`:'';
    if(k==='shaved'){ Zn.red=w(`<path d="${shortCap(4)}" fill="${C.r}" opacity=".42"/>`); Zn.blue=w(`<path d="M128 112 C140 80 220 80 232 112" stroke="${C.b}" stroke-width="5" fill="none" stroke-linecap="round"/>`); return Zn; }
    if(k==='curly'){ const d=curlyDims(amt), RX=d.rx+d.r*.4, RY=d.ry+d.r*.4, pt=t=>`${(180+Math.cos(t)*RX).toFixed(1)} ${(d.cy+Math.sin(t)*RY).toFixed(1)}`;
      const GX=Math.max(d.rx-d.r*.2,78), GY=Math.max(d.ry-d.r*.2,84), gp=t=>`${(180+Math.cos(t)*GX).toFixed(1)} ${(d.cy+Math.sin(t)*GY).toFixed(1)}`;
      Zn.green=w(`<path d="M${gp(Math.PI*.9)} A${GX.toFixed(1)} ${GY.toFixed(1)} 0 1 1 ${gp(Math.PI*.1)}" fill="none" stroke="${C.g}" stroke-width="16" opacity=".45"/>`);
      Zn.yellow=w(`<ellipse cx="180" cy="${d.cy}" rx="${d.rx+d.r}" ry="${d.ry+d.r}" fill="none" stroke="${C.y}" stroke-width="4"/>`+(ph==='late'?(()=>{const t=curlyDims(targetAmt(a));return `<ellipse cx="180" cy="${t.cy}" rx="${t.rx+t.r}" ry="${t.ry+t.r}" fill="none" stroke="${C.y}" stroke-width="2.5" stroke-dasharray="6 6"/>`;})():''));
      const RX2=Math.max(RX,86); const pr=t=>`${(180+Math.cos(t)*RX2).toFixed(1)} ${(d.cy+Math.sin(t)*RY).toFixed(1)}`;
      Zn.red=w(`<path d="M${pr(Math.PI*.05)} A${RX2.toFixed(1)} ${RY.toFixed(1)} 0 0 1 ${pr(Math.PI*.24)}" stroke="${C.r}" stroke-width="8" fill="none" stroke-linecap="round"/><path d="M${pr(Math.PI*.76)} A${RX2.toFixed(1)} ${RY.toFixed(1)} 0 0 1 ${pr(Math.PI*.95)}" stroke="${C.r}" stroke-width="8" fill="none" stroke-linecap="round"/>`);
      Zn.blue=w(`<path d="M124 100 A56 36 0 0 1 236 100" stroke="${C.b}" stroke-width="5" fill="none" stroke-dasharray="2 9" stroke-linecap="round"/>`); return Zn; }
    if(k==='short'){ const t=capT(Math.max(amt,.5));
      Zn.green=w(`<path d="${shortCap(t)}" fill="${C.g}" opacity=".45"/>`);
      Zn.yellow=w(MIR(`<path d="M127 88 C122 98 120 108 122 118" stroke="${C.y}" stroke-width="5" fill="none" stroke-linecap="round"/>`));
      Zn.red=w(MIR(`<circle cx="120" cy="142" r="11" fill="none" stroke="${C.r}" stroke-width="4"/><path d="M124 120 L124 132" stroke="${C.r}" stroke-width="5" stroke-linecap="round"/>`));
      Zn.blue=w(`<path d="M134 90 C150 72 210 72 226 90" stroke="${C.b}" stroke-width="5" fill="none" stroke-linecap="round"/>`); return Zn; }
    const b=hairB(amt), bt=hairB(targetAmt(a)), bv=Math.min(b,306);
    Zn.green=w(b>=165?MIR(`<path d="${curtainB(b,st)}" fill="${C.g}" opacity=".45"/>`):MIR(`<path d="M106 122 C100 ${b-14} 106 ${b} 118 ${b} L126 ${b-8} L128 122 Z" fill="${C.g}" opacity=".45"/>`));
    const y0=Math.max(112,b-120);
    Zn.yellow=w((b-14>y0+12?MIR(`<path d="M102 ${y0} C98 ${(y0+(b-y0)*.4).toFixed(1)} 100 ${(y0+(b-y0)*.7).toFixed(1)} 104 ${b-14}" stroke="${C.y}" stroke-width="6" fill="none" stroke-linecap="round"/>`):'')+(ph==='late'&&bt>b+4?(()=>{const y=Math.min(bt,306);return MIR(`<path d="M103 ${y-6} Q114 ${y+3} 136 ${y-1}" stroke="${C.y}" stroke-width="3" fill="none" stroke-dasharray="5 5"/>`);})():''));
    Zn.red=w(MIR(`<path d="M103 ${bv-6} Q114 ${bv+3} ${bv<215?126:136} ${bv-1}" stroke="${C.r}" stroke-width="7" fill="none" stroke-linecap="round" opacity=".9"/>`));
    Zn.blue=w(MIR(`<path d="M128 120 C126 ${Math.min(152,b-30)} 129 ${Math.min(178,b-16)} 134 ${Math.min(200,b-6)}" stroke="${C.b}" stroke-width="6" fill="none" stroke-linecap="round"/>`));
    return Zn; }
  const wd=2.5+6*amt+4;
  Zn.green=MIR(`<path d="${browD(st)}" stroke="${C.g}" stroke-width="${wd}" stroke-linecap="round" fill="none" opacity=".6"/>`);
  Zn.yellow=MIR(`<path d="M150 101 l1 -4 M156 100 l1 -4 M162 101 l1 -4" stroke="${C.y}" stroke-width="2.4" stroke-linecap="round"/>`);
  Zn.red=`<ellipse cx="180" cy="114" rx="6" ry="7" fill="${C.r}" opacity=".7"/>`+MIR(`<circle cx="140" cy="120.5" r="1.5" fill="${C.r}"/><circle cx="145" cy="121" r="1.5" fill="${C.r}"/><circle cx="150" cy="121" r="1.5" fill="${C.r}"/>`);
  Zn.blue=MIR(`<circle cx="140" cy="117" r="4.5" fill="none" stroke="${C.b}" stroke-width="2.4"/>`);
  return Zn;
}
/* outline of an area, for target and edit-zone hints */
function areaOutline(a,amt,at){ const st=S.look[a], g=S.g;
  if(a==='beard'){ if(st==='none') return ''; const L=beardL(amt); return `<g transform="${bT(g)}"><path d="${st==='goatee'?goateeOuter(L):beardOuter(L,MV[st]||MV.square)}" fill="none" ${at}/></g>`; }
  if(a==='hair'){ if(st==='curly'&&amt>=2){ const c=curlyDims(amt); return `<g transform="${hT(g)}"><ellipse cx="180" cy="${c.cy}" rx="${c.rx+c.r}" ry="${c.ry+c.r}" fill="none" ${at}/></g>`; }
    return `<g transform="${hT(g)}"><path d="${amt>=9?hairBackPath(hairB(amt),st):shortCap(capT(Math.max(amt,.5)))}" fill="none" ${at}/></g>`; }
  return MIR(`<path d="${browD(st)}" fill="none" ${at}/>`); }
/* every goal area's zones at a given month; zones not used that month stay faint */
function overlayAt(mo,focus,all){ let s='';
  goalAreas().filter(a=>all||!tplArea||tplArea===a).forEach(a=>{ const amt=amountAt(a,mo), ph=phaseAt(a,mo), act=actsFor(a,ph), Zg=zoneGeo(a,amt,ph);
    ZONEKEYS.forEach(z=>{ if(!Zg[z]) return; const op=focus?(focus===z?1:.07):(act[z]?1:.16); s+=`<g opacity="${op}">${Zg[z]}</g>`; }); });
  return s; }
/* ---------- natural regrowth between cleanups: curls, flyaways, strays (the "before"), and what scissors remove (the "after") ---------- */
function rng(s){ s=s%2147483647; if(s<=0) s+=2147483646; return ()=>((s=s*16807%2147483647)-1)/2147483646; }
function bz3(p0,p1,p2,p3,t){ const u=1-t; return [u*u*u*p0[0]+3*u*u*t*p1[0]+3*u*t*t*p2[0]+t*t*t*p3[0],u*u*u*p0[1]+3*u*u*t*p1[1]+3*u*t*t*p2[1]+t*t*t*p3[1]]; }
function bz2(p0,p1,p2,t){ const u=1-t; return [u*u*p0[0]+2*u*t*p1[0]+t*t*p2[0],u*u*p0[1]+2*u*t*p1[1]+t*t*p2[1]]; }
const F1=n=>(+n).toFixed(1);
function curlOut(p,c,r,col,sw){ let nx=p[0]-c[0], ny=p[1]-c[1]; const d=Math.hypot(nx,ny)||1; nx/=d; ny/=d;
  return `<path d="M${F1(p[0]-nx*2)} ${F1(p[1]-ny*2)} q${F1(nx*r-ny*r)} ${F1(ny*r+nx*r)} ${F1(nx*r*1.7)} ${F1(ny*r*1.7)} q${F1(ny*r*.9)} ${F1(-nx*r*.9)} ${F1(-nx*r*.5)} ${F1(-ny*r*.5)}" stroke="${col}" stroke-width="${sw}" fill="none" stroke-linecap="round"/>`; }
const dash=(x,y,dx,dy,col,sw)=>`<path d="M${F1(x)} ${F1(y)} l${F1(dx)} ${F1(dy)}" stroke="${col}" stroke-width="${sw||1.5}" stroke-linecap="round"/>`;
function messGeo(a,amt,g){
  g=g||S.g; const st=S.look[a], hc=HAIRCOL[g], M={}, R=rng(97+Math.round(amt*10));
  if(a==='beard'){ if(amt<.25&&st!=='none') return M; const w=x=>x?`<g transform="${bT(g)}">${x}</g>`:'';
    const k=geoKind(a,amt), v=MV[st]||MV.square, L=beardL(amt), b=205+100*L;
    let red='';
    if(k==='none'||k==='goatee'||k==='mustache'){ const n=k==='none'?70:k==='mustache'?56:44; for(let i=0;i<n;i++){ let x=118+R()*124, y=118+R()*(k==='none'?90:72); if(k==='goatee'&&x>154&&x<206&&y>176) continue; if(x>162&&x<198&&y>168&&y<194) continue; red+=`<circle cx="${F1(x)}" cy="${F1(y)}" r=".7" fill="${hc}" opacity=".5"/>`; } }
    else { [0,1].forEach(m=>{ for(let i=0;i<6;i++){ const x=130+R()*15, y=122+R()*20, xx=m?360-x:x; red+=dash(xx,y,(m?1:-1)*(1+R()*2),3+R()*2,hc,1.4); } });
      if(b<262) for(let i=0;i<7;i++) red+=dash(158+R()*44,b+14+R()*16,R()*3-1.5,3+R()*2,hc,1.4); }
    M.red=w(red);
    if(amt>=1&&k!=='none'){ let blue=''; for(let i=0;i<6;i++){ const x=165+i*6+R()*2; blue+=dash(x,179+R()*1.5,R()*2-1,5+R()*3,hc,1.5); } M.blue=w(blue); }
    if(k==='mustache'&&amt>=1){ M.yellow=w([[153,182,-1],[207,182,1]].map(([x,y,d])=>curlOut([x,y],[180,178],2.6,hc,1.8)+curlOut([x+d*2,y+3],[180,176],2.2,hc,1.6)).join('')); }
    if(amt>=1.5&&k!=='none'&&k!=='mustache'){ let yel=''; const r=2.2+Math.min(amt,14)*.32, sw=2+Math.min(amt,12)*.06;
      if(k==='goatee'){ const bb=196+100*L, c=[180,192]; for(let i=0;i<6;i++){ const t=.3+R()*.7, p=bz3([158,186],[156,bb-10],[168,bb],[180,bb+5],t); yel+=curlOut(p,c,r,hc,sw)+curlOut([360-p[0],p[1]],c,r,hc,sw); } }
      else { const W=v.w*L, T=v.tip*L, kk=v.k, c=[180,(114+b)/2-8], n=Math.min(9,Math.round(2+amt*.55));
        for(let i=0;i<n;i++){ const t=.32+R()*.68, p=bz3([116,114],[112-W,170],[118-W,b-38],[180-kk-8,b-6],t); yel+=curlOut(p,c,r*(k==='short'?.55:1),hc,sw)+curlOut([360-p[0]+R()*3,p[1]+R()*4],c,r*(k==='short'?.55:1),hc,sw); }
        for(let i=0;i<Math.round(n/2);i++){ const p=bz2([180-kk-8,b-6],[180,b+6+T],[180+kk+8,b-6],R()); yel+=curlOut(p,c,r*(k==='short'?.55:1),hc,sw); } }
      M.yellow=w(yel); }
    return M; }
  if(a==='hair'){ const w=x=>x?`<g transform="${hT(g)}">${x}</g>`:''; const k=geoKind(a,amt);
    if(k==='shaved'){ let red=''; for(let i=0;i<60;i++){ const t=Math.PI*(1.08+R()*.84), rr=R(); red+=`<circle cx="${F1(180+Math.cos(t)*54*rr)}" cy="${F1(118+Math.sin(t)*62*rr)}" r=".9" fill="${hc}" opacity=".7"/>`; } M.red=w(red);
      let blue=''; for(let i=0;i<10;i++){ const x=132+R()*96; blue+=dash(x,84+Math.abs(x-180)*.35,R()*2-1,3,hc,1.2); } M.blue=w(blue); return M; }
    if(k==='curly'){ const d=curlyDims(amt), c=[180,d.cy]; let yel='', red='', blue='';
      for(let i=0;i<28;i++){ const t=R()*Math.PI*2; yel+=curlOut([180+Math.cos(t)*(d.rx+d.r*.9),d.cy+Math.sin(t)*(d.ry+d.r*.9)],c,3+R()*2.5,hc,1.6); }
      for(let i=0;i<9;i++){ const q=R()*.36, t=Math.PI*(q<.18?.08+q:.74+q), x=180+Math.cos(t)*(d.rx+d.r*.7), y=d.cy+Math.sin(t)*(d.ry+d.r*.7); red+=dash(x,y,-2,5,hc,1.3)+dash(x,y,2,5,hc,1.3); }
      for(let i=0;i<7;i++){ const t=Math.PI*(1.15+R()*.7); blue+=curlOut([180+Math.cos(t)*60,100+Math.sin(t)*40],[180,110],2.5+R()*1.5,hc,1.5); }
      M.yellow=w(yel); M.red=w(red); M.blue=w(blue); return M; }
    if(k==='short'){ if(amt<1.5) return M; let yel='', red='', blue='';
      [0,1].forEach(m=>{ const X=x=>m?360-x:x;
        for(let i=0;i<4;i++){ const y=94+R()*22; yel+=curlOut([X(121-R()*2),y],[180,110],2+amt*.25,hc,1.6); }
        for(let i=0;i<5;i++){ red+=dash(X(117+R()*12),128+R()*10,(m?1:-1)*(R()*2),3+R()*3,hc,1.4); }
        red+=dash(X(124),132,(m?1:-1)*.5,4+R()*2,hc,1.4); });
      for(let i=0;i<5;i++){ const x=142+R()*76; blue+=dash(x,74+Math.abs(x-180)*.22,R()*4-2,6+Math.min(amt,8)*.8,hc,1.5); }
      M.yellow=w(yel); M.red=w(red); M.blue=w(blue); return M; }
    const b=hairB(amt), bv=Math.min(b,306); let yel='', red='', blue='';
    [0,1].forEach(m=>{ const X=x=>m?360-x:x; for(let i=0;i<6;i++){ const y=118+R()*Math.max(10,b-130); yel+=`<path d="M${F1(X(100))} ${F1(y)} q${m?4:-4} -3 ${m?8:-8} 1 q${m?3:-3} 3 ${m?6:-6} 0" stroke="${hc}" stroke-width="1.5" fill="none" stroke-linecap="round"/>`; } });
    const hemY=x=>{ if(st==='blunt'||st==='bob') return bv; const dpt=st==='u'?26:16, t=(x-118)/124; return bv+2*(1-t)*t*dpt; };
    const xs=[106,113,120,127,233,240,247,254];
    xs.forEach(x=>{ const y=bv-1; red+=dash(x,y,-2.2,5,hc,1.3)+dash(x,y,2.2,5,hc,1.3)+dash(x,y,0,6,hc,1.2); });
    [[150,84,-4,13],[205,82,4,13],[176,79,-2,14]].forEach(([x,y,dx,dy])=>{ blue+=`<path d="M${x} ${y} q${dx} ${dy*.5} ${dx*.4} ${dy}" stroke="${hc}" stroke-width="1.4" fill="none" stroke-linecap="round"/>`; });
    M.yellow=w(yel); M.red=w(red); M.blue=w(blue); return M; }
  let red='', yel='', blue='';
  for(let i=0;i<5;i++) red+=dash(175+R()*10,106+R()*12,R()*2-1,2.5,hc,1.2);
  [0,1].forEach(m=>{ const X=x=>m?360-x:x;
    for(let i=0;i<3;i++) red+=dash(X(139+R()*10),119.5+R()*1.5,(m?-1:1)*1.5,1.6,hc,1.1);
    for(let i=0;i<3;i++) yel+=dash(X(151+i*5+R()*2),104,(m?-1:1)*.6,-6-R()*2,hc,1.2);
    for(let i=0;i<2;i++) blue+=dash(X(135+R()*4),117+R()*3,(m?1:-1)*2.5,1.5,hc,1.1); });
  M.red=red; M.yellow=yel; M.blue=blue; return M;
}
const NOCUT={hairLong:{early:['red']},brows:{now:['blue'],early:['blue']},hairGrowout:{now:['blue'],early:['blue']}};
function cutsNow(a,ph,z,act){ if(!S.custom&&ph==='now'&&startAmt(a)>targetAmt(a)) return true; const n=NOCUT[fam(a)]; return !!act[z]&&!(n&&n[ph]&&n[ph].includes(z)); }
/* mode: 'before' = a month of regrowth; 'after' = what is left after this month's scissors and cleanup; 'snip' = show before, then snip */
function messAt(mo,mode){ let s='';
  goalAreas().forEach(a=>{ const amt=amountAt(a,mo), ph=phaseAt(a,mo), act=actsFor(a,ph), Mg=messGeo(a,amt);
    ZONEKEYS.forEach(z=>{ if(!Mg[z]) return; const cut=cutsNow(a,ph,z,act); if(mode==='after'&&cut) return; s+=mode==='snip'&&cut?`<g class="snip">${Mg[z]}</g>`:Mg[z]; }); });
  return C.dark&&s?`<g filter="url(#rim)">${s}</g>`:s; }
/* learn stage: all four zones, animated in */
function learnZones(q,focus){ const a=kind(), t=targetAmt(a), s0=startAmt(a), Zg=zoneGeo(a,s0+(t-s0)*q,'mid');
  const d={green:.2,yellow:1.2,red:2.3,blue:3.2};
  return ZONEKEYS.filter(z=>Zg[z]).map(z=>`<g class="a-fade" style="animation-delay:${focus!=null?0:d[z]}s;opacity:${focus==null||focus===z?1:.12}">${Zg[z]}</g>`).join(''); }
function zoneLabels(focus){
  const k=kind(), dl=z=>focus!=null?0:({green:.5,yellow:1.6,red:2.6,blue:3.5})[z];
  const P0={beard:{green:[180,244,'middle'],yellow:[352,262,'end'],red:[8,150,'start'],blue:[352,192,'end']},
            hair:{green:[8,230,'start'],yellow:[352,200,'end'],red:[352,296,'end'],blue:[8,150,'start']},
            brows:{green:[8,40,'start'],yellow:[352,40,'end'],red:[180,300,'middle'],blue:[8,214,'start']}}[k];
  const NAMES={green:'LET GROW',yellow:'SHAPE LIGHTLY',red:'CLEAN UP',blue:'DETAIL'};
  return ZONEKEYS.filter(z=>focus==null||focus===z).map(z=>pill(P0[z][0],P0[z][1],NAMES[z],z==='yellow'?'#9A7A00':ZONECOL[z],'a-pop',dl(z),P0[z][2])).join('');
}
function scene(i,opt){
  opt=opt||{}; const k=kind(), Kk=K[k], still=opt.still||RM, mini=opt.mini, zo=zoomOn(); let s='';
  const P=mini?()=>'':pill;
  if(i===0){
    const tgt=k==='brows'?`<g opacity=".55">${areaOutline(k,targetAmt(k),`stroke="${C.acc}" stroke-width="10" stroke-linecap="round" stroke-dasharray="3 3"`)}</g>`:areaOutline(k,targetAmt(k),`stroke="${C.acc}" stroke-width="2.5" stroke-dasharray="6 6"`);
    s+=Z(`<g class="a-fade">${face(0)}</g><g class="a-pulse">${tgt}</g>`);
    const pr=['Keep my face'].concat(lines('priorities').slice(0,3));
    pr.forEach((p,j)=>{s+=P(10,22+j*24,`${j+1}  ${tr(p,20)}`,j?C.pill:C.b,'a-drop',.3+j*.3);});
    s+=P(350,300,'Target',C.acc,'a-pop',.8,'end');
  }
  if(i===1){
    const r= k==='beard'?{x:132,y:98,w:96,h:72}: k==='hair'?{x:134,y:98,w:92,h:92}:{x:138,y:122,w:84,h:72};
    const edit=`<g class="a-pulse" style="animation-delay:1.6s">${areaOutline(k,Math.max(startAmt(k),k==='hair'?2:.4),k==='brows'?`stroke="${C.y}" stroke-width="1.6" stroke-dasharray="2 2"`:`stroke="${C.y}" stroke-width="3"`)}</g>`;
    s+=Z(`${face(0)}<rect class="a-draw" pathLength="1" x="${r.x}" y="${r.y}" width="${r.w}" height="${r.h}" rx="12" fill="rgba(255,255,255,.08)" stroke="${C.b}" stroke-width="${zo?1.8:3}"/>${edit}`);
    if(!zo) s+=`<rect x="44" y="12" width="272" height="300" rx="10" fill="none" stroke="${C.ink}" stroke-width="1.5" opacity=".35"/>`;
    const [lx,ly]=zp(r.x+r.w/2, r.y+r.h);
    s+=P(lx,Math.min(ly+18,306),'FACE LOCKED',C.b,'a-fade',1.2,'middle');
    s+=P(180,zo?28:(k==='beard'?248:300),'Edit zone: '+tr(val('area'),14),'#8A6A00','a-fade',1.8,'middle');
  }
  if(i===2){
    s+=Z(face(0));
    if(!mini) s+=`<g class="a-scan"><rect x="0" y="-2" width="360" height="3" fill="${C.b}" opacity=".85"/><rect x="0" y="-14" width="360" height="12" fill="${C.b}" opacity=".12"/></g>`;
    Kk.scan.forEach((p,j)=>{
      const [fx,fy,obs,label,lx,ly]=p, [x,y]=zp(fx,fy), d=.6+j*.7, tw=label.length*6.1+16;
      if(!mini) s+=`<line class="a-fade" style="animation-delay:${d}s" x1="${x}" y1="${y}" x2="${lx<180?lx+tw:lx}" y2="${ly}" stroke="${C.ink}" stroke-width="1.2" opacity=".55"/>`;
      s+=`<circle class="a-pop" style="animation-delay:${d}s" cx="${x}" cy="${y}" r="${mini?9:6}" fill="${obs?C.b:'#fff'}" stroke="${C.b}" stroke-width="${mini?4:2.5}"/>`;
      s+=P(lx,ly,label,obs?C.b:'#6B7486','a-fade',d+.15);
    });
  }
  if(i===3){
    const names=lines('options');
    Kk.variants.forEach((v,j)=>{
      const x=(j%2)*180, y=Math.floor(j/2)*160, win=j===winIdx();
      s+=`<g transform="translate(${x} ${y}) scale(.5)"><rect x="6" y="6" width="348" height="308" rx="18" fill="${C.tile}"/><g clip-path="url(#tileclip)"><g class="${win?'':'a-dim'}" style="animation-delay:2.2s;${win||!still?'':'opacity:.4'}">${Z(face(1,{v}))}</g></g></g>`;
      s+=P(x+90,y+16,tr(names[j]||VNAMES[k][j],24),win?C.acc:C.pill,'a-fade',.2+j*.35,'middle');
      if(win){
        s+=`<rect class="a-draw" style="animation-delay:2s" pathLength="1" x="${x+4}" y="${y+4}" width="172" height="152" rx="12" fill="none" stroke="${C.acc}" stroke-width="${mini?8:4}"/>`;
        s+=`<g class="a-pop" style="animation-delay:2.6s"><circle cx="${x+156}" cy="${y+136}" r="${mini?22:14}" fill="${C.g}"/><path d="M${x+149} ${y+136} l5 5 l9 -10" stroke="#fff" stroke-width="3" fill="none" stroke-linecap="round"/></g>`;
      }
    });
  }
  if(i===4){
    const ms=milestones(), N=ms.length, xs=ms.map((_,j)=>40+j*(280/(N-1)));
    s+=Z(`<g data-tl="char">${personAt(0)}</g>`);
    s+=`<rect x="20" y="6" width="320" height="38" rx="12" fill="${C.panel}"/>`;
    s+=`<line x1="${xs[0]}" y1="18" x2="${xs[N-1]}" y2="18" stroke="${C.ink}" stroke-width="2" opacity=".3"/>`;
    s+=`<line data-tl="fill" x1="${xs[0]}" y1="18" x2="${xs[0]}" y2="18" stroke="${C.acc}" stroke-width="${mini?5:3}"/>`;
    xs.forEach((x,j)=>{s+=`<circle data-tl="d${j}" cx="${x}" cy="18" r="${mini?8:5.5}" fill="${C.dot}" stroke="${C.ink}" stroke-width="1.5"/>`; if(!mini) s+=`<text x="${x}" y="37" text-anchor="middle" font-family="Figtree,sans-serif" font-size="11" font-weight="700" fill="${C.ink}">${esc(ms[j].l)}</text>`;});
  }
  if(i===5){
    const q=k==='hair'?.85:k==='brows'?.9:.8, f=opt.zone==null?null:opt.zone;
    s+=Z(face(q)+learnZones(q,f));
    if(!mini) s+=zoneLabels(f);
  }
  if(i===6){
    const q=.8;
    s+=`<g transform="translate(0 30) scale(.5)"><rect x="6" y="6" width="348" height="308" rx="18" fill="${C.tile}"/><g clip-path="url(#tileclip)">${Z(face(0))}</g></g>`;
    s+=`<g transform="translate(180 30) scale(.5)"><rect x="6" y="6" width="348" height="308" rx="18" fill="${C.tile}"/>`;
    s+= `<g clip-path="url(#tileclip)">`+(still ? Z(face(q)) : `<g class="a-out" style="animation-delay:2.4s">${Z(face(q,{drift:1}))}</g><g class="a-fade" style="animation-delay:2.7s">${Z(face(q))}</g>`)+`</g>`;
    s+=`</g>`;
    s+=P(90,22,'Your photo',C.pill,'a-fade',0,'middle');
    s+=P(270,22,'Generated',C.pill,'a-fade',0,'middle');
    if(!still){
      s+=`<g class="a-pop" style="animation-delay:.9s"><g class="a-out" style="animation-delay:2.4s"><circle cx="340" cy="60" r="14" fill="${C.r}"/><path d="M334 54 l12 12 M346 54 l-12 12" stroke="#fff" stroke-width="3" stroke-linecap="round"/></g></g>`;
      s+=pill(270,206,'Face drifted, redo',C.r,'a-out',2.4,'middle').replace('style="animation-delay:2.4s"','style="animation:pop .4s 1s both, fadeOut .3s 2.4s forwards"');
    }
    s+=`<g class="a-pop" style="animation-delay:${still?0:2.9}s"><circle cx="340" cy="60" r="${mini?22:14}" fill="${C.g}"/><path d="M333 60 l5 5 l9 -10" stroke="#fff" stroke-width="3" fill="none" stroke-linecap="round"/></g>`;
    if(!mini){
      ['Same eyes, nose, skin, age','Only the '+tr(val('area'),18)+' changed','Consistent across all stages'].forEach((c,j)=>{const y=236+j*26,dd=(still?0:3.2)+j*.4;
        s+=`<g class="a-fade" style="animation-delay:${dd}s"><circle cx="70" cy="${y}" r="8" fill="${C.g}"/><path d="M66 ${y} l3 3 l5 -6" stroke="#fff" stroke-width="2.2" fill="none" stroke-linecap="round"/><text x="86" y="${y+4.5}" font-family="Source Sans 3,sans-serif" font-size="14" font-weight="600" fill="${C.ink}">${esc(c)}</text></g>`;});
    }
  }
  if(i===7){
    const ms=milestones(), N=ms.length;
    s+=`<g transform="translate(10 40) scale(.45)" class="a-fade"><rect x="6" y="6" width="348" height="308" rx="18" fill="${C.tile}"/><g clip-path="url(#tileclip)">${Z(face(0))}</g></g>`;
    s+=`<g transform="translate(188 40) scale(.45)" class="a-fade" style="animation-delay:.6s"><rect x="6" y="6" width="348" height="308" rx="18" fill="${C.tile}"/><g clip-path="url(#tileclip)">${Z(face(1))}</g></g>`;
    s+=`<path class="a-draw" style="animation-delay:.3s" pathLength="1" d="M166 112 L184 112 M178 105 L185 112 L178 119" stroke="${C.acc}" stroke-width="3.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/>`;
    s+=P(91,30,'Now: '+tr(startLbl(),14),C.pill,'a-fade',0,'middle');
    s+=P(269,30,'Goal: '+tr(targetLbl(),14),C.acc,'a-fade',.6,'middle');
    const xs=ms.map((_,j)=>36+j*(288/(N-1)));
    s+=`<line x1="${xs[0]}" y1="226" x2="${xs[N-1]}" y2="226" stroke="${C.ink}" stroke-width="2" opacity=".25"/>`;
    s+=`<line class="a-draw" style="animation-delay:1s" pathLength="1" x1="${xs[0]}" y1="226" x2="${xs[N-1]}" y2="226" stroke="${C.acc}" stroke-width="${mini?6:3.5}"/>`;
    xs.forEach((x,j)=>{s+=`<g class="a-pop" style="animation-delay:${1+j*.25}s"><circle cx="${x}" cy="226" r="${mini?10:7}" fill="${j===N-1?C.acc:C.dot}" stroke="${C.acc}" stroke-width="2.5"/></g>`; if(!mini) s+=`<text class="a-fade" style="animation-delay:${1+j*.25}s" x="${x}" y="250" text-anchor="middle" font-family="Figtree,sans-serif" font-size="11" font-weight="700" fill="${C.ink}">${esc(ms[j].l)}</text>`;});
    s+=P(180,290,'Your roadmap',C.g,'a-pop',2.6,'middle');
  }
  return s;
}
/* timeline driver: time → month → face (with the month's template on the Plan stage) */
function tlDuration(){ return 300+(milestones().length-1)*1550+1200; }
function timeline(el,t){
  if(!el.querySelector('[data-tl="char"]')) return;
  const ms=milestones(), N=ms.length, seg=1100, hold=450, t2=Math.max(0,t-300);
  let j=Math.floor(t2/(seg+hold)), r=Math.min(1,(t2-j*(seg+hold))/seg), mo;
  if(j>=N-1) mo=ms[N-1].mo; else { const e=r<.5?2*r*r:1-Math.pow(-2*r+2,2)/2; mo=ms[j].mo+(ms[j+1].mo-ms[j].mo)*e; }
  drawAt(el,mo);
}
function drawAt(el,mo,snip){
  const g=el.querySelector('[data-tl="char"]'), fill=el.querySelector('[data-tl="fill"]'); if(!g) return;
  const plan=el===svg&&phase==='plan', tpl=plan&&tplOn;
  const mess=plan?messAt(mo,baMode==='before'?'before':(snip&&!RM?'snip':'after')):'';
  g.innerHTML=personAt(mo)+mess+(tpl?`<g class="noanim">${overlayAt(mo,tplFocus)}</g>`:'');
  const ms=milestones(), N=ms.length, xs=ms.map((_,j)=>40+j*(280/(N-1)));
  let x=xs[N-1];
  for(let j=0;j<N-1;j++){ if(mo<=ms[j+1].mo+1e-9){ const f=(mo-ms[j].mo)/Math.max(1e-6,ms[j+1].mo-ms[j].mo); x=xs[j]+(xs[j+1]-xs[j])*Math.max(0,Math.min(1,f)); break; } }
  if(fill) fill.setAttribute('x2',x);
  for(let q=0;q<N;q++){ const d=el.querySelector(`[data-tl="d${q}"]`); if(d){ const on=ms[q].mo<=mo+1e-6; d.setAttribute('fill',on?C.acc:C.dot); d.setAttribute('stroke',on?C.acc:C.ink); } }
}


let DEMO='beard';
const DS={beard:{g:'man',skin:'medium',goals:['beard'],custom:false,look:{beard:'square',hair:'shaved',brows:'straight'},lvl:{beard:2},picked:{},prio:[],ready:false},
 hair:{g:'woman',skin:'medium',goals:['hair'],custom:false,look:{hair:'layers',beard:'none',brows:'soft'},lvl:{hair:4},picked:{},prio:[],ready:false},
 brows:{g:'woman',skin:'medium',goals:['brows'],custom:false,look:{brows:'soft',beard:'none',hair:'u'},lvl:{brows:1},picked:{},prio:[],ready:false}};
const DEMO_EX={
 beard:['Longest, fullest beard in 12 months. Neat, never bushy.','Only the beard may change. Eyes, nose, skin and gray strands stay put.','Dense chin, lighter upper cheeks, curls at the jaw. Cheek density is flagged as a guess.','Rounded-square wins: it keeps width for fullness without lengthening the face.','Cheek coverage never grows past what he has today. Only length and shape change.','Grow the body. Snip single curls. Clean strays above the cheek line. Trim lip hairs.','Version one widened his eyes and narrowed his head, so it was redone.','Short today to rounded-square in 12 months, with what to do at every checkpoint.'],
 hair:['Healthy mid-back length with face-framing layers in 18 months.','Only hair length and shape may change. Face, skin, color and wave stay put.','Dense crown, thinner ends, shorter face-framing pieces. Split ends are flagged as a guess.','Long layers win: ends look thicker and every stage looks intentional.','No added thickness or color. The hair only gets longer and the layers settle.','Grow the lengths. Blend layers lightly. Dust split ends only. Keep face-framing.','Version one slimmed her face and enlarged her eyes, so it was redone.','Shoulder length to long layers in 18 months, with what to do at every checkpoint.'],
 brows:['Fuller, natural brows in 6 months.','Only the brows may change. Eyes, skin and face shape stay put.','Full center, sparse tails, strays between the brows. Sparse tails are flagged as a guess.','Soft arch wins: it follows the brow bone without looking drawn on.','Sparse areas fill in over time. No added color or density beyond real growth.','Grow the body. Trim long hairs. Clean strays between. Define the tail.','Version one enlarged her eyes, so it was redone.','Sparse to a full soft arch in 6 months, with what to do at every checkpoint.']};
function withDemo(fn){ const save=JSON.parse(JSON.stringify(S)), src=SRC; Object.assign(S,JSON.parse(JSON.stringify(DS[DEMO]))); sync(); SRC=P[DEMO]; try{ return fn(); } finally { Object.keys(S).forEach(k=>delete S[k]); Object.assign(S,save); SRC=src; } }


const P={
 beard:{area:'beard',pro:'master barber, men\'s grooming consultant and facial-hair stylist',proName:'barber',
  goal:'grow the longest, fullest, most stylish beard that suits my face',timeframe:'12 months',milestones:'now, 1, 3, 6, 9 and 12 months',
  priorities:'Maximize healthy length and apparent fullness\nLook sophisticated, masculine and professional\nAvoid an unkempt or overly bushy look\nKeep maintenance simple and realistic\nAvoid trims that delay length growth',
  style:'Full, long beard (10–15+ cm if my growth allows)\nLightly tapered upper sideburns blending into my shaved head\nFull, natural cheek lines with controlled side volume\nRounded-square or subtly tapered bottom, not a sharp point\nFull, neat mustache\nNatural dark color with my gray strands kept',
  options:'Long tapered full beard\nRounded-square long beard\nSubtle ducktail\nNatural long beard with controlled side volume',
  green:'chin, lower cheeks, main beard body, under-jaw support, lower length',yellow:'single curls past the outline, flyaways at the jaw corners, minor balancing',
  red:'isolated hairs above the natural cheek line, neck hairs below the chosen neckline, strays around the ears',blue:'mustache hairs hanging over the upper lip',
  detail:'my sideburns (scalp-to-beard transition)',tools:'beard oil, an electric trimmer',risk:'cutting through the main beard with a short guard'},
 hair:{area:'hair',pro:'senior hairstylist and hair-care consultant',proName:'stylist',
  goal:'grow my hair to healthy mid-back length with soft face-framing layers',timeframe:'18 months',milestones:'now, 3, 6, 9, 12 and 18 months',
  priorities:'Keep the ends thick and healthy as length grows\nLook polished and intentional at every stage\nAvoid an awkward in-between phase where possible\nKeep daily styling under 10 minutes\nAvoid trims that take back my growth',
  style:'Mid-back length with soft long layers\nFace-framing pieces starting around the cheekbones\nThick, healthy-looking ends\nMy natural color and texture',
  options:'One-length blunt cut\nU-shape\nV-shape\nLong layers with face-framing',
  green:'mid-lengths and all the length I am growing',yellow:'light layer blending and shape balancing',red:'split or damaged ends only (a dusting of a few millimeters)',blue:'face-framing pieces and fringe',
  detail:'my face-framing pieces and fringe',tools:'shampoo, conditioner, a blow-dryer, a flat iron',risk:'a stylist taking off "just a few inches" at every visit, and heat damage from daily hot tools'},
 brows:{area:'eyebrows',pro:'brow specialist and grooming consultant',proName:'brow artist',
  goal:'grow fuller, natural-looking brows that suit my face',timeframe:'6 months',milestones:'now, 1, 2, 3, 4 and 6 months',
  priorities:'Let sparse areas fill in\nLook groomed during the grow-out\nKeep my natural arch\nNo daily makeup required',
  style:'Natural, fuller brows\nSoft start and a defined tail\nBrushed-up texture',
  options:'Straight natural brow\nSoft arch\nHigh arch\nBrushed-up feathered brow',
  green:'the brow body and any sparse areas filling in',yellow:'long hairs that extend past the brushed-up shape',red:'strays between the brows and well below the arch',blue:'the tail and where it ends',
  detail:'the brow tails and the space between the brows',tools:'tweezers, a spoolie',risk:'over-tweezing hairs that would have filled in the shape'},
 custom:{}
};
const MS={'3 months':'now, 2 weeks, 1, 2 and 3 months','6 months':'now, 1, 2, 3, 4 and 6 months','12 months':'now, 1, 3, 6, 9 and 12 months','18 months':'now, 3, 6, 9, 12 and 18 months','24 months':'now, 3, 6, 12, 18 and 24 months'};
P.beard.pro='master barber, grooming consultant and facial-hair stylist';
P.custom={area:'',pro:'',proName:'barber or stylist',goal:'',timeframe:'12 months',milestones:MS['12 months'],priorities:'',style:'',options:'',green:'',yellow:'',red:'',blue:'',detail:'',tools:'',risk:''};
const VB={face:'60 20 240 300',beard:'92 76 176 244',hair:'30 6 300 314',brows:'126 88 108 52'};
function goalIcon(g){
  if(g==='custom') return `<svg viewBox="0 0 80 64"><circle cx="40" cy="32" r="22" fill="none" stroke="currentColor" stroke-width="3" stroke-dasharray="5 5" opacity=".5"/><path d="M40 22v20M30 32h20" stroke="currentColor" stroke-width="4" stroke-linecap="round"/></svg>`;
  const lk={...S.look}; if(!S.goals.includes(g)||S.custom) lk[g]=goalDef(g);
  const st=stOf((a,s)=>targetAmt(a,s)*(a===g?.75:1),{look:lk});
  if(g==='beard'&&st.hair.a>9) st.hair.a=6;
  return `<svg viewBox="${g==='brows'?'122 86 116 56':g==='beard'?'96 64 168 210':'40 10 280 300'}">${person(st)}</svg>`;
}
const PRIOS={beard:['Maximum length','Fullness','Professional look','Never looks bushy','Low daily effort','No length-losing trims'],
 hair:['Maximum length','Thick, healthy ends','Polished at every stage','Low daily effort','No big chops','Less heat damage'],
 brows:['Fill sparse areas','Keep my natural arch','Groomed during grow-out','No daily makeup','Natural look','Even on both sides'],
 custom:['Maximum growth','Fullness','Polished at every stage','Low daily effort','Natural look','No setbacks']};

const ACT={
 beardLong:{
  now:{green:'Comb and oil daily. No guard on the main beard.',red:'Clean strays above the cheek line and below the neckline.',blue:'Trim mustache hairs over the lip.'},
  early:{green:'Let it grow. No trims for length; this is the awkward phase.',red:'Tidy the cheek line and neckline every 1 to 2 weeks.',blue:'Snip lip hairs as needed.'},
  mid:{green:'Keep all the length. A little balm lays down jaw-corner curls.',yellow:'Scissors only on single curls past the outline.',red:'Cheek line and neckline weekly.',blue:'Keep the lip line clear.'},
  late:{green:'Keep all the under-jaw length.',yellow:'Shape the bottom toward the {t}: remove only what sticks out past the dashed line.',red:'Cheek line and neckline weekly.',blue:'Keep the lip line clear.'},
  goal:{green:'Oil and comb daily.',yellow:'Monthly shape check to hold the {t}.',red:'Edges weekly.',blue:'Lip line weekly.'}},
 beardShort:{
  now:{green:'Let it grow to your guard length, about {cm}.',red:'Clean the cheek line and neckline.',blue:'Trim hairs over the lip.'},
  early:{green:'Let it reach {cm}. No trimming the body yet.',red:'Edges weekly.',blue:'Lip line.'},
  mid:{green:'Same guard over the whole beard every 1 to 2 weeks.',yellow:'Square off the outline at the jaw corners.',red:'Edges weekly.',blue:'Lip line.'},
  late:{green:'Same guard over the whole beard every 1 to 2 weeks.',yellow:'Square off the outline at the jaw corners.',red:'Edges weekly.',blue:'Lip line.'},
  goal:{green:'Same guard over the whole beard every 1 to 2 weeks to hold {cm}.',yellow:'Keep the outline crisp.',red:'Cheek line and neckline weekly.',blue:'Lip line weekly.'}},
 goatee:{
  now:{green:'Let the chin and mustache grow.',red:'Shave the cheeks, jawline and neck clean.',blue:'Clear the lip line.'},
  early:{green:'Keep growing the chin and mustache.',red:'Shave cheeks and neck every 2 to 3 days.',blue:'Lip line.'},
  mid:{green:'Keep the length.',yellow:'Sharpen the goatee outline.',red:'Shave cheeks and neck every 2 to 3 days.',blue:'Tidy the mouth corners.'},
  late:{green:'Keep the length.',yellow:'Shape toward the {t}: follow the dashed line.',red:'Shave cheeks and neck every 2 to 3 days.',blue:'Mouth corners.'},
  goal:{green:'Keep the length even.',yellow:'Keep the {t} outline sharp.',red:'Shave cheeks and neck every 2 to 3 days.',blue:'Lip line and mouth corners.'}},
 mustache:{
  now:{green:'Let the mustache grow over the top lip line.',red:'Shave the cheeks, chin and neck.',blue:'Keep the lip line clear.'},
  early:{green:'Keep growing it; comb it sideways daily.',red:'Shave cheeks, chin and neck every 2 to 3 days.',blue:'Snip hairs that reach the lip.'},
  mid:{green:'Keep the length.',yellow:'Trim the outline at the mouth corners.',red:'Shave cheeks, chin and neck every 2 to 3 days.',blue:'Lip line.'},
  late:{green:'Keep the length.',yellow:'Shape toward the {t}: even both sides.',red:'Shave cheeks, chin and neck every 2 to 3 days.',blue:'Lip line.'},
  goal:{green:'Comb and a little wax daily.',yellow:'Weekly outline check.',red:'Shave cheeks, chin and neck every 2 to 3 days.',blue:'Keep the lip line clear.'}},
 beardNone:{
  now:{red:'Shave the whole beard area.',blue:'Check the neck and jawline for missed hairs.'},
  goal:{red:'Shave every 1 to 2 days, with the grain.',blue:'Check the neck and jawline.'}},
 hairLong:{
  now:{green:'Keep all the length.',red:'Dust split ends only, a few millimeters.',blue:'Lightly refresh the face-framing pieces.'},
  early:{green:'No length trims. Detangle from the ends up.',red:'Low heat and a heat protectant; no cutting.',blue:'Face-framing pieces only.'},
  mid:{green:'Keep growing.',yellow:'Blend the layers lightly so the grow-out looks intentional.',red:'Dust the ends at your salon visit.',blue:'Refresh the face-framing pieces.'},
  late:{green:'Keep the length.',yellow:'Shape the hemline toward the dashed {t} line.',red:'Remove damaged ends only.',blue:'Face-framing pieces.'},
  goal:{green:'Protect the length.',yellow:'Hold the {t} shape.',red:'Dust the ends every 10 to 12 weeks.',blue:'Refresh the face-framing pieces.'}},
 hairGrowout:{
  now:{green:'Let the top and sides grow.',red:'Tidy the neckline only.',blue:'Sweep the fringe aside and let it grow.'},
  early:{green:'Keep growing. No cuts on top.',red:'Neckline tidy every 6 to 8 weeks so the back does not run ahead.',blue:'Clip or sweep the fringe aside.'},
  mid:{green:'Keep the length on top.',yellow:'Even out the back and sides so they meet.',red:'Trim the back only if it outgrows the sides.',blue:'Blend the fringe into the sides.'},
  late:{green:'Keep the length.',yellow:'Start shaping toward the {t}.',red:'Dust the ends.',blue:'Face-framing pieces.'},
  goal:{green:'Protect the length.',yellow:'Hold the {t} shape.',red:'Dust the ends every 10 to 12 weeks.',blue:'Refresh the face-framing pieces.'}},
 hairShort:{
  now:{green:'Let the top grow to about {cm}.',red:'Clean the neckline and around the ears.',blue:'Shape the fringe or part.'},
  early:{green:'Keep growing toward {cm} on top.',red:'Neckline and ears every 2 to 3 weeks.',blue:'Fringe and hairline.'},
  mid:{green:'Keep the top at about {cm}.',yellow:'Blend the sides into the top.',red:'Neckline and ears every 2 to 3 weeks.',blue:'Fringe and hairline.'},
  late:{green:'Keep the top at about {cm}.',yellow:'Blend the sides into the top.',red:'Neckline and ears every 2 to 3 weeks.',blue:'Fringe and hairline.'},
  goal:{green:'Cut every 3 to 5 weeks to hold the {t}.',yellow:'Blend the sides into the top.',red:'Neckline and ears every 2 weeks.',blue:'Fringe and hairline.'}},
 hairShaved:{
  now:{red:'Clip or shave it all down, no guard.',blue:'Clean the hairline and around the ears.'},
  goal:{red:'Shave or clip every 2 to 4 days.',blue:'Hairline and around the ears.'}},
 hairCurly:{
  now:{green:'Keep the length. Never brush it dry.',red:'Trim only dry or split ends.',blue:'Define the front curls.'},
  early:{green:'Grow it out. Moisturize and sleep on satin.',red:'Dry ends only.',blue:'Front curls.'},
  mid:{green:'Keep growing.',yellow:'Dry cut, curl by curl, to shape the outline.',red:'Dry ends only.',blue:'Front curls and edges.'},
  late:{green:'Keep the length.',yellow:'Shape toward the dashed {t} outline.',red:'Dry ends only.',blue:'Front curls and edges.'},
  goal:{green:'Protect the curls.',yellow:'Reshape the outline every 3 to 4 months.',red:'Ends only.',blue:'Edges and front curls.'}},
 brows:{
  now:{green:'Stop tweezing the brow body.',red:'Remove only strays between the brows and well below the arch.',blue:'Brush up daily.'},
  early:{green:'Let the gaps fill. New hairs show in 2 to 3 months.',red:'Strays between the brows only.',blue:'Pencil sparse spots if you like.'},
  mid:{green:'Keep the body full.',yellow:'Trim only long hairs past the brushed-up shape.',red:'Strays only.',blue:'Brush up daily.'},
  late:{green:'Keep the body full.',yellow:'Trim long hairs past the shape.',red:'Strays only.',blue:'Define where the tail ends.'},
  goal:{green:'Brush up daily.',yellow:'Trim long hairs monthly.',red:'Weekly stray check.',blue:'Keep the tail line.'}},
 custom:{
  now:{green:'Leave {G} alone.',red:'Tidy {R}.',blue:'Detail work on {B}.'},
  early:{green:'Let {G} grow.',red:'Tidy only {R}.'},
  mid:{green:'Keep {G}.',yellow:'Lightly shape {Y}.',red:'Tidy {R}.',blue:'Detail work on {B}.'},
  late:{green:'Keep {G}.',yellow:'Shape {Y} toward your look.',red:'Tidy {R}.',blue:'Detail work on {B}.'},
  goal:{green:'Keep {G}.',yellow:'Lightly shape {Y}.',red:'Tidy {R}.',blue:'Detail work on {B}.'}}
};
const SCRIPT={
 beardLong:{now:'Clean the cheek line and the neckline only. Scissors on single flyaways. No guard on the main beard. Keep all my length.',
  early:'No trim today, please. Only tidy the neckline and the hairs over my lip. I am growing it out.',
  mid:'Shape only: scissors on the curls past the outline. Keep the width and all the length under the jaw.',
  late:'Start shaping the bottom toward a {t}: remove only what sticks out. Keep my length.',
  goal:'Keep the {t}: edges and neckline, then scissors on flyaways. Do not shorten the beard.'},
 beardShort:{now:'Clean the cheek line and neckline. Leave the rest to grow to about {cm}.',early:'Edges only, please. I am letting it reach about {cm}.',
  mid:'Same guard all over at about {cm}. Square the jaw corners and clean the edges.',late:'Same guard all over at about {cm}. Square the jaw corners and clean the edges.',
  goal:'Keep the {t}: same guard all over at about {cm}, crisp cheek line and neckline.'},
 goatee:{now:'Shave the cheeks, jawline and neck clean. Leave the chin and mustache to grow.',early:'Shave around the goatee only, please. Leave the chin and mustache.',
  mid:'Sharpen the goatee outline and shave the cheeks and neck clean.',late:'Shape toward a {t}: sharpen the outline and keep the length.',goal:'Keep the {t}: sharp outline, cheeks and neck shaved clean.'},
 mustache:{now:'Shave the cheeks, chin and neck clean. Leave the mustache to grow.',early:'Shave around the mustache only, please.',mid:'Tidy the mustache outline at the corners. Shave the rest clean.',late:'Shape the mustache evenly on both sides; keep the length.',goal:'Keep the mustache: outline and lip line, everything else shaved clean.'},
 beardNone:{goal:'Clean shave, please, including the neckline.'},
 hairLong:{now:'Dust the ends only, a few millimeters. Keep my length. Lightly refresh the face-framing pieces.',
  early:'No length off today, please. Just tidy the face-framing pieces. I am growing it out.',
  mid:'Blend the layers lightly so the grow-out looks intentional. Dust the ends only.',
  late:'Shape the hemline toward {t}, removing damaged ends only. Keep the length.',
  goal:'Keep my {t}: dust the ends only, a few millimeters, every 10 to 12 weeks.'},
 hairGrowout:{now:'Tidy the neckline only. Leave the top and sides to grow.',early:'Neckline only, please. I am growing it out.',
  mid:'Even out the back and sides so they meet. Keep all the length on top.',late:'Start shaping toward {t}. Dust the ends only.',goal:'Keep my {t}: dust the ends only, a few millimeters.'},
 hairShort:{now:'Keep about {cm} on top. Blend the sides. Clean the neckline and around the ears.',early:'Neckline and ears only, please. I am letting the top grow to about {cm}.',
  mid:'Keep about {cm} on top and blend the sides into it. Clean the neckline.',late:'Keep about {cm} on top and blend the sides into it. Clean the neckline.',
  goal:'Keep the {t}: about {cm} on top, sides blended, neckline clean.'},
 hairShaved:{goal:'All over with no guard, please. Clean the hairline and neckline.'},
 hairCurly:{now:'Dry cut, curl by curl. Remove dry ends only. Keep my length.',early:'No length off, please. Only dry ends.',
  mid:'Dry cut to shape the outline. Keep the length.',late:'Shape toward a {t} outline, removing as little as possible.',goal:'Keep the {t}: dry cut to reshape, ends only.'},
 brows:{now:'Remove only strays between the brows and well below the arch. Do not thin or reshape the body.',
  early:'Please leave my brows alone except strays between them. I am growing them out.',
  mid:'Trim only long hairs past the brushed-up shape. No tweezing the body.',
  late:'Define where the tail ends and tidy strays. Keep the body full.',
  goal:'Keep the {t}: strays and the tail only, no thinning.'}
};
/* zone texts for the AI prompt, by style family */
const ZT={
 beardShort:{green:'the whole beard at one even guard length',yellow:'the outline at the cheek line and jaw corners',red:'neck hairs below the neckline and strays above the cheek line',blue:'mustache hairs over the upper lip',detail:'my cheek line and neckline',risk:'taking the guard too short or pushing the neckline up onto the jaw'},
 goatee:{green:'the chin and mustache',yellow:'the goatee outline',red:'the cheeks, jawline and neck (shaved clean)',blue:'the lip line and mouth corners',detail:'the goatee outline and where it meets the mustache',risk:'uneven sides on the goatee outline'},
 mustache:{green:'the mustache',yellow:'the mustache outline and corners',red:'the cheeks, chin and neck (shaved clean)',blue:'the lip line',detail:'the mustache corners and lip line',risk:'uneven sides or cutting into the lip line'},
 beardNone:{green:'nothing (clean-shaven)',yellow:'nothing',red:'the whole beard area',blue:'the neck and jawline',detail:'my jawline and neck',risk:'razor irritation from shaving against the grain'},
 hairGrowout:{green:'the top and sides while they grow',yellow:'where the back and sides meet as they even out',red:'the neckline (tidy only)',blue:'the fringe as it grows past the eyes',detail:'the back and sides during the awkward stage',risk:'a stylist cutting the top to match the sides'},
 hairShort:{green:'the length on top',yellow:'where the sides blend into the top',red:'the neckline and around the ears',blue:'the fringe and hairline',detail:'the side blend and neckline',risk:'sides taken too short with the clipper'},
 hairShaved:{green:'nothing (kept shaved)',yellow:'nothing',red:'the whole scalp',blue:'the hairline edges and around the ears',detail:'the hairline and around the ears',risk:'nicks and ingrown hairs from a dull blade'},
 hairCurly:{green:'the curls and their volume',yellow:'the outer silhouette',red:'dry or split ends only',blue:'the front curls and edges',detail:'the curl pattern at the front',risk:'brushing curls dry, or a wet cut that springs up shorter'}
};
const STYLE_EXTRA={beardLong:['Full, natural cheek lines with controlled side volume','A neat, full mustache','My natural color kept, including any gray'],hairLong:['Thick, healthy-looking ends','My natural color and texture'],brows:['Natural, fuller brows','Brushed-up texture'],beardShort:['One even guard length','Crisp cheek line and neckline'],goatee:['Clean-shaven cheeks and neck','Sharp goatee outline'],hairShort:['Clean neckline','Sides blended into the top'],hairCurly:['Defined curls, no frizz','Natural texture kept'],hairGrowout:['No awkward mullet stage','Back and sides meet evenly']};
const WHERE={beard:{long:{green:'shaded beard',yellow:'outline',red:'upper-cheek patches, by the ears and the neckline',blue:'line over the lip'},
  short:{green:'shaded beard',yellow:'outline',red:'cheek patches, by the ears and the neckline',blue:'line over the lip'},
  goatee:{green:'chin and mustache',yellow:'goatee outline',red:'shaded cheeks and jaw',blue:'line over the lip'},mustache:{green:'the mustache',yellow:'mustache outline',red:'shaded cheeks and chin',blue:'lip line'},none:{red:'whole beard area',blue:'line over the lip'}},
 hair:{long:{green:'front lengths',yellow:'outer line',red:'the ends at the hem',blue:'face-framing strands'},short:{green:'top',yellow:'side lines',red:'rings at the ears and sideburns, plus the neckline behind',blue:'fringe line'},
  shaved:{red:'whole scalp',blue:'hairline'},curly:{green:'curl volume',yellow:'outer outline',red:'bottom ends',blue:'front curls'}},
 brows:{brows:{green:'shaded brow body',yellow:'ticks on top',red:'between and below the brows',blue:'tail circle'}}};
const TPL_NAME={green:'Let grow, leave alone',yellow:'Shape lightly',red:'Clean up',blue:'Detail'};
const ZNAME={green:'Green (let grow)',yellow:'Yellow (shape lightly)',red:'Red (clean up)',blue:'Blue (detail)'};
function fillT(s,a){ return s.replace(/\{t\}/g,styleName(a).toLowerCase()).replace(/\{cm\}/g,a==='brows'?'':cmTxt(targetAmt(a))).replace(/\{G\}/g,val('green')).replace(/\{Y\}/g,val('yellow')).replace(/\{R\}/g,val('red')).replace(/\{B\}/g,val('blue')); }
function actsFor(a,ph){ const f=fam(a), T=ACT[f]; let r={...(T[ph]||T.goal)};
  if(!S.custom&&ph==='now'&&startAmt(a)>targetAmt(a)){ r={...(T.goal||r)}; r.red=(targetAmt(a)<=.05?'Take it all off today.':'Cut down to the {t} today, about {cm}.')+(r.red?' Then: '+r.red.replace(/^./,c=>c.toLowerCase()):''); r.green=targetAmt(a)<=.05?null:'Keep everything that fits the {t}.'; delete r.yellow; }
  else if(!S.custom&&ph==='now'&&a==='beard'&&startAmt(a)<.5&&f!=='beardNone'){ r={green:'Let it grow from clean. Wash it daily; start beard oil once it passes 1 cm.',red:'From week 2, keep the neckline and cheek line clean.'}; }
  Object.keys(r).forEach(z=>{ if(r[z]) r[z]=fillT(r[z],a); }); return r; }
function whereFor(a,amt){ return (WHERE[a]||{})[geoKind(a,amt)]||{}; }
function scriptFor(a,ph){
  if(S.custom) return ({now:`Tidy only: ${val('red')}. Keep ${val('green')} untouched. Keep my length.`,early:`No cutting today. Tidy only: ${val('red')}.`,mid:`Light shaping only: ${val('yellow')}. Keep my length.`,late:`Shape toward my target, removing as little as possible. Keep ${val('green')}.`,goal:`Maintain the look: ${val('red')} and light shaping only.`})[ph];
  if(ph==='now'&&a==='beard'&&startAmt(a)<.5&&fam(a)!=='beardNone') return 'Nothing to cut yet. Just clean the neckline once it starts to show.';
  if(ph==='now'&&startAmt(a)>targetAmt(a)) return targetAmt(a)<=.05?'Take it all off today, please, and clean the edges.':fillT('Please cut it down to a {t} today, about {cm}. Then clean the edges.',a);
  const tb=SCRIPT[fam(a)]; return fillT(tb[ph]||tb.goal,a); }
function sayFor(e){ const A=goalAreas(); return A.map(a=>{ const t=scriptFor(a,phaseAt(a,e.mo)); return A.length>1?`${cap1(areaWord(a))}: ${t}`:t; }).join(' '); }
function growLine(a,mo){ const amt=amountAt(a,mo), s=startAmt(a), t=targetAmt(a), q=progressAt(a,mo), nm=styleName(a), A=cap1(areaWord(a));
  if(S.custom) return `${cap1(raw('area')||'Your goal')}: about ${Math.round(q*100)}% of the way`;
  if(a==='brows') return q>=.999?`Brows: filled in to the ${nm.toLowerCase()} shape`:`Brows: about ${Math.round(q*100)}% filled in`;
  if(s>t) return mo<=1e-6?`${A}: ${cmTxt(s)} today; cut to ${nm.toLowerCase()} (${cmTxt(t)})`:`${A}: kept at ${nm.toLowerCase()} (${cmTxt(t)})`;
  if(Math.abs(s-t)<1e-6) return `${A}: kept at ${nm.toLowerCase()} (${cmTxt(t)})`;
  return `${A}: about ${cmTxt(amt)}${mo>0?`, +${(amt-s).toFixed(1)} cm`:''}, ${q>=.999?nm+' length reached':Math.round(q*100)+'% of the way to '+nm}`; }
function capShort(mo){ const n=x=>x<10?x.toFixed(1):x.toFixed(0); return goalAreas().map(a=>{ const q=progressAt(a,mo); if(S.custom) return `${Math.round(q*100)}% of the way`; if(a==='brows') return `brows ${Math.round(q*100)}%`; return `${areaWord(a)} ${n(amountAt(a,mo))} cm`; }).join(', '); }
function reachNote(){ if(S.custom) return ''; const T=totalMo();
  return goalAreas().filter(a=>progressAt(a,T)<.999).map(a=> a==='brows'?`Brows need about ${Math.ceil(growMonths(a))} months to fill in fully, longer than this plan.`
    :`At natural growth your ${areaWord(a)} reaches about ${cmTxt(amountAt(a,T))} by month ${moTxt(T)}. ${styleName(a)} needs about ${cmTxt(targetAmt(a))}, around month ${Math.ceil(growMonths(a))}.`).join(' '); }
function prioList(){ if(S.custom) return PRIOS.custom; const out=[]; const CUT=['Clean, sharp edges','Easy upkeep','Looks polished right away'];
  const L=goalAreas().map(a=>startAmt(a)>targetAmt(a)?CUT.concat(PRIOS[a].filter(p=>!/length|chop|Maximum|Fill/i.test(p))):PRIOS[a]);
  for(let i=0;i<9;i++) L.forEach(l=>{ if(l[i]&&!out.includes(l[i])) out.push(l[i]); }); return out.length?out.slice(0,9):PRIOS.custom; }
function planText(){ const A=goalAreas();
  let t=`MY LOOK PLAN\nCharacter: ${GN[S.g]}\nGoal: ${val('goal')}\nStarting point: ${startLbl()}\nTarget: ${targetLbl()}\nTimeframe: ${tf}\nPriorities: 1. Keep my face  ${lines('priorities').slice(0,4).map((p,i)=>`${i+2}. ${p}`).join('  ')}\n${basis()}\n${reachNote()?reachNote()+'\n':''}\nMONTH BY MONTH\n`;
  monthEntries().forEach(e=>{ t+=`\n${e.l.toUpperCase()}${e.cp?' (checkpoint)':''}\n`;
    A.forEach(a=>{ t+=`- ${growLine(a,e.mo)}\n`; const r=actsFor(a,phaseAt(a,e.mo)); ZONEKEYS.forEach(z=>{ if(r[z]) t+=`  ${ZNAME[z]}: ${r[z]}\n`; }); });
    if(e.cp) t+=`- Say to your ${val('proName')}: "${sayFor(e)}"\n`; });
  t+=`\nRULES EVERY WEEK\n- Leave alone: ${val('green')}\n- Shape lightly: ${val('yellow')}\n- Clean up: ${val('red')}\n- Detail: ${val('blue')}\n- Never: ${val('risk')}\n\nEVERY 3 MONTHS\nTake new front and side photos and run the Look Blueprint prompt again.`;
  return t; }

const $=id=>document.getElementById(id);
const SAVED=(()=>{ try{ return JSON.parse(localStorage.getItem('lb-app3')||'null'); }catch(e){ return null; } })();
const svg=$('svg'), stage=$('stage');

/* ---------- prompt ---------- */
const FIELDS=['goal','style','options','priorities','tools','green','yellow','red','blue','detail','risk','milestones','area','pro','proName'];
let plain='';
function build(){
  const M=k=>'\u0001'+val(k)+'\u0002';
  const L_=k=>val(k).split('\n').map(x=>x.trim()).filter(Boolean);
  const pr=L_('priorities').map((x,i)=>`${i+2}. \u0001${x}\u0002`).join('\n');
  const st=L_('style').map(x=>`* \u0001${x}\u0002`).join('\n');
  const op=L_('options').map((x,i)=>`${i+1}. \u0001${x}\u0002`).join('\n');
  const t=`MASTER PROMPT — PERSONALIZED ${M('area').toUpperCase()} PLAN & VISUALIZATION

ROLE
Act as an expert ${M('pro')}, and as a careful photorealistic image editor. Own the whole workflow: analyze, design, visualize, verify, correct and deliver.

1. OBJECTIVE
Goal: ${M('goal')} over the next ${M('timeframe')}.${reachNote()?' '+reachNote()+' Show the look I will realistically have at the end of the timeframe, and the full target separately.':''}
Priorities, in order:
1. Preserve my exact facial identity in every image.
${pr}
Preferred final style:
${st}
Do not promise a specific result by a specific date. Treat all projections as illustrative.

2. SOURCE IMAGES & IDENTITY LOCK
I will attach:
A. A front-facing photo of me.
B. A side-profile photo of me.
C. (Optional) A reference layout or infographic whose style I like.
Use A and B as the only identity source. Preserve my head and face shape, eyes, eyelids, ${goalAreas().includes('brows')?'':'brows, '}nose, lips, cheek structure, skin texture, natural asymmetry, apparent age, and my existing ${M('area')} pattern and color, including any gray.
Change only my ${M('area')}: length, shape, grooming and styling.
Do not beautify, de-age, slim, reconstruct or substitute my face. Do not use stock or generic faces.
Reuse my original photos as the identity source for every image, including small thumbnails. Prefer localized edits with the face protected over full regeneration.
If you cannot preserve my identity reliably, say so. Never describe an approximate likeness as exact.

3. ANALYSIS
From my photos, assess my ${M('area')} region by region: density, natural boundaries, growth direction, texture or curl, current length, asymmetries, and areas that need more time.
Label each finding OBSERVED (visible in the photos) or ASSUMED.
Do not invent measurements the photos cannot support.
Explain how to make it look deliberately shaped while allowing maximum healthy growth.

4. STYLE SELECTION
Compare these options against my actual proportions:
${op}
Choose the most flattering one and explain why. Favor natural density and clean, controlled edges over dramatic or artificial shapes.

5. VISUALS
A. Target look: one front and one side or three-quarter image at ${M('timeframe')}. Realistic, not exaggerated.
B. Progression: consistent images at ${M('milestones')}. Same face, angle, expression and lighting. Growth must look natural; do not invent density or coverage I don't have.
C. Zone map drawn on my own photos, color-coded:
   GREEN (leave alone / let grow): ${M('green')}
   YELLOW (light shaping only): ${M('yellow')}
   RED (clean up / remove): ${M('red')}
   BLUE (detail zone): ${M('blue')}
   Mark exact areas. Make clear that a colored region is an area to check, not an area to cut in full.
D. Close-up of ${M('detail')}: where it starts, where light work is allowed, where it must stop, and what stays untouched. Give tool settings only if they fit my actual length.
E. One-page master infographic for my phone: current views, target look, zone map, milestones, detail instructions, weekly routine, minimal tools. Every face must be recognizably mine.

6. BEGINNER PROCEDURE
Give simple, safe, step-by-step answers to:
1. What do I do today?
2. What do I leave untouched?
3. How do I decide whether a borderline hair or section needs cutting, or just styling back into place?
4. Which tools should I use, and which settings, if any?
5. How do I keep ${M('detail')} tidy while growing?
6. Where exactly are my lines and boundaries?
7. How do I avoid accidentally losing length?
8. How do I keep both sides balanced?
9. When should I stop and just let it grow?
Only shape after combing or brushing it into its normal position.
Warn me explicitly about: ${M('risk')}.

7. TOOLS & PRODUCTS
I already own: ${M('tools')}.
Recommend extra purchases only if they add real value. Prioritize affordable, simple options, and tell me what to skip.

8. MAINTENANCE PLAN (${M('timeframe')})
Daily: quick grooming and product use.
Weekly or biweekly: small cleanups and detail work.
Every 4–8 weeks: check the overall shape; consider minimal professional shaping that preserves length.
Every 3 months: compare photos, reassess, adjust the shape, and update projections.
Explain when doing nothing is the right call.

9. QUALITY CONTROL (before showing me any image)
1. Compare each face with my original photos.
2. Confirm the proportions are recognizably mine.
3. Confirm only the intended ${M('area')} changes were made.
4. Confirm the face is consistent across all stages.
5. Check for unrealistic density, malformed shapes or inconsistent texture.
6. Check that labels and arrows match the anatomy underneath.
7. Check that all text is readable and consistent.
8. Redo failed images instead of presenting them as successful.
If high-fidelity editing isn't possible, annotate my original photos instead and give me a separate, clearly labeled concept sketch of the style.

10. FINAL DELIVERABLES
1. Target look: front and side previews
2. Growth timeline: now to ${M('timeframe')}
3. Color-coded zone map
4. Close-up map of ${M('detail')}
5. Daily and weekly checklist
6. Tool guide: what I own, what to buy, what to skip
7. A short script I can show my ${M('proName')} so no length I want to keep gets removed
8. One-page master infographic for my phone

EXECUTION
Work autonomously through analysis, design, generation, validation and revision. My original photos are the source of truth, not earlier AI images. Identity fidelity beats visual drama. Health and density beat excessive styling.
Start by analyzing my photos, then deliver the strongest verified result you can.`;
  plain=t.replace(/[\u0001\u0002]/g,'');
  $('rPrompt').innerHTML=esc(t).replace(/\u0001/g,'<mark>').replace(/\u0002/g,'</mark>');
  renderFixes(); save();
}
function resetGoal(){
  Object.assign(S,{g:'man',skin:'medium',goals:[],custom:false,look:{...KEEP.man},lvl:{},picked:{},base:{},ready:false,prio:[]}); sync(); wz=1;
  tf='12 months'; FIELDS.forEach(k=>$('f-'+k).value=P.beard[k]||''); $('f-milestones').value=MS[tf]; composeFields(); build();
}
function optionsFor(a){ const keys=STY[a].map(x=>x[0]), i=Math.max(0,keys.indexOf(S.look[a])), st=Math.max(0,Math.min(keys.length-4,i-1)); return keys.slice(st,st+4).map(k=>styleName(a,k)); }
function composeFields(){
  if(S.custom) return; const A=goalAreas(); if(!A.length) return; const one=A.length===1;
  const pick=(a,k)=>{ const zt=ZT[fam(a)]||{}; return (k in zt)?zt[k]:P[a][k]; };
  const per=k=>one?pick(A[0],k):A.map(a=>`${cap1(P[a].area)}: ${pick(a,k)}`).join('; ');
  const F={};
  F.area=A.map(a=>P[a].area).join(' and ');
  F.pro=A.map(a=>P[a].pro).join(', plus ');
  { const n=[...new Set(A.map(a=>P[a].proName))]; F.proName=n.length>2?n.slice(0,-1).join(', ')+' or '+n[n.length-1]:n.join(' or '); }
  ['green','yellow','red','blue','detail','risk'].forEach(k=>F[k]=per(k));
  F.tools=[...new Set(A.flatMap(a=>P[a].tools.split(/,\s*/)))].join(', ');
  F.goal=A.map(a=>{ const from=LV[a][lvIdx(a)][0].toLowerCase(), to=styleName(a).toLowerCase(); return startAmt(a)>targetAmt(a)?`cut my ${P[a].area} from ${from} down to ${/^[aeiou]/.test(to)?'an':'a'} ${to} look`:`take my ${P[a].area} from ${from} to ${/^[aeiou]/.test(to)?'an':'a'} ${to} look`; }).join(', and ');
  const keep=AREAS.filter(a=>!isGoal(a)&&!(a==='beard'&&S.look.beard==='none')).map(a=>`Keep my ${P[a].area} as ${a==='brows'?'they are':'it is'}: ${styleName(a)}`);
  const extra=one?(STYLE_EXTRA[fam(A[0])]||[]):[];
  F.style=A.map(a=>`${one?'Preferred':cap1(P[a].area)}: ${styleName(a)}${a!=='brows'?` (about ${cmTxt(targetAmt(a))})`:''}`).concat(extra).concat(keep).join('\n');
  F.options=A.flatMap(a=>optionsFor(a).map(o=>one?o:`${cap1(P[a].area)}: ${o}`)).join('\n');
  F.priorities=(S.prio.length?S.prio:prioList().slice(0,3)).join('\n');
  F.milestones=MS[tf];
  Object.keys(F).forEach(k=>{ const el=$('f-'+k); if(el) el.value=F[k]; });
  build();
}
function setTF(k){ tf=k; $('f-milestones').value=MS[k]; build(); }
FIELDS.forEach(k=>$('f-'+k).addEventListener('input',build));

/* ---------- persistence (this browser only) ---------- */
let phase='learn', wz=1, wzPicked=false, wzTfPicked=false;
function save(){ try{ const f={}; FIELDS.forEach(k=>f[k]=$('f-'+k).value); localStorage.setItem('lb-app3',JSON.stringify({S,tf,f,wz,wzPicked,wzTfPicked,phase,c:[$('wzArea').value,$('wzGoalTxt').value,$('wzLook').value]})); }catch(e){} }
function restore(){ try{ const d=SAVED; if(!d||!d.S||!d.S.look||!Array.isArray(d.S.goals)) return null;
  Object.assign(S,d.S); S.lvl=S.lvl||{}; S.picked=S.picked||{}; if(!GEO[S.g]) S.g='man'; if(!SKINS[S.skin]) S.skin='medium'; sync();
  tf=d.tf||tf; FIELDS.forEach(k=>{ if(d.f&&k in d.f) $('f-'+k).value=d.f[k]; });
  wz=Math.min(d.wz||1,5); wzPicked=!!d.wzPicked; wzTfPicked=!!d.wzTfPicked; if(d.c){$('wzArea').value=d.c[0]||'';$('wzGoalTxt').value=d.c[1]||'';$('wzLook').value=d.c[2]||'';}
  return d.phase||null; }catch(e){ return null; } }

/* ---------- sound: Kokoro Heart clips on Web Audio, iPhone silent-mode safe ---------- */
var voiceOn=true; try{voiceOn=localStorage.getItem('lb-voice')!=='off';}catch(e){}
let AC=null, silentEl=null, src=null, narrKey=null, narrHeld=false; const BUF={};
function iosUnlock(){
  try{ if(navigator.audioSession&&navigator.audioSession.type!=='playback') navigator.audioSession.type='playback'; }catch(e){}
  if(!('audioSession' in navigator)){ try{ if(!silentEl){ silentEl=new Audio('audio/silence.mp3'); silentEl.loop=true; silentEl.setAttribute('playsinline',''); } const p=silentEl.play(); if(p&&p.catch) p.catch(()=>{}); }catch(e){} }
}
function wake(){ iosUnlock(); if(AC&&AC.state!=='running'&&!narrHeld){ try{ const p=AC.resume(); if(p&&p.catch) p.catch(()=>{}); }catch(e){} } }
['pointerdown','touchend','click','keydown'].forEach(ev=>document.addEventListener(ev,wake,{passive:true,capture:true}));
document.addEventListener('visibilitychange',()=>{ if(!document.hidden) wake(); });
function getBuf(key){ if(!BUF[key]) BUF[key]=fetch('audio/'+key+'.mp3').then(r=>r.arrayBuffer()).then(a=>new Promise((res,rej)=>AC.decodeAudioData(a,res,rej))); return BUF[key]; }
function initAudio(){
  iosUnlock();
  if(AC){ wake(); return; }
  try{ AC=new (window.AudioContext||window.webkitAudioContext)(); try{AC.resume();}catch(e){} }catch(e){ AC=null; return; }
  ['w1','w2','w3','w4','w5'].forEach(k=>getBuf(k).catch(()=>{}));
}
function stopSrc(){ if(src){ try{src.stop();}catch(e){} src=null; } }
function say(key){
  narrKey=key; stopSrc(); if(!voiceOn||!AC) return;
  getBuf(key).then(b=>{ if(narrKey!==key||!voiceOn) return; stopSrc(); src=AC.createBufferSource(); src.buffer=b; src.connect(AC.destination); src.start(); }).catch(()=>{});
}
function holdNarr(h){ narrHeld=h; if(!AC) return; try{ h?AC.suspend():AC.resume(); }catch(e){} }
let firstTap=false;
document.addEventListener('pointerdown',()=>{ if(firstTap) return; firstTap=true; initAudio(); if(phase==='learn') say('s'+(idx+1)); if(phase==='goal'&&narr(wz)) say(narr(wz)); },{capture:true});
function syncVoice(){ $('voiceBtn').setAttribute('aria-pressed',voiceOn); $('voiceLbl').textContent=voiceOn?'Voice on':'Voice off'; }
$('voiceBtn').onclick=()=>{ voiceOn=!voiceOn; try{localStorage.setItem('lb-voice',voiceOn?'on':'off');}catch(e){} syncVoice(); if(!voiceOn){ narrKey=null; stopSrc(); } else { initAudio(); if(phase==='learn') say('s'+(idx+1)); if(phase==='goal'&&narr(wz)) say(narr(wz)); } };

/* ---------- 1 LEARN: story on the stage ---------- */
const DUR=[6000,6500,7000,6500,0,7000,7000,6500];
const VDUR={"w1": 2.45, "w2": 4.12, "w3": 3.26, "w4": 1.34, "w5": 3.54, "s1": 8.64, "s2": 8.17, "s3": 11.14, "s4": 7.62, "s5": 9.19, "s6": 11.84, "s7": 8.58, "s8": 8.73};
const dur=i=>{ const base=i===4?withDemo(tlDuration):DUR[i]; return voiceOn?Math.max(base,VDUR['s'+(i+1)]*1000+1300):base; };
let idx=0, playing=!RM, holding=false, stageT=0, ended=false;
const sb=$('storybar');
for(let j=0;j<8;j++){ const b=document.createElement('button'); b.setAttribute('aria-label','Step '+(j+1)); b.innerHTML='<i><b></b></i>'; b.onclick=e=>{e.stopPropagation(); learnGo(j);}; sb.appendChild(b); }
const fills=[...sb.querySelectorAll('b')];
function drawStory(){ fills.forEach((f,j)=>f.style.width=(j<idx?100:j>idx?0:Math.min(100,stageT/dur(idx)*100))+'%'); }
function avatarSVG(){ return zoomOn()?`<g transform="translate(180 120) scale(1.5) translate(-180 -120)">${face(.9)}</g>`:face(0); }
function learnRender(){
  withDemo(()=>{
    svg.innerHTML=scene(idx);
    $('lAv').innerHTML=avatarSVG();
    let ch='';
    if(idx===2) ch=`<span class="chip"><span class="dot" style="background:${C.b}"></span>Seen in photo</span><span class="chip" style="animation-delay:.2s"><span class="dot" style="border:2px solid ${C.b}"></span>A guess to confirm</span>`;
    if(idx===5) ch=ZONEKEYS.map((z,j)=>`<span class="chip" style="animation-delay:${.2+j*1.05}s"><span class="dot" style="background:${ZONECOL[z]}"></span>${esc(tr(val(z),36))}</span>`).join('');
    $('lChips').innerHTML=ch;
    stageT=0; drawStory(); if(idx===4) timeline(svg,RM?1e9:0);
  });
  $('lK').textContent=`How it works, step ${idx+1} of 8`;
  $('lTitle').textContent=STEPS[idx][0]; $('lWhat').textContent=STEPS[idx][1]; $('lEx').textContent=DEMO_EX[DEMO][idx];
  say('s'+(idx+1)); syncStage();
}
function learnGo(i){ ended=false; if(!RM&&!holding) playing=true; idx=Math.max(0,Math.min(7,i)); learnRender(); }
document.querySelectorAll('[data-demo]').forEach(b=>b.onclick=()=>{ DEMO=b.dataset.demo; document.querySelectorAll('[data-demo]').forEach(x=>x.setAttribute('aria-pressed',x===b)); learnRender(); });
const ICON={pause:'<svg width="12" height="14" viewBox="0 0 12 14"><rect width="4" height="14" fill="currentColor"/><rect x="8" width="4" height="14" fill="currentColor"/></svg>',play:'<svg width="12" height="14" viewBox="0 0 12 14"><path d="M0 0l12 7-12 7z" fill="currentColor"/></svg>',replay:'<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.6" stroke-linecap="round"><path d="M4 12a8 8 0 1 0 2.4-5.7M4 4v5h5"/></svg>'};
function syncStage(){
  const story=phase==='learn';
  sb.hidden=!story; $('stageBtn').hidden=!(story||phase==='plan');
  $('sbLabel').hidden=story; $('sbLabel').textContent={goal:'Live preview',plan:'Month by month. Tap the picture to pause.',prompt:'What the AI must do'}[phase]||'';
  if(story){
    stage.classList.toggle('paused',!playing||holding); holdNarr(!playing||holding);
    $('stageBtn').innerHTML=ended?ICON.replay:playing?ICON.pause:ICON.play; $('stageBtn').setAttribute('aria-label',ended?'Replay':playing?'Pause':'Play');
  } else { stage.classList.remove('paused'); if(narrHeld) holdNarr(false); }
  if(phase==='plan'){ const end=!playOn&&pSel>=ENT.length-1; $('stageBtn').innerHTML=playOn?ICON.pause:end?ICON.replay:ICON.play; $('stageBtn').setAttribute('aria-label',playOn?'Pause':end?'Play again':'Play'); }
}
$('stageBtn').onclick=e=>{ e.stopPropagation();
  if(phase==='plan'){ heroToggle(); return; }
  if(ended){ playing=true; learnGo(0); return; } playing=!playing; syncStage(); };
let px=0,py=0,holdTimer=0,moved=false;
stage.addEventListener('pointerdown',e=>{ px=e.clientX;py=e.clientY;moved=false; if(phase==='learn') holdTimer=setTimeout(()=>{holding=true;syncStage();},280); });
stage.addEventListener('pointermove',e=>{ if(Math.abs(e.clientX-px)>10||Math.abs(e.clientY-py)>10){moved=true;clearTimeout(holdTimer);} });
stage.addEventListener('pointerup',e=>{
  clearTimeout(holdTimer);
  if(phase==='plan'){ if(!moved) heroToggle(); return; }
  if(phase!=='learn') return;
  if(holding){ holding=false; syncStage(); return; }
  const dx=e.clientX-px;
  if(Math.abs(dx)>40&&Math.abs(dx)>Math.abs(e.clientY-py)){ learnGo(dx<0?idx+1:idx-1); return; }
  if(moved) return; const r=stage.getBoundingClientRect(); learnGo((e.clientX-r.left)<r.width*.33?idx-1:idx+1);
});
stage.addEventListener('pointercancel',()=>{ clearTimeout(holdTimer); holding=false; syncStage(); });
document.addEventListener('keydown',e=>{ if(phase!=='learn'||/INPUT|TEXTAREA/.test(document.activeElement.tagName)) return; if(e.key==='ArrowRight') learnGo(idx+1); if(e.key==='ArrowLeft') learnGo(idx-1); });

/* ---------- NOW + GOAL: five short steps, live preview on the stage ---------- */
const NSTEPS=5, QS=['Who are you today?','What do you want to change?','Mix and match your look','How long can you give it?','What matters most?'];
const STEPWHY=['This picture stands in for you in every month of your plan. Pick what is true today; growth starts from here.',
 'Pick one or more. Anything you don\'t pick stays as it is today.',
 'Your goals grow from today to the style you tap. You can also restyle what you keep, to see it all together.',
 '{GROW} about 1.25 cm (½ inch) a month; brows take 3 to 4 months to fill in. If the time is too short for the full look, your plan says when you will get there.',
 'Keeping your face is always #1. Your top 3 decide what the plan and the AI prompt protect first.'];
const narr=n=>({1:'w2',2:'w1',3:'w3',4:'w4',5:'w5'})[n]||null;
let advTimer=0, wzAnim=null;
function advance(to,delay){ clearTimeout(advTimer); advTimer=setTimeout(()=>{ if(phase!=='goal') return; if(to>NSTEPS) finishGoal(); else goalShow(to); }, RM?0:(delay||420)); }
const tileSVG=(vb,inner)=>`<svg viewBox="${vb}">${inner}</svg>`;
function setGender(g){ S.g=g; AREAS.forEach(a=>{ if(!S.picked[a]) S.look[a]=isGoal(a)?goalDef(a):baseLook(a); }); sync(); S.prio=S.prio.filter(x=>prioList().includes(x)); composeFields(); }
function setToday(a,st,lv){ S.base=S.base||{}; S.base[a]=st; S.lvl[a]=lv; if(!S.picked[a]) S.look[a]=isGoal(a)?goalDef(a):st; sync(); composeFields(); }
function toggleGoal(g){
  if(g==='beard'&&noBeard()) return;
  if(g==='custom'){ S.custom=!S.custom; if(S.custom){ S.goals=[]; AREAS.forEach(a=>{ if(!S.picked[a]) S.look[a]=baseLook(a); }); } sync(); S.prio=S.prio.filter(x=>prioList().includes(x)); return; }
  S.custom=false; const i=S.goals.indexOf(g);
  if(i>=0){ S.goals.splice(i,1); if(!S.picked[g]) S.look[g]=baseLook(g); }
  else { S.goals.push(g); if(!S.picked[g]) S.look[g]=goalDef(g); }
  S.goals=AREAS.filter(a=>S.goals.includes(a)); sync(); S.prio=S.prio.filter(x=>prioList().includes(x)); composeFields();
}
function todayTiles(a){ const L=TODAY[a], cls=L.length===5?'five':'';
  return `<div class="arealbl">${cap1(areaWord(a))} today</div><div class="tiles ${cls}">${L.map(([st,n,lv])=>{ const s0=st||S.look.brows;
    const on=S.base&&S.base[a]===s0&&S.lvl[a]===lv;
    return `<button class="tile" data-ta="${a}" data-ts="${s0}" data-tv="${lv}" aria-pressed="${!!on}">${tileSVG(VB[a],person(stOf((x,s)=>targetAmt(x,s),{look:{...S.look,...(S.base||{}),[a]:s0},amt:{...todayAmts(),[a]:todayAmt(a,s0,lv)}})))}<b>${n}</b></button>`; }).join('')}</div>`; }
function mixTiles(a){ const goal=isGoal(a);
  return `<div class="arealbl">${cap1(areaWord(a))}: ${goal?'your goal':'keep as'}</div><div class="tiles">${STY[a].map(([st,n])=>`<button class="tile" data-ma="${a}" data-mv="${st}" aria-pressed="${S.look[a]===st}">${tileSVG(VB[a],person(stateQ(1,{look:{[a]:st}})))}<b>${n}</b></button>`).join('')}</div>`; }
function goalBody(){
  const B=$('gBody'), custom=S.custom; sync();
  $('gCustom').hidden=!(wz===2&&custom); $('gLook').hidden=!(wz===3&&custom); $('gWhy').textContent=STEPWHY[wz-1].replace('{GROW}',noBeard()?'Hair grows':'Hair and beards grow');
  if(wz===1){
    B.innerHTML=`<div class="tiles three">${['man','woman','neutral'].map(g=>`<button class="tile" data-gn="${g}" aria-pressed="${S.g===g}">${tileSVG('60 26 240 294',person(stOf((a,s)=>targetAmt(a,s),{g,look:{...KEEP[g],...(S.base||{})},amt:todayAmts()})))}<b>${GN[g]}</b></button>`).join('')}</div>
      <div class="arealbl">Skin tone</div><div class="swatches">${Object.keys(SKINS).map(k=>`<button class="sw" data-sk="${k}" aria-pressed="${S.skin===k}" aria-label="${k} skin tone" style="background:${SKINS[k][0]}"></button>`).join('')}</div>
      ${areasFor().map(todayTiles).join('')}
      <p class="help">No sound? Turn the volume up and tap once; it plays even when an iPhone is on silent.</p>`;
    B.querySelectorAll('[data-gn]').forEach(b=>b.onclick=()=>{ setGender(b.dataset.gn); goalBody(); goalStage(true); goalActions(); save(); });
    B.querySelectorAll('[data-sk]').forEach(b=>b.onclick=()=>{ S.skin=b.dataset.sk; goalBody(); goalStage(true); save(); });
    B.querySelectorAll('[data-ta]').forEach(b=>b.onclick=()=>{ setToday(b.dataset.ta,b.dataset.ts,+b.dataset.tv); goalBody(); goalStage(true); save(); });
  }
  if(wz===2){
    B.innerHTML=`<div class="goals">${GOALS.filter(([g])=>!(g==='beard'&&noBeard())).map(([g,t,sub])=>`<button class="goal" data-g="${g}" aria-pressed="${g==='custom'?S.custom:(!S.custom&&S.goals.includes(g))}">${goalIcon(g)}<b>${t}</b><small>${sub}</small></button>`).join('')}</div>`;
    B.querySelectorAll('[data-g]').forEach(b=>b.onclick=()=>{ toggleGoal(b.dataset.g); wzPicked=true; goalBody(); goalStage(true); goalActions(); save(); if(b.dataset.g==='custom'&&S.custom) $('wzArea').focus(); });
    $('wzLv').innerHTML=GENLV.map(([n],j)=>`<button type="button" data-cl="${j}" aria-pressed="${S.lvl.custom===j}">${n}</button>`).join('');
    $('wzLv').querySelectorAll('[data-cl]').forEach(b=>b.onclick=()=>{ S.lvl.custom=+b.dataset.cl; goalBody(); goalStage(true); goalActions(); save(); });
  }
  if(wz===3){
    const order=custom?[kind()].concat(areasFor().filter(a=>a!==kind())):goalAreas().concat(areasFor().filter(a=>!isGoal(a)));
    B.innerHTML=order.map(mixTiles).join('');
    B.querySelectorAll('[data-ma]').forEach(b=>b.onclick=()=>{ const a=b.dataset.ma; S.look[a]=b.dataset.mv; S.picked[a]=true; composeFields(); goalBody(); goalStage(true); wzAnim={type:'grow',t:0}; save(); });
  }
  if(wz===4){
    B.innerHTML=`<div class="tiles five">${Object.keys(MS).map(m=>`<button class="tile big" data-tf="${m}" aria-pressed="${wzTfPicked&&tf===m}"><b>${m.split(' ')[0]}</b><small>months</small></button>`).join('')}</div>`;
    B.querySelectorAll('[data-tf]').forEach(b=>b.onclick=()=>{ setTF(b.dataset.tf); wzTfPicked=true; composeFields(); goalBody(); wzAnim={type:'tl',t:0}; goalStage(false); goalActions(); advance(5,700); });
  }
  if(wz===5){
    const list=prioList();
    B.innerHTML=`<div class="prios">${list.map(p=>{const i=S.prio.indexOf(p);return `<button data-p="${esc(p)}" aria-pressed="${i>=0}"><i>${i>=0?i+2:''}</i>${esc(p)}</button>`;}).join('')}</div>`;
    B.querySelectorAll('[data-p]').forEach(b=>b.onclick=()=>{ const p=b.dataset.p, i=S.prio.indexOf(p); clearTimeout(advTimer); let added=false; if(i>=0) S.prio.splice(i,1); else if(S.prio.length<3){ S.prio.push(p); added=true; } goalBody(); goalCap(); save(); if(added&&S.prio.length===3) advance(6,650); });
  }
}
function goalCap(){
  const gl=S.custom?('Something else'+($('wzArea').value.trim()?': '+$('wzArea').value.trim():'')):(S.goals.length?S.goals.map(cap1).join(' + '):'Pick at least one');
  const t=[`Today: ${GN[S.g]}. ${cap1(todayLbl())}`, gl, `${startLbl()} → ${targetLbl()}`, `${targetLbl()} in ${wzTfPicked?tf:'how long?'}`,
    S.prio.length?S.prio.map((p,i)=>`${i+2}. ${p}`).join('  '):'Pick what matters most'][wz-1];
  $('stageCap').hidden=false; $('stageCap').textContent=t;
}
function goalStage(reset){
  if(reset) wzAnim=null;
  let s='';
  if(wz===1) s=`<g class="a-pop">${person(stOf((a,st)=>targetAmt(a,st),{look:{...S.look,...(S.base||{})},amt:todayAmts()}))}</g>`;
  if(wz===2){ const out=goalAreas().map(a=>areaOutline(a,targetAmt(a),a==='brows'?`stroke="${C.acc}" stroke-width="8" stroke-linecap="round" stroke-dasharray="3 3" opacity=".6"`:`stroke="${C.acc}" stroke-width="2.5" stroke-dasharray="6 6"`)).join('');
    s=Z(`<g class="a-pop">${face(0)}</g><g class="a-pulse">${(S.custom||S.goals.length)?out:''}</g>`); }
  if(wz===3) s=Z(`<g data-wz="char">${face(0)}</g>`);
  if(wz>=4){ s=scene(4,{}); if(!wzAnim) wzAnim={type:'tl',t:0}; }
  svg.innerHTML=s; goalCap();
  if(wz===3&&!wzAnim) wzAnim={type:'grow',t:0};
  if(wz>=4) timeline(svg,RM?1e9:0);
  if(wz===3&&RM){ const g=svg.querySelector('[data-wz="char"]'); if(g) g.innerHTML=face(1); }
}
function wzTick(dt){
  if(!wzAnim||RM) return; wzAnim.t+=dt;
  if(wzAnim.type==='grow'){ const g=svg.querySelector('[data-wz="char"]'); if(!g){wzAnim=null;return;}
    const r=Math.min(1,wzAnim.t/1600), e=r<.5?2*r*r:1-Math.pow(-2*r+2,2)/2; g.innerHTML=face(e); if(wzAnim.t>3600) wzAnim={type:'grow',t:0}; }
  if(wzAnim.type==='tl'){ timeline(svg,wzAnim.t); if(wzAnim.t>tlDuration()+1500) wzAnim.t=0; }
}
function goalActions(){
  const m=$('actMain'); let label='Continue', on=true;
  if(wz===1) label='Next: my goal';
  if(wz===2){ on=S.custom?$('wzArea').value.trim().length>0:S.goals.length>0; if(!on) label=S.custom?'Name the area':'Pick at least one'; }
  if(wz===4){ on=wzTfPicked; if(!on) label='Tap a timeframe'; }
  if(wz===5) label='See my plan';
  m.textContent=label; m.disabled=!on; m.classList.toggle('accent',on);
  $('actBack').hidden=wz===1;
}
function goalShow(n){
  clearTimeout(advTimer); wz=n;
  $('gK').textContent=n===1?'Now':`Goal, step ${n-1} of ${NSTEPS-1}`; $('gQ').textContent=QS[n-1];
  goalBody(); goalStage(true); goalActions(); $('panel').scrollTop=0; save(); refreshPhases();
  if(phase==='goal'){ const k=narr(n); if(k) say(k); else { narrKey=null; stopSrc(); } }
}
function applyGoal(){
  if(S.custom){ const area=$('wzArea').value.trim();
    FIELDS.forEach(k=>{ $('f-'+k).value=P.custom[k]||''; });
    $('f-area').value=area; $('f-goal').value=$('wzGoalTxt').value.trim()||`grow my ${area} into a look that suits my face`;
    const look=$('wzLook').value.trim(); if(look) $('f-style').value=look;
    const D={green:`the ${area||'area'} you are growing`,yellow:'edges that stick out past your shape',red:'strays outside the area',blue:'the finest detail line',detail:`the edges of my ${area||'area'}`,risk:'cutting off growth you want to keep',tools:'scissors, a small trimmer',pro:'stylist and grooming consultant',proName:'barber or stylist',style:look||`A neat, natural ${area||'look'} that suits my face`,options:'Natural\nTrimmed close\nShaped\nFuller'};
    Object.keys(D).forEach(k=>{ if(!$('f-'+k).value.trim()) $('f-'+k).value=D[k]; });
    $('f-priorities').value=S.prio.length?S.prio.join('\n'):PRIOS.custom.slice(0,3).join('\n'); $('f-milestones').value=MS[tf]; build(); return; }
  composeFields();
}
function finishGoal(){
  if(S.custom){ if(S.lvl.custom==null) S.lvl.custom=1; const a=kind(); if(a==='beard'&&/must/i.test(raw('area'))&&!S.picked.beard) S.look.beard='mustache'; else if(a==='beard'&&/goatee|chin/i.test(raw('area'))&&!S.picked.beard) S.look.beard='goatee'; else if(targetAmt(a)<1) S.look[a]=goalDef(a); }
  else { if(!S.goals.length) S.goals=[noBeard()?'hair':'beard']; goalAreas().forEach(a=>{ if(S.lvl[a]==null) S.lvl[a]=lvIdx(a); }); }
  sync(); applyGoal(); S.ready=true; pSel=0; showPhase('plan'); }
$('gRestart').onclick=()=>{ clearTimeout(advTimer); wzPicked=false; wzTfPicked=false; resetGoal(); ['wzArea','wzGoalTxt','wzLook'].forEach(id=>$(id).value=''); goalShow(1); refreshPhases(); };
['wzArea','wzGoalTxt','wzLook'].forEach(id=>$(id).addEventListener('input',()=>{ if(id==='wzArea') $('f-area').value=$(id).value; goalActions(); goalCap(); save(); }));

/* ---------- 3 PLAN: month-by-month templates generated from your answers ---------- */
let baMode='after', tplOn=true, tplFocus=null, tplArea=null, pSel=0, heroMo=0, heroTo=0, ENT=[];
function msPerMo(){ return Math.max(380,Math.min(900,9000/Math.max(1,totalMo()))); }
const HOLD=2800; let playOn=false, holdT=0, heroRate=.002;
function heroTick(dt){
  if(heroMo<heroTo&&RM){ heroMo=heroTo; drawAt(svg,heroMo,false); holdT=0; return; }
  if(heroMo<heroTo){ heroMo=Math.min(heroTo,heroMo+dt*heroRate); drawAt(svg,heroMo,heroMo>=heroTo); if(heroMo>=heroTo) holdT=0; return; }
  if(playOn){ holdT+=dt; if(holdT>=HOLD){ if(pSel<ENT.length-1) stepTo(pSel+1); else { playOn=false; syncStage(); } } } }
function stepTo(i){ pSel=i; heroTo=ENT[i].mo; heroRate=Math.max(1e-4,(heroTo-heroMo)/650); holdT=0; if(heroMo>=heroTo||RM){ heroMo=heroTo; drawAt(svg,heroMo,!RM); } planMark(); }
function heroJump(i){ playOn=false; pSel=Math.max(0,Math.min(ENT.length-1,i)); heroMo=heroTo=ENT[pSel].mo; drawAt(svg,heroMo,true); planMark(); syncStage(); }
function heroGo(i){ playOn=false; i=Math.max(0,Math.min(ENT.length-1,i)); heroMo=Math.min(ENT[i].mo,ENT[Math.max(0,i-1)].mo); stepTo(i); syncStage(); }
function heroPlayAll(){ ENT=ENT.length?ENT:monthEntries(); playOn=true; heroMo=0; heroTo=0; pSel=0; holdT=0; drawAt(svg,0,!RM); planMark(); syncStage(); }
function heroToggle(){ if(playOn){ playOn=false; } else if(pSel>=ENT.length-1&&heroMo>=heroTo){ heroPlayAll(); return; } else { playOn=true; holdT=Math.min(holdT,HOLD-1200); } syncStage(); }
function legendRender(){
  const e=ENT[pSel]||{mo:0,l:'Now'}, A0=goalAreas(); if(tplArea&&!A0.includes(tplArea)) tplArea=null; const A=tplArea?[tplArea]:A0, multi=A.length>1;
  const ta=$('tplAreas'); ta.hidden=A0.length<2||!tplOn;
  if(A0.length>1){ ta.innerHTML=[null].concat(A0).map(a=>`<button type="button" data-ta="${a||''}" aria-pressed="${tplArea===a}">${a?cap1(areaWord(a)):'All'}</button>`).join('');
    ta.querySelectorAll('[data-ta]').forEach(b=>b.onclick=()=>{ tplArea=b.dataset.ta||null; svg.innerHTML=scene(4,{}); legendRender(); drawAt(svg,heroMo); }); }
  const info=A.map(a=>{ const amt=amountAt(a,e.mo), ph=phaseAt(a,e.mo); return {a,act:actsFor(a,ph),zg:zoneGeo(a,amt,ph),wh:whereFor(a,amt)}; });
  $('pLegend').innerHTML=ZONEKEYS.map(z=>{
    const rows=info.filter(x=>x.zg[z]||x.act[z]); if(!rows.length) return '';
    const any=rows.some(x=>x.act[z]), tag=z==='green'?(any?'Grow':'Rest'):(any?'This month':'Not yet');
    const body=rows.map(x=>`<small><u>${multi?esc(cap1(areaWord(x.a)))+': ':''}${x.wh[z]?'On the face: '+esc(x.wh[z])+'.':'Not drawn for this style.'}</u> ${esc(x.act[z]||(z==='green'?'Nothing to grow here.':'Nothing this month.'))}</small>`).join('');
    return `<button type="button" class="lg" data-z="${z}" aria-pressed="${tplFocus===z}"><i class="${z==='yellow'||z==='blue'?'ln':''}" style="background:${ZONECOL[z]};border-color:${ZONECOL[z]}"></i><span><b>${TPL_NAME[z]}</b>${body}</span><em class="${any?'go':''}">${tag}</em></button>`; }).join('');
  $('pLegend').classList.toggle('solo',tplFocus!=null); $('pLegend').classList.toggle('off',!tplOn);
  $('tplNote').textContent=tplOn?(tplFocus?`Showing only ${TPL_NAME[tplFocus].toLowerCase()}. Tap it again to see all four.`:`Bright colors are this month's jobs; faint ones wait for a later month. Tap a color to see only that zone.`):'Template hidden. Turn it on to see the zones on the face.';
  $('tplOn').setAttribute('aria-pressed',tplOn); $('tplOff').setAttribute('aria-pressed',!tplOn);
  document.querySelectorAll('#pLegend [data-z]').forEach(b=>b.onclick=()=>{ tplFocus=tplFocus===b.dataset.z?null:b.dataset.z; legendRender(); drawAt(svg,heroMo); });
}
function baSync(){ $('baBefore').setAttribute('aria-pressed',baMode==='before'); $('baAfter').setAttribute('aria-pressed',baMode==='after'); }
$('baBefore').onclick=()=>{ baMode='before'; baSync(); drawAt(svg,heroMo); };
$('baAfter').onclick=()=>{ baMode='after'; baSync(); drawAt(svg,heroMo,true); };
$('tplOn').onclick=()=>{ tplOn=true; legendRender(); drawAt(svg,heroMo); };
$('tplOff').onclick=()=>{ tplOn=false; tplFocus=null; legendRender(); drawAt(svg,heroMo); };
$('mPrev').onclick=()=>heroJump(pSel-1);
$('mNext').onclick=()=>heroGo(pSel+1);
function planMark(){
  const e=ENT[pSel]; if(!e) return;
  $('tplTitle').textContent=`Template for ${e.l.toLowerCase()==='now'?'now':e.l}`; $('mPrev').disabled=pSel===0; $('mNext').disabled=pSel===ENT.length-1;
  $('mLbl').textContent=e.cp?`${e.l} (checkpoint)`:e.l;
  document.querySelectorAll('[data-cp]').forEach(b=>b.setAttribute('aria-current',+b.dataset.cp===pSel?'step':'false'));
  $('pGrow').innerHTML=goalAreas().map(a=>`<span>${esc(growLine(a,e.mo))}</span>`).join('');
  legendRender(); $('stageCap').hidden=true;
  const A=goalAreas(), jobs=[];
  if(A.length>1) A.forEach(a=>{ const r=actsFor(a,phaseAt(a,e.mo)); const z=['red','yellow','blue','green'].find(k=>r[k]); if(z) jobs.push([z,cap1(areaWord(a))+': '+r[z]]); });
  else { const r=actsFor(A[0],phaseAt(A[0],e.mo)); ['red','yellow','blue','green'].forEach(z=>{ if(r[z]) jobs.push([z,r[z]]); }); }
  $('explain').innerHTML=`<b>${esc(e.l)}${e.cp?' (checkpoint)':''}: ${esc(capShort(e.mo))}</b>`+jobs.slice(0,3).map(([z,t])=>`<span><i style="background:${ZONECOL[z]}"></i>${esc(t)}</span>`).join('');
}
function cardsRender(){
  const A=goalAreas(), pro=val('proName'), vb=zoomOn()?'128 78 104 74':'64 26 232 294';
  $('pCps').innerHTML=ENT.map((e,j)=>{ const acts=[];
    A.forEach(a=>{ const r=actsFor(a,phaseAt(a,e.mo)); ZONEKEYS.forEach(z=>{ if(r[z]) acts.push([z,(A.length>1?cap1(areaWord(a))+': ':'')+r[z]]); }); });
    const say=e.cp?sayFor(e):'';
    return `<div class="cp" data-cp="${j}" role="button" tabindex="0"><svg viewBox="${vb}">${personAt(e.mo)}${messAt(e.mo,'after')}${overlayAt(e.mo,null,true)}</svg><span><b>${esc(e.l)}${e.cp?' <em class="cpk">Checkpoint</em>':''}</b><small>${A.map(a=>esc(growLine(a,e.mo))).join('<br>')}</small><ul class="acts">${acts.map(([z,t])=>`<li><i style="background:${ZONECOL[z]}"></i><span>${esc(t)}</span></li>`).join('')}</ul></span>${say?`<div class="say"><span class="who">${j===0?'Say to your '+esc(pro)+' today':'Say to your '+esc(pro)+' at '+esc(e.l.toLowerCase())}</span><q>${esc(say)}</q><span class="sbtns"><button class="btn small" data-show="${j}">Show</button><button class="btn small" data-say="${j}">Copy</button></span></div>`:''}</div>`; }).join('');
  document.querySelectorAll('[data-cp]').forEach(b=>{ b.onclick=()=>heroGo(+b.dataset.cp); b.onkeydown=ev=>{ if(ev.key==='Enter'||ev.key===' '){ ev.preventDefault(); heroGo(+b.dataset.cp); } }; });
  document.querySelectorAll('[data-say]').forEach(b=>b.onclick=ev=>{ ev.stopPropagation(); copyText(sayFor(ENT[+b.dataset.say]),'Script copied'); });
  document.querySelectorAll('[data-show]').forEach(b=>b.onclick=ev=>{ ev.stopPropagation(); barberOpen(+b.dataset.show,b); });
}
/* ---------- tracker: the day you started, today's month, the next visit ---------- */
const DAYMS=864e5, MOD=30.4375;
let startISO=null; try{ startISO=localStorage.getItem('lb-start'); if(startISO&&!/^\d{4}-\d{2}-\d{2}$/.test(startISO)) startISO=null; }catch(e){}
let trackJumped=false;
const isoDay=d=>`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`;
const noon=iso=>{ const [y,m,d]=iso.split('-').map(Number); return new Date(y,m-1,d,12); };
function dateAt(mo){ return new Date(noon(startISO||isoDay(new Date())).getTime()+Math.round(mo*MOD)*DAYMS); }
function dayNo(){ return startISO?Math.floor((noon(isoDay(new Date()))-noon(startISO))/DAYMS)+1:null; }
function curIdx(){ const d=dayNo(); if(d==null) return 0; const m=(d-1)/MOD; let k=0; ENT.forEach((e,j)=>{ if(e.mo<=m+1e-6) k=j; }); return k; }
function nextVisit(){ const d=dayNo(); const m=d==null?-1:(d-1)/MOD; return ENT.findIndex(e=>e.cp&&e.mo*MOD>=m*MOD-.5&&e.mo>0)??-1; }
const nice=l=>l.toLowerCase()==='now'?'the first month':l.replace(/^(\d+) wk$/,'week $1');
const fmtDay=d=>d.toLocaleDateString(undefined,{weekday:'short',month:'short',day:'numeric'});
function setStart(iso){ startISO=iso; try{ iso?localStorage.setItem('lb-start',iso):localStorage.removeItem('lb-start'); }catch(e){} trackJumped=false; if(iso){ pSel=curIdx(); trackJumped=true; heroJump(pSel); } trackRender(); }
function trackRender(){
  const el=$('pToday'), pro=val('proName'); if(!ENT.length) return;
  if(!startISO){
    el.innerHTML=`<h3>Track it day by day</h3><p class="muted sm">Set the day you start. The plan then opens on the right month and tells you when to book your ${esc(pro)}.</p>
      <div class="trk-btns"><button type="button" class="btn small accent" id="tNow">I start today</button><label class="datef">or I started on <input type="date" id="tDate" max="${isoDay(new Date())}"></label></div>`;
    $('tNow').onclick=()=>setStart(isoDay(new Date()));
    $('tDate').onchange=ev=>{ const v=ev.target.value; if(/^\d{4}-\d{2}-\d{2}$/.test(v)&&noon(v)<=new Date(Date.now()+DAYMS)) setStart(v); };
    return;
  }
  const d=Math.max(1,dayNo()), total=Math.round(ENT[ENT.length-1].mo*MOD), done=d>total, ci=curIdx(), nv=nextVisit();
  let next='';
  if(done) next=`You reached the end of this plan. Take new front and side photos and set your next goal.`;
  else if(nv>=0){ const nd=dateAt(ENT[nv].mo), left=Math.round((noon(isoDay(nd))-noon(isoDay(new Date())))/DAYMS);
    next=`Next ${esc(pro)} visit: <b>${esc(ENT[nv].l.toLowerCase()==='now'?'today':cap1(nice(ENT[nv].l)))}</b>, ${esc(fmtDay(nd))} (${left<=0?'today':left===1?'tomorrow':'in '+left+' days'}).`; }
  el.innerHTML=`<div class="trk-top"><b class="trk-big">Day ${Math.min(d,total)}</b><span class="trk-of">of ${total}, on ${esc(nice(ENT[ci].l))} jobs</span></div>
    <div class="trk-bar"><i id="tBar"></i></div><p>${next}</p>
    <div class="trk-btns"><button type="button" class="btn small" id="tSee">See ${esc(cap1(nice(ENT[ci].l)).replace('The first month','this month'))}</button>${nv>=0&&!done?`<button type="button" class="btn small accent" id="tShow">${/[ ,]/.test(pro)?'Show at my visit':'Show my '+esc(pro)}</button>`:''}<button type="button" class="btn small" id="tCal">Add visits to my calendar</button></div>
    <button type="button" class="linkbtn" id="tReset">Started on ${esc(fmtDay(noon(startISO)))}. Change</button>`;
  $('tBar').style.width=Math.min(100,100*d/total)+'%';
  $('tSee').onclick=()=>heroJump(ci);
  if($('tShow')) $('tShow').onclick=ev=>barberOpen(nv,ev.currentTarget);
  $('tCal').onclick=calendarFile;
  $('tReset').onclick=()=>setStart(null);
}
/* calendar file: every checkpoint visit (with what to say) plus a weekly tidy reminder */
function calendarFile(){
  const pro=val('proName'), P=cap1(pro), stamp=new Date().toISOString().replace(/[-:]/g,'').replace(/\.\d+Z$/,'Z');
  const tx=t=>String(t).replace(/\\/g,'\\\\').replace(/;/g,'\\;').replace(/,/g,'\\,').replace(/\r?\n/g,'\\n');
  const fold=l=>{ const out=[]; let cur='', n=0; for(const ch of l){ const b=new TextEncoder().encode(ch).length; if(n+b>74){ out.push(cur); cur=' '; n=1; } cur+=ch; n+=b; } out.push(cur); return out.join('\r\n'); };
  const dd=d=>isoDay(d).replace(/-/g,''), L=['BEGIN:VCALENDAR','VERSION:2.0','PRODID:-//sghadimi.com//Look Blueprint//EN','CALSCALE:GREGORIAN','METHOD:PUBLISH'];
  ENT.forEach((e,j)=>{ if(!e.cp) return; const d=dateAt(e.mo); if(d<noon(isoDay(new Date()))) return;
    const acts=[]; goalAreas().forEach(a=>{ const r=actsFor(a,phaseAt(a,e.mo)); ZONEKEYS.forEach(z=>{ if(r[z]) acts.push('- '+r[z]); }); });
    L.push('BEGIN:VEVENT',`UID:lb-${dd(d)}-${j}@sghadimi.com`,`DTSTAMP:${stamp}`,`DTSTART;VALUE=DATE:${dd(d)}`,`DTEND;VALUE=DATE:${dd(new Date(d.getTime()+DAYMS))}`,
      fold('SUMMARY:'+tx(`${P} visit, ${e.l.toLowerCase()==='now'?'start':e.l.toLowerCase()} (Look Blueprint)`)),
      fold('DESCRIPTION:'+tx(`Say to your ${pro}: "${sayFor(e)}"\n\nThis month:\n${acts.join('\n')}\n\nBy then: about ${capShort(e.mo)}`)),
      'BEGIN:VALARM','ACTION:DISPLAY','TRIGGER:-P3D',fold('DESCRIPTION:'+tx(`Book your ${pro} for ${e.l.toLowerCase()}`)),'END:VALARM','END:VEVENT'); });
  const weeks=Math.max(1,Math.round(ENT[ENT.length-1].mo*MOD/7)), w1=new Date(Math.max(dateAt(7/MOD).getTime(),noon(isoDay(new Date())).getTime()));
  L.push('BEGIN:VEVENT',`UID:lb-weekly-${dd(w1)}@sghadimi.com`,`DTSTAMP:${stamp}`,`DTSTART;VALUE=DATE:${dd(w1)}`,`DTEND;VALUE=DATE:${dd(new Date(w1.getTime()+DAYMS))}`,`RRULE:FREQ=WEEKLY;COUNT=${weeks}`,
    fold('SUMMARY:'+tx('Weekly tidy (Look Blueprint)')),fold('DESCRIPTION:'+tx(`Clean up: ${val('red')}\nLeave alone: ${val('green')}\nNever: ${val('risk')}`)),'END:VEVENT','END:VCALENDAR');
  saveFile('look-blueprint-visits.ics',L.join('\r\n')+'\r\n','text/calendar','Calendar file saved. Open it to add the visits.');
}
/* inside Claude the viewer hands out files; on the open web a normal download does */
let DL=null; try{ if(window.claude&&window.claude.use) window.claude.use('downloads').then(d=>{DL=d;}).catch(()=>{}); }catch(e){}
async function saveFile(name,text,type,okMsg){
  if(DL){ try{ await DL.save({filename:name,data:text}); showToast(okMsg); }catch(e){ showToast('File not saved.'); } return; }
  const blob=new Blob([text],{type}), a=document.createElement('a');
  a.href=URL.createObjectURL(blob); a.download=name; document.body.appendChild(a); a.click(); a.remove(); setTimeout(()=>URL.revokeObjectURL(a.href),4000);
  showToast(okMsg);
}
/* barber card: big, bright, one checkpoint at a time */
let bIdx=0, bFrom=null;
const CPS=()=>ENT.map((e,j)=>e.cp?j:-1).filter(j=>j>=0);
function barberDraw(){
  const e=ENT[bIdx], pro=val('proName'), A=goalAreas();
  $('bTitle').textContent=/[ ,]/.test(pro)?'For my visit':`For my ${pro}`;
  $('bSvg').innerHTML=personAt(e.mo)+messAt(e.mo,'after')+overlayAt(e.mo,null,true);
  $('bWhen').textContent=(e.mo===0?'Today':e.l+(startISO?', '+fmtDay(dateAt(e.mo)):''))+`: ${capShort(e.mo)}`;
  $('bSay').textContent=sayFor(e);
  const acts=[]; A.forEach(a=>{ const r=actsFor(a,phaseAt(a,e.mo)); ['green','red','yellow','blue'].forEach(z=>{ if(r[z]) acts.push([z,(A.length>1?cap1(areaWord(a))+': ':'')+r[z]]); }); });
  const ZC={green:'z-g',yellow:'z-y',red:'z-r',blue:'z-b'};
  $('bActs').innerHTML=acts.map(([z,t])=>`<li><i class="${ZC[z]}"></i><span><b>${TPL_NAME[z]}:</b> ${esc(t)}</span></li>`).join('');
  const c=CPS(), k=c.indexOf(bIdx); $('bPrev').disabled=k<=0; $('bNext').disabled=k<0||k>=c.length-1;
}
function barberOpen(j,from){ bIdx=ENT[j]&&ENT[j].cp?j:(CPS()[0]||0); bFrom=from||document.activeElement; barberDraw(); $('bCard').hidden=false; $('bClose').focus(); }
function barberClose(){ $('bCard').hidden=true; if(bFrom&&bFrom.focus) bFrom.focus(); }
$('bClose').onclick=barberClose;
$('bCard').onclick=ev=>{ if(ev.target.id==='bCard') barberClose(); };
$('bPrev').onclick=()=>{ const c=CPS(), k=c.indexOf(bIdx); if(k>0){ bIdx=c[k-1]; barberDraw(); } };
$('bNext').onclick=()=>{ const c=CPS(), k=c.indexOf(bIdx); if(k<c.length-1){ bIdx=c[k+1]; barberDraw(); } };
document.addEventListener('keydown',ev=>{ if($('bCard').hidden) return;
  if(ev.key==='Escape'){ ev.preventDefault(); barberClose(); return; }
  if(ev.key==='Tab'){ const f=[...$('bCard').querySelectorAll('button:not(:disabled)')]; if(!f.length) return; const i=f.indexOf(document.activeElement);
    if(ev.shiftKey&&i<=0){ ev.preventDefault(); f[f.length-1].focus(); } else if(!ev.shiftKey&&i===f.length-1){ ev.preventDefault(); f[0].focus(); } } });
function planRender(){
  ENT=monthEntries(); if(pSel>=ENT.length) pSel=0;
  svg.innerHTML=scene(4,{}); heroMo=heroTo=ENT[pSel].mo; drawAt(svg,heroMo);
  const title=S.custom?cap1(raw('area')||'Your goal'):goalAreas().map(a=>cap1(areaWord(a))).join(' + ');
  $('pSum').innerHTML=`<svg viewBox="90 30 180 180">${avatarSVG()}</svg><div><b>${esc(title)}: ${esc(startLbl())} → ${esc(targetLbl())}</b><small>${esc(tf)}, ${esc(GN[S.g].toLowerCase())}${S.prio.length?', '+esc(S.prio.join(', ')):''}</small></div><button class="btn small" id="pEdit">Edit</button>`;
  $('pEdit').onclick=()=>{ showPhase('goal'); goalShow(2); };
  cardsRender();
  const rule=(c,lab,v)=>`<div><i style="background:${c}"></i><span><b>${lab}:</b> ${esc(v)}</span></div>`;
  $('pRules').innerHTML=rule(C.g,'Leave alone',val('green'))+rule(C.y,'Shape lightly',val('yellow'))+rule(C.r,'Clean up',val('red'))+rule(C.b,'Detail',val('blue'))+rule('#8A93A3','Never',val('risk'));
  const rn=reachNote(); $('pReach').textContent=rn; $('pReach').hidden=!rn; $('pBasis').textContent=basis();
  baSync(); planMark(); trackRender();
}
$('pCopyPlan').onclick=()=>copyText(planText(),'Plan copied');

/* ---------- 4 PROMPT ---------- */
const PHOTOS=[['Front photo','Face the camera, chin level, eyes open.'],['Side photo','Turn 90°, same distance and light.'],['Even daylight','Face a window. No overhead shadows.'],['Neutral face, no filters','No beauty mode, no portrait blur.']];
$('rPhotos').innerHTML=PHOTOS.map((p,j)=>`<label class="check" for="ph${j}"><input type="checkbox" id="ph${j}"><span><b>${p[0]}</b><small>${p[1]}</small></span></label>`).join('');
function renderFixes(){
  const a=val('area');
  const F=[['The face changed',`The face in that image no longer matches my original photo. Redo it from my original front photo. Edit only my ${a} and keep my eyes, nose, skin and age exactly as photographed.`],
   ['Too thick or fake',`That ${a} looks denser than my real growth. Redo it with the density and coverage visible in my current photo. Only length and shape should change.`],
   ['It keeps failing',`Image editing isn't keeping my face accurate. Switch to the fallback: mark the color zones on my original photos, and give me a separate, clearly labeled concept sketch of the style.`]];
  $('rFixes').innerHTML=F.map((f,j)=>`<div class="fix"><div class="row"><b>${f[0]}</b><button class="btn small" data-fix="${j}">Copy fix</button></div><p class="muted">${esc(f[1])}</p></div>`).join('');
  document.querySelectorAll('[data-fix]').forEach(b=>b.onclick=()=>copyText(F[+b.dataset.fix][1],'Fix copied'));
}
const WHY=[['Ranked priorities','Your face first, then your goals in order. When two goals clash, the AI follows your order instead of guessing.'],['Identity lock','Your photos are the only face source and only one area may change. This blocks de-aged, smoothed "stranger" faces.'],['Seen vs. guessed','Every finding is labeled, so you know which parts rest on your photos.'],['Forced comparison','Four named styles are weighed against your face, and the pick comes with a reason.'],['Zones, not haircuts','A color means check this area, not cut all of it.'],['Check, redo, or admit it','Failures are redone; if your face can\'t be kept, you get marked-up real photos instead of a convincing fake.']];
$('rWhy').innerHTML=WHY.map(w=>`<details class="why"><summary>${w[0]}</summary><p>${w[1]}</p></details>`).join('');
$('rExpand').onclick=()=>{ const p=$('rPrev'); p.classList.toggle('open'); $('rExpand').textContent=p.classList.contains('open')?'Collapse':'Show full prompt'; };
function promptRender(){ svg.innerHTML=scene(6,{}); $('stageCap').hidden=false; $('stageCap').textContent='Check every image against your photo'; }

/* ---------- copy ---------- */
const toast=$('toast'); let tt=0;
function showToast(m){ toast.textContent=m; toast.classList.add('show'); clearTimeout(tt); tt=setTimeout(()=>toast.classList.remove('show'),1800); }
async function copyText(text,label){
  try{ await navigator.clipboard.writeText(text); showToast(label||'Copied'); }
  catch(e){ const ta=document.createElement('textarea'); ta.value=text; ta.setAttribute('readonly',''); ta.style.position='fixed'; ta.style.opacity='0'; document.body.appendChild(ta); ta.select(); let ok=false; try{ok=document.execCommand('copy');}catch(_){} ta.remove(); showToast(ok?(label||'Copied'):'Copy blocked: select the text instead'); }
}

/* ---------- journey ---------- */
const ORDER=['goal','plan','prompt'];
function refreshPhases(){
  const cur=phase==='goal'?(wz===1?0:1):2;
  document.querySelectorAll('#phases button').forEach(b=>{ const i={now:0,goal:1,plan:2}[b.dataset.ph];
    b.classList.toggle('on',i===cur); b.classList.toggle('done',i<cur); b.disabled=(i===2&&!S.ready)||(i===1&&!S.ready&&!wzPicked&&wz===1); b.setAttribute('aria-current',i===cur?'step':'false'); });
}
function actions(){
  const back=$('actBack'), main=$('actMain'); main.classList.remove('nudge'); main.disabled=false; main.classList.add('accent');
  if(phase==='learn'){ back.hidden=true; main.textContent=S.ready?'Back to my plan':'Set my goal'; if(ended) main.classList.add('nudge'); }
  if(phase==='goal'){ back.hidden=false; goalActions(); }
  if(phase==='plan'){ back.hidden=false; main.textContent='Get my AI prompt'; }
  if(phase==='prompt'){ back.hidden=false; main.textContent='Copy AI prompt'; }
}
$('actMain').onclick=()=>{
  if(phase==='learn'){ if(S.ready) showPhase('plan'); else { showPhase('goal'); } return; }
  if(phase==='goal'){ if(wz<NSTEPS) goalShow(wz+1); else finishGoal(); return; }
  if(phase==='plan'){ showPhase('prompt'); return; }
  if(phase==='prompt'){ copyText(plain,'Prompt copied'); }
};
$('actBack').onclick=()=>{
  if(phase==='goal'){ if(wz>1) goalShow(wz-1); return; }
  if(phase==='plan'){ showPhase('goal'); goalShow(NSTEPS); return; }
  if(phase==='prompt'){ showPhase('plan'); }
};
document.querySelectorAll('#phases button').forEach(b=>b.onclick=()=>{ if(b.disabled) return; const p=b.dataset.ph; if(p==='plan'){ showPhase('plan'); return; } showPhase('goal'); goalShow(p==='now'?1:2); });
function showPhase(p){
  clearTimeout(advTimer); phase=p; narrKey=null; stopSrc(); if(narrHeld) holdNarr(false);
  ORDER.forEach(x=>$('sc-'+x).hidden=x!==p);
  $('stageCap').hidden=true; $('explain').hidden=p!=='plan'; document.querySelector('.app').classList.toggle('inplan',p==='plan'); $('panel').scrollTop=0;
  if(p==='learn'){ learnRender(); }
  if(p==='goal'){ goalShow(wz); }
  if(p==='plan'){ if(tplArea==null&&goalAreas().length>=3) tplArea=goalAreas()[0]; planRender(); if(startISO){ heroJump(curIdx()); } else if(!RM) heroPlayAll(); }
  if(p==='prompt'){ promptRender(); }
  syncStage(); refreshPhases(); actions(); save();
}
let last=0;
function loop(ts){
  const dt=last?Math.min(100,ts-last):0; last=ts;
  if(phase==='learn'&&playing&&!holding){
    stageT+=dt; if(idx===4) withDemo(()=>timeline(svg,stageT)); drawStory();
    if(stageT>=dur(idx)){ if(idx<7) learnGo(idx+1); else { playing=false; ended=true; syncStage(); actions(); } }
  }
  if(phase==='goal') wzTick(dt);
  if(phase==='plan') heroTick(dt);
  requestAnimationFrame(loop);
}
function rerenderTheme(){ applyPalette(); if(phase==='learn') learnRender(); if(phase==='goal') goalStage(true); if(phase==='plan') planRender(); if(phase==='prompt') promptRender(); }
try{ matchMedia('(prefers-color-scheme: dark)').addEventListener('change',rerenderTheme); }catch(e){}
try{ new MutationObserver(rerenderTheme).observe(document.documentElement,{attributes:true,attributeFilter:['data-theme']}); }catch(e){}

resetGoal(); syncVoice();
const resumed=restore(); build();
showPhase(resumed&&resumed!=='learn'&&(resumed!=='plan'&&resumed!=='prompt'||S.ready)?resumed:'goal');
requestAnimationFrame(loop);
})();
look.css (look, layout, light and dark, fonts)321 lines

Raw file

@font-face{font-family:"Big Shoulders Display";font-weight:700;font-display:swap;src:url(./fonts/big-shoulders-display-latin-700-normal.woff2) format("woff2")}
@font-face{font-family:"Big Shoulders Display";font-weight:800;font-display:swap;src:url(./fonts/big-shoulders-display-latin-800-normal.woff2) format("woff2")}
@font-face{font-family:"Figtree";font-weight:400;font-display:swap;src:url(./fonts/figtree-latin-400-normal.woff2) format("woff2")}
@font-face{font-family:"Figtree";font-weight:600;font-display:swap;src:url(./fonts/figtree-latin-600-normal.woff2) format("woff2")}
@font-face{font-family:"Figtree";font-weight:700;font-display:swap;src:url(./fonts/figtree-latin-700-normal.woff2) format("woff2")}
@font-face{font-family:"Figtree";font-weight:800;font-display:swap;src:url(./fonts/figtree-latin-800-normal.woff2) format("woff2")}

/* LOOK BLUEPRINT · "In the chair"
   VOICE   friendly barber/stylist, plain words
   IDEA    a barbershop station: lit vanity mirror, tiled wall, brass fittings, barber-pole stripe
   PICTURE the mirror (stage) with bulbs; your character in a pinstriped barber cape
   COLOUR  mint tile + porcelain by day, bottle green + brass at night; barber red/blue only on the pole
   TYPE    Big Shoulders Display (shop-window lettering) for titles, Figtree for everything else */
:root{
  --ink:#0F2E2A; --muted:#3D5F58; --paper:#D2F0E4; --card:#FFFFFF; --line:#A6D8C6;
  --accent:#C2185B; --accent-soft:#FDE0EC; --on-accent:#FFFFFF; --stage:#B3E5D4; --glass:#BFEEDD;
  --brass1:#FFDC78; --brass2:#E8991A; --brass3:#9A5808; --pole-r:#E3263A; --pole-b:#1F4FD1; --neon:none;
  --display:"Big Shoulders Display","Arial Narrow",system-ui,sans-serif;
  --body:"Figtree","Segoe UI",system-ui,sans-serif;
  --mono:ui-monospace,Menlo,Consolas,monospace;
  color-scheme:light;
}
@media (prefers-color-scheme: dark){
  :root:not([data-theme="light"]){--ink:#F6F1E4;--muted:#A7D3C8;--paper:#04201F;--card:#0B3532;--line:#1B544D;--accent:#FF5FA2;--accent-soft:#4A1636;--on-accent:#2A0716;--stage:#0E443F;--glass:#0D4A43;--neon:0 0 6px rgba(255,95,162,.75),0 0 20px rgba(255,95,162,.4);color-scheme:dark}
}
:root[data-theme="dark"]{--ink:#F6F1E4;--muted:#A7D3C8;--paper:#04201F;--card:#0B3532;--line:#1B544D;--accent:#FF5FA2;--accent-soft:#4A1636;--on-accent:#2A0716;--stage:#0E443F;--glass:#0D4A43;--neon:0 0 6px rgba(255,95,162,.75),0 0 20px rgba(255,95,162,.4);color-scheme:dark}
*{box-sizing:border-box;-webkit-tap-highlight-color:transparent}
html,body{margin:0;height:100%}
body{background:var(--paper);color:var(--ink);font:16.5px/1.5 var(--body);-webkit-font-smoothing:antialiased;overflow:hidden}
button{font:inherit;color:inherit}
:focus-visible{outline:3px solid var(--accent);outline-offset:2px}
[hidden]{display:none !important}
.defs{position:absolute}
.gbody{display:grid;gap:12px}
.fixes{display:grid;gap:8px}
.note0{font-size:14.5px}
.note{font-size:14.5px;margin-top:-4px}
.z-g{background:#22A84A}.z-y{background:#F2B705}.z-r{background:#E8382E}.z-b{background:#2370F0}
h1,h2,h3,h4{font-family:var(--display);margin:0;line-height:1.05;text-wrap:balance;font-weight:800;letter-spacing:.005em}
p{margin:0}
.muted{color:var(--muted)}

.app{height:100%;max-width:560px;margin:0 auto;display:flex;flex-direction:column;background:var(--paper)}
@media (min-width:600px){.app{box-shadow:0 0 0 1px var(--line)}}

/* header: shop sign + barber-pole journey */
.top{flex:none;padding:calc(8px + env(safe-area-inset-top)) 16px 6px;display:grid;gap:8px;background:var(--paper)}
.toprow{display:flex;justify-content:space-between;align-items:center;gap:10px}
.toprow b{display:inline-flex;align-items:center;gap:10px;font:800 28px/1 var(--display);letter-spacing:.01em;white-space:nowrap;text-shadow:var(--neon)}
.pole{flex:none;width:12px;height:28px;border-radius:6px;box-shadow:inset 0 0 0 1.5px rgba(0,0,0,.25),0 0 0 2px var(--brass2);background:repeating-linear-gradient(-35deg,var(--pole-r) 0 4px,#fff 4px 8px,var(--pole-b) 8px 12px,#fff 12px 16px) 0 0/12px 22.9px;animation:polev 1.6s linear infinite}
@keyframes polev{to{background-position:0 22.9px}}
@media (max-width:360px){.toprow b{font-size:23px;gap:7px}.pole{width:10px;height:24px}}
@media (max-width:400px){#voiceLbl{display:none}.iconbtn{padding:7px 9px}}
@media (max-height:620px) and (orientation:portrait){.stage{height:30vh;min-height:140px}}
.iconbtn{display:inline-flex;align-items:center;gap:6px;border:1px solid var(--line);background:var(--card);border-radius:999px;padding:6px 12px;font-weight:700;font-size:13.5px;cursor:pointer}
.iconbtn .woff{display:none}
.iconbtn[aria-pressed="false"] .won{display:none}
.iconbtn[aria-pressed="false"] .woff{display:inline}
.phases{display:grid;grid-template-columns:repeat(3,1fr);gap:4px}
.phases button{border:0;background:transparent;padding:0;cursor:pointer;display:grid;gap:4px;text-align:left}
.phases button i{display:block;height:9px;border-radius:5px;background:var(--line);box-shadow:inset 0 1px 2px rgba(0,0,0,.12)}
.phases button span{font:700 13.5px var(--body);color:var(--muted)}
.phases button.done i,.phases button.on i{background:repeating-linear-gradient(-45deg,var(--pole-r) 0 5px,#FBFAF6 5px 10px,var(--pole-b) 10px 15px,#FBFAF6 15px 20px);background-size:28.3px 28.3px}
.phases button.done i{opacity:.7}
.phases button.on i{animation:pole 2.4s linear infinite}
.phases button.on span{color:var(--ink)}
.phases button:disabled{cursor:not-allowed;opacity:.5}
@keyframes pole{to{background-position:28.3px 0}}
.why0{font-size:15.5px;color:var(--muted);margin-top:-4px;max-width:62ch}

/* the mirror: brass frame, bulbs, tiled wall behind the character */
.stagewrap{flex:none;padding:0 16px}
.mirror{position:relative;padding:9px 18px;border-radius:24px;background:linear-gradient(150deg,var(--brass1),var(--brass2) 38%,var(--brass1) 58%,var(--brass3));box-shadow:0 1px 0 rgba(255,255,255,.4) inset,0 10px 24px -14px rgba(0,0,0,.45)}
.mirror::before,.mirror::after{content:"";position:absolute;top:16px;bottom:16px;width:12px;background:radial-gradient(circle at 6px 50%,#FFFBEA 0 3px,#F7DC9C 3.4px 4.6px,rgba(255,226,150,0) 5.4px) 0 0/12px 34px repeat-y}
.mirror::before{left:3px}.mirror::after{right:3px}
.mirror::before,.mirror::after{animation:bulbs 1.4s steps(1) both}.mirror::after{animation-delay:.15s}
@keyframes bulbs{0%{opacity:.15}30%{opacity:1}42%{opacity:.3}55%{opacity:1}}
:root[data-theme="dark"] .mirror::before,:root[data-theme="dark"] .mirror::after{filter:drop-shadow(0 0 4px #FFD98A)}
@media (prefers-color-scheme: dark){:root:not([data-theme="light"]) .mirror::before,:root:not([data-theme="light"]) .mirror::after{filter:drop-shadow(0 0 4px #FFD98A)}}
.stage{position:relative;height:min(36vh,310px);min-height:180px;border-radius:15px;overflow:hidden;touch-action:pan-y;user-select:none;-webkit-user-select:none;
  background:radial-gradient(ellipse 70% 60% at 50% 28%,rgba(255,244,214,.5),rgba(255,244,214,0) 70%),
    repeating-linear-gradient(0deg,rgba(0,0,0,0) 0 25px,rgba(0,0,0,.07) 25px 26px),
    repeating-linear-gradient(90deg,rgba(0,0,0,0) 0 51px,rgba(0,0,0,.06) 51px 52px),var(--glass);
  box-shadow:inset 0 0 0 2px rgba(255,255,255,.35),inset 0 8px 24px rgba(0,0,0,.18)}
.stage::after{content:"";position:absolute;inset:0;pointer-events:none;background:linear-gradient(115deg,rgba(255,255,255,0) 30%,rgba(255,255,255,.13) 38%,rgba(255,255,255,0) 46%)}
.stage svg#svg{display:block;width:100%;height:100%}
.stage.paused svg *{animation-play-state:paused !important}
.stagebar{display:flex;align-items:center;gap:10px;height:32px}
.storybar{flex:1;display:flex;gap:4px}
.sblabel{flex:1;font:600 13.5px var(--body);color:var(--muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.storybar button{flex:1;border:0;background:transparent;padding:6px 0;cursor:pointer}
.storybar button i{display:block;height:4px;border-radius:2px;background:var(--line);overflow:hidden}
.storybar button i b{display:block;height:100%;width:0;background:var(--accent)}
.stagebtn{flex:none;width:30px;height:30px;border-radius:50%;border:0;background:var(--ink);color:var(--paper);display:grid;place-items:center;cursor:pointer}
.stagecap{position:absolute;left:50%;bottom:10px;transform:translateX(-50%);max-width:92%;background:rgba(18,34,32,.84);color:#fff;font:700 13.5px var(--body);padding:6px 14px;border-radius:999px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;pointer-events:none}

/* panel */
.panel{flex:1;overflow-y:auto;-webkit-overflow-scrolling:touch;padding:14px 16px 26px}
.screen{display:grid;gap:14px}
.k{font:700 14px var(--body);color:var(--accent)}
.screen h2{font-size:36px}
.card{background:var(--card);border:1px solid var(--line);border-radius:18px;padding:14px;display:grid;gap:10px}
.card h3{font-size:22px}
.row{display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap}
.seg{display:inline-flex;background:var(--paper);border:1px solid var(--line);border-radius:999px;padding:3px;gap:2px}
.seg button{border:0;background:transparent;padding:6px 13px;border-radius:999px;font-weight:700;font-size:14px;cursor:pointer}
.seg button[aria-pressed="true"]{background:var(--ink);color:var(--paper)}
.exbox{display:flex;gap:10px;align-items:flex-start;background:var(--accent-soft);border-radius:12px;padding:10px 12px;font-size:15.5px;line-height:1.4}
.exbox svg{flex:none;width:36px;height:36px;border-radius:50%;background:var(--stage)}
.exbox small{display:block;font:700 12.5px var(--body);color:var(--accent)}
.chips{display:flex;gap:6px;flex-wrap:wrap}
.chip{display:inline-flex;align-items:center;gap:6px;font:600 13px var(--body);padding:3px 10px;border:1px solid var(--line);border-radius:999px;animation:fade .5s both}
.dot{width:10px;height:10px;border-radius:50%;flex:none}
.help{font-size:13.5px;color:var(--muted)}

/* choices: style cards on a barber's board */
.goals{display:grid;grid-template-columns:1fr 1fr;gap:10px}
.goal,.tile{position:relative;border:0;background:var(--card);box-shadow:inset 0 0 0 1px var(--line);cursor:pointer;text-align:center;display:grid;justify-items:center}
.goal{border-radius:16px;padding:10px 8px 12px;gap:3px}
.goal svg{width:84px;height:68px;border-radius:12px;background:var(--stage)}
.goal b{font:800 21px/1.1 var(--display)}
.goal small{color:var(--muted);font-size:13px;line-height:1.25}
.tile{border-radius:14px;padding:5px 5px 8px;gap:5px}
.tile svg{width:100%;height:64px;border-radius:10px;background:var(--stage)}
.tile b{font-size:13.5px;line-height:1.2}
.goal[aria-pressed="true"],.tile[aria-pressed="true"]{box-shadow:inset 0 0 0 2.5px var(--accent);background:var(--accent-soft)}
.goal[aria-pressed="true"]::after,.tile[aria-pressed="true"]::after{content:"";position:absolute;top:6px;right:6px;width:18px;height:18px;border-radius:50%;background:var(--accent) url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 18 18'%3E%3Cpath d='M5 9.3l2.6 2.6L13 6.5' fill='none' stroke='%23fff' stroke-width='2.2' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E") center/18px no-repeat}
.tiles{display:grid;grid-template-columns:repeat(4,1fr);gap:8px}
.tiles.five{grid-template-columns:repeat(5,1fr)}
.tile.big b{font:800 30px/1 var(--display)}
.tile.big small{font-size:12.5px;color:var(--muted)}
.tile.big{padding:14px 4px}
.prios{display:flex;flex-wrap:wrap;gap:8px}
.prios button{border:1px solid var(--line);background:var(--card);border-radius:999px;padding:8px 14px 8px 8px;font-weight:700;font-size:14.5px;cursor:pointer;display:inline-flex;align-items:center;gap:8px}
.prios button i{width:24px;height:24px;border-radius:50%;border:1.5px dashed var(--line);display:grid;place-items:center;font:800 15px var(--display);font-style:normal}
.prios button[aria-pressed="true"]{border-color:var(--accent);background:var(--accent-soft)}
.prios button[aria-pressed="true"] i{background:var(--accent);border:0;color:var(--on-accent)}
.linkbtn{border:0;background:none;color:var(--muted);font-weight:700;font-size:14.5px;cursor:pointer;padding:6px 0;justify-self:start;text-decoration:underline;text-underline-offset:3px}

/* plan: summary, appointment book */
.sum{display:grid;grid-template-columns:46px 1fr auto;gap:10px;align-items:center}
.sum svg{width:46px;height:46px;border-radius:50%;background:var(--stage)}
.sum b{display:block;font-size:15.5px;line-height:1.25}
.sum small{display:block;color:var(--muted);font-size:13.5px;line-height:1.3}
.cps{display:grid;gap:10px;position:relative;padding-left:18px}
.cps::before{content:"";position:absolute;left:6px;top:14px;bottom:14px;width:2px;background:var(--line)}
.cp{position:relative;display:grid;grid-template-columns:58px 1fr;gap:12px;align-items:start;text-align:left;background:var(--paper);border:0;box-shadow:inset 0 0 0 1px var(--line);border-radius:14px;padding:10px;cursor:pointer}
.cp::before{content:"";position:absolute;left:-17px;top:16px;width:10px;height:10px;border-radius:50%;background:var(--paper);border:2px solid var(--muted)}
.cp svg{width:58px;height:58px;border-radius:10px;background:var(--stage)}
.cp b{display:block;font:800 22px/1.05 var(--display)}
.cp small{display:block;color:var(--muted);font-size:13.5px;margin:2px 0 4px}
.cp .f{display:block;font-size:15px;line-height:1.4}
.cp .sh{display:flex;gap:8px;align-items:flex-start;margin-top:6px;font-size:14px;color:var(--muted)}
.cp .sh i{flex:none;width:8px;height:8px;border-radius:50%;background:#E3B400;margin-top:6px}
.cp .say{grid-column:1 / -1;display:grid;grid-template-columns:1fr auto;gap:4px 10px;align-items:center;background:var(--card);border-radius:12px;padding:9px 11px;border:1px dashed var(--accent)}
.cp .say .who{grid-column:1 / -1;font:700 13px var(--body);color:var(--accent)}
.cp .say q{font-size:15px;line-height:1.4;quotes:"\201C" "\201D"}
.cp .say .btn{align-self:start}
.cp[aria-current="step"]{box-shadow:inset 0 0 0 2.5px var(--accent);background:var(--accent-soft)}
.cp[aria-current="step"]::before{background:var(--accent);border-color:var(--accent)}
.noanim *{animation:none!important}
.lghead{display:flex;justify-content:space-between;align-items:center;gap:10px}
.legend{display:grid;gap:6px}
.lg{display:grid;grid-template-columns:16px 1fr auto;gap:10px;align-items:start;text-align:left;border:0;box-shadow:inset 0 0 0 1px transparent;background:var(--paper);border-radius:12px;padding:8px 10px;cursor:pointer;font:inherit;color:inherit;width:100%}
.lg i{width:16px;height:16px;border-radius:5px;margin-top:3px}
.lg i.ln{background:transparent!important;border:4px solid;border-radius:50%}
.lg b{display:block;font:800 19px/1.1 var(--display)}
.lg small{display:block;color:var(--muted);font-size:13.5px;line-height:1.35}
.lg small u{text-decoration:none;font-weight:700;color:var(--ink)}
.lg em{font:700 12px var(--body);font-style:normal;padding:2px 9px;border-radius:999px;border:1px solid var(--line);white-space:nowrap;margin-top:2px;color:var(--muted)}
.lg em.go{border-color:var(--accent);color:var(--accent)}
.lg[aria-pressed="true"]{box-shadow:inset 0 0 0 2px var(--accent);background:var(--accent-soft)}
.legend.solo .lg[aria-pressed="false"]{opacity:.5}
.legend.off{display:none}
.tiles.three,.tiles.six{grid-template-columns:repeat(3,1fr)}
.tiles.three svg{height:100px}
.arealbl{font:800 20px/1.1 var(--display);color:var(--ink);margin:8px 0 -4px}
.swatches{display:flex;gap:10px;flex-wrap:wrap}
.sw{width:44px;height:44px;border-radius:50%;border:3px solid var(--card);box-shadow:0 0 0 1px var(--line);cursor:pointer;padding:0}
.sw[aria-pressed="true"]{box-shadow:0 0 0 3px var(--accent)}
.scrub{display:grid;grid-template-columns:44px minmax(0,1fr) 44px;gap:8px;align-items:center}
.scrubmid{display:grid;gap:0;min-width:0}
.scrubmid .k{font:800 22px/1.05 var(--display);color:var(--ink)}
.scrub input{width:100%;accent-color:var(--accent);height:28px;margin:0}
.stepb{width:44px;height:44px;border-radius:50%;border:1px solid var(--line);background:var(--paper);font-size:22px;font-weight:700;cursor:pointer;line-height:1;padding:0}
.stepb:disabled{opacity:.4;cursor:default}
.areaseg{justify-self:start}
.muted.sm{font-size:13.5px}
.help.up{margin-top:-4px}
/* the month's jobs under the mirror: a printed appointment slip */
.explain{margin-top:8px;background:var(--card);border-radius:12px;padding:8px 12px 9px;font-size:13.5px;line-height:1.38;box-shadow:inset 0 0 0 1px var(--line);background-image:radial-gradient(circle at 0 50%,var(--paper) 0 6px,transparent 6.5px),radial-gradient(circle at 100% 50%,var(--paper) 0 6px,transparent 6.5px)}
.explain b{display:block;font:800 18px/1.15 var(--display);margin-bottom:2px}
.explain span{display:block}
.explain i{display:inline-block;width:9px;height:9px;border-radius:50%;margin-right:7px;vertical-align:0}
.app.inplan .stage{height:min(30vh,290px)}
@media (max-height:680px) and (orientation:portrait){.app.inplan .stage{height:24vh;min-height:122px}.explain{font-size:12.5px;padding:5px 10px;margin-top:5px}.explain b{font-size:15px}.mirror{padding:6px 14px}}
.seg.wrap{flex-wrap:wrap;border-radius:14px}
.tiles.seven{grid-template-columns:repeat(4,1fr)}
@keyframes snip{to{opacity:0;transform:scale(.4) rotate(25deg)}}
.snip>*{animation:snip .5s ease-in .9s forwards;transform-box:fill-box;transform-origin:center}
.growl{display:grid;gap:2px;font-size:14.5px;font-weight:600}
.lg small+small{margin-top:4px}
.cpk{font:700 12px var(--body);font-style:normal;color:var(--on-accent);background:var(--accent);border-radius:999px;padding:2px 8px;margin-left:8px;vertical-align:3px;letter-spacing:0}
.acts{list-style:none;margin:6px 0 0;padding:0;display:grid;gap:4px}
.acts li{display:grid;grid-template-columns:10px 1fr;gap:8px;font-size:14.5px;line-height:1.35}
.acts li i{width:10px;height:10px;border-radius:50%;margin-top:5px}
.rules{display:grid;gap:8px}
.rules div{display:grid;grid-template-columns:10px 1fr;gap:10px;font-size:15px;line-height:1.35}
.rules i{width:10px;min-height:18px;border-radius:5px}
.script{margin:0;padding:12px 14px;border:1px dashed var(--accent);background:var(--paper);border-radius:12px;font-size:16px;line-height:1.45}

/* prompt */
.check{display:grid;grid-template-columns:28px 1fr;gap:10px;align-items:start;padding:8px 0;border-top:1px solid var(--line);cursor:pointer}
.check:first-child{border-top:0}
.check input{width:22px;height:22px;accent-color:var(--accent);margin:1px 0 0}
.check b{display:block;font-size:15.5px}
.check small{color:var(--muted);font-size:14px}
.preview{position:relative}
.preview pre{margin:0;font:13px/1.6 var(--mono);white-space:pre-wrap;word-break:break-word;max-height:200px;overflow:hidden;background:var(--paper);border-radius:12px;padding:12px}
.preview.open pre{max-height:none}
.preview:not(.open)::after{content:"";position:absolute;left:0;right:0;bottom:0;height:70px;border-radius:0 0 12px 12px;background:linear-gradient(transparent,var(--paper));pointer-events:none}
.preview mark{background:var(--accent-soft);color:inherit;border-radius:3px;padding:0 2px;box-shadow:inset 0 -2px 0 var(--accent)}
.fix{display:grid;gap:6px;padding:12px;border-radius:12px;background:var(--paper)}
.fix p{font-size:14.5px}
details.acc{background:var(--card);border:1px solid var(--line);border-radius:18px}
details.acc>summary{cursor:pointer;list-style:none;display:flex;justify-content:space-between;align-items:center;padding:14px;font:800 20px var(--display)}
details.acc>summary::-webkit-details-marker{display:none}
details.acc>summary::after{content:"+";font:800 24px var(--display);color:var(--accent)}
details.acc[open]>summary::after{content:"–"}
details.acc .inner{display:grid;gap:12px;padding:0 14px 14px}
.field{display:grid;gap:5px}
.field>span{font-weight:700;font-size:14.5px}
.field>small{color:var(--muted);font-size:13px;margin-top:-3px}
input[type=text],textarea{width:100%;font:16px/1.4 var(--body);color:var(--ink);background:var(--paper);border:1px solid var(--line);border-radius:10px;padding:9px 11px}
textarea{resize:vertical;min-height:76px}
textarea.short{min-height:52px}
.zone{display:grid;grid-template-columns:10px 1fr;gap:10px}
.zone i{border-radius:5px}
.why p{color:var(--muted);font-size:15px;padding:0 0 10px}
.why summary{cursor:pointer;padding:10px 0;font-weight:700;list-style:none;border-top:1px solid var(--line)}
.why summary::-webkit-details-marker{display:none}

/* action bar: brass fittings */
.actions{flex:none;display:flex;gap:10px;padding:10px 16px calc(10px + env(safe-area-inset-bottom));background:var(--paper);border-top:1px solid var(--line)}
.btn{display:inline-flex;align-items:center;justify-content:center;gap:8px;min-height:50px;border-radius:14px;border:1px solid var(--line);background:var(--card);font-weight:800;font-size:16.5px;cursor:pointer;padding:0 16px;text-decoration:none;white-space:nowrap}
.btn.accent{border:0;color:#24190A;background:linear-gradient(180deg,var(--brass1),var(--brass2));box-shadow:inset 0 1px 0 rgba(255,255,255,.55),0 2px 0 var(--brass3)}
.btn.small{min-height:38px;font-size:14px;padding:0 12px}
.btn:disabled{opacity:.5;cursor:not-allowed}
.btn:active{transform:translateY(1px)}
.actions #actBack{flex:1}
.actions #actMain{flex:2.2}
.toast{position:fixed;left:50%;top:calc(14px + env(safe-area-inset-top));transform:translate(-50%,-90px);background:var(--ink);color:var(--paper);padding:10px 18px;border-radius:999px;font-weight:700;z-index:20;transition:transform .3s}
.toast.show{transform:translate(-50%,0)}

/* phone held sideways: mirror on the left, panel on the right */
@media (orientation:landscape) and (max-height:540px){
  .app{max-width:none;display:grid;grid-template-columns:minmax(0,44%) minmax(0,1fr);grid-template-rows:auto minmax(0,1fr) auto;grid-template-areas:"top top" "stage panel" "stage actions"}
  .top{grid-area:top;display:flex;align-items:center;gap:16px;padding-top:calc(6px + env(safe-area-inset-top));padding-bottom:6px}
  .toprow{flex:none;gap:12px}
  .phases{flex:1}
  .stagewrap{grid-area:stage;display:flex;flex-direction:column;min-height:0;padding:0 0 10px 16px}
  .mirror{flex:1 1 0;min-height:90px;display:flex;flex-direction:column}
  .stage{height:auto;flex:1 1 0;min-height:0}
  .stage svg#svg{position:absolute;inset:0}
  .explain{font-size:12.5px;padding:5px 10px;margin-top:6px}.explain b{font-size:15px}
  .panel{grid-area:panel;padding-top:6px}
  .actions{grid-area:actions;border-top:0}
}
@keyframes fade{from{opacity:0}}
@keyframes fadeOut{to{opacity:0}}
@keyframes drop{from{opacity:0;transform:translateY(-30px)}}
@keyframes pop{from{opacity:0;transform:scale(.6)}}
@keyframes draw{from{stroke-dasharray:1;stroke-dashoffset:1}to{stroke-dasharray:1;stroke-dashoffset:0}}
@keyframes pulse{50%{opacity:.35}}
@keyframes scan{from{transform:translateY(20px)}to{transform:translateY(300px)}}
@keyframes dim{to{opacity:.35}}
@keyframes nudge{50%{transform:scale(1.03)}}
.a-fade{animation:fade .6s both}
.a-out{animation:fadeOut .4s forwards}
.a-drop{animation:drop .6s cubic-bezier(.2,.9,.3,1.3) both;transform-box:fill-box}
.a-pop{animation:pop .5s cubic-bezier(.2,.9,.3,1.3) both;transform-box:fill-box;transform-origin:center}
.a-draw{animation:draw 1.3s ease-out both}
.a-pulse{animation:pulse 1.6s ease-in-out infinite}
.a-scan{animation:scan 2.6s linear infinite}
.a-dim{animation:dim .5s forwards}
.nudge{animation:nudge 1.4s ease-in-out infinite}
@media (prefers-reduced-motion: reduce){*,*::before,*::after{animation:none !important;transition:none !important}}

/* tracker: day count and next visit */
.trk{display:grid;gap:10px;background:var(--card);border-radius:18px;padding:14px;box-shadow:inset 0 0 0 2px var(--accent)}
.trk h3{font-size:22px}
.trk-top{display:flex;align-items:baseline;gap:8px;flex-wrap:wrap}
.trk-big{font:800 44px/0.9 var(--display);color:var(--accent);text-shadow:var(--neon)}
.trk-of{font-weight:700;color:var(--muted)}
.trk-bar{height:12px;border-radius:6px;background:var(--line);overflow:hidden}
.trk-bar i{display:block;height:100%;background:repeating-linear-gradient(-45deg,var(--pole-r) 0 5px,#fff 5px 10px,var(--pole-b) 10px 15px,#fff 15px 20px)}
.trk p{font-size:15.5px;line-height:1.4}
.trk-btns{display:flex;flex-wrap:wrap;gap:8px}
.datef{display:inline-flex;align-items:center;gap:8px;font-weight:700;font-size:14px;color:var(--muted)}
.datef input{font:600 15px var(--body);color:var(--ink);background:var(--paper);border:1px solid var(--line);border-radius:10px;padding:7px 9px}
.cp .say .sbtns{display:flex;gap:6px;flex-wrap:wrap;justify-content:flex-end}
/* barber card: full screen, bright, big type, to hold up in the chair */
.bcard{position:fixed;inset:0;z-index:30;background:rgba(4,20,19,.72);display:grid;place-items:center;padding:12px}
.bsheet{width:min(520px,100%);max-height:100%;overflow:auto;background:#FFFDF6;color:#10201E;border-radius:22px;padding:16px;display:grid;gap:12px;box-shadow:0 0 0 6px var(--brass2),0 20px 60px rgba(0,0,0,.5)}
.bhead{display:flex;align-items:center;gap:10px}
.bhead h2{flex:1;font-size:30px;color:#10201E}
.bhead .iconbtn{background:#fff;color:#10201E;border-color:#C8D6D0}
.bpic{border-radius:16px;background:repeating-linear-gradient(0deg,rgba(0,0,0,0) 0 25px,rgba(0,0,0,.06) 25px 26px),#BFEEDD;height:min(34vh,300px)}
.bpic svg{display:block;width:100%;height:100%}
.bwhen{font:800 22px/1.1 var(--display);color:#C2185B}
.bsay{margin:0;font:700 22px/1.35 var(--body);border-left:6px solid #C2185B;padding:4px 0 4px 14px}
.bsheet .acts li{font-size:16px}
.bnav{display:flex;gap:8px}
@media (max-width:400px){.bsay{font-size:18.5px}.bwhen{font-size:19px}.bhead h2{font-size:26px}.bsheet{padding:12px;gap:9px}}
.bnav .btn{flex:1;background:#fff;color:#10201E;border-color:#C8D6D0}
@media (orientation:landscape) and (max-height:540px){.bsheet{width:min(820px,100%);grid-template-columns:minmax(0,40%) 1fr;align-items:start}.bhead,.bnav{grid-column:1 / -1}.bpic{grid-row:2 / span 3;height:62vh}}

.home{font:700 13.5px var(--body);color:var(--muted);text-decoration:none;margin-right:auto;margin-left:10px;white-space:nowrap}
.home:hover{color:var(--accent)}
@media (max-width:360px){.home{font-size:12.5px;margin-left:6px}}
kit/site.py (splits the preview page into these three files)29 lines

Raw file

"""Build the sghadimi.com copy of Look Blueprint from the preview page.
Splits the inline <style>/<script> into look.css/look.js (the site's CSP allows no inline code),
swaps Google Fonts for local woff2 files, adds the site description and a back link.
Usage: python3 kit/site.py <preview index.html> <out dir> <fonts dir>"""
import sys, os, re, shutil
src, out, fontdir = sys.argv[1], sys.argv[2], sys.argv[3]
s = open(src, encoding='utf8').read()
css = re.search(r'<style>(.*?)</style>', s, re.S).group(1)
js = re.search(r'<script>(.*?)</script>', s, re.S).group(1)
faces = ''.join(f'@font-face{{font-family:"{fam}";font-weight:{w};font-display:swap;src:url(./fonts/{f}) format("woff2")}}\n'
  for fam, w, f in [('Big Shoulders Display',700,'big-shoulders-display-latin-700-normal.woff2'),('Big Shoulders Display',800,'big-shoulders-display-latin-800-normal.woff2'),
                    ('Figtree',400,'figtree-latin-400-normal.woff2'),('Figtree',600,'figtree-latin-600-normal.woff2'),('Figtree',700,'figtree-latin-700-normal.woff2'),('Figtree',800,'figtree-latin-800-normal.woff2')])
css = faces + css + '\n.home{font:700 13.5px var(--body);color:var(--muted);text-decoration:none;margin-right:auto;margin-left:10px;white-space:nowrap}\n.home:hover{color:var(--accent)}\n@media (max-width:360px){.home{font-size:12.5px;margin-left:6px}}\n'
s = re.sub(r'<link rel="preconnect"[^>]*>\n?', '', s)
s = re.sub(r'<link href="https://fonts\.googleapis\.com[^>]*>\n?', '', s)
s = re.sub(r'<style>.*?</style>', '<link rel="stylesheet" href="./look.css">', s, flags=re.S)
s = re.sub(r'<script>.*?</script>', '<script src="./look.js" defer></script>', s, flags=re.S)
s = s.replace('<title>Look Blueprint Master Prompt</title>', '<title>Look Blueprint: your grooming plan and AI prompt</title>\n<meta name="description" content="Free: set your look today, pick beard, hair or brow goals and mix styles, then watch a month-by-month plan with a cleanup template on the face and get an AI prompt that keeps your own face. No sign-up.">\n<link rel="icon" href="/favicon.svg">')
assert s.count('Look Blueprint</b>') == 1
s = s.replace('Look Blueprint</b>', 'Look Blueprint</b><a class="home" href="/all/">Free tools ›</a>')
assert 'style="' not in s[s.index('<body>'):], 'inline style left in markup'
assert '<script>' not in s
os.makedirs(os.path.join(out, 'fonts'), exist_ok=True)
open(os.path.join(out, 'index.html'), 'w', encoding='utf8').write(s)
open(os.path.join(out, 'look.css'), 'w', encoding='utf8').write(css)
open(os.path.join(out, 'look.js'), 'w', encoding='utf8').write(js)
for f in re.findall(r'url\(\./fonts/([^)]+)\)', css): shutil.copy(os.path.join(fontdir, f), os.path.join(out, 'fonts', f))
print('built', out)

Need a tool like this, built for your own work?

Take this one free. If you need your own version, with your lists, your rules and your name on it, I build it and hand it over. Fixed price agreed up front, and the first call is free.

How it works and what it costs Book a free call ↗

Or write to me · how to use what is here