Home / Admin / Well-B Assessment App
Duplicate Snippet

Embed Snippet on Your Site

Well-B Assessment App

App HTML File

Aravind James James Latha
<10
Code Preview
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Well-B Assessment</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Lora:wght@400;500;600&family=Montserrat:wght@400;500;600&display=swap" />
<script crossorigin src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
<script crossorigin src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/7.23.6/babel.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2"></script>
<style>
  html, body { margin: 0; padding: 0; background: #FFFAF1; }
  * { box-sizing: border-box; }
</style>
</head>
<body>
<div id="root"></div>
<script type="text/babel" data-presets="react">
const { useState, useEffect, useMemo } = React;
/* ============================================================
   SUPABASE CONFIG
   ============================================================ */
const SUPABASE_URL = "https://ixhpoyllvresutnubyvp.supabase.co";
const SUPABASE_ANON = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Iml4aHBveWxsdnJlc3V0bnVieXZwIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzkwMTYxNTAsImV4cCI6MjA5NDU5MjE1MH0.JJkLREEj33Wqg_nmeQrmYYew-kyAjB4MEfW9MLxk_aw";
const sb = supabase.createClient(SUPABASE_URL, SUPABASE_ANON);
const C = { dark:"#1A3637", gold:"#D6BA96", sage:"#677C69", forest:"#40534D", cream:"#FFFAF1", white:"#FFFFFF", border:"rgba(26,54,55,0.10)" };
const LOGO = "https://wellbalign.ae/wp-content/uploads/2026/05/global-013.webp";
const WHATSAPP = "https://wa.me/971565774921";
const FB = "'Montserrat',system-ui,sans-serif";
const FH = "'Lora',Georgia,serif";
/* ---------- supabase helpers ---------- */
async function validateCode(code){
  const c = (code||"").trim().toUpperCase();
  const { data, error } = await sb.from("companies").select("*").eq("code", c).eq("active", true).maybeSingle();
  if (error || !data) return null;
  return { company: data.company };
}
async function loadParticipant(email){
  const { data } = await sb.from("participants").select("*").eq("email",(email||"").trim().toLowerCase()).maybeSingle();
  if (!data) return null;
  return { profile: data.profile, data: data.data };
}
async function saveParticipant(rec){
  const email = rec.profile.email.trim().toLowerCase();
  const { error } = await sb.from("participants").upsert({
    email, name: rec.profile.name, profile: rec.profile, data: rec.data, updated_at: new Date().toISOString()
  }, { onConflict: "email" });
  if (error) console.error("save error", error);
  return !error;
}
async function saveReport(reportId, profile, data, scores, overall){
  const { error } = await sb.from("reports").upsert({
    report_id: reportId, email: profile.email.trim().toLowerCase(),
    profile, data, scores, overall
  }, { onConflict: "report_id" });
  if (error) console.error("report error", error);
  return !error;
}
/* ---------- styles ---------- */
const card={background:C.white,border:`0.5px solid ${C.border}`,borderRadius:12,padding:20,marginBottom:16};
const cardTitle={color:C.sage,fontSize:10,textTransform:"uppercase",fontWeight:600,letterSpacing:"0.08em",fontFamily:FB,marginBottom:12};
const infoNote={borderLeft:`2px solid ${C.sage}`,background:"rgba(103,124,105,0.07)",padding:"10px 14px",borderRadius:6,fontSize:13,color:C.dark,marginBottom:16,lineHeight:1.5,fontFamily:FB};
const recoveryWrap={borderLeft:`3px solid ${C.gold}`,background:"rgba(26,54,55,0.03)",padding:16,borderRadius:8,marginBottom:16};
const labelStyle={fontSize:14,color:C.dark,fontWeight:500,marginBottom:10,fontFamily:FB,lineHeight:1.45};
const inputStyle={width:"100%",padding:"11px 12px",border:`1px solid ${C.border}`,borderRadius:8,fontSize:14,fontFamily:FB,color:C.dark,background:C.white,boxSizing:"border-box"};
function btnPrimary(a=true){return{background:a?C.dark:"rgba(26,54,55,0.08)",color:a?C.gold:"rgba(26,54,55,0.4)",border:"none",borderRadius:8,padding:"12px 22px",fontSize:14,fontWeight:600,fontFamily:FB,cursor:a?"pointer":"not-allowed"};}
const btnGold={background:C.gold,color:C.dark,border:"none",borderRadius:8,padding:"13px 24px",fontSize:14,fontWeight:600,fontFamily:FB,cursor:"pointer"};
const btnBack={background:"transparent",color:C.dark,border:`1px solid ${C.dark}`,borderRadius:8,padding:"11px 20px",fontSize:13,fontWeight:600,fontFamily:FB,cursor:"pointer"};
function RadioGroup({options,value,onChange}){
  return (
    <div style={{display:"flex",flexDirection:"column",gap:8}}>
      {options.map((opt,i)=>{const sel=value===i;return(
        <button key={i} onClick={()=>onChange(i)} style={{textAlign:"left",padding:"11px 14px",borderRadius:8,border:sel?`1px solid ${C.dark}`:`1px solid ${C.border}`,background:sel?"rgba(26,54,55,0.05)":C.white,color:C.dark,fontSize:13.5,fontFamily:FB,cursor:"pointer",lineHeight:1.4,fontWeight:sel?600:400}}>{opt}</button>
      );})}
    </div>
  );
}
function Likert({count,value,onChange,startAt=0}){
  const items=[];for(let i=0;i<count;i++)items.push(startAt+i);
  return (
    <div style={{display:"flex",gap:6,flexWrap:"wrap"}}>
      {items.map((v)=>{const sel=value===v;return(
        <button key={v} onClick={()=>onChange(v)} style={{minWidth:40,padding:"10px 12px",borderRadius:8,border:sel?"none":`1px solid ${C.border}`,background:sel?C.dark:C.white,color:sel?C.gold:C.dark,fontWeight:600,fontSize:14,fontFamily:FB,cursor:"pointer"}}>{v}</button>
      );})}
    </div>
  );
}
function CheckList({options,value=[],onChange}){
  const toggle=(o)=>{onChange(value.includes(o)?value.filter(v=>v!==o):[...value,o]);};
  return (
    <div style={{display:"flex",flexDirection:"column",gap:7}}>
      {options.map((opt,i)=>{const sel=value.includes(opt);return(
        <button key={i} onClick={()=>toggle(opt)} style={{textAlign:"left",padding:"10px 13px",borderRadius:8,border:sel?`1px solid ${C.dark}`:`1px solid ${C.border}`,background:sel?"rgba(26,54,55,0.05)":C.white,color:C.dark,fontSize:13,fontFamily:FB,cursor:"pointer"}}>
          <span style={{color:sel?C.dark:"rgba(26,54,55,0.3)",marginRight:8,fontWeight:700}}>{sel?"\u2713":"\u25CB"}</span>{opt}
        </button>
      );})}
    </div>
  );
}
function QuestionRadio({q,options,value,onChange}){
  return (<div style={{marginBottom:18}}><div style={labelStyle}>{q}</div><RadioGroup options={options} value={value} onChange={onChange}/></div>);
}
/* ============================================================ CONTENT ============================================================ */
const STRESS_DYN=["","Minimal","Very Low","Low","Below Average","Moderate","Above Average","Elevated","High","Very High","Overwhelming"];
const STRESSORS=["Work pressure and deadlines","Financial concerns","Family responsibilities","Health concerns","Relationship challenges","Job uncertainty","Commute and travel fatigue","Physical symptoms or pain","Social isolation","Environmental factors","Career growth pressure","Work-life balance"];
const BODY_SIGNS=["Headaches or migraines","Muscle tension or neck/back pain","Digestive issues or bloating","Difficulty sleeping","Irritability or mood swings","Difficulty concentrating or focusing","Low energy or chronic fatigue","Skin issues or hair loss","Increased heart rate or palpitations","Emotional eating or loss of appetite","Withdrawal from social activities","Anxiety or persistent overthinking"];
const NEURO_Q=[
{q:"How do you currently recover from stressful periods?",o:["No recovery practice — I just push through","Occasional rest or distraction (TV, scrolling)","I have some recovery habits but use them inconsistently","I have a regular neuroregulation practice (breathing, movement, rest, nature)"]},
{q:"After a stressful event, how quickly do you typically return to a calm baseline?",o:["Rarely — I stay elevated for days","Slowly — it takes a day or two","Moderately — several hours","Quickly — within an hour or less"]},
{q:"Do you practice any form of intentional recovery — breathwork, movement, nature time, or deliberate rest?",o:["Never","Occasionally — once a week or less","Regularly but not consistently","Daily — it is a non-negotiable part of my routine"]}];
const POSTURAL_Q=[
{q:"Neck posture at your workstation — how does your head sit relative to your shoulders?",o:["Neutral — ear aligned directly over shoulder","Slightly forward — mild forward head posture","Moderately forward — chin clearly ahead of shoulder line","Significantly forward + regular neck pain, stiffness, or headaches"]},
{q:"Shoulder position — when sitting at your desk, how are your shoulders?",o:["In a straight line — relaxed and back","Slightly hunched forward — mild rounding","Moderately hunched — shoulders clearly rounded forward","Significantly hunched + upper back or shoulder pain daily"]},
{q:"Lower back — stand naturally against a wall. Can you slide your flat hand behind your lower back?",o:["Yes, hand fits comfortably — normal lordosis, no pain","Too much space — excessive arch + occasional low back ache","No space (flat back) + occasional low back pain","Daily low back pain — regardless of posture"]},
{q:"Deep neck flexor endurance — gently tuck your chin. How long before your neck trembles or fatigues?",o:["30+ seconds — comfortable and easy","15-30 seconds — mild effort","Under 15 seconds","Cannot hold — neck pain or weakness immediately"]},
{q:"Thoracic rotation (seated) — sit upright, cross arms on chest, rotate left then right.",o:["Equal full rotation both sides — no discomfort","Mild restriction on one side","Moderate restriction + mid-back tightness","Significant restriction or pain on rotation"]}];
const JOINTS=["Neck","Upper back","Lower back","Left shoulder","Right shoulder","Left elbow","Right elbow","Left wrist","Right wrist","Left hip","Right hip","Left knee","Right knee","Left ankle","Right ankle"];
const JOINT_LEVELS=["None","Mild","Moderate","Significant"];
const FUNCTIONAL_Q=[
{q:"Apley Scratch Test A — internal rotation",o:["Full reach, no pain","Reached but with mild discomfort","Could not fully reach — limited range of motion","Significant pain or very limited range"]},
{q:"Apley Scratch Test B — external rotation",o:["Full reach, no pain","Reached but with mild discomfort","Could not fully reach — limited range of motion","Significant pain or very limited range"]},
{q:"Phalen Wrist Test — hold both wrists in full flexion for 60 seconds",o:["No symptoms at all","Mild tingling after 45-60 seconds","Tingling or numbness within 30 seconds","Immediate symptoms or pain — possible carpal tunnel concern"]},
{q:"Single-leg balance — stand on one leg with eyes open for 10 seconds",o:["Stable on both sides — no wavering","Slight wobble but maintained on both sides","Could not maintain 10 seconds on one side","Significant instability on both sides"]},
{q:"Foot arch — stand barefoot on a hard floor",o:["Clear arch visible — normal foot structure","Mild flattening — mild flat foot","Flat foot — foot largely contacts the ground","Flat foot + foot or ankle pain when standing or walking"]}];
const PHYS_RECOVERY_Q=[
{q:"How many hours of sleep do you typically get on work nights?",o:["Less than 5 hours","5-6 hours","6-7 hours","7-9 hours (recommended by sleep science)"]},
{q:"How many days per week do you engage in deliberate physical exercise (minimum 30 minutes)?",o:["0 days — fully sedentary","1-2 days per week","3-4 days per week","5+ days per week (meets WHO physical activity guideline)"]},
{q:"Do you perform any regular stretching or mobility work to counter desk posture?",o:["Never","Occasionally — less than once a week","1-2 times per week","Daily or most days"]},
{q:"Do you take movement breaks away from your desk during the workday?",o:["Never — seated all day","Once or twice a day","Every 1-2 hours briefly","Every 30-45 minutes (ergonomically recommended)"]}];
const WHO5=["I have felt cheerful and in good spirits","I have felt calm and relaxed","I have felt active and vigorous","I woke up feeling fresh and rested","My daily life has been filled with things that interest me"];
const PSS10=["Felt upset because of something unexpected?","Felt unable to control important things in your life?","Felt nervous and stressed?","Felt difficulties piling up so high you could not overcome them?","Been able to control irritations in your life?","Felt that things were going your way?","Been able to handle personal problems?","Felt confident about handling personal problems?","Felt that things were going well?","Been angered by things outside your control?"];
const PSS_REVERSE=[4,5,6,7,8];
const MENTAL_RECOVERY_Q=[
{q:"Do you practice any breathing technique for stress regulation?",o:["Never — not aware of any technique","Aware of techniques but rarely practice","Practice occasionally when very stressed","Practice regularly — daily or most days"]},
{q:"Do you practice mindfulness, meditation, or any structured mental relaxation?",o:["Never","Occasionally","Weekly practice","Daily practice (10 or more minutes)"]},
{q:"Do you have deliberate screen-free or digital detox time daily?",o:["No — screens stay on until I sleep","Occasionally switch off before bed","30-60 minutes of screen-free wind-down","A consistent screen-free routine before sleep every night"]},
{q:"When experiencing significant stress or mental strain, do you seek support?",o:["Never — I manage alone","Rarely","Sometimes talk to a trusted friend or colleague","Actively seek support and know where to go"]}];
const SWLS=["In most ways my life is close to my ideal","The conditions of my life are excellent","I am satisfied with my life","So far I have gotten the important things I want in life","If I could live my life over, I would change almost nothing"];
const PANAS=[{t:"Interested",pos:true},{t:"Distressed",pos:false},{t:"Excited",pos:true},{t:"Upset",pos:false},{t:"Strong",pos:true},{t:"Guilty",pos:false},{t:"Enthusiastic",pos:true},{t:"Nervous",pos:false},{t:"Proud",pos:true},{t:"Afraid",pos:false}];
const EMO_RECOVERY_Q=[
{q:"Do you engage in any reflective practice — journaling, gratitude log, or expressive writing?",o:["Never","Occasionally when upset","Weekly habit","Daily reflective practice"]},
{q:"Do you have a regular creative outlet (art, music, cooking, writing, sport)?",o:["None","Rarely","Sometimes (monthly)","Regularly (weekly or more)"]},
{q:"How comfortable are you expressing difficult emotions in a healthy way?",o:["Very uncomfortable — I suppress or avoid emotions","Somewhat uncomfortable","Mostly comfortable","Very comfortable — I express and process emotions well"]},
{q:"Do you consciously practice gratitude or positive reframing in daily life?",o:["Never","Rarely","Sometimes","Yes — a consistent daily habit"]}];
const BREAKFAST_T=["Not eaten","Before 7 AM","7-8 AM","8-9 AM","9-10 AM","After 10 AM"];
const LUNCH_T=["Not eaten","11 AM-12 PM","12-1:30 PM","1:30-3 PM","After 3 PM"];
const DINNER_T=["Not eaten","6-7:30 PM","7:30-9 PM","9-10 PM","After 10 PM"];
const MEAL_PATTERN_Q=[
{q:"How often do you skip a main meal?",o:["Daily — regularly skip one or more meals","4-6 times a week","1-3 times a week","Rarely — I eat all main meals consistently"]},
{q:"How consistent is your daily eating schedule?",o:["Very inconsistent — meal times vary widely","Somewhat inconsistent","Mostly consistent","Very consistent — same meal times every day"]},
{q:"How often do you eat a heavy meal within 2 hours of sleeping?",o:["Almost every night","Often (4-5 nights per week)","Occasionally (1-2 nights per week)","Rarely or never"]},
{q:"During Ramadan or fasting periods, do you plan your Suhoor and Iftar meals for nutritional balance?",o:["No — eat whatever is available","Minimal planning","Some attention to balance","Yes — deliberately plan balanced and nutritious meals for both"]}];
const DIETARY_Q=[
{q:"How many portions of vegetables and fruit do you eat per day?",o:["0-1 portion","2-3 portions","4-5 portions","5+ portions daily — meets the WHO recommendation"]},
{q:"How often do you choose whole grains over refined carbohydrates?",o:["Never — mostly refined carbs","Rarely","Sometimes — a mix of both","Mostly whole grains (brown rice, oats, wholemeal bread)"]},
{q:"How would you rate your daily protein intake?",o:["Very low — minimal protein-rich foods","Below adequate","Adequate for my activity level","Good — varied protein sources consumed daily"]},
{q:"How often do you eat fried foods, processed meats, or foods high in saturated fat?",o:["Daily — main part of my diet","Often (4-5 times per week)","Occasionally (1-3 times per week)","Rarely — I actively limit these"]},
{q:"How would you estimate your salt intake? WHO recommends under 5g per day.",o:["High — heavy use of salt and salty snacks","Moderately high","Moderate","Low — I limit added salt and avoid processed foods"]},
{q:"How often do you eat from fast food outlets or ultra-processed ready meals per week?",o:["Daily or more","4-6 times per week","1-3 times per week","Rarely or never"]}];
const HYDRATION_Q=[
{q:"How much plain water do you drink daily? 2-3 litres recommended — higher in UAE heat.",o:["Less than 1 litre","1-1.5 litres","1.5-2.5 litres","2.5+ litres daily"]},
{q:"How often do you consume sugar-sweetened beverages?",o:["Multiple times daily","Once daily","A few times a week","Rarely or never"]},
{q:"Do you drink water consistently throughout the day?",o:["Rarely drink water — often dehydrated","Mainly only at mealtimes","Fairly consistent through the day","Regular consistent hydration throughout the entire day"]}];
const DEFICIENCY=["Fatigue + bone aches + low mood (Vitamin D)","Tiredness + pale skin + breathlessness (Iron)","Tingling hands/feet + memory fog (Vitamin B12)","Muscle cramps + poor sleep + headaches (Magnesium)","Hair loss + slow wound healing + low immunity (Zinc)","Weight gain + cold sensitivity + hair thinning (Iodine/Thyroid)","Weak nails + muscle spasms + dental issues (Calcium)","None of the above — no regular symptoms"];
const NUT_RECOVERY_Q=[
{q:"Do you take any supplements?",o:["No supplements at all","Occasionally or randomly","Yes — based on personal preference","Yes — based on a blood test or doctor recommendation"]},
{q:"How do you feel your energy levels across the day?",o:["Very low — fatigued most of the day","Moderate — significant energy dips after meals","Reasonable — some afternoon dip","Consistently good energy throughout the day"]},
{q:"Where do you typically eat your meals?",o:["Always on the go — rarely properly seated","At my desk while actively working","Seated but with screen on","A dedicated meal break completely away from screen and work"]}];
const FIN_CASHFLOW=[
{q:"Do you know — without checking — approximately how much you spent last month?",o:["No idea","Not really — I just check my balance","Roughly, but not precisely","Yes, I track it closely"],p:[0,1,2,4]},
{q:"At the end of each month, do you save a fixed amount before spending?",o:["I do not save regularly","Rarely — most of it gets spent","Sometimes, if there is money left over","Yes — savings go out automatically first"],p:[0,1,2,4]},
{q:"How long could you maintain your current lifestyle if your income stopped today?",o:["2 weeks or less","Less than 3 months","3-6 months","6 months or more"],p:[0,1,3,4]},
{q:"How would you describe your relationship with debt?",o:["Debt feels out of control","Carrying a balance, paying minimums","Manageable debt with a clear payoff plan","No consumer debt — cards paid in full monthly"],p:[0,1,2,4]}];
const FIN_PROTECTION=[
{q:"If you were unable to work for 6 months due to illness or accident, what would happen?",o:["It would be a serious crisis","I would have to borrow or rely on family","My savings would cover it, just about","I have income protection insurance"],p:[0,1,2,4]},
{q:"Do you have life insurance or critical illness cover adequate for your family needs?",o:["None — but I have dependants","Only what my employer provides","Some cover, but not sure if it is enough","Yes — reviewed and adequate"],p:[0,1,2,4]},
{q:"Do you have a will or estate plan in place (especially important in the UAE)?",o:["No dependants, not relevant yet","No — I have not thought about it","In progress / partially done","Yes — documented and up to date"],p:[0,0,2,4]},
{q:"How confident are you that your health insurance covers a serious medical event?",o:["Worried — I know there are gaps","Unsure — I have never checked the limits","Fairly confident — employer covers it","Very confident — I know my policy well"],p:[0,1,2,4]}];
const FIN_GROWTH=[
{q:"Do you have a retirement plan beyond your UAE end-of-service gratuity?",o:["Nothing in place","Relying mostly on gratuity","Some savings, but no structured plan","Yes — active investments or pension outside gratuity"],p:[0,1,2,4]},
{q:"Are your savings and investments growing faster than inflation?",o:["I do not invest — not sure where to start","Mostly in a bank account earning little","Partially — some invested, some in savings","Yes — invested in diversified assets"],p:[0,1,2,4]},
{q:"Do you have a clear financial goal with a timeline attached to it?",o:["No goals set","I think about it but have not planned it","A general idea, nothing specific","Yes — written down with a specific target"],p:[0,1,2,4]},
{q:"How do you feel when you think about your financial future?",o:["Overwhelmed — I avoid thinking about it","Anxious — I know I need to do more","Cautiously optimistic — working on it","Confident — I have a clear plan"],p:[0,1,3,4]}];
const FIN_RECOVERY_Q=[
{q:"Have you ever consulted a financial advisor or used a structured financial planning tool?",o:["Never — managing entirely alone","Occasionally looked things up online","Used a financial app or resource","Consulted a certified financial planner"]},
{q:"When facing financial pressure, what is your primary coping approach?",o:["Worry and avoidance — I try not to think about it","Talk to family or friends for emotional support","Research solutions and reduce spending proactively","Make a clear plan and seek professional advice"]}];
const SOCIAL_Q=[
{q:"How many family members do you feel at ease talking to about personal matters?",o:["None","1 person","2-3 people","4 or more people"]},
{q:"How many friends do you feel comfortable talking to about private matters?",o:["None","1 person","2-3 people","4 or more people"]},
{q:"How often do you see or speak with family or close friends?",o:["Less than monthly","Monthly","Weekly","Daily or almost daily"]},
{q:"When you need help or support, is there someone reliably available to you?",o:["Never","Rarely","Sometimes","Always — I have reliable support"]},
{q:"How often do you feel isolated from those around you?",o:["Often","Sometimes","Rarely","Never"]},
{q:"How often do you feel you lack companionship?",o:["Often","Sometimes","Rarely","Never"]},
{q:"Do you feel a genuine sense of belonging in your team or organisation?",o:["Strongly disagree","Disagree","Agree","Strongly agree"]},
{q:"Do you feel psychologically safe to speak up, share ideas, or raise concerns at work?",o:["Never — I stay silent","Rarely","Sometimes","Always — open and trusted environment"]}];
const SOCIAL_RECOVERY_Q=[
{q:"Do you have regular quality time for yourself — intentional solitude to rest and recharge?",o:["Never — always busy, no personal space","Rarely","Sometimes","Yes — I actively protect personal restoration time"]},
{q:"Do you maintain meaningful social connections outside of work?",o:["Very isolated outside work","Minimal connections","Some meaningful connections","Rich, active social life outside work"]},
{q:"Are you involved in any community, volunteer, or group activity?",o:["None","Occasionally","Monthly involvement","Regular, active involvement"]}];
const ENV_WORK_Q=[
{q:"Is your workspace well-lit with adequate natural daylight?",o:["No natural light","Minimal","Some natural light for part of day","Abundant all day"]},
{q:"How would you rate the air quality and ventilation in your office?",o:["Very poor","Poor","Acceptable","Good — fresh, well-ventilated"]},
{q:"How often does workplace noise affect your concentration?",o:["Very often","Often","Occasionally","Rarely"]},
{q:"Is the AC temperature comfortable?",o:["Very uncomfortable","Somewhat","Mostly comfortable","Always comfortable"]},
{q:"How would you rate your workstation setup?",o:["Very poorly set up","Basic","Fairly ergonomic","Fully assessed and adjusted"]},
{q:"Do you have easy access to clean drinking water at work?",o:["No access","Limited","Accessible but not near","Always easy"]},
{q:"Does your workplace support healthy food choices?",o:["No healthy options","Few","Some","Strong healthy culture"]},
{q:"Does your organisation have active green or sustainability practices?",o:["None","Minimal — recycling","Moderate","Strong — certified or active programme"]}];
const ENV_HOME_Q=[
{q:"How would you describe the quality of your home living environment?",o:["Very poor","Fair","Good","Excellent — comfortable, clean, restorative"]},
{q:"What is your typical daily commute time (one way)?",o:["Over 90 minutes","60-90 minutes","30-60 minutes","Under 30 minutes"]},
{q:"Does your commute significantly affect your energy, mood, or wellbeing?",o:["Severely","Often draining","Occasionally","Rarely"]},
{q:"Do you have access to green spaces, parks, or nature?",o:["No access","Very limited","Occasional","Easy and regular access"]}];
const ENV_RECOVERY_Q=[
{q:"Do you regularly spend time outdoors in natural settings?",o:["Never","Rarely (monthly)","Sometimes (weekly)","Regularly — deliberate priority"]},
{q:"Do you personalise or optimise your workspace for comfort?",o:["No — default and cluttered","Minimal","Some","Intentionally designed"]},
{q:"Do you take regular breaks away from your work environment?",o:["Never","Rarely","1-2 per day","Regular including outdoor time"]}];
const COMMIT_PILLARS=["Physical","Mental","Emotional","Nutritional","Financial","Social","Environmental","Neuroregulation"];
const RECOVERY_SUGGESTIONS={
Physical:"Prioritise 7-9 hours sleep, take a movement break every 45 minutes, and start a 5-minute daily stretching routine targeting neck and hip flexors.",
Mental:"Practice box breathing daily (4s in, 4s hold, 4s out, 4s hold). Set a screen-off time 30 minutes before bed and identify one trusted person to talk to.",
Emotional:"Start a 3-line daily gratitude journal. Identify one creative outlet you enjoy. Practice naming and expressing your emotions rather than suppressing them.",
Nutritional:"Focus on meal timing consistency, increase vegetable intake to 5 daily portions, reduce sugar-sweetened beverages, and book a blood test for Vitamin D and Iron.",
Financial:"Build a basic monthly budget, review your UAE end-of-service or DEWS entitlement, and prioritise building a small emergency fund before investing.",
Social:"Schedule one meaningful social connection this week, identify a workplace peer you can open up to, and explore one community or group to join.",
Environmental:"Ask for an ergonomic workstation assessment, add 10 minutes of daily outdoor time, and bring one plant or personal element to your workspace."};
const PILLARS=["Physical","Mental","Emotional","Nutritional","Financial","Social","Environmental"];
const NEUTRAL=50;
/* ============================================================ COMPLETENESS ============================================================ */
function nm(v){return v!==undefined&&v!==null&&String(v).trim()!=="";}
function physicalComplete(d){const a=d.physical||{};if(!(a.gender&&nm(a.age)&&nm(a.height)&&nm(a.weight)))return false;for(let i=0;i<5;i++)if(typeof a["post_"+i]!=="number")return false;for(let i=0;i<15;i++)if(typeof a["joint_"+i]!=="number")return false;for(let i=0;i<5;i++)if(typeof a["func_"+i]!=="number")return false;for(let i=0;i<4;i++)if(typeof a["prec_"+i]!=="number")return false;return true;}
function mentalComplete(d){const a=d.mental||{};for(let i=0;i<5;i++)if(typeof a["who_"+i]!=="number")return false;for(let i=0;i<10;i++)if(typeof a["pss_"+i]!=="number")return false;for(let i=0;i<4;i++)if(typeof a["mrec_"+i]!=="number")return false;return true;}
function emotionalComplete(d){const a=d.emotional||{};for(let i=0;i<5;i++)if(typeof a["swls_"+i]!=="number")return false;for(let i=0;i<10;i++)if(typeof a["pan_"+i]!=="number")return false;for(let i=0;i<4;i++)if(typeof a["erec_"+i]!=="number")return false;return true;}
function nutritionalComplete(d){const a=d.nutritional||{};if(!(a.breakfast&&a.lunch&&a.dinner))return false;for(let i=0;i<4;i++)if(typeof a["mp_"+i]!=="number")return false;for(let i=0;i<6;i++)if(typeof a["diet_"+i]!=="number")return false;for(let i=0;i<3;i++)if(typeof a["hyd_"+i]!=="number")return false;if(!(a.deficiency&&a.deficiency.length>0))return false;for(let i=0;i<3;i++)if(typeof a["nrec_"+i]!=="number")return false;return true;}
function socialComplete(d){const a=d.social||{};for(let i=0;i<8;i++)if(typeof a["soc_"+i]!=="number")return false;for(let i=0;i<3;i++)if(typeof a["srec_"+i]!=="number")return false;return true;}
function environmentalComplete(d){const a=d.environmental||{};for(let i=0;i<8;i++)if(typeof a["ew_"+i]!=="number")return false;for(let i=0;i<4;i++)if(typeof a["eh_"+i]!=="number")return false;for(let i=0;i<3;i++)if(typeof a["erc_"+i]!=="number")return false;return true;}
function neuroComplete(d){const s=d.stress||{};for(let i=0;i<3;i++)if(typeof s["neuro_"+i]!=="number")return false;return true;}
/* ============================================================ SCORING ============================================================ */
const POST_PTS=[[20,13,7,0],[20,13,7,0],[20,10,10,0],[20,13,7,0],[20,13,7,0]];
const FUNC_PTS=[[20,13,7,0],[20,13,7,0],[20,13,7,0],[20,13,7,0],[20,13,7,0]];
const PREC_PTS=[[0,8,17,25],[0,8,17,25],[0,8,17,25],[0,8,17,25]];
const JOINT_PTS=[6.67,4.44,2.22,0];
function bmiScore(h,w){if(!h||!w)return NEUTRAL;const m=h/100,b=w/(m*m);if(b<18.5)return 60;if(b<25)return 100;if(b<30)return 70;if(b<35)return 40;if(b<40)return 20;return 0;}
function physicalScore(d){const a=d.physical||{};const A=bmiScore(Number(a.height),Number(a.weight));let B=0;for(let i=0;i<5;i++){const v=a["post_"+i];B+=typeof v==="number"?POST_PTS[i][v]:20*(NEUTRAL/100);}let Cj=0;for(let i=0;i<15;i++){const v=a["joint_"+i];Cj+=typeof v==="number"?JOINT_PTS[v]:6.67*(NEUTRAL/100);}let D=0;for(let i=0;i<5;i++){const v=a["func_"+i];D+=typeof v==="number"?FUNC_PTS[i][v]:20*(NEUTRAL/100);}let E=0;for(let i=0;i<4;i++){const v=a["prec_"+i];E+=typeof v==="number"?PREC_PTS[i][v]:25*(NEUTRAL/100);}return Math.round(A*0.20+B*0.25+Cj*0.20+D*0.20+E*0.15);}
const MREC_PTS=[[0,8,17,25],[0,8,17,25],[0,8,17,25],[0,8,17,25]];
function mentalScore(d){const a=d.mental||{};let who=0;WHO5.forEach((_,i)=>{const v=a["who_"+i];who+=typeof v==="number"?v:2.5;});const A=(who/25)*100;let raw=0;PSS10.forEach((_,i)=>{const v=a["pss_"+i];if(typeof v==="number")raw+=PSS_REVERSE.includes(i)?4-v:v;else raw+=2;});const B=100-(raw/40)*100;let Cr=0;for(let i=0;i<4;i++){const v=a["mrec_"+i];Cr+=typeof v==="number"?MREC_PTS[i][v]:25*(NEUTRAL/100);}return Math.round(A*0.40+B*0.40+Cr*0.20);}
const EREC_PTS=[[0,8,17,25],[0,8,17,25],[0,8,17,25],[0,8,17,25]];
function emotionalScore(d){const a=d.emotional||{};let sw=0;SWLS.forEach((_,i)=>{const v=a["swls_"+i];sw+=typeof v==="number"?v:4;});const A=((sw-5)/30)*100;let pos=0,neg=0;PANAS.forEach((it,i)=>{const v=a["pan_"+i];const val=typeof v==="number"?v:3;if(it.pos)pos+=val;else neg+=val;});const B=((pos-5)/20)*100;const Cn=100-(((neg-5)/20)*100);let D=0;for(let i=0;i<4;i++){const v=a["erec_"+i];D+=typeof v==="number"?EREC_PTS[i][v]:25*(NEUTRAL/100);}const cl=(x)=>Math.max(0,Math.min(100,x));return Math.round(cl(A)*0.35+cl(B)*0.30+cl(Cn)*0.15+D*0.20);}
const BREAKFAST_PTS={"Not eaten":0,"Before 7 AM":8,"7-8 AM":10,"8-9 AM":8,"9-10 AM":5,"After 10 AM":2};
const LUNCH_PTS={"Not eaten":0,"11 AM-12 PM":8,"12-1:30 PM":10,"1:30-3 PM":7,"After 3 PM":3};
const DINNER_PTS={"Not eaten":0,"6-7:30 PM":10,"7:30-9 PM":8,"9-10 PM":4,"After 10 PM":0};
const MP_PTS=[[0,8,17,25],[0,8,17,25],[0,8,17,25],[0,8,17,25]];
const DIET_PTS=[[0,10,20,30],[0,5,12,20],[0,5,12,20],[0,5,12,20],[0,3,7,10],[0,0,5,10]];
const DIET_MAX=[30,20,20,20,10,10];
const HYD_PTS=[[0,15,30,40],[0,10,25,40],[0,7,13,20]];
const HYD_MAX=[40,40,20];
const NREC_PTS=[[0,11,22,33],[0,11,22,33],[0,11,22,33]];
function nutritionalScore(d){const a=d.nutritional||{};const bk=a.breakfast?(BREAKFAST_PTS[a.breakfast]??5):5;const ln=a.lunch?(LUNCH_PTS[a.lunch]??5):5;const dn=a.dinner?(DINNER_PTS[a.dinner]??5):5;const mt=((bk+ln+dn)/30)*100;let pat=0;for(let i=0;i<4;i++){const v=a["mp_"+i];pat+=typeof v==="number"?MP_PTS[i][v]:25*(NEUTRAL/100);}const A=mt*0.40+pat*0.60;let bS=0;for(let i=0;i<6;i++){const v=a["diet_"+i];bS+=typeof v==="number"?DIET_PTS[i][v]:DIET_MAX[i]*(NEUTRAL/100);}const B=(bS/110)*100;let cS=0;for(let i=0;i<3;i++){const v=a["hyd_"+i];cS+=typeof v==="number"?HYD_PTS[i][v]:HYD_MAX[i]*(NEUTRAL/100);}const Ch=(cS/100)*100;const def=a.deficiency||[];let D;if(def.length===0)D=60;else if(def.includes(DEFICIENCY[7]))D=100;else D=Math.max(0,100-def.filter(x=>x!==DEFICIENCY[7]).length*15);let E=0;for(let i=0;i<3;i++){const v=a["nrec_"+i];E+=typeof v==="number"?NREC_PTS[i][v]:33*(NEUTRAL/100);}return Math.round(A*0.20+B*0.30+Ch*0.15+D*0.20+E*0.15);}
const LSNS_PTS=[[0,8,17,25],[0,8,17,25],[0,8,17,25],[0,8,17,25]];
const UCLA_PTS=[[0,17,33,50],[0,17,33,50]];
const WORKCON_PTS=[[0,17,33,50],[0,17,33,50]];
const SREC_PTS=[[0,11,22,33],[0,11,22,33],[0,11,22,33]];
function socialScore(d){const a=d.social||{};let A=0;for(let i=0;i<4;i++){const v=a["soc_"+i];A+=typeof v==="number"?LSNS_PTS[i][v]:25*(NEUTRAL/100);}let B=0;for(let i=0;i<2;i++){const v=a["soc_"+(i+4)];B+=typeof v==="number"?UCLA_PTS[i][v]:50*(NEUTRAL/100);}let Cw=0;for(let i=0;i<2;i++){const v=a["soc_"+(i+6)];Cw+=typeof v==="number"?WORKCON_PTS[i][v]:50*(NEUTRAL/100);}let D=0;for(let i=0;i<3;i++){const v=a["srec_"+i];D+=typeof v==="number"?SREC_PTS[i][v]:33*(NEUTRAL/100);}return Math.round(A*0.30+B*0.20+Cw*0.20+D*0.30);}
const ENVW_PTS=[[0,7,15,20],[0,5,12,20],[0,5,12,15],[0,5,10,15],[0,5,12,20],[0,3,7,10],[0,2,5,10],[0,2,5,10]];
const ENVW_MAX=[20,20,15,15,20,10,10,10];
const ENVH_PTS=[[0,8,17,25],[0,8,17,25],[0,8,17,25],[0,8,17,25]];
const ENVR_PTS=[[0,11,22,33],[0,11,22,33],[0,11,22,33]];
function environmentalScore(d){const a=d.environmental||{};let aS=0;for(let i=0;i<8;i++){const v=a["ew_"+i];aS+=typeof v==="number"?ENVW_PTS[i][v]:ENVW_MAX[i]*(NEUTRAL/100);}const A=(aS/120)*100;let B=0;for(let i=0;i<4;i++){const v=a["eh_"+i];B+=typeof v==="number"?ENVH_PTS[i][v]:25*(NEUTRAL/100);}let Ce=0;for(let i=0;i<3;i++){const v=a["erc_"+i];Ce+=typeof v==="number"?ENVR_PTS[i][v]:33*(NEUTRAL/100);}return Math.round(A*0.50+B*0.25+Ce*0.25);}
const NEURO_PTS=[[0,33,67,100],[0,33,67,100],[0,33,67,100]];
function neuroScore(d){if(!neuroComplete(d))return null;const s=d.stress||{};let sum=0;for(let i=0;i<3;i++)sum+=NEURO_PTS[i][s["neuro_"+i]];return Math.round(sum/3);}
function finLeg(a,arr,pf){let s=0,an=0;arr.forEach((qq,i)=>{const idx=a[pf+"_"+i];if(typeof idx==="number"){s+=qq.p[idx];an++;}});return{score:s,answered:an};}
function financialDetail(d){const a=d.financial||{};const cf=finLeg(a,FIN_CASHFLOW,"cf");const pr=finLeg(a,FIN_PROTECTION,"pr");const gr=finLeg(a,FIN_GROWTH,"gr");return{cf,pr,gr,total:cf.score+pr.score+gr.score,totalAnswered:cf.answered+pr.answered+gr.answered};}
function financialScore(d){const x=financialDetail(d);if(x.totalAnswered<12)return null;return Math.round((x.total/48)*100);}
function finBand(t){if(t>=40)return{label:"Strong foundation",color:"#3F7D5B"};if(t>=28)return{label:"Building momentum",color:C.gold};if(t>=16)return{label:"Foundations at risk",color:"#C9892F"};return{label:"Urgent attention needed",color:"#B5453C"};}
function financialInsights(d){const a=d.financial||{};const x=financialDetail(d);const o=[];const q3=a.cf_2!=null?FIN_CASHFLOW[2].p[a.cf_2]:null;const q6=a.pr_1!=null?FIN_PROTECTION[1].p[a.pr_1]:null;const q7=a.pr_2!=null?FIN_PROTECTION[2].p[a.pr_2]:null;const q9=a.gr_0!=null?FIN_GROWTH[0].p[a.gr_0]:null;if(x.cf.answered===4&&x.cf.score<8)o.push("Your cash flow clarity needs work — without knowing where money goes it is hard to build anything on top.");if(q3!=null&&q3<=1)o.push("Your emergency buffer is below the recommended 3-6 months. This is the single highest-priority gap to fix.");if(x.pr.answered===4&&x.pr.score<8)o.push("Your protection is the weakest leg. In the UAE with no state safety net this is where real risk lives.");if(q7===0&&q6!=null&&q6<=1)o.push("No will or estate plan is a significant risk for expatriates in the UAE.");if(x.gr.answered===4&&x.gr.score<8)o.push("Your growth leg needs attention — if your money is not growing above inflation it is quietly losing value.");if(q9!=null&&q9<=1)o.push("Relying on gratuity as your main retirement plan is a common trap. UAE gratuity is capped at two years salary.");if(x.cf.answered===4&&x.pr.answered===4&&x.gr.answered===4&&x.cf.score>=8&&x.pr.score>=8&&x.gr.score>=8)o.push("Your scores are solid across all three areas. The conversation now is about optimisation not gap-filling.");return o;}
function pillarScore(d,n){switch(n){case"Physical":return physicalComplete(d)?physicalScore(d):null;case"Mental":return mentalComplete(d)?mentalScore(d):null;case"Emotional":return emotionalComplete(d)?emotionalScore(d):null;case"Nutritional":return nutritionalComplete(d)?nutritionalScore(d):null;case"Financial":return financialScore(d);case"Social":return socialComplete(d)?socialScore(d):null;case"Environmental":return environmentalComplete(d)?environmentalScore(d):null;default:return null;}}
function bmiInfo(h,w){if(!h||!w)return null;const m=h/100,b=w/(m*m);let cat="";if(b<18.5)cat="Underweight";else if(b<25)cat="Normal";else if(b<30)cat="Overweight";else if(b<35)cat="Obese I";else if(b<40)cat="Obese II";else cat="Obese III";return{bmi:b.toFixed(1),cat};}
function bmrInfo(g,age,h,w){if(!g||!age||!h||!w)return null;const base=10*w+6.25*h-5*age;return Math.round(g==="Male"?base+5:base-161);}
function bandColor(v){if(v==null)return{c:"rgba(26,54,55,0.25)",label:"Not started"};if(v>=75)return{c:"#3F7D5B",label:"Strong"};if(v>=60)return{c:C.gold,label:"Building"};if(v>=40)return{c:"#C9892F",label:"Needs focus"};return{c:"#B5453C",label:"Urgent attention"};}
/* ---------- charts ---------- */
function MiniRing({value,size=64}){const r=size/2-6,cir=2*Math.PI*r,v=value==null?0:Math.max(0,Math.min(100,value)),off=cir-(v/100)*cir,b=bandColor(value);return(<svg width={size} height={size} style={{flexShrink:0}}><circle cx={size/2} cy={size/2} r={r} fill="none" stroke="rgba(26,54,55,0.08)" strokeWidth="6"/>{value!=null&&<circle cx={size/2} cy={size/2} r={r} fill="none" stroke={b.c} strokeWidth="6" strokeDasharray={cir} strokeDashoffset={off} strokeLinecap="round" transform={"rotate(-90 "+(size/2)+" "+(size/2)+")"}/>}<text x="50%" y="50%" textAnchor="middle" dominantBaseline="middle" fontSize="15" fontWeight="700" fontFamily={FH} fill={C.dark}>{value==null?"\u2014":v+"%"}</text></svg>);}
function SpiderChart({data,size=250}){const PAD=64,VB=size,cx=VB/2,cy=VB/2,R=VB/2-PAD,n=PILLARS.length;const pts=PILLARS.map((p,i)=>{const ang=(Math.PI*2*i)/n-Math.PI/2;const val=data[p]==null?0:Math.max(0,Math.min(100,data[p]))/100;const co=Math.cos(ang),si=Math.sin(ang);return{x:cx+co*R*val,y:cy+si*R*val,lx:cx+co*(R+26),ly:cy+si*(R+26),ax:cx+co*R,ay:cy+si*R,co,name:p};});return(<svg width={size} height={size} viewBox={"0 0 "+VB+" "+VB} style={{overflow:"visible",maxWidth:"100%"}}>{[0.25,0.5,0.75,1].map((rr,i)=>(<polygon key={i} points={PILLARS.map((_,j)=>{const ang=(Math.PI*2*j)/n-Math.PI/2;return (cx+Math.cos(ang)*R*rr)+","+(cy+Math.sin(ang)*R*rr);}).join(" ")} fill="none" stroke="rgba(26,54,55,0.10)" strokeWidth="1"/>))}{pts.map((p,i)=><line key={i} x1={cx} y1={cy} x2={p.ax} y2={p.ay} stroke="rgba(26,54,55,0.10)" strokeWidth="1"/>)}<polygon points={pts.map(p=>p.x+","+p.y).join(" ")} fill="rgba(214,186,150,0.30)" stroke={C.gold} strokeWidth="2"/>{pts.map((p,i)=><circle key={i} cx={p.x} cy={p.y} r="3.5" fill={C.dark}/>)}{pts.map((p,i)=>{const an=p.co>0.25?"start":p.co<-0.25?"end":"middle";return<text key={i} x={p.lx} y={p.ly} fontSize="11" fontFamily={FB} fontWeight="600" fill={C.sage} textAnchor={an} dominantBaseline="middle">{p.name}</text>;})}</svg>);}
function RingChart({value,label,size=92}){const r=size/2-8,cir=2*Math.PI*r,v=value==null?0:value,off=cir-(v/100)*cir,b=bandColor(value);return(<div style={{textAlign:"center"}}><svg width={size} height={size}><circle cx={size/2} cy={size/2} r={r} fill="none" stroke="rgba(26,54,55,0.08)" strokeWidth="7"/>{value!=null&&<circle cx={size/2} cy={size/2} r={r} fill="none" stroke={b.c} strokeWidth="7" strokeDasharray={cir} strokeDashoffset={off} strokeLinecap="round" transform={"rotate(-90 "+(size/2)+" "+(size/2)+")"}/>}<text x="50%" y="50%" textAnchor="middle" dominantBaseline="middle" fontSize="18" fontWeight="700" fontFamily={FH} fill={C.dark}>{value==null?"\u2014":v+"%"}</text></svg><div style={{fontSize:11,color:C.sage,fontWeight:600,fontFamily:FB,marginTop:2}}>{label}</div></div>);}
const emptyData=()=>({stress:{},physical:{},mental:{},emotional:{},nutritional:{},financial:{},social:{},environmental:{},commitments:{},consult:{},done:{}});
/* ============================================================ APP ============================================================ */
function App(){
  const [screen,setScreen]=useState("register");
  const [activePillar,setActivePillar]=useState(null);
  const [profile,setProfile]=useState(null);
  const [data,setData]=useState(emptyData());
  const [toast,setToast]=useState("");
  const [reg,setReg]=useState({name:"",email:"",phone:"",department:"",company:"",accessCode:"",consent:false});
  const [regErr,setRegErr]=useState("");
  const [resumeMsg,setResumeMsg]=useState("");
  const [busy,setBusy]=useState(false);
  const flash=(m)=>{setToast(m);setTimeout(()=>setToast(""),2600);};
  const handleRegister=async()=>{
    setRegErr("");
    const {name,email,phone,department,company,accessCode,consent}=reg;
    if(!name||!email||!phone||!department||!company||!accessCode){setRegErr("All fields including the company access code are required.");return;}
    if(!/^\S+@\S+\.\S+$/.test(email)){setRegErr("Please enter a valid email address.");return;}
    if(!consent){setRegErr("Please provide consent to continue.");return;}
    setBusy(true);
    const cr=await validateCode(accessCode);
    if(!cr){setBusy(false);setRegErr("Invalid or inactive company access code. Please check with your HR team.");return;}
    const ex=await loadParticipant(email);
    const prof={name,email,phone,department,company,accessCode:accessCode.trim().toUpperCase(),companyName:cr.company};
    if(ex&&ex.data){
      const sn=((ex.profile&&ex.profile.name)||"").trim().toLowerCase();
      if(sn&&sn!==name.trim().toLowerCase()){setBusy(false);setRegErr("This email is already registered under a different name. Enter the exact name used at registration to resume.");return;}
      setProfile(ex.profile||prof);setData(Object.assign(emptyData(),ex.data,{done:ex.data.done||{}}));flash("Welcome back — your progress has been restored.");
    } else {
      setProfile(prof);const f=emptyData();setData(f);await saveParticipant({profile:prof,data:f});
    }
    setBusy(false);setScreen("dashboard");
  };
  const tryResume=async()=>{
    setRegErr("");setResumeMsg("");
    if(!/^\S+@\S+\.\S+$/.test(reg.email)){setRegErr("Enter your registered email to resume.");return;}
    if(!reg.name.trim()){setRegErr("Enter the full name you registered with to resume.");return;}
    setBusy(true);
    const ex=await loadParticipant(reg.email);
    setBusy(false);
    if(ex&&ex.data){
      const sn=((ex.profile&&ex.profile.name)||"").trim().toLowerCase();
      if(sn!==reg.name.trim().toLowerCase()){setResumeMsg("Email and name do not match our records. Please enter the exact name used at registration.");return;}
      setProfile(ex.profile);setData(Object.assign(emptyData(),ex.data,{done:ex.data.done||{}}));flash("Welcome back — your progress has been restored.");setScreen("dashboard");
    } else setResumeMsg("No saved assessment found for that email. Please register.");
  };
  const setPillarField=(pillar,key,value)=>{setData(prev=>{const n=Object.assign({},prev);n[pillar]=Object.assign({},prev[pillar]);n[pillar][key]=value;return n;});};
  const savePillar=(pillar)=>{setData(prev=>{const n=Object.assign({},prev,{done:Object.assign({},prev.done,{[pillar]:true})});saveParticipant({profile,data:n});return n;});flash(pillar+" saved.");setScreen("dashboard");};
  const saveCommitments=()=>{setData(prev=>{const n=Object.assign({},prev,{done:Object.assign({},prev.done,{Commitments:true})});saveParticipant({profile,data:n});return n;});flash("Commitments saved.");setScreen("consultation");};
  const doLogout=()=>{setProfile(null);setData(emptyData());setReg({name:"",email:"",phone:"",department:"",company:"",accessCode:"",consent:false});setScreen("register");};
  const scores=useMemo(()=>{const s={};PILLARS.forEach(p=>{s[p]=pillarScore(data,p);});return s;},[data]);
  const allDone=PILLARS.every(p=>data.done&&data.done[p]);
  const overall=useMemo(()=>{const v=PILLARS.map(p=>scores[p]).filter(x=>x!=null);return v.length===0?null:Math.round(v.reduce((a,b)=>a+b,0)/v.length);},[scores]);
  const commitFilled=useMemo(()=>{let f=0;COMMIT_PILLARS.forEach(p=>{const c=(data.commitments&&data.commitments[p])||{};if(["start","stop","reduce","expect"].some(k=>(c[k]||"").trim()))f++;});return f;},[data.commitments]);
  if(screen==="register")return <RegisterScreen reg={reg} setReg={setReg} regErr={regErr} resumeMsg={resumeMsg} busy={busy} onRegister={handleRegister} onResume={tryResume} toast={toast}/>;
  if(screen==="dashboard")return <Dashboard profile={profile} data={data} scores={scores} overall={overall} allDone={allDone} commitFilled={commitFilled} setActivePillar={setActivePillar} setScreen={setScreen} onLogout={doLogout} toast={toast}/>;
  if(screen==="pillar")return (<Shell><Header/><PillarScreen pillar={activePillar} data={data} setField={setPillarField} onSave={savePillar} onSaveCommit={saveCommitments} onBack={()=>setScreen("dashboard")}/><Footer/><Toast msg={toast}/></Shell>);
  if(screen==="consultation")return (<Shell><Header right={<button onClick={()=>setScreen("dashboard")} style={Object.assign({},btnBack,{borderColor:C.gold,color:C.gold,padding:"7px 14px",fontSize:12})}>Dashboard</button>}/><ConsultationScreen data={data} setField={setPillarField} allDone={allDone} onContinue={()=>setScreen("results")} onDashboard={()=>setScreen("dashboard")}/><Footer/><Toast msg={toast}/></Shell>);
  if(screen==="results")return <ResultsPage profile={profile} data={data} scores={scores} overall={overall} onBack={()=>setScreen("dashboard")} onViewReport={()=>setScreen("report")} flash={flash}/>;
  if(screen==="report")return <ReportPage profile={profile} data={data} scores={scores} overall={overall} onClose={()=>setScreen("results")}/>;
  return (<Shell><Header/><div style={card}><button onClick={()=>setScreen(profile?"dashboard":"register")} style={btnGold}>Continue</button></div><Footer/></Shell>);
}
function Shell({children}){return <div style={{background:C.cream,minHeight:"100vh",padding:"16px 14px 40px",fontFamily:FB}}><div style={{maxWidth:720,margin:"0 auto"}}>{children}</div></div>;}
function Header({right}){return <div style={{background:C.dark,borderRadius:16,padding:"16px 18px",marginBottom:16,display:"flex",alignItems:"center",justifyContent:"space-between"}}><div style={{display:"flex",alignItems:"center",gap:12}}><img src={LOGO} alt="Well-B Align" style={{width:56,height:56,borderRadius:10,background:C.dark}}/><div><div style={{fontFamily:FH,fontSize:18,color:C.gold}}>Well-B Assessment</div><div style={{fontSize:11,color:"rgba(255,250,241,0.6)",fontFamily:FB}}>Breathe ~ Balance ~ Bloom</div></div></div>{right}</div>;}
function Footer(){return <div style={{textAlign:"center",fontSize:10.5,color:C.sage,fontFamily:FB,marginTop:24,lineHeight:1.6}}>Well-B Align · [email protected] · wellbalign.ae</div>;}
function Toast({msg}){if(!msg)return null;return <div style={{position:"fixed",bottom:24,left:"50%",transform:"translateX(-50%)",background:C.dark,color:C.gold,padding:"12px 22px",borderRadius:10,fontSize:13,fontWeight:600,fontFamily:FB,zIndex:999,maxWidth:"90%",textAlign:"center"}}>{msg}</div>;}
function PillarCard({title,subtitle,done,onClick}){return <div style={Object.assign({},card,{cursor:"pointer",display:"flex",justifyContent:"space-between",alignItems:"center"})} onClick={onClick}><div style={{flex:1}}><div style={cardTitle}>{done?"Completed":"Tap to open"}</div><div style={{fontFamily:FH,fontSize:16,color:C.dark}}>{title}</div><div style={{fontSize:12,color:C.sage,fontFamily:FB,marginTop:3}}>{subtitle}</div></div><div style={{marginLeft:14}}>{done?<div style={{width:30,height:30,borderRadius:"50%",background:"rgba(63,125,91,0.14)",color:"#3F7D5B",display:"flex",alignItems:"center",justifyContent:"center",fontWeight:700}}>{"\u2713"}</div>:<div style={{fontSize:20,color:C.gold}}>{"\u203A"}</div>}</div></div>;}
function RegisterScreen({reg,setReg,regErr,resumeMsg,busy,onRegister,onResume,toast}){
  return (<Shell><Header/>
    <div style={card}>
      <div style={cardTitle}>Register</div>
      <div style={infoNote}>Welcome to the Well-B Assessment. Register below to begin. To resume later, log in with the <strong>same email and full name</strong> you register with.</div>
      {[["Full Name","name","text"],["Email Address","email","email"],["Phone Number","phone","tel"],["Department","department","text"],["Company / Organisation","company","text"]].map(([lbl,k,tp])=>(
        <div key={k} style={{marginBottom:12}}><div style={Object.assign({},labelStyle,{marginBottom:6})}>{lbl}</div><input style={inputStyle} type={tp} value={reg[k]} onChange={e=>setReg(Object.assign({},reg,{[k]:e.target.value}))}/></div>
      ))}
      <div style={{marginBottom:14}}>
        <div style={Object.assign({},labelStyle,{marginBottom:6})}>Company Access Code</div>
        <div style={Object.assign({},infoNote,{marginBottom:8,fontSize:12})}>Your HR or wellness team will have provided this code. Contact <strong>[email protected]</strong> if you do not have one.</div>
        <input style={Object.assign({},inputStyle,{textTransform:"uppercase",letterSpacing:"0.08em",fontWeight:600})} type="text" placeholder="e.g. WELLB-COMPANY-2026" value={reg.accessCode} onChange={e=>setReg(Object.assign({},reg,{accessCode:e.target.value.toUpperCase()}))}/>
      </div>
      <button onClick={()=>setReg(Object.assign({},reg,{consent:!reg.consent}))} style={{textAlign:"left",width:"100%",padding:"11px 13px",borderRadius:8,border:reg.consent?`1px solid ${C.dark}`:`1px solid ${C.border}`,background:reg.consent?"rgba(26,54,55,0.05)":C.white,color:C.dark,fontSize:12.5,fontFamily:FB,cursor:"pointer",lineHeight:1.45,marginBottom:14}}>
        <span style={{fontWeight:700,marginRight:8,color:reg.consent?C.dark:"rgba(26,54,55,0.3)"}}>{reg.consent?"\u2713":"\u25CB"}</span>
        I consent to Well-B Align storing and using my responses for wellness programme purposes. My information will be kept confidential and used only to support my personal wellness journey.
      </button>
      {regErr&&<div style={{color:"#B5453C",fontSize:12.5,marginBottom:12,fontFamily:FB}}>{regErr}</div>}
      <div style={{display:"flex",gap:10,flexWrap:"wrap"}}>
        <button onClick={onRegister} disabled={busy} style={btnGold}>{busy?"Please wait…":"Register & Continue"}</button>
        <button onClick={onResume} disabled={busy} style={btnBack}>Resume with my email</button>
      </div>
      {resumeMsg&&<div style={{color:C.sage,fontSize:12.5,marginTop:10,fontFamily:FB}}>{resumeMsg}</div>}
    </div>
    <Footer/><Toast msg={toast}/>
  </Shell>);
}
function Dashboard({profile,data,scores,overall,allDone,commitFilled,setActivePillar,setScreen,onLogout,toast}){
  const bmi=bmiInfo(Number(data.physical.height),Number(data.physical.weight));
  const bmr=bmrInfo(data.physical.gender,Number(data.physical.age),Number(data.physical.height),Number(data.physical.weight));
  const sv=data.stress.level;const fd=financialDetail(data);const ns=neuroScore(data);const nb=bandColor(ns);
  const dc=PILLARS.filter(p=>data.done&&data.done[p]).length;
  return (<Shell><Header right={<button onClick={onLogout} style={Object.assign({},btnBack,{borderColor:C.gold,color:C.gold,padding:"7px 14px",fontSize:12})}>Log out</button>}/>
    <div style={Object.assign({},card,{background:C.dark,color:C.gold,padding:22})}>
      <div style={{fontFamily:FH,fontSize:22}}>Hello, {profile.name.split(" ")[0]}</div>
      <div style={{fontSize:12.5,color:"rgba(255,250,241,0.65)",fontFamily:FB,marginTop:4}}>{profile.companyName||profile.company} · {profile.department}</div>
      <div style={{marginTop:16}}><div style={{fontSize:11,color:"rgba(255,250,241,0.6)",fontFamily:FB,marginBottom:6,textTransform:"uppercase",letterSpacing:"0.08em"}}>Progress · {dc} of 7 pillars</div><div style={{height:8,borderRadius:4,background:"rgba(255,250,241,0.12)",overflow:"hidden"}}><div style={{width:(dc/7*100)+"%",height:"100%",background:C.gold}}/></div></div>
    </div>
    <div style={card}><div style={cardTitle}>Your Wellbeing Map</div><div style={{display:"flex",justifyContent:"center",padding:"2px 0"}}><SpiderChart data={scores} size={250}/></div>
      {allDone?(<div style={{textAlign:"center",marginTop:2}}><div style={{fontFamily:FH,fontSize:42,color:C.gold,lineHeight:1}}>{overall}%</div><div style={Object.assign({},cardTitle,{marginBottom:0,marginTop:6})}>Overall Well-B Score</div><button onClick={()=>setScreen("results")} style={Object.assign({},btnGold,{marginTop:14})}>View My Well-B Score</button></div>):(<div style={{textAlign:"center",fontSize:12,color:C.sage,fontFamily:FB,marginTop:2}}>Complete all 7 pillars to unlock your overall Well-B Score.</div>)}
    </div>
    <div style={{display:"flex",justifyContent:"center",gap:16,marginBottom:14,flexWrap:"wrap"}}>{[["#B5453C","Urgent <40"],["#C9892F","Needs focus 40–59"],[C.gold,"Building 60–74"],["#3F7D5B","Strong 75+"]].map(([c,t])=>(<div key={t} style={{display:"flex",alignItems:"center",gap:6,fontSize:10.5,color:C.sage,fontFamily:FB,fontWeight:600}}><span style={{width:9,height:9,borderRadius:"50%",background:c,display:"inline-block"}}/>{t}</div>))}</div>
    <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12,marginBottom:12}}>
      <div style={Object.assign({},card,{marginBottom:0})}><div style={cardTitle}>Stress Indicator</div>{sv?(<div><div style={{fontFamily:FH,fontSize:28,color:C.dark}}>{sv}<span style={{fontSize:14,color:C.sage}}>/10</span></div><div style={{fontSize:12,color:C.sage,fontFamily:FB}}>{STRESS_DYN[sv]}</div></div>):(<div style={{fontSize:12.5,color:C.sage,fontFamily:FB}}>Not yet recorded</div>)}<div style={{fontSize:10,color:C.sage,fontFamily:FB,marginTop:8,fontStyle:"italic"}}>Baseline — not in overall score</div></div>
      <div style={Object.assign({},card,{marginBottom:0})}><div style={cardTitle}>BMI & BMR</div>{bmi?(<div><div style={{fontFamily:FH,fontSize:28,color:C.dark}}>{bmi.bmi}</div><div style={{fontSize:12,color:C.sage,fontFamily:FB}}>{bmi.cat}</div>{bmr&&<div style={{fontSize:11.5,color:C.dark,fontFamily:FB,marginTop:8}}>BMR <strong>{bmr}</strong> kcal/day</div>}</div>):(<div style={{fontSize:12.5,color:C.sage,fontFamily:FB}}>Enter height & weight in Physical</div>)}</div>
    </div>
    <div style={Object.assign({},card,{cursor:"pointer",borderLeft:`4px solid ${nb.c}`,display:"flex",alignItems:"center",justifyContent:"space-between"})} onClick={()=>{setActivePillar("Stress");setScreen("pillar");}}>
      <div><div style={cardTitle}>Neuroregulation Recovery</div><div style={{fontFamily:FH,fontSize:16,color:C.dark}}>How well you return to balance</div><div style={{fontSize:10.5,color:C.sage,fontFamily:FB,marginTop:4,fontStyle:"italic"}}>Separate recovery score — not part of overall</div></div><MiniRing value={ns}/>
    </div>
    <PillarCard title="Stress Baseline & Neuroregulation" done={data.done.Stress} onClick={()=>{setActivePillar("Stress");setScreen("pillar");}} subtitle={sv?("Current level "+sv+"/10 — "+STRESS_DYN[sv]):"Establish your stress baseline"}/>
    <div style={cardTitle}>The 7 Pillars — tap any to begin</div>
    <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12,marginBottom:16}}>
      {PILLARS.map(p=>{const dn=data.done[p];const sc=scores[p];const b=bandColor(dn?sc:null);const st=dn?b.label:(p==="Financial"&&fd.totalAnswered>0?fd.totalAnswered+"/12 answered":"Tap to begin");return(
        <div key={p} onClick={()=>{setActivePillar(p);setScreen("pillar");}} style={Object.assign({},card,{marginBottom:0,cursor:"pointer",padding:"16px 14px",borderLeft:`4px solid ${b.c}`,display:"flex",flexDirection:"column",alignItems:"center",textAlign:"center"})}>
          <MiniRing value={dn?sc:null}/><div style={{fontFamily:FH,fontSize:15,color:C.dark,marginTop:10}}>{p}</div><div style={{fontSize:10.5,color:dn?b.c:C.sage,fontFamily:FB,fontWeight:600,marginTop:4,textTransform:"uppercase",letterSpacing:"0.04em"}}>{st}</div>
          {p==="Financial"&&fd.totalAnswered>0&&<div style={{fontSize:9.5,color:C.sage,fontFamily:FB,marginTop:6,lineHeight:1.5}}>Cash {fd.cf.score}/16<br/>Protect {fd.pr.score}/16 · Grow {fd.gr.score}/16</div>}
        </div>);})}
    </div>
    <div style={Object.assign({},card,{cursor:"pointer",borderLeft:`4px solid ${C.gold}`})} onClick={()=>{setActivePillar("Commitments");setScreen("pillar");}}>
      <div style={cardTitle}>My Commitments</div><div style={{display:"flex",justifyContent:"space-between",alignItems:"center"}}><div style={{fontFamily:FH,fontSize:16,color:C.dark}}>30-Day Commitment Plan</div><span style={{fontSize:11,fontWeight:700,fontFamily:FB,padding:"5px 12px",borderRadius:20,background:commitFilled===0?"rgba(26,54,55,0.07)":"rgba(63,125,91,0.12)",color:commitFilled===0?C.sage:"#3F7D5B"}}>{commitFilled===0?"Pending":commitFilled+"/8 done"}</span></div>
    </div>
    <Footer/><Toast msg={toast}/>
  </Shell>);
}
function PillarScreen({pillar,data,setField,onSave,onSaveCommit,onBack}){
  const title=pillar==="Commitments"?"My Commitments":pillar==="Stress"?"Stress Baseline & Neuroregulation":pillar+" Wellbeing";
  return (<div>
    <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:14}}><button onClick={onBack} style={btnBack}>{"\u2039"} Dashboard</button><div style={{fontFamily:FH,fontSize:17,color:C.dark}}>{title}</div></div>
    {pillar==="Stress"&&<StressPillar data={data} setField={setField}/>}
    {pillar==="Physical"&&<PhysicalPillar data={data} setField={setField}/>}
    {pillar==="Mental"&&<MentalPillar data={data} setField={setField}/>}
    {pillar==="Emotional"&&<EmotionalPillar data={data} setField={setField}/>}
    {pillar==="Nutritional"&&<NutritionalPillar data={data} setField={setField}/>}
    {pillar==="Financial"&&<FinancialPillar data={data} setField={setField}/>}
    {pillar==="Social"&&<SocialPillar data={data} setField={setField}/>}
    {pillar==="Environmental"&&<EnvironmentalPillar data={data} setField={setField}/>}
    {pillar==="Commitments"&&<CommitmentsPillar data={data} setField={setField}/>}
    <div style={{display:"flex",gap:10,marginTop:8,marginBottom:30}}>{pillar==="Commitments"?<button onClick={onSaveCommit} style={btnGold}>Save Commitments</button>:<button onClick={()=>onSave(pillar)} style={btnGold}>Save Pillar</button>}<button onClick={onBack} style={btnBack}>Cancel</button></div>
  </div>);
}
function StressPillar({data,setField}){const s=data.stress;const set=(k,v)=>setField("stress",k,v);const lvl=s.level||5;return(<div>
  <div style={infoNote}>Stress is not always harmful. Eustress energises and motivates us — distress depletes us. This section helps identify where your stress sits and how effectively you are recovering from it.</div>
  <div style={card}><div style={cardTitle}>Stress Level</div><div style={labelStyle}>How would you rate your current overall stress level?</div><input type="range" min="1" max="10" value={lvl} onChange={e=>set("level",Number(e.target.value))} style={{width:"100%",accentColor:C.gold}}/><div style={{display:"flex",justifyContent:"space-between",fontSize:10.5,color:C.sage,fontFamily:FB,marginTop:4}}><span>1 = Minimal</span><span>5 = Moderate</span><span>10 = Overwhelming</span></div><div style={{textAlign:"center",marginTop:10,fontFamily:FH,fontSize:22,color:C.dark}}>{lvl} — {STRESS_DYN[lvl]}</div></div>
  <div style={card}><div style={cardTitle}>Stress Triggers</div><div style={{fontSize:12,color:C.sage,fontFamily:FB,marginBottom:10}}>Select all that apply</div><CheckList options={STRESSORS} value={s.stressors||[]} onChange={v=>set("stressors",v)}/><input style={Object.assign({},inputStyle,{marginTop:10})} placeholder="Other (please specify)" value={s.stressorsOther||""} onChange={e=>set("stressorsOther",e.target.value)}/></div>
  <div style={card}><div style={cardTitle}>How Does Stress Show Up in Your Body and Life?</div><div style={{fontSize:12,color:C.sage,fontFamily:FB,marginBottom:10}}>Check any signs you experience regularly</div><CheckList options={BODY_SIGNS} value={s.bodySigns||[]} onChange={v=>set("bodySigns",v)}/><input style={Object.assign({},inputStyle,{marginTop:10})} placeholder="Other (please specify)" value={s.bodySignsOther||""} onChange={e=>set("bodySignsOther",e.target.value)}/></div>
  <div style={recoveryWrap}><div style={cardTitle}>Neuroregulation — Recovery Commitment</div><div style={Object.assign({},infoNote,{marginBottom:14})}>Recovery from stress is not about avoiding it — it is about how quickly and effectively you return to a state of balance. This is neuroregulation.</div>{NEURO_Q.map((it,i)=><QuestionRadio key={i} q={it.q} options={it.o} value={s["neuro_"+i]} onChange={v=>set("neuro_"+i,v)}/>)}</div>
</div>);}
function PhysicalPillar({data,setField}){const p=data.physical;const set=(k,v)=>setField("physical",k,v);const bmi=bmiInfo(Number(p.height),Number(p.weight));const bmr=bmrInfo(p.gender,Number(p.age),Number(p.height),Number(p.weight));return(<div>
  <div style={card}><div style={cardTitle}>Biometric Measurements</div>
    <div style={{marginBottom:12}}><div style={Object.assign({},labelStyle,{marginBottom:6})}>Gender</div><RadioGroup options={["Male","Female"]} value={p.gender==="Male"?0:p.gender==="Female"?1:undefined} onChange={i=>set("gender",i===0?"Male":"Female")}/></div>
    {[["Age (years)","age"],["Height (cm)","height"],["Weight (kg)","weight"]].map(([lbl,k])=>(<div key={k} style={{marginBottom:12}}><div style={Object.assign({},labelStyle,{marginBottom:6})}>{lbl}</div><input style={inputStyle} type="number" value={p[k]||""} onChange={e=>set(k,e.target.value)}/></div>))}
    {bmi&&<div style={{marginTop:8}}><div style={{display:"flex",justifyContent:"space-between",fontSize:13,fontFamily:FB,color:C.dark,marginBottom:6}}><span style={{fontWeight:600}}>BMI {bmi.bmi}</span><span style={{color:C.sage}}>{bmi.cat}</span></div></div>}
    {bmr&&<div style={Object.assign({},infoNote,{marginTop:12,marginBottom:0})}>Estimated BMR (Mifflin-St Jeor): <strong>{bmr} kcal/day</strong></div>}
  </div>
  <div style={card}><div style={cardTitle}>Vital Signs (recorded only)</div>{[["Systolic BP (mmHg)","systolic"],["Diastolic BP (mmHg)","diastolic"],["Resting Heart Rate (bpm)","hr"],["SpO2 (%)","spo2"]].map(([lbl,k])=>(<div key={k} style={{marginBottom:12}}><div style={Object.assign({},labelStyle,{marginBottom:6})}>{lbl}</div><input style={inputStyle} type="number" value={p[k]||""} onChange={e=>set(k,e.target.value)}/></div>))}
    <div style={{marginBottom:12}}><div style={Object.assign({},labelStyle,{marginBottom:6})}>Fasting Blood Glucose (mmol/L) — leave blank if unknown</div><input style={inputStyle} type="number" value={p.glucose||""} onChange={e=>set("glucose",e.target.value)}/></div>
    <div><div style={Object.assign({},labelStyle,{marginBottom:6})}>Activity Level</div><RadioGroup options={["Sedentary","Light 1-2 days per week","Moderate 3-5 days per week","Very active 6-7 days per week"]} value={p.activity} onChange={v=>set("activity",v)}/></div>
  </div>
  <div style={card}><div style={cardTitle}>Postural Screening</div>{POSTURAL_Q.map((it,i)=><QuestionRadio key={i} q={"Q"+(i+1)+". "+it.q} options={it.o} value={p["post_"+i]} onChange={v=>set("post_"+i,v)}/>)}</div>
  <div style={card}><div style={cardTitle}>Major Joint Pain Screening</div><div style={infoNote}>None = no pain, Mild = occasional, Moderate = regular discomfort, Significant = persistent pain</div>{JOINTS.map((j,i)=>(<div key={i} style={{marginBottom:10}}><div style={{fontSize:13,color:C.dark,fontFamily:FB,marginBottom:5,fontWeight:500}}>{j}</div><div style={{display:"flex",gap:6}}>{JOINT_LEVELS.map((lv,li)=>{const sel=p["joint_"+i]===li;return<button key={li} onClick={()=>set("joint_"+i,li)} style={{flex:1,padding:"8px 4px",borderRadius:6,fontSize:11.5,fontFamily:FB,border:sel?"none":`1px solid ${C.border}`,background:sel?C.dark:C.white,color:sel?C.gold:C.dark,fontWeight:sel?600:400,cursor:"pointer"}}>{lv}</button>;})}</div></div>))}</div>
  <div style={card}><div style={cardTitle}>Functional Movement Tests</div>{FUNCTIONAL_Q.map((it,i)=><QuestionRadio key={i} q={"Q"+(i+1)+". "+it.q} options={it.o} value={p["func_"+i]} onChange={v=>set("func_"+i,v)}/>)}</div>
  <div style={recoveryWrap}><div style={cardTitle}>Recovery — Physical Activity and Rest Habits</div>{PHYS_RECOVERY_Q.map((it,i)=><QuestionRadio key={i} q={"Q"+(i+1)+". "+it.q} options={it.o} value={p["prec_"+i]} onChange={v=>set("prec_"+i,v)}/>)}</div>
</div>);}
function MentalPillar({data,setField}){const m=data.mental;const set=(k,v)=>setField("mental",k,v);return(<div>
  <div style={card}><div style={cardTitle}>WHO-5 Wellbeing Index</div><div style={infoNote}>Over the past 2 weeks: 0 = At no time · 5 = All of the time</div>{WHO5.map((q,i)=><div key={i} style={{marginBottom:16}}><div style={labelStyle}>{"Q"+(i+1)+". "+q}</div><Likert count={6} value={m["who_"+i]} onChange={v=>set("who_"+i,v)}/></div>)}</div>
  <div style={card}><div style={cardTitle}>PSS-10 Perceived Stress Scale</div><div style={infoNote}>In the last month: 0 = Never · 4 = Very often</div>{PSS10.map((q,i)=><div key={i} style={{marginBottom:16}}><div style={labelStyle}>{"Q"+(i+1)+". "+q}{PSS_REVERSE.includes(i)&&<span style={{color:C.sage,fontSize:11}}> (reverse scored)</span>}</div><Likert count={5} value={m["pss_"+i]} onChange={v=>set("pss_"+i,v)}/></div>)}</div>
  <div style={recoveryWrap}><div style={cardTitle}>Recovery — Breathing and Mental Coping Practices</div>{MENTAL_RECOVERY_Q.map((it,i)=><QuestionRadio key={i} q={"Q"+(i+1)+". "+it.q} options={it.o} value={m["mrec_"+i]} onChange={v=>set("mrec_"+i,v)}/>)}</div>
</div>);}
function EmotionalPillar({data,setField}){const e=data.emotional;const set=(k,v)=>setField("emotional",k,v);return(<div>
  <div style={card}><div style={cardTitle}>Satisfaction With Life Scale (SWLS)</div><div style={infoNote}>1 = Strongly disagree to 7 = Strongly agree</div>{SWLS.map((q,i)=><div key={i} style={{marginBottom:16}}><div style={labelStyle}>{"Q"+(i+1)+". "+q}</div><Likert count={7} startAt={1} value={e["swls_"+i]} onChange={v=>set("swls_"+i,v)}/></div>)}</div>
  <div style={card}><div style={cardTitle}>PANAS — Positive and Negative Affect</div><div style={infoNote}>1 = Very slightly to 5 = Extremely</div>{PANAS.map((it,i)=><div key={i} style={{marginBottom:14}}><div style={labelStyle}>{"Q"+(i+1)+". "+it.t}<span style={{color:C.sage,fontSize:11}}> ({it.pos?"positive":"negative"})</span></div><Likert count={5} startAt={1} value={e["pan_"+i]} onChange={v=>set("pan_"+i,v)}/></div>)}</div>
  <div style={recoveryWrap}><div style={cardTitle}>Recovery — Emotional Regulation Habits</div>{EMO_RECOVERY_Q.map((it,i)=><QuestionRadio key={i} q={"Q"+(i+1)+". "+it.q} options={it.o} value={e["erec_"+i]} onChange={v=>set("erec_"+i,v)}/>)}</div>
</div>);}
function NutritionalPillar({data,setField}){const n=data.nutritional;const set=(k,v)=>setField("nutritional",k,v);const DD=({label,k,opts})=>(<div style={{marginBottom:12}}><div style={Object.assign({},labelStyle,{marginBottom:6})}>{label}</div><select style={inputStyle} value={n[k]||""} onChange={e=>set(k,e.target.value)}><option value="">Select…</option>{opts.map(o=><option key={o} value={o}>{o}</option>)}</select></div>);return(<div>
  <div style={card}><div style={cardTitle}>Meal Timing</div><div style={infoNote}>Research increasingly links consistent meal timing to improved metabolic and overall health outcomes.</div><DD label="Breakfast time" k="breakfast" opts={BREAKFAST_T}/><DD label="Lunch time" k="lunch" opts={LUNCH_T}/><DD label="Dinner time" k="dinner" opts={DINNER_T}/></div>
  <div style={card}><div style={cardTitle}>Meal Pattern</div>{MEAL_PATTERN_Q.map((it,i)=><QuestionRadio key={i} q={"Q"+(i+1)+". "+it.q} options={it.o} value={n["mp_"+i]} onChange={v=>set("mp_"+i,v)}/>)}</div>
  <div style={card}><div style={cardTitle}>Dietary Recall — Food Groups</div><div style={infoNote}>WHO recommends at least 5 portions of fruit and vegetables daily.</div>{DIETARY_Q.map((it,i)=><QuestionRadio key={i} q={"Q"+(i+1)+". "+it.q} options={it.o} value={n["diet_"+i]} onChange={v=>set("diet_"+i,v)}/>)}</div>
  <div style={card}><div style={cardTitle}>Hydration and Sugar-Sweetened Beverages</div>{HYDRATION_Q.map((it,i)=><QuestionRadio key={i} q={"Q"+(i+1)+". "+it.q} options={it.o} value={n["hyd_"+i]} onChange={v=>set("hyd_"+i,v)}/>)}</div>
  <div style={card}><div style={cardTitle}>Nutritional Deficiency Symptom Screening</div><div style={infoNote}>Check any symptoms you experience regularly. Always confirm with a blood test.</div><CheckList options={DEFICIENCY} value={n.deficiency||[]} onChange={v=>set("deficiency",v)}/></div>
  <div style={recoveryWrap}><div style={cardTitle}>Recovery — Supplements, Energy and Eating Environment</div>{NUT_RECOVERY_Q.map((it,i)=><QuestionRadio key={i} q={"Q"+(i+1)+". "+it.q} options={it.o} value={n["nrec_"+i]} onChange={v=>set("nrec_"+i,v)}/>)}</div>
</div>);}
function FinancialPillar({data,setField}){const f=data.financial;const set=(k,v)=>setField("financial",k,v);const det=financialDetail(data);const ins=financialInsights(data);const band=finBand(det.total);
  const Leg=({title,arr,pf})=>(<div style={card}><div style={cardTitle}>{title}</div>{arr.map((it,i)=>(<div key={i} style={{marginBottom:18}}><div style={labelStyle}>{"Q"+(i+1)+". "+it.q}</div><div style={{display:"flex",flexDirection:"column",gap:8}}>{it.o.map((opt,oi)=>{const sel=f[pf+"_"+i]===oi;return<button key={oi} onClick={()=>set(pf+"_"+i,oi)} style={{textAlign:"left",padding:"11px 14px",borderRadius:8,border:sel?`1px solid ${C.dark}`:`1px solid ${C.border}`,background:sel?"rgba(26,54,55,0.05)":C.white,color:C.dark,fontSize:13.5,fontFamily:FB,cursor:"pointer",lineHeight:1.4,fontWeight:sel?600:400}}>{opt}</button>;})}</div></div>))}</div>);
  return(<div>
  <div style={infoNote}>Scored out of 48 across three legs of 16. Progress: <strong>{det.totalAnswered} of 12 answered</strong>. All 12 required for a Financial score.</div>
  <div style={card}><div style={cardTitle}>Financial Score</div><div style={{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:10,marginBottom:12}}>{[["Cash Flow",det.cf],["Protection",det.pr],["Growth",det.gr]].map(([lbl,leg])=>(<div key={lbl} style={{textAlign:"center",padding:"10px 4px",background:"rgba(26,54,55,0.03)",borderRadius:8}}><div style={{fontFamily:FH,fontSize:20,color:C.dark}}>{leg.score}<span style={{fontSize:12,color:C.sage}}>/16</span></div><div style={{fontSize:10.5,color:C.sage,fontFamily:FB,fontWeight:600}}>{lbl}</div></div>))}</div><div style={{display:"flex",justifyContent:"space-between",alignItems:"center"}}><div style={{fontFamily:FH,fontSize:18,color:C.dark}}>{det.total}<span style={{fontSize:13,color:C.sage}}>/48</span></div><span style={{fontSize:12,fontWeight:700,color:band.color,fontFamily:FB}}>{band.label}</span></div><div style={{height:8,borderRadius:4,background:"rgba(26,54,55,0.08)",marginTop:8,overflow:"hidden"}}><div style={{width:(det.total/48*100)+"%",height:"100%",background:band.color}}/></div></div>
  <Leg title="Cash Flow Clarity (Q1–4)" arr={FIN_CASHFLOW} pf="cf"/>
  <Leg title="Protection (Q5–8)" arr={FIN_PROTECTION} pf="pr"/>
  <Leg title="Growth (Q9–12)" arr={FIN_GROWTH} pf="gr"/>
  {ins.length>0&&<div style={card}><div style={cardTitle}>Your Financial Insights</div>{ins.map((t,i)=><div key={i} style={Object.assign({},infoNote,{marginBottom:i===ins.length-1?0:10})}>{t}</div>)}</div>}
  <div style={recoveryWrap}><div style={cardTitle}>Recovery — Financial Stress Coping</div>{FIN_RECOVERY_Q.map((it,i)=><QuestionRadio key={i} q={"Q"+(i+1)+". "+it.q} options={it.o} value={f["frec_"+i]} onChange={v=>set("frec_"+i,v)}/>)}</div>
  <div style={Object.assign({},card,{border:`1.5px solid ${C.gold}`})}><div style={cardTitle}>Complimentary Financial Session</div><div style={{fontSize:13,color:C.dark,fontFamily:FB,lineHeight:1.55,marginBottom:14}}>Your financial wellbeing score reveals where your money foundations are strongest — and where hidden gaps may be quietly costing you. Would you like a complimentary 30-minute online session with our financial wellbeing expert?</div><RadioGroup options={["Yes — I would like a complimentary session","No, thank you"]} value={f.ctaSession} onChange={v=>set("ctaSession",v)}/></div>
</div>);}
function SocialPillar({data,setField}){const s=data.social;const set=(k,v)=>setField("social",k,v);return(<div>
  <div style={card}><div style={cardTitle}>Social Connection</div>{SOCIAL_Q.map((it,i)=><QuestionRadio key={i} q={"Q"+(i+1)+". "+it.q} options={it.o} value={s["soc_"+i]} onChange={v=>set("soc_"+i,v)}/>)}</div>
  <div style={recoveryWrap}><div style={cardTitle}>Recovery — Social Recharge and Community</div>{SOCIAL_RECOVERY_Q.map((it,i)=><QuestionRadio key={i} q={"Q"+(i+1)+". "+it.q} options={it.o} value={s["srec_"+i]} onChange={v=>set("srec_"+i,v)}/>)}</div>
</div>);}
function EnvironmentalPillar({data,setField}){const e=data.environmental;const set=(k,v)=>setField("environmental",k,v);return(<div>
  <div style={card}><div style={cardTitle}>Workplace Environment</div>{ENV_WORK_Q.map((it,i)=><QuestionRadio key={i} q={"Q"+(i+1)+". "+it.q} options={it.o} value={e["ew_"+i]} onChange={v=>set("ew_"+i,v)}/>)}</div>
  <div style={card}><div style={cardTitle}>Home and Commute</div>{ENV_HOME_Q.map((it,i)=><QuestionRadio key={i} q={"Q"+(i+1)+". "+it.q} options={it.o} value={e["eh_"+i]} onChange={v=>set("eh_"+i,v)}/>)}</div>
  <div style={recoveryWrap}><div style={cardTitle}>Recovery — Restorative Environment Habits</div>{ENV_RECOVERY_Q.map((it,i)=><QuestionRadio key={i} q={"Q"+(i+1)+". "+it.q} options={it.o} value={e["erc_"+i]} onChange={v=>set("erc_"+i,v)}/>)}</div>
</div>);}
function CommitmentsPillar({data,setField}){const c=data.commitments||{};const setBlock=(p,fl,v)=>{const cur=Object.assign({},c[p]||{});cur[fl]=v;setField("commitments",p,cur);};return(<div>
  <div style={infoNote}>For each pillar, write one commitment in each area. These will appear in your Well-B Score report and support your 30-day wellness journey.</div>
  {COMMIT_PILLARS.map(p=>{const blk=c[p]||{};return(<div key={p} style={card}><div style={cardTitle}>{p}</div>{[["start","I will START","One thing I will start doing..."],["stop","I will STOP","One thing I will stop doing..."],["reduce","I will REDUCE","One thing I will reduce..."],["expect","What I expect in 30 days","What I expect to feel or achieve..."]].map(([k,lbl,ph])=>(<div key={k} style={{marginBottom:10}}><div style={{fontSize:11,color:C.sage,fontWeight:600,fontFamily:FB,marginBottom:4,textTransform:"uppercase"}}>{lbl}</div><textarea style={Object.assign({},inputStyle,{minHeight:52,resize:"vertical"})} placeholder={ph} value={blk[k]||""} onChange={e=>setBlock(p,k,e.target.value)}/></div>))}</div>);})}
  <div style={Object.assign({},infoNote,{marginBottom:0})}>After saving, you will be asked about a complimentary one-to-one wellbeing consultation.</div>
</div>);}
function ConsultationScreen({data,setField,allDone,onContinue,onDashboard}){const consult=data.consult||{};const setC=(k,v)=>setField("consult",k,v);return(<div>
  <div style={{fontFamily:FH,fontSize:17,color:C.dark,marginBottom:14}}>One Last Step</div>
  <div style={Object.assign({},card,{border:`1.5px solid ${C.gold}`})}><div style={cardTitle}>Complimentary Consultation</div><div style={{fontSize:13.5,color:C.dark,fontFamily:FB,lineHeight:1.55,marginBottom:16}}>Would you like a member of the Well-B Align team to contact you and schedule a complimentary one-to-one online wellbeing consultation?</div><RadioGroup options={["Yes — please contact me","No, thank you"]} value={consult.want} onChange={v=>setC("want",v)}/>{consult.want===0&&<div style={{marginTop:16}}><div style={labelStyle}>Do you have a gender preference for your consultant?</div><RadioGroup options={["Female Practitioner preferred","Male Practitioner preferred","Anyone is fine"]} value={consult.genderPref} onChange={v=>setC("genderPref",v)}/></div>}</div>
  <div style={{display:"flex",gap:10,marginBottom:30}}>{allDone?<button onClick={onContinue} style={btnGold}>Continue to My Well-B Score</button>:<button onClick={onDashboard} style={btnGold}>Back to Dashboard</button>}</div>
  {!allDone&&<div style={infoNote}>You still have pillars to complete. Finish all 7 to view your full Well-B Score.</div>}
</div>);}
function ResultsPage({profile,data,scores,overall,onBack,onViewReport,flash}){
  const [sending,setSending]=useState(false);const [sent,setSent]=useState(false);
  const ranked=PILLARS.map(p=>({p,s:scores[p]})).filter(x=>x.s!=null).sort((a,b)=>a.s-b.s);const low3=ranked.slice(0,3);
  const bmi=bmiInfo(Number(data.physical.height),Number(data.physical.weight));const sv=data.stress.level;const ns=neuroScore(data);
  const sendReport=async()=>{
    setSending(true);
    try{
      const reportId=(profile.email.split("@")[0])+"-"+Date.now().toString(36);
      await saveReport(reportId,profile,data,scores,overall);
      const consult=data.consult||{};
      const cw=consult.want!=null?(consult.want===0?"Yes — please contact me":"No, thank you"):"Not answered";
      const cp=consult.genderPref!=null?["Female Practitioner preferred","Male Practitioner preferred","Anyone is fine"][consult.genderPref]:"—";
      const fc=data.financial&&data.financial.ctaSession!=null?(data.financial.ctaSession===0?"Yes":"No"):"Not answered";
      const { error }=await sb.functions.invoke("send-report",{body:{profile,scores,overall,reportId,consult:{want:cw,pref:cp},finCta:fc,neuroScore:ns,bmi,stressLevel:sv}});
      if(error){flash("Report saved. Email service will process shortly.");}
      else{flash("Report emailed to you and Well-B Align.");}
      setSent(true);
    }catch(e){flash("Report saved. View it with the button above.");setSent(true);}
    setSending(false);
  };
  return(<div style={{background:C.cream,minHeight:"100vh",padding:"16px 14px 40px",fontFamily:FB}}><div style={{maxWidth:720,margin:"0 auto"}}>
    <div style={{marginBottom:14}}><button onClick={onBack} style={btnBack}>{"\u2039"} Back to Dashboard</button></div>
    <div style={{position:"relative",background:C.dark,borderRadius:16,padding:"34px 24px",overflow:"hidden",marginBottom:16,textAlign:"center"}}><img src={LOGO} alt="" style={{position:"absolute",right:-30,bottom:-30,width:200,height:200,opacity:0.05,filter:"grayscale(1)"}}/><div style={{position:"relative"}}><div style={{fontFamily:FH,fontSize:22,color:C.gold}}>{profile.name}</div><div style={{fontFamily:FH,fontSize:56,color:C.gold,lineHeight:1.1,marginTop:8}}>{overall==null?"\u2014":overall+"%"}</div><div style={{fontSize:11,color:"rgba(255,250,241,0.7)",textTransform:"uppercase",letterSpacing:"0.12em",fontFamily:FB,marginTop:4}}>My Well-B Score</div></div></div>
    <div style={card}><div style={cardTitle}>Pillar Scores</div><div style={{display:"grid",gridTemplateColumns:"repeat(auto-fit,minmax(90px,1fr))",gap:14,justifyItems:"center"}}>{PILLARS.map(p=><RingChart key={p} value={scores[p]} label={p}/>)}</div></div>
    <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12,marginBottom:16}}><div style={Object.assign({},card,{marginBottom:0})}><div style={cardTitle}>Stress Indicator</div><div style={{fontFamily:FH,fontSize:24,color:C.dark}}>{sv?sv+"/10":"\u2014"}</div><div style={{fontSize:12,color:C.sage,fontFamily:FB}}>{sv?STRESS_DYN[sv]:"Not recorded"}</div></div><div style={Object.assign({},card,{marginBottom:0})}><div style={cardTitle}>BMI Indicator</div><div style={{fontFamily:FH,fontSize:24,color:C.dark}}>{bmi?bmi.bmi:"\u2014"}</div><div style={{fontSize:12,color:C.sage,fontFamily:FB}}>{bmi?bmi.cat:"Not recorded"}</div></div></div>
    <div style={card}><div style={cardTitle}>Priority Focus Areas</div>{low3.length===0&&<div style={{fontSize:12.5,color:C.sage,fontFamily:FB}}>Complete pillars to see priority areas.</div>}{low3.map(({p,s})=>{const b=bandColor(s);return(<div key={p} style={{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"10px 0",borderBottom:`1px solid ${C.border}`}}><div style={{fontFamily:FB,fontSize:14,color:C.dark,fontWeight:500}}>{p}</div><span style={{fontSize:11,fontWeight:700,color:b.c,background:b.c+"1F",padding:"4px 10px",borderRadius:20,fontFamily:FB}}>{s}% · {b.label}</span></div>);})}</div>
    <div style={card}><div style={cardTitle}>Personalised Recovery Suggestions</div>{low3.map(({p})=>(<div key={p} style={Object.assign({},recoveryWrap,{marginBottom:12})}><div style={{fontFamily:FH,fontSize:15,color:C.dark,marginBottom:5}}>{p}</div><div style={{fontSize:13,color:C.dark,fontFamily:FB,lineHeight:1.55}}>{RECOVERY_SUGGESTIONS[p]}</div></div>))}</div>
    <button onClick={onViewReport} style={Object.assign({},btnGold,{width:"100%",marginBottom:10})}>View My Full Report</button>
    <button onClick={sendReport} disabled={sending} style={Object.assign({},btnPrimary(!sending),{width:"100%",marginBottom:16})}>{sending?"Sending…":sent?"Email sent ✓ — send again":"Email Report to me & Well-B Align"}</button>
    <div style={{background:C.dark,borderRadius:12,padding:22,marginBottom:16,textAlign:"center"}}><div style={{fontFamily:FH,fontSize:18,color:C.gold}}>Ready to take the next step?</div><div style={{fontSize:13,color:"rgba(255,250,241,0.85)",fontFamily:FB,margin:"8px 0 16px",lineHeight:1.5}}>Connect with our Well-B Align team for your complimentary consultation</div><a href={WHATSAPP} target="_blank" rel="noreferrer" style={Object.assign({},btnGold,{display:"inline-block",textDecoration:"none"})}>Chat on WhatsApp</a><div style={{fontSize:10.5,color:"rgba(255,250,241,0.55)",fontFamily:FB,marginTop:14}}>[email protected] · wellbalign.ae</div></div>
    <div style={{fontSize:10.5,color:C.sage,fontFamily:FB,lineHeight:1.6,padding:"0 4px"}}>This assessment is for general wellness awareness only and does not constitute medical advice, diagnosis, or treatment. All clinical findings should be reviewed by a qualified healthcare professional.<br/>Well-B Align · [email protected] · wellbalign.ae</div>
  </div></div>);
}
function ReportPage({profile,data,scores,overall,onClose}){
  const ranked=PILLARS.map(p=>({p,s:scores[p]})).filter(x=>x.s!=null).sort((a,b)=>a.s-b.s);const low3=ranked.slice(0,3);
  const bmi=bmiInfo(Number(data.physical.height),Number(data.physical.weight));const bmr=bmrInfo(data.physical.gender,Number(data.physical.age),Number(data.physical.height),Number(data.physical.weight));
  const sv=data.stress.level;const ns=neuroScore(data);const fin=financialDetail(data);const consult=data.consult||{};
  const QA=({q,a})=>(<div style={{padding:"7px 0",borderBottom:`1px solid ${C.border}`}}><div style={{fontSize:12,color:C.dark,fontFamily:FB,fontWeight:500}}>{q}</div><div style={{fontSize:12,color:C.sage,fontFamily:FB,marginTop:2}}>{a==null||a===""?"— not answered":a}</div></div>);
  const Sec=({title,children})=><div style={card}><div style={cardTitle}>{title}</div>{children}</div>;
  const s=data.stress||{},ph=data.physical||{},mn=data.mental||{},em=data.emotional||{},nu=data.nutritional||{},fz=data.financial||{},so=data.social||{},en=data.environmental||{},cm=data.commitments||{};
  return(<div style={{background:C.cream,minHeight:"100vh",padding:"16px 14px 40px",fontFamily:FB}}><div style={{maxWidth:720,margin:"0 auto"}}>
    <div style={{marginBottom:14,display:"flex",justifyContent:"space-between"}}>{onClose?<button onClick={onClose} style={btnBack}>{"\u2039"} Back</button>:<span/>}<button onClick={()=>window.print()} style={btnGold}>Print / Save as PDF</button></div>
    <div style={{position:"relative",background:C.dark,borderRadius:16,padding:"34px 24px",overflow:"hidden",marginBottom:16,textAlign:"center"}}><img src={LOGO} alt="" style={{position:"absolute",right:-30,bottom:-30,width:200,height:200,opacity:0.05,filter:"grayscale(1)"}}/><div style={{position:"relative"}}><div style={{fontFamily:FH,fontSize:22,color:C.gold}}>{profile.name}</div><div style={{fontSize:12.5,color:"rgba(255,250,241,0.75)",fontFamily:FB,marginTop:3}}>{profile.companyName||profile.company} · {profile.department}</div><div style={{fontFamily:FH,fontSize:56,color:C.gold,lineHeight:1.1,marginTop:10}}>{overall==null?"\u2014":overall+"%"}</div><div style={{fontSize:11,color:"rgba(255,250,241,0.7)",textTransform:"uppercase",letterSpacing:"0.12em",fontFamily:FB,marginTop:4}}>My Well-B Score</div></div></div>
    <Sec title="Wellbeing Map"><div style={{display:"flex",justifyContent:"center"}}><SpiderChart data={scores} size={250}/></div></Sec>
    <Sec title="Pillar Scores"><div style={{display:"grid",gridTemplateColumns:"repeat(auto-fit,minmax(90px,1fr))",gap:14,justifyItems:"center"}}>{PILLARS.map(p=><RingChart key={p} value={scores[p]} label={p}/>)}</div></Sec>
    <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12,marginBottom:16}}><div style={Object.assign({},card,{marginBottom:0})}><div style={cardTitle}>Stress Indicator</div><div style={{fontFamily:FH,fontSize:24,color:C.dark}}>{sv?sv+"/10":"\u2014"}</div><div style={{fontSize:12,color:C.sage,fontFamily:FB}}>{sv?STRESS_DYN[sv]:"Not recorded"}</div></div><div style={Object.assign({},card,{marginBottom:0})}><div style={cardTitle}>BMI & BMR</div><div style={{fontFamily:FH,fontSize:24,color:C.dark}}>{bmi?bmi.bmi:"\u2014"}</div><div style={{fontSize:12,color:C.sage,fontFamily:FB}}>{bmi?bmi.cat:"Not recorded"}{bmr?" · BMR "+bmr+" kcal/day":""}</div></div></div>
    <Sec title="Neuroregulation Recovery"><div style={{fontFamily:FH,fontSize:24,color:C.dark}}>{ns==null?"\u2014":ns+"%"}</div><div style={{fontSize:12,color:C.sage,fontFamily:FB}}>{ns==null?"Not completed":bandColor(ns).label} · separate from overall</div></Sec>
    <Sec title="Financial Detail"><div style={{fontSize:13,color:C.dark,fontFamily:FB}}>Cash Flow {fin.cf.score}/16 · Protection {fin.pr.score}/16 · Growth {fin.gr.score}/16 · Total {fin.total}/48 — {finBand(fin.total).label}</div></Sec>
    <Sec title="Priority Focus Areas">{low3.length===0&&<div style={{fontSize:12.5,color:C.sage,fontFamily:FB}}>Complete pillars to see priority areas.</div>}{low3.map(({p,s:sc})=>{const b=bandColor(sc);return(<div key={p} style={{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"9px 0",borderBottom:`1px solid ${C.border}`}}><span style={{fontSize:14,color:C.dark,fontFamily:FB,fontWeight:500}}>{p}</span><span style={{fontSize:11,fontWeight:700,color:b.c,background:b.c+"1F",padding:"4px 10px",borderRadius:20,fontFamily:FB}}>{sc}% · {b.label}</span></div>);})}</Sec>
    <Sec title="Personalised Recovery Suggestions">{low3.map(({p})=>(<div key={p} style={Object.assign({},recoveryWrap,{marginBottom:12})}><div style={{fontFamily:FH,fontSize:15,color:C.dark,marginBottom:5}}>{p}</div><div style={{fontSize:13,color:C.dark,fontFamily:FB,lineHeight:1.55}}>{RECOVERY_SUGGESTIONS[p]}</div></div>))}</Sec>
    <Sec title="My 30-Day Commitments">{COMMIT_PILLARS.map(p=>{const b=cm[p]||{};const items=[];if((b.start||"").trim())items.push(["Start",b.start]);if((b.stop||"").trim())items.push(["Stop",b.stop]);if((b.reduce||"").trim())items.push(["Reduce",b.reduce]);if((b.expect||"").trim())items.push(["30 days",b.expect]);if(items.length===0)return null;return(<div key={p} style={{marginBottom:12}}><div style={{fontFamily:FH,fontSize:14,color:C.dark,marginBottom:4}}>{p}</div>{items.map(([lbl,val],i)=><div key={i} style={{fontSize:12.5,color:C.dark,fontFamily:FB,marginBottom:3}}><span style={{color:C.sage,fontWeight:600}}>{lbl}: </span>{val}</div>)}</div>);})}</Sec>
    <Sec title="Consultation Requests"><QA q="Wellbeing consultation" a={consult.want!=null?(consult.want===0?"Yes — please contact me":"No, thank you"):null}/><QA q="Consultant gender preference" a={consult.genderPref!=null?["Female Practitioner preferred","Male Practitioner preferred","Anyone is fine"][consult.genderPref]:null}/><QA q="Complimentary financial session" a={fz.ctaSession!=null?(fz.ctaSession===0?"Yes":"No"):null}/></Sec>
    <div style={Object.assign({},cardTitle,{fontSize:12,marginTop:24,marginBottom:8})}>Full Assessment Record — Every Question & Answer</div>
    <Sec title="Stress Baseline"><QA q="Current stress level" a={s.level?s.level+"/10 — "+STRESS_DYN[s.level]:null}/><QA q="Stress triggers" a={(s.stressors||[]).join(", ")+(s.stressorsOther?" · Other: "+s.stressorsOther:"")}/><QA q="Body signs" a={(s.bodySigns||[]).join(", ")+(s.bodySignsOther?" · Other: "+s.bodySignsOther:"")}/>{NEURO_Q.map((it,i)=><QA key={i} q={it.q} a={s["neuro_"+i]!=null?it.o[s["neuro_"+i]]:null}/>)}</Sec>
    <Sec title="Physical Wellbeing"><QA q="Gender" a={ph.gender}/><QA q="Age" a={ph.age}/><QA q="Height (cm)" a={ph.height}/><QA q="Weight (kg)" a={ph.weight}/><QA q="BMI" a={bmi?bmi.bmi+" — "+bmi.cat:null}/><QA q="BMR" a={bmr?bmr+" kcal/day":null}/><QA q="Systolic / Diastolic (recorded only)" a={ph.systolic||ph.diastolic?(ph.systolic||"—")+"/"+(ph.diastolic||"—"):null}/><QA q="Resting Heart Rate" a={ph.hr}/><QA q="SpO2" a={ph.spo2}/><QA q="Fasting Glucose" a={ph.glucose}/><QA q="Activity Level" a={ph.activity!=null?["Sedentary","Light 1-2 days","Moderate 3-5 days","Very active 6-7 days"][ph.activity]:null}/>{POSTURAL_Q.map((it,i)=><QA key={"po"+i} q={"Postural: "+it.q} a={ph["post_"+i]!=null?it.o[ph["post_"+i]]:null}/>)}{JOINTS.map((j,i)=><QA key={"j"+i} q={"Joint — "+j} a={ph["joint_"+i]!=null?JOINT_LEVELS[ph["joint_"+i]]:null}/>)}{FUNCTIONAL_Q.map((it,i)=><QA key={"f"+i} q={"Functional: "+it.q} a={ph["func_"+i]!=null?it.o[ph["func_"+i]]:null}/>)}{PHYS_RECOVERY_Q.map((it,i)=><QA key={"pr"+i} q={"Recovery: "+it.q} a={ph["prec_"+i]!=null?it.o[ph["prec_"+i]]:null}/>)}</Sec>
    <Sec title="Mental Wellbeing">{WHO5.map((q,i)=><QA key={"w"+i} q={"WHO-5: "+q} a={mn["who_"+i]}/>)}{PSS10.map((q,i)=><QA key={"p"+i} q={"PSS-10: "+q} a={mn["pss_"+i]}/>)}{MENTAL_RECOVERY_Q.map((it,i)=><QA key={"m"+i} q={"Recovery: "+it.q} a={mn["mrec_"+i]!=null?it.o[mn["mrec_"+i]]:null}/>)}</Sec>
    <Sec title="Emotional Wellbeing">{SWLS.map((q,i)=><QA key={"s"+i} q={"SWLS: "+q} a={em["swls_"+i]}/>)}{PANAS.map((it,i)=><QA key={"pa"+i} q={"PANAS: "+it.t+" ("+(it.pos?"positive":"negative")+")"} a={em["pan_"+i]}/>)}{EMO_RECOVERY_Q.map((it,i)=><QA key={"e"+i} q={"Recovery: "+it.q} a={em["erec_"+i]!=null?it.o[em["erec_"+i]]:null}/>)}</Sec>
    <Sec title="Nutritional Wellbeing"><QA q="Breakfast time" a={nu.breakfast}/><QA q="Lunch time" a={nu.lunch}/><QA q="Dinner time" a={nu.dinner}/>{MEAL_PATTERN_Q.map((it,i)=><QA key={"mp"+i} q={it.q} a={nu["mp_"+i]!=null?it.o[nu["mp_"+i]]:null}/>)}{DIETARY_Q.map((it,i)=><QA key={"di"+i} q={it.q} a={nu["diet_"+i]!=null?it.o[nu["diet_"+i]]:null}/>)}{HYDRATION_Q.map((it,i)=><QA key={"hy"+i} q={it.q} a={nu["hyd_"+i]!=null?it.o[nu["hyd_"+i]]:null}/>)}<QA q="Deficiency symptoms" a={(nu.deficiency||[]).join(", ")}/>{NUT_RECOVERY_Q.map((it,i)=><QA key={"nr"+i} q={"Recovery: "+it.q} a={nu["nrec_"+i]!=null?it.o[nu["nrec_"+i]]:null}/>)}</Sec>
    <Sec title="Financial Wellbeing">{FIN_CASHFLOW.map((it,i)=><QA key={"cf"+i} q={"Cash Flow: "+it.q} a={fz["cf_"+i]!=null?it.o[fz["cf_"+i]]+" ("+it.p[fz["cf_"+i]]+" pts)":null}/>)}{FIN_PROTECTION.map((it,i)=><QA key={"pr"+i} q={"Protection: "+it.q} a={fz["pr_"+i]!=null?it.o[fz["pr_"+i]]+" ("+it.p[fz["pr_"+i]]+" pts)":null}/>)}{FIN_GROWTH.map((it,i)=><QA key={"gr"+i} q={"Growth: "+it.q} a={fz["gr_"+i]!=null?it.o[fz["gr_"+i]]+" ("+it.p[fz["gr_"+i]]+" pts)":null}/>)}<QA q="Leg totals" a={"Cash "+fin.cf.score+"/16 · Protection "+fin.pr.score+"/16 · Growth "+fin.gr.score+"/16 · Total "+fin.total+"/48"}/>{FIN_RECOVERY_Q.map((it,i)=><QA key={"fr"+i} q={"Recovery: "+it.q} a={fz["frec_"+i]!=null?it.o[fz["frec_"+i]]:null}/>)}<QA q="Complimentary financial session" a={fz.ctaSession!=null?(fz.ctaSession===0?"Yes":"No"):null}/></Sec>
    <Sec title="Social Wellbeing">{SOCIAL_Q.map((it,i)=><QA key={"so"+i} q={it.q} a={so["soc_"+i]!=null?it.o[so["soc_"+i]]:null}/>)}{SOCIAL_RECOVERY_Q.map((it,i)=><QA key={"sr"+i} q={"Recovery: "+it.q} a={so["srec_"+i]!=null?it.o[so["srec_"+i]]:null}/>)}</Sec>
    <Sec title="Environmental Wellbeing">{ENV_WORK_Q.map((it,i)=><QA key={"ew"+i} q={"Workplace: "+it.q} a={en["ew_"+i]!=null?it.o[en["ew_"+i]]:null}/>)}{ENV_HOME_Q.map((it,i)=><QA key={"eh"+i} q={"Home/Commute: "+it.q} a={en["eh_"+i]!=null?it.o[en["eh_"+i]]:null}/>)}{ENV_RECOVERY_Q.map((it,i)=><QA key={"er"+i} q={"Recovery: "+it.q} a={en["erc_"+i]!=null?it.o[en["erc_"+i]]:null}/>)}</Sec>
    <div style={{background:C.dark,borderRadius:12,padding:22,marginBottom:16,textAlign:"center"}}><div style={{fontFamily:FH,fontSize:18,color:C.gold}}>Ready to take the next step?</div><div style={{fontSize:13,color:"rgba(255,250,241,0.85)",fontFamily:FB,margin:"8px 0 16px",lineHeight:1.5}}>Connect with our Well-B Align team for your complimentary consultation</div><a href={WHATSAPP} target="_blank" rel="noreferrer" style={Object.assign({},btnGold,{display:"inline-block",textDecoration:"none"})}>Chat on WhatsApp</a><div style={{fontSize:10.5,color:"rgba(255,250,241,0.55)",fontFamily:FB,marginTop:14}}>[email protected] · wellbalign.ae</div></div>
    <div style={{fontSize:10.5,color:C.sage,fontFamily:FB,lineHeight:1.6,padding:"0 4px"}}>This assessment is for general wellness awareness only and does not constitute medical advice, diagnosis, or treatment. All clinical findings should be reviewed by a qualified healthcare professional.<br/>Well-B Align · [email protected] · wellbalign.ae</div>
  </div></div>);
}
ReactDOM.createRoot(document.getElementById("root")).render(<App/>);
</script>
</body>
</html>

Comments

Add a Comment