(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,'&').replace(//g,'>'); 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}${p}`; /* 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=``; return {u:'',m:cm<1?`${m}`: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:``,m:``}; } const b=205+100*L; let u=``; if(gray&&cm>=3&&sh!=='goatee') u+=``; 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;i158&&x<202&&y<196) continue; c+=``; } u+=c; } return {u,m:``}; } /* 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=``; if(v==='feather'){for(let k=0;k<6;k++){const x=146+k*4.5;s+=``;}} return `${s}${s}`; } /* 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=``; for(let i=0;i<20;i++){ const t=i/20*Math.PI*2; s+=``; } return `${s}`; } 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+=``; } return `${s}${s}`; } 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=''; if(curly) s+=`${curlyBack(ha,hc)}`; else if(long) s+=``; s+= g==='woman' ? `` : ``; s+=``; s+=``; if(ha<2&&!curly) s+=``; s+=brows(W.a,W.s,hc); const ey=G.eye, ex=G.ex, ex2=360-ex; s+=``; s+= g==='woman' ? `` : ``; const nb=G.nose; s+=``; if(g!=='man'&&!drift){ const op=g==='woman'?.35:.2; s+=``; } const bd=g==='woman'?{u:'',m:''}:beardSVG(B.a,B.s,hc,g==='man'); if(bd.u) s+=`${bd.u}`; const my=G.mouth; s+= g==='woman' ? `` : ``; if(bd.m) s+=`${bd.m}`; if(curly) s+=`${curlyFront(ha,hc)}`; else if(long){ const b=hairB(ha); let f=''; if(b>=165){ const c=curtainB(b,hs); f+=MIR(``); } f+=``; s+=`${f}`; } else if(ha>=.2){ const p=shortCap(capT(ha)); s+=``; } return s+''; } 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 `${text}`; } /* ---------- 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() ? `${content}` : 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?`${x}`:''; const lip=w(``); if(k==='none'){ Zn.red=w(``); 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(``); Zn.yellow=w(``); Zn.red=w(MIR(``)+``); Zn.blue=w(``); return Zn; } if(k==='goatee'){ Zn.green=w(``); Zn.yellow=w(``+(ph==='late'?``:'')); Zn.red=w(MIR(``)); Zn.blue=lip; return Zn; } Zn.green=w(``); Zn.yellow=w(``+(ph==='late'?``:'')); Zn.red=w(MIR(``)+``+(b<262?``:'')); Zn.blue=lip; return Zn; } if(a==='hair'){ const w=x=>x?`${x}`:''; if(k==='shaved'){ Zn.red=w(``); Zn.blue=w(``); 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(``); Zn.yellow=w(``+(ph==='late'?(()=>{const t=curlyDims(targetAmt(a));return ``;})():'')); 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(``); Zn.blue=w(``); return Zn; } if(k==='short'){ const t=capT(Math.max(amt,.5)); Zn.green=w(``); Zn.yellow=w(MIR(``)); Zn.red=w(MIR(``)); Zn.blue=w(``); return Zn; } const b=hairB(amt), bt=hairB(targetAmt(a)), bv=Math.min(b,306); Zn.green=w(b>=165?MIR(``):MIR(``)); const y0=Math.max(112,b-120); Zn.yellow=w((b-14>y0+12?MIR(``):'')+(ph==='late'&&bt>b+4?(()=>{const y=Math.min(bt,306);return MIR(``);})():'')); Zn.red=w(MIR(``)); Zn.blue=w(MIR(``)); return Zn; } const wd=2.5+6*amt+4; Zn.green=MIR(``); Zn.yellow=MIR(``); Zn.red=``+MIR(``); Zn.blue=MIR(``); 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 ``; } if(a==='hair'){ if(st==='curly'&&amt>=2){ const c=curlyDims(amt); return ``; } return ``; } return MIR(``); } /* 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+=`${Zg[z]}`; }); }); 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 ``; } const dash=(x,y,dx,dy,col,sw)=>``; 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?`${x}`:''; 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;i154&&x<206&&y>176) continue; if(x>162&&x<198&&y>168&&y<194) continue; red+=``; } } 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;ix?`${x}`:''; 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+=``; } 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+=``; } }); 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+=``; }); 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?`${Mg[z]}`:Mg[z]; }); }); return C.dark&&s?`${s}`: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=>`${Zg[z]}`).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'?`${areaOutline(k,targetAmt(k),`stroke="${C.acc}" stroke-width="10" stroke-linecap="round" stroke-dasharray="3 3"`)}`:areaOutline(k,targetAmt(k),`stroke="${C.acc}" stroke-width="2.5" stroke-dasharray="6 6"`); s+=Z(`${face(0)}${tgt}`); 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=`${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"`)}`; s+=Z(`${face(0)}${edit}`); if(!zo) s+=``; 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+=``; 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+=``; s+=``; 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+=`${Z(face(1,{v}))}`; 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+=``; s+=``; } }); } if(i===4){ const ms=milestones(), N=ms.length, xs=ms.map((_,j)=>40+j*(280/(N-1))); s+=Z(`${personAt(0)}`); s+=``; s+=``; s+=``; xs.forEach((x,j)=>{s+=``; if(!mini) s+=`${esc(ms[j].l)}`;}); } 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+=`${Z(face(0))}`; s+=``; s+= ``+(still ? Z(face(q)) : `${Z(face(q,{drift:1}))}${Z(face(q))}`)+``; s+=``; 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+=``; 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+=``; 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+=`${esc(c)}`;}); } } if(i===7){ const ms=milestones(), N=ms.length; s+=`${Z(face(0))}`; s+=`${Z(face(1))}`; s+=``; 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+=``; s+=``; xs.forEach((x,j)=>{s+=``; if(!mini) s+=`${esc(ms[j].l)}`;}); 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?`${overlayAt(mo,tplFocus)}`:''); const ms=milestones(), N=ms.length, xs=ms.map((_,j)=>40+j*(280/(N-1))); let x=xs[N-1]; for(let j=0;jdelete 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 ``; 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 `${person(st)}`; } 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,'').replace(/\u0002/g,''); 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=''; b.onclick=e=>{e.stopPropagation(); learnGo(j);}; sb.appendChild(b); } const fills=[...sb.querySelectorAll('b')]; function drawStory(){ fills.forEach((f,j)=>f.style.width=(jidx?0:Math.min(100,stageT/dur(idx)*100))+'%'); } function avatarSVG(){ return zoomOn()?`${face(.9)}`:face(0); } function learnRender(){ withDemo(()=>{ svg.innerHTML=scene(idx); $('lAv').innerHTML=avatarSVG(); let ch=''; if(idx===2) ch=`Seen in photoA guess to confirm`; if(idx===5) ch=ZONEKEYS.map((z,j)=>`${esc(tr(val(z),36))}`).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:'',play:'',replay:''}; 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){ 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)=>`${inner}`; 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 `
${cap1(areaWord(a))} today
${L.map(([st,n,lv])=>{ const s0=st||S.look.brows; const on=S.base&&S.base[a]===s0&&S.lvl[a]===lv; return ``; }).join('')}
`; } function mixTiles(a){ const goal=isGoal(a); return `
${cap1(areaWord(a))}: ${goal?'your goal':'keep as'}
${STY[a].map(([st,n])=>``).join('')}
`; } 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=`
${['man','woman','neutral'].map(g=>``).join('')}
Skin tone
${Object.keys(SKINS).map(k=>``).join('')}
${areasFor().map(todayTiles).join('')}

No sound? Turn the volume up and tap once; it plays even when an iPhone is on silent.

`; 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=`
${GOALS.filter(([g])=>!(g==='beard'&&noBeard())).map(([g,t,sub])=>``).join('')}
`; 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)=>``).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=`
${Object.keys(MS).map(m=>``).join('')}
`; 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=`
${list.map(p=>{const i=S.prio.indexOf(p);return ``;}).join('')}
`; 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=`${person(stOf((a,st)=>targetAmt(a,st),{look:{...S.look,...(S.base||{})},amt:todayAmts()}))}`; 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(`${face(0)}${(S.custom||S.goals.length)?out:''}`); } if(wz===3) s=Z(`${face(0)}`); 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); if(heroMo>=heroTo) holdT=0; return; } if(playOn){ holdT+=dt; if(holdT>=HOLD){ if(pSel=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=>``).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=>`${multi?esc(cap1(areaWord(x.a)))+': ':''}${x.wh[z]?'On the face: '+esc(x.wh[z])+'.':'Not drawn for this style.'} ${esc(x.act[z]||(z==='green'?'Nothing to grow here.':'Nothing this month.'))}`).join(''); return ``; }).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=>`${esc(growLine(a,e.mo))}`).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=`${esc(e.l)}${e.cp?' (checkpoint)':''}: ${esc(capShort(e.mo))}`+jobs.slice(0,3).map(([z,t])=>`${esc(t)}`).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 `
${personAt(e.mo)}${messAt(e.mo,'after')}${overlayAt(e.mo,null,true)}${esc(e.l)}${e.cp?' Checkpoint':''}${A.map(a=>esc(growLine(a,e.mo))).join('
')}
    ${acts.map(([z,t])=>`
  • ${esc(t)}
  • `).join('')}
${say?`
${j===0?'Say to your '+esc(pro)+' today':'Say to your '+esc(pro)+' at '+esc(e.l.toLowerCase())}${esc(say)}
`:''}
`; }).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=`

Track it day by day

Set the day you start. The plan then opens on the right month and tells you when to book your ${esc(pro)}.

`; $('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: ${esc(ENT[nv].l.toLowerCase()==='now'?'today':cap1(nice(ENT[nv].l)))}, ${esc(fmtDay(nd))} (${left<=0?'today':left===1?'tomorrow':'in '+left+' days'}).`; } el.innerHTML=`
Day ${Math.min(d,total)}of ${total}, on ${esc(nice(ENT[ci].l))} jobs

${next}

${nv>=0&&!done?``:''}
`; $('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{ 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])=>`
  • ${TPL_NAME[z]}: ${esc(t)}
  • `).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{ 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=`${avatarSVG()}
    ${esc(title)}: ${esc(startLbl())} → ${esc(targetLbl())}${esc(tf)}, ${esc(GN[S.g].toLowerCase())}${S.prio.length?', '+esc(S.prio.join(', ')):''}
    `; $('pEdit').onclick=()=>{ showPhase('goal'); goalShow(2); }; cardsRender(); const rule=(c,lab,v)=>`
    ${lab}: ${esc(v)}
    `; $('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)=>``).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)=>`
    ${f[0]}

    ${esc(f[1])}

    `).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=>`
    ${w[0]}

    ${w[1]}

    `).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{ if(phase==='learn'){ if(S.ready) showPhase('plan'); else { showPhase('goal'); } return; } if(phase==='goal'){ if(wz{ 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); })();