'use client';
import {BelongingWelcome} from '@/components/section-welcome';
import {useRef,useState} from 'react';
import {Crown,Flower2,Star} from 'lucide-react';
import {ageRanges,avatarStyles} from '@/lib/profile';
import {aspects} from '@/lib/life';
const sections=[{id:'mental',name:'Wellbeing'},{id:'finances',name:'Finances'},{id:'physical',name:'Physical health'}];
const selected=(profile:any,id:string)=>profile.priorities.some((x:string)=>id==='mental'?['mental','emotional','spiritual','relationships'].includes(x):x===id);
const icons={crown:Crown,flower:Flower2,star:Star};
export function ProfileIdentity({profile,change}:any){const [error,setError]=useState(''),[busy,setBusy]=useState(false);const upload=useRef<HTMLInputElement>(null),version=useRef(0);const Icon=icons[profile.avatar as keyof typeof icons]||Crown;const update=(key:string,value:any)=>change((p:any)=>p.profile[key]=value);
async function photo(file:File|undefined){if(!file)return;const token=++version.current;setError('');if(!['image/jpeg','image/png','image/webp'].includes(file.type)||file.size>8*1024*1024){setError('Choose a JPG, PNG or WebP photo smaller than 8 MB.');return;}setBusy(true);const url=URL.createObjectURL(file);try{const image=new Image();image.src=url;await image.decode();const side=Math.min(image.width,image.height);if(!side)throw new Error('This photo could not be read.');const canvas=document.createElement('canvas');canvas.width=320;canvas.height=320;const ctx=canvas.getContext('2d');if(!ctx)throw new Error('Photo upload is not supported in this browser.');ctx.fillStyle='#ffffff';ctx.fillRect(0,0,320,320);ctx.drawImage(image,(image.width-side)/2,(image.height-side)/2,side,side,0,0,320,320);let value=canvas.toDataURL('image/jpeg',.82);for(const quality of [.65,.5,.35]){if(value.length<=65000)break;value=canvas.toDataURL('image/jpeg',quality);}if(value.length>65000)throw new Error('This photo is too detailed. Please choose another photo.');if(version.current===token)update('photo',value);}catch(e:any){setError(e.message||'This photo could not be opened. Try another image.');}finally{URL.revokeObjectURL(url);if(version.current===token)setBusy(false);if(upload.current)upload.current.value='';}}
return <section className="panel profileidentity"><div className="identityheading"><div className="profileportrait">{profile.photo?<img src={profile.photo} alt="Your private profile photo" width="88" height="88"/>:<Icon size={36} aria-hidden="true"/>}</div><div><p className="eyebrow">YOUR PRIVATE PROFILE</p><h2>{profile.displayName||'Make this space yours'}</h2><p>A preferred name is enough. Everything here is optional.</p></div></div><div className="profilephotocontrols"><label className="secondary uploadlabel">{busy?'Preparing photo…':'Choose a photo'}<input ref={upload} type="file" accept="image/jpeg,image/png,image/webp" disabled={busy} onChange={e=>photo(e.target.files?.[0])}/></label>{profile.photo&&<button className="textbutton" disabled={busy} onClick={()=>update('photo','')}>Remove photo</button>}<span className="note">Square preview · JPG, PNG or WebP · Up to 8 MB</span></div>{error&&<p className="error" role="alert">{error}</p>}<div className="avataroptions"><span>Or choose an avatar</span>{avatarStyles.map(v=>{const Avatar=icons[v as keyof typeof icons];return <button key={v} className={profile.avatar===v&&!profile.photo?'active':''} aria-label={`Use ${v} avatar`} aria-pressed={profile.avatar===v&&!profile.photo} disabled={busy} onClick={()=>change((p:any)=>{p.profile.avatar=v;p.profile.photo='';})}><Avatar size={24}/></button>})}</div><div className="twofields"><label className="field"><span>Preferred name</span><input className="textinput" maxLength={50} value={profile.displayName} placeholder="What should we call you?" onChange={e=>update('displayName',e.target.value)}/></label><label className="field"><span>Age range (optional)</span><select className="textinput" value={profile.ageRange} onChange={e=>update('ageRange',e.target.value)}>{ageRanges.map(v=><option key={v} value={v}>{v==='unspecified'?'Prefer not to say':v}</option>)}</select></label></div><div className="field"><span>Your current priorities</span><div className="symptoms">{sections.map(a=><button key={a.id} aria-pressed={selected(profile,a.id)} className={selected(profile,a.id)?'active':''} onClick={()=>change((p:any)=>{const list=p.profile.priorities;p.profile.priorities=selected(p.profile,a.id)?list.filter((x:string)=>a.id==='mental'?!['mental','emotional','spiritual','relationships'].includes(x):x!==a.id):[...list,a.id];if(!list.includes(a.id)&&list.length===0)p.profile.focus=a.id;})}>{a.name}</button>)}</div></div><p className="note">Choose as many priorities as you like. Your priorities help you decide what to work on. Age and photo do not change your recommendations.</p><div className="reserve"><b>Your body measurements stay in Physical health</b><p>Weight, height, muscle mass and body fat are optional health records, separate from your profile.</p></div></section>}
export function WelcomeProfile({profile,change}:any){const [step,setStep]=useState(0);const finish=()=>change((p:any)=>p.profile.welcomeComplete=true);return <section className="panel welcomeflow" aria-label="Welcome to Sovereign"><BelongingWelcome name=""/><p className="eyebrow">YOUR SPACE · STEP {step+1} OF 3</p><h1>{['What should we call you?','What matters most right now?','How much detail feels right for you?'][step]}</h1><p>You can skip any question and change your choices in My Profile.</p>{step===0&&<label className="field"><span>Preferred name (optional)</span><input autoFocus className="textinput" maxLength={50} value={profile.displayName} placeholder="Your preferred name" onChange={e=>change((p:any)=>p.profile.displayName=e.target.value)}/></label>}{step===1&&<div className="symptoms">{sections.map(a=><button aria-pressed={selected(profile,a.id)} className={selected(profile,a.id)?'active':''} key={a.id} onClick={()=>change((p:any)=>{const list=p.profile.priorities;p.profile.priorities=selected(p.profile,a.id)?list.filter((x:string)=>a.id==='mental'?!['mental','emotional','spiritual','relationships'].includes(x):x!==a.id):[...list,a.id];if(!list.includes(a.id)&&list.length===0)p.profile.focus=a.id;})}>{a.name}</button>)}</div>}{step===2&&<div className="welcomechoices">{[['simple','A simple start','One mood question in your daily check-in.'],['detailed','A little more detail','Mood, energy and stress in your daily check-in.']].map(([v,label,description])=><button aria-pressed={profile.structure===v} className={profile.structure===v?'active':''} key={v} onClick={()=>change((p:any)=>p.profile.structure=v)}><b>{label}</b><span>{description}</span></button>)}</div>}<div className="welcomebuttons">{step>0&&<button className="secondary" onClick={()=>setStep(step-1)}>Back</button>}<button className="primarybutton" onClick={()=>step<2?setStep(step+1):finish()}>{step===2?'Open my space':'Continue'}</button><button className="textbutton" onClick={finish}>Skip setup</button></div></section>}
export function ReminderPreferences({profile,change}:any){return <section className="panel"><h3>Your Support-Circle Identity</h3><label className="field"><span>Suggested support-circle display name (optional)</span><input className="textinput" maxLength={50} value={profile.supportName} placeholder="A name you choose to share" onChange={e=>change((p:any)=>p.profile.supportName=e.target.value)}/></label><p className="note">Confirm this name when joining or creating a circle. Existing memberships keep the name you joined with. Your private photo, age, measurements, budget and journal are not added to messages.</p></section>}
