/* eslint-disable */
/* Nutri Physician — Health Audit
   3-step sliding wizard → graphical results card.
   Formulas: ICMR-NIN 2020, Mifflin-St Jeor (BMR), Deurenberg (Body Fat),
   Asia-Pacific BMI cutoffs. */

const { useState, useMemo, useRef, useEffect } = React;

/* ───────── DATA ───────── */
const ACTIVITY = [
{ id: 'sedentary', label: 'Sedentary', desc: 'Desk job · little/no exercise', pal: 1.4, mult: 1.2 },
{ id: 'light', label: 'Lightly Active', desc: 'Light exercise 1–3 days / week', pal: 1.55, mult: 1.375 },
{ id: 'moderate', label: 'Moderately Active', desc: 'Exercise 3–5 days / week', pal: 1.7, mult: 1.55 },
{ id: 'heavy', label: 'Very Active', desc: 'Hard exercise 6–7 days / week', pal: 1.85, mult: 1.725 },
{ id: 'athlete', label: 'Athlete / Physical', desc: 'Physical job + daily training', pal: 2.0, mult: 1.9 }];


const GOALS = [
{ id: 'lose', label: 'Lose Weight', desc: 'Calorie deficit (–500 kcal)', delta: -500 },
{ id: 'maintain', label: 'Maintain', desc: 'Stay at current weight', delta: 0 },
{ id: 'gain', label: 'Gain Muscle', desc: 'Calorie surplus (+300 kcal)', delta: 300 }];


/* ───────── HELPERS ───────── */
const cmFromFtIn = (ft, inch) => Number(ft) * 30.48 + Number(inch) * 2.54;
const kgFromLb = (lb) => Number(lb) * 0.453592;
const round = (n, d = 0) => {
  const f = Math.pow(10, d);return Math.round(n * f) / f;
};

function computeResults(input) {
  const { gender, age, heightCm, weightKg, waistCm, activityId, goalId } = input;
  const act = ACTIVITY.find((a) => a.id === activityId) || ACTIVITY[1];
  const goal = GOALS.find((g) => g.id === goalId) || GOALS[1];

  // IBW — Broca modified for Indians
  const ibw = Math.max(35, (heightCm - 100) * 0.9);

  // BMI
  const heightM = heightCm / 100;
  const bmi = weightKg / (heightM * heightM);
  const bmiBand =
  bmi < 18.5 ? { name: 'Underweight', tone: 'amber', pos: bmi / 18.5 * 0.18 } :
  bmi < 23 ? { name: 'Healthy', tone: 'green', pos: 0.18 + (bmi - 18.5) / (23 - 18.5) * 0.22 } :
  bmi < 25 ? { name: 'Overweight', tone: 'amber', pos: 0.40 + (bmi - 23) / (25 - 23) * 0.20 } :
  bmi < 30 ? { name: 'Obese I', tone: 'red', pos: 0.60 + (bmi - 25) / (30 - 25) * 0.20 } :
  { name: 'Obese II', tone: 'red', pos: Math.min(1, 0.80 + (bmi - 30) / 10 * 0.20) };


  // Body Fat — Deurenberg
  const sex = gender === 'male' ? 1 : 0;
  const bodyFat = Math.max(3, 1.20 * bmi + 0.23 * age - 10.8 * sex - 5.4);
  const bfHealthy = gender === 'male' ? [10, 20] : [18, 28];
  const bfBand =
  bodyFat < bfHealthy[0] ? 'low' :
  bodyFat <= bfHealthy[1] ? 'healthy' :
  bodyFat <= bfHealthy[1] + 7 ? 'high' : 'very-high';


  // BMR (Mifflin-St Jeor)
  const bmr = gender === 'male' ?
  10 * weightKg + 6.25 * heightCm - 5 * age + 5 :
  10 * weightKg + 6.25 * heightCm - 5 * age - 161;

  // TDEE & target calories
  const tdee = bmr * act.mult;
  const targetCals = Math.max(1000, tdee + goal.delta);

  // RDA (ICMR-NIN 2020)
  // Protein: 0.83 g/kg IBW (sedentary), 1.0 (moderate), 1.2 (heavy+)
  const proteinPerKg = act.pal >= 1.8 ? 1.2 : act.pal >= 1.6 ? 1.0 : 0.83;
  const proteinG = round(proteinPerKg * ibw);
  const fatG = round(targetCals * 0.27 / 9);
  const carbG = round(targetCals * 0.58 / 4);
  const fiberG = round(targetCals / 2000 * 40);

  // Metabolic age — derived from body composition deviations (not raw BMR,
  // which scales with body mass and gives misleading "young" ages to heavy people).
  // Healthy midpoints: ~15% BF male / ~25% female; BMI 22; waist-to-height 0.45.
  const bfMid = gender === 'male' ? 15 : 25;
  const bfPenalty = bodyFat <= bfMid ?
  Math.max(-3, (bfMid - bodyFat) * -0.3) // very lean → up to −3 yrs
  : (bodyFat - bfMid) * 0.6; // each % over mid → +0.6 yrs
  const bmiPenalty = bmi >= 23 ? (bmi - 23) * 0.7 : 0;
  const whr = waistCm / heightCm;
  const whrPenalty = whr >= 0.5 ? (whr - 0.5) * 40 : 0;
  let metAge = age + bfPenalty + bmiPenalty + whrPenalty;
  // Cap: at most 5 yrs younger or 25 yrs older than chronological
  metAge = Math.max(age - 5, Math.min(age + 25, metAge));
  metAge = Math.max(16, Math.min(99, Math.round(metAge)));

  // Waist-to-height ratio band (whr already computed above)
  const whrBand = whr < 0.43 ? 'low' : whr <= 0.5 ? 'healthy' : whr <= 0.57 ? 'high' : 'very-high';

  // Water (35 ml/kg)
  const waterMl = Math.round(weightKg * 35);
  const waterGlasses = Math.round(waterMl / 250);

  // Verdict — warm & encouraging
  const flags = [
  bmiBand.tone !== 'green',
  bfBand !== 'healthy',
  whrBand !== 'healthy' && whrBand !== 'low',
  metAge > age + 5].
  filter(Boolean).length;

  const verdict =
  flags === 0 ? {
    tone: 'green',
    headline: 'You\'re tracking beautifully.',
    sub: 'Your numbers sit in the healthy range across the board. Let\'s keep it that way — small habit tweaks compound for decades.'
  } :
  flags <= 2 ? {
    tone: 'amber',
    headline: 'A couple of numbers need attention.',
    sub: 'You\'re not in the red — but a few markers are drifting. The earlier you correct course, the easier the fix. Here\'s where to focus.'
  } : {
    tone: 'red',
    headline: 'Your body is asking for help.',
    sub: 'Several markers are outside the healthy band. This is fixable — and the right nutrition plan can shift these numbers in 12 weeks. Let\'s talk.'
  };


  return {
    ibw: round(ibw, 1), bmi: round(bmi, 1), bmiBand,
    bodyFat: round(bodyFat, 1), bfHealthy, bfBand,
    bmr: round(bmr), tdee: round(tdee), targetCals: round(targetCals),
    proteinG, fatG, carbG, fiberG,
    whr: round(whr, 2), whrBand,
    metAge, waterMl, waterGlasses,
    verdict, goalLabel: goal.label
  };
}

/* Average urban Indian benchmark — composite from NFHS-5 / ICMR-INDIAB / national surveys */
function avgIndian(age, gender) {
  // Rough mean BMI / waist by age band, urban
  const bands = [
  { lo: 18, hi: 24, m: { bmi: 23.4, waist: 84, bf: 19 }, f: { bmi: 23.1, waist: 79, bf: 28 } },
  { lo: 25, hi: 34, m: { bmi: 24.6, waist: 89, bf: 22 }, f: { bmi: 24.3, waist: 83, bf: 30 } },
  { lo: 35, hi: 44, m: { bmi: 25.4, waist: 92, bf: 25 }, f: { bmi: 25.2, waist: 86, bf: 32 } },
  { lo: 45, hi: 54, m: { bmi: 25.8, waist: 94, bf: 26 }, f: { bmi: 26.0, waist: 88, bf: 34 } },
  { lo: 55, hi: 99, m: { bmi: 25.5, waist: 95, bf: 27 }, f: { bmi: 25.7, waist: 89, bf: 35 } }];

  const band = bands.find((b) => age >= b.lo && age <= b.hi) || bands[2];
  return band[gender === 'male' ? 'm' : 'f'];
}

/* ───────── UI PRIMITIVES ───────── */

function ProgressDots({ step, total }) {
  return (
    <div className="ha-progress">
      {Array.from({ length: total }).map((_, i) =>
      <div key={i} className={`ha-dot ${i <= step ? 'on' : ''}`}>
          <span className="ha-dot-fill" />
        </div>
      )}
    </div>);

}

function SegToggle({ options, value, onChange }) {
  return (
    <div className="ha-seg">
      {options.map((o) =>
      <button
        key={o.id}
        type="button"
        className={`ha-seg-btn ${value === o.id ? 'on' : ''}`}
        onClick={() => onChange(o.id)}>
        
          {o.icon && <span className="ha-seg-icon">{o.icon}</span>}
          {o.label}
        </button>
      )}
    </div>);

}

function NumberField({ label, value, onChange, suffix, min, max, step = 1 }) {
  return (
    <label className="ha-field">
      <span className="ha-field-label">{label}</span>
      <div className="ha-field-row">
        <input
          type="number"
          inputMode="numeric"
          value={value === '' ? '' : value}
          min={min} max={max} step={step}
          onChange={(e) => onChange(e.target.value === '' ? '' : Number(e.target.value))} />
        
        {suffix && <span className="ha-field-suffix">{suffix}</span>}
      </div>
    </label>);

}

function ChoiceList({ options, value, onChange }) {
  return (
    <div className="ha-choices">
      {options.map((o) =>
      <button
        key={o.id}
        type="button"
        className={`ha-choice ${value === o.id ? 'on' : ''}`}
        onClick={() => onChange(o.id)}>
        
          <div className="ha-choice-main">
            <div className="ha-choice-label">{o.label}</div>
            <div className="ha-choice-desc">{o.desc}</div>
          </div>
          <div className="ha-choice-tick">
            <svg viewBox="0 0 24 24" width="14" height="14"><path d="M4 12l5 5L20 6" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" /></svg>
          </div>
        </button>
      )}
    </div>);

}

/* ───────── STEP 1 — BASICS ───────── */
function Step1({ data, set, onNext }) {
  const [unit, setUnit] = useState('metric'); // metric | imperial
  const [ft, setFt] = useState(data._ft ?? '');
  const [inch, setInch] = useState(data._in ?? '');
  const [lb, setLb] = useState(data._lb ?? '');

  // Push converted values back
  useEffect(() => {
    if (unit === 'imperial') {
      if (ft !== '' && inch !== '') set({ heightCm: round(cmFromFtIn(ft, inch), 1), _ft: ft, _in: inch });
      if (lb !== '') set({ weightKg: round(kgFromLb(lb), 1), _lb: lb });
    }
  }, [unit, ft, inch, lb]);

  const valid = data.gender && data.age >= 12 && data.age <= 99 &&
  data.heightCm >= 120 && data.heightCm <= 230 &&
  data.weightKg >= 25 && data.weightKg <= 250;

  return (
    <div className="ha-step">
      <div className="ha-step-head">
        <span className="ha-step-tag">Step 1 of 3</span>
        <h3>Tell us about you</h3>
        <p>The basics — so we know whose body we're reading.</p>
      </div>

      <div className="ha-row">
        <div className="ha-field">
          <span className="ha-field-label">Gender</span>
          <SegToggle
            options={[
            { id: 'male', label: 'Male' },
            { id: 'female', label: 'Female' }]
            }
            value={data.gender}
            onChange={(v) => set({ gender: v })} />
          
        </div>
        <NumberField label="Age" value={data.age} onChange={(v) => set({ age: v })} suffix="yrs" min={12} max={99} />
      </div>

      <div className="ha-field" style={{ marginTop: '1.4rem' }}>
        <div className="ha-field-label-row">
          <span className="ha-field-label">Units</span>
          <SegToggle
            options={[
            { id: 'metric', label: 'cm / kg' },
            { id: 'imperial', label: 'ft·in / lb' }]
            }
            value={unit}
            onChange={setUnit} />
          
        </div>
      </div>

      <div className="ha-row" style={{ marginTop: '0.8rem' }}>
        {unit === 'metric' ?
        <NumberField label="Height" value={data.heightCm} onChange={(v) => set({ heightCm: v })} suffix="cm" min={120} max={230} /> :

        <div className="ha-field">
            <span className="ha-field-label">Height</span>
            <div className="ha-field-row ha-field-split">
              <input type="number" inputMode="numeric" placeholder="ft" value={ft} onChange={(e) => setFt(e.target.value === '' ? '' : Number(e.target.value))} />
              <span className="ha-field-suffix">ft</span>
              <input type="number" inputMode="numeric" placeholder="in" value={inch} onChange={(e) => setInch(e.target.value === '' ? '' : Number(e.target.value))} />
              <span className="ha-field-suffix">in</span>
            </div>
          </div>
        }

        {unit === 'metric' ?
        <NumberField label="Weight" value={data.weightKg} onChange={(v) => set({ weightKg: v })} suffix="kg" min={25} max={250} step={0.5} /> :

        <div className="ha-field">
            <span className="ha-field-label">Weight</span>
            <div className="ha-field-row">
              <input type="number" inputMode="numeric" placeholder="lb" value={lb} onChange={(e) => setLb(e.target.value === '' ? '' : Number(e.target.value))} />
              <span className="ha-field-suffix">lb</span>
            </div>
          </div>
        }
      </div>

      <div className="ha-actions">
        <button className="ha-btn-primary" disabled={!valid} onClick={onNext}>
          Continue <span>→</span>
        </button>
      </div>
    </div>);

}

/* ───────── STEP 2 — WAIST ───────── */
function Step2({ data, set, onNext, onBack, unit }) {
  // Use a single waist input (cm or inch)
  const [wUnit, setWUnit] = useState('cm');
  const [wIn, setWIn] = useState('');

  useEffect(() => {
    if (wUnit === 'in' && wIn !== '') {
      set({ waistCm: round(Number(wIn) * 2.54, 1) });
    }
  }, [wUnit, wIn]);

  const valid = data.waistCm >= 40 && data.waistCm <= 200;

  return (
    <div className="ha-step">
      <div className="ha-step-head">
        <span className="ha-step-tag">Step 2 of 3</span>
        <h3>Measure your waist</h3>
        <p>Waist tells us more about diabetes risk than weight ever could. Measure around your belly button, relaxed.</p>
      </div>

      <div className="ha-illu-row">
        <div className="ha-illu">
          <svg viewBox="0 0 200 240" width="100%" height="220">
            <defs>
              <linearGradient id="bodyG" x1="0" x2="0" y1="0" y2="1">
                <stop offset="0" stopColor="#2d6e31" stopOpacity="0.15" />
                <stop offset="1" stopColor="#2d6e31" stopOpacity="0.04" />
              </linearGradient>
            </defs>
            {/* simple body silhouette */}
            <path d="M100 18 C 88 18 80 28 80 40 C 80 52 88 60 100 60 C 112 60 120 52 120 40 C 120 28 112 18 100 18 Z" fill="url(#bodyG)" stroke="#2d6e31" strokeWidth="1.5" />
            <path d="M70 70 Q 100 64 130 70 L 138 130 Q 130 150 122 156 L 122 220 L 108 220 L 105 170 L 95 170 L 92 220 L 78 220 L 78 156 Q 70 150 62 130 Z" fill="url(#bodyG)" stroke="#2d6e31" strokeWidth="1.5" />
            {/* waist ring */}
            <ellipse cx="100" cy="135" rx="44" ry="9" fill="none" stroke="#f4622a" strokeWidth="2.5" strokeDasharray="4 3" />
            <text x="100" y="139" textAnchor="middle" fontSize="9" fill="#f4622a" fontFamily="DM Sans, sans-serif" fontWeight="600">measure here</text>
          </svg>
        </div>

        <div className="ha-illu-inputs">
          <div className="ha-field">
            <div className="ha-field-label-row">
              <span className="ha-field-label">Waist circumference</span>
              <SegToggle
                options={[{ id: 'cm', label: 'cm' }, { id: 'in', label: 'in' }]}
                value={wUnit}
                onChange={setWUnit} />
              
            </div>
            <div className="ha-field-row">
              {wUnit === 'cm' ?
              <input type="number" inputMode="numeric" placeholder="e.g. 86" value={data.waistCm || ''} onChange={(e) => set({ waistCm: e.target.value === '' ? '' : Number(e.target.value) })} min={40} max={200} /> :

              <input type="number" inputMode="numeric" placeholder="e.g. 34" value={wIn} onChange={(e) => setWIn(e.target.value)} min={16} max={80} />
              }
              <span className="ha-field-suffix">{wUnit}</span>
            </div>
            <div className="ha-help">
              ICMR risk thresholds (Indian adults):
              <ul>
                <li>Men: high risk above <b>90 cm</b></li>
                <li>Women: high risk above <b>80 cm</b></li>
              </ul>
            </div>
          </div>
        </div>
      </div>

      <div className="ha-actions">
        <button className="ha-btn-ghost" onClick={onBack}>← Back</button>
        <button className="ha-btn-primary" disabled={!valid} onClick={onNext}>Continue <span>→</span></button>
      </div>
    </div>);

}

/* ───────── STEP 3 — LIFESTYLE ───────── */
function Step3({ data, set, onBack, onSubmit }) {
  const valid = data.activityId && data.goalId;

  return (
    <div className="ha-step">
      <div className="ha-step-head">
        <span className="ha-step-tag">Step 3 of 3</span>
        <h3>Your lifestyle &amp; goal</h3>
        <p>Activity changes everything — from how many calories you burn to how much protein you need.</p>
      </div>

      <div className="ha-subhead">How active are you on a typical day?</div>
      <ChoiceList
        options={ACTIVITY}
        value={data.activityId}
        onChange={(v) => set({ activityId: v })} />
      

      <div className="ha-subhead" style={{ marginTop: '1.6rem' }}>Your primary goal</div>
      <ChoiceList
        options={GOALS}
        value={data.goalId}
        onChange={(v) => set({ goalId: v })} />
      

      <div className="ha-actions">
        <button className="ha-btn-ghost" onClick={onBack}>← Back</button>
        <button className="ha-btn-primary" disabled={!valid} onClick={onSubmit}>
          See My Results <span>→</span>
        </button>
      </div>
    </div>);

}

/* ───────── RESULT GRAPHICS ───────── */

function BMIGauge({ bmi, band }) {
  // semicircle 180°
  const R = 70,cx = 90,cy = 90;
  const angleFor = (pos) => Math.PI - pos * Math.PI; // pos 0..1 → 180°..0°
  const stops = [
  { p: 0.00, c: '#5fa3d8' }, // underweight
  { p: 0.18, c: '#5fa3d8' },
  { p: 0.18, c: '#2d6e31' }, // healthy
  { p: 0.40, c: '#2d6e31' },
  { p: 0.40, c: '#f5a623' }, // overweight
  { p: 0.60, c: '#f5a623' },
  { p: 0.60, c: '#e04d18' }, // obese
  { p: 1.00, c: '#9c2a0e' }];

  const segs = [
  { from: 0, to: 0.18, c: '#5fa3d8', label: 'Under' },
  { from: 0.18, to: 0.40, c: '#2d6e31', label: 'Healthy' },
  { from: 0.40, to: 0.60, c: '#f5a623', label: 'Over' },
  { from: 0.60, to: 1.00, c: '#e04d18', label: 'Obese' }];

  const pointerAngle = angleFor(band.pos);
  const px = cx + (R - 4) * Math.cos(pointerAngle);
  const py = cy - (R - 4) * Math.sin(pointerAngle);

  return (
    <svg viewBox="0 0 180 120" width="100%" style={{ maxWidth: 220 }}>
      {segs.map((s, i) => {
        const a1 = angleFor(s.from),a2 = angleFor(s.to);
        const x1 = cx + R * Math.cos(a1),y1 = cy - R * Math.sin(a1);
        const x2 = cx + R * Math.cos(a2),y2 = cy - R * Math.sin(a2);
        return (
          <path
            key={i}
            d={`M ${x1} ${y1} A ${R} ${R} 0 0 1 ${x2} ${y2}`}
            stroke={s.c} strokeWidth="14" fill="none" strokeLinecap="butt" opacity="0.92" />);


      })}
      {/* pointer */}
      <line x1={cx} y1={cy} x2={px} y2={py} stroke="#1a1208" strokeWidth="2.5" strokeLinecap="round" />
      <circle cx={cx} cy={cy} r="5" fill="#1a1208" />
      <text x={cx} y={cy + 25} textAnchor="middle" fontSize="20" fontFamily="Playfair Display, serif" fontWeight="700" fill="#1a1208">{bmi}</text>
    </svg>);

}

function BodyFatBar({ value, healthy, band }) {
  // scale 0..50%
  const max = 50;
  const pct = Math.min(100, value / max * 100);
  const h1 = healthy[0] / max * 100;
  const h2 = healthy[1] / max * 100;
  const color = band === 'healthy' ? '#2d6e31' : band === 'low' ? '#5fa3d8' : band === 'high' ? '#f5a623' : '#e04d18';

  return (
    <div className="bf-bar-wrap">
      <div className="bf-bar">
        <div className="bf-band" style={{ left: `${h1}%`, width: `${h2 - h1}%` }} />
        <div className="bf-marker" style={{ left: `${pct}%`, background: color }}>
          <div className="bf-marker-label">{value}%</div>
        </div>
      </div>
      <div className="bf-bar-ticks">
        <span>0</span><span>15</span><span>25</span><span>35</span><span>50%</span>
      </div>
    </div>);

}

function MacroDonut({ p, c, f, cals }) {
  const pKcal = p * 4,cKcal = c * 4,fKcal = f * 9;
  const total = pKcal + cKcal + fKcal;
  const segs = [
  { kcal: pKcal, c: '#f4622a', label: 'Protein' },
  { kcal: cKcal, c: '#2d6e31', label: 'Carbs' },
  { kcal: fKcal, c: '#f5a623', label: 'Fat' }];

  const R = 50,C = 2 * Math.PI * R;
  let offset = 0;
  return (
    <svg viewBox="0 0 140 140" width="100%" style={{ maxWidth: 180 }}>
      <g transform="translate(70 70) rotate(-90)">
        <circle r={R} fill="none" stroke="#ede8e0" strokeWidth="16" />
        {segs.map((s, i) => {
          const frac = s.kcal / total;
          const len = frac * C;
          const el =
          <circle key={i} r={R} fill="none" stroke={s.c} strokeWidth="16"
          strokeDasharray={`${len} ${C - len}`} strokeDashoffset={-offset}
          strokeLinecap="butt" />;


          offset += len;
          return el;
        })}
      </g>
      <text x="70" y="68" textAnchor="middle" fontFamily="Playfair Display, serif" fontWeight="700" fontSize="22" fill="#1a1208" style={{ fill: "rgb(193, 193, 193)" }}>{cals}</text>
      <text x="70" y="84" textAnchor="middle" fontFamily="DM Sans, sans-serif" fontSize="9" fill="#7a6e5f" letterSpacing="2" style={{ fill: "rgb(186, 186, 186)" }}>KCAL / DAY</text>
    </svg>);

}

function WaterRow({ glasses }) {
  const total = Math.min(16, glasses);
  return (
    <div className="water-row">
      {Array.from({ length: total }).map((_, i) =>
      <svg key={i} viewBox="0 0 14 20" width="16" height="22">
          <path d="M7 1 L12 7 L12 15 Q 12 19 7 19 Q 2 19 2 15 L 2 7 Z" fill="#5fa3d8" opacity={0.85} />
        </svg>
      )}
    </div>);

}

function CompareBar({ label, you, avg, suffix, betterLower = true }) {
  // both you and avg, place on same scale 0..max where max = 1.4× higher of two
  const max = Math.max(you, avg) * 1.4;
  const youPct = you / max * 100;
  const avgPct = avg / max * 100;
  const youBetter = betterLower ? you <= avg : you >= avg;
  return (
    <div className="cmp-row">
      <div className="cmp-label">{label}</div>
      <div className="cmp-bars">
        <div className="cmp-track">
          <div className="cmp-fill you" style={{ width: `${youPct}%`, background: youBetter ? '#2d6e31' : '#e04d18' }}>
            <span>You · {you}{suffix}</span>
          </div>
        </div>
        <div className="cmp-track">
          <div className="cmp-fill avg" style={{ width: `${avgPct}%` }}>
            <span>Avg Indian · {avg}{suffix}</span>
          </div>
        </div>
      </div>
    </div>);

}

/* ───────── WHAT-IF PROJECTION ───────── */
function projectAtLoss(input, kgLost) {
  const newWeight = Math.max(40, input.weightKg - kgLost);
  const heightM = input.heightCm / 100;
  const newBMI = newWeight / (heightM * heightM);
  const sex = input.gender === 'male' ? 1 : 0;
  const newBF = Math.max(3, 1.20 * newBMI + 0.23 * input.age - 10.8 * sex - 5.4);
  // Waist tends to shrink ~1 cm per kg lost (approximate)
  const newWaist = Math.max(50, input.waistCm - kgLost * 1.0);
  const newWhr = newWaist / input.heightCm;
  // Metabolic age — same composition-based formula as main results
  const bfMid = input.gender === 'male' ? 15 : 25;
  const bfPenalty = newBF <= bfMid ?
  Math.max(-3, (bfMid - newBF) * -0.3) :
  (newBF - bfMid) * 0.6;
  const bmiPenalty = newBMI >= 23 ? (newBMI - 23) * 0.7 : 0;
  const whrPenalty = newWhr >= 0.5 ? (newWhr - 0.5) * 40 : 0;
  let newMetAge = input.age + bfPenalty + bmiPenalty + whrPenalty;
  newMetAge = Math.max(input.age - 5, Math.min(input.age + 25, newMetAge));
  newMetAge = Math.max(16, Math.min(99, Math.round(newMetAge)));
  // Weeks at 0.5 kg/week (sustainable 500 kcal deficit)
  const weeks = Math.ceil(kgLost / 0.5);
  return { newWeight: round(newWeight, 1), newBMI: round(newBMI, 1), newBF: round(newBF, 1),
    newWaist: round(newWaist, 1), newWhr: round(newWhr, 2), newMetAge, weeks };
}

function bandFor(value, healthyLo, healthyHi) {
  if (value < healthyLo) return 'low';
  if (value <= healthyHi) return 'healthy';
  return 'high';
}

function WhatIfPanel({ input, results }) {
  // Sensible default — about half-way to ideal weight, or 3kg if already healthy
  const ibw = results.ibw;
  const excess = Math.max(0, input.weightKg - ibw);
  const maxLoss = Math.min(20, Math.max(5, Math.ceil(excess + 2)));
  const defaultLoss = Math.min(maxLoss, Math.max(3, Math.round(excess * 0.6)));
  const [kgLost, setKgLost] = useState(defaultLoss);

  const p = useMemo(() => projectAtLoss(input, kgLost), [input, kgLost]);
  const healthyBF = results.bfHealthy;

  // Wins
  const wins = [];
  if (results.bmi >= 23 && p.newBMI < 23) wins.push({ icon: '✓', text: 'BMI back in the healthy Asia-Pacific band' });else
  if (results.bmi >= 25 && p.newBMI < 25) wins.push({ icon: '✓', text: 'You exit the obese band' });
  if (results.bodyFat > healthyBF[1] && p.newBF <= healthyBF[1]) wins.push({ icon: '✓', text: 'Body fat enters healthy range' });
  if (results.whr > 0.5 && p.newWhr <= 0.5) wins.push({ icon: '✓', text: 'Waist-to-Height drops below the T2D risk threshold (0.5)' });
  if (results.metAge > input.age && p.newMetAge <= input.age) wins.push({ icon: '✓', text: `Metabolic age aligns with your real age (${input.age})` });
  if (kgLost >= 5 && results.bmi >= 25) wins.push({ icon: '✓', text: 'Studies: 5–7% weight loss can reverse pre-diabetes' });
  if (kgLost >= 3) wins.push({ icon: '✓', text: `Blood pressure typically drops 5–10 mmHg` });
  if (wins.length === 0) wins.push({ icon: '✓', text: 'Even small drops compound — better energy, sleep, mobility' });

  // Don't show if user is underweight or already at/below ideal
  if (input.weightKg <= ibw - 2) return null;

  const formatArrow = (oldV, newV, betterLower = true) => {
    const better = betterLower ? newV < oldV : newV > oldV;
    const diff = Math.abs(round(oldV - newV, 1));
    return (
      <div className={`wi-arrow ${better ? 'good' : 'neutral'}`}>
        <span>↓ {diff}</span>
      </div>);

  };

  return (
    <div className="ha-whatif-card">
      <div className="wi-head">
        <span className="ha-section-tag">What If You Lost Weight?</span>
        <h4>Here's how your numbers move if you drop <em>{kgLost} kg</em>.</h4>
        <p className="wi-sub">Drag the slider. Every number updates live — and the timeline assumes a sustainable 0.5 kg / week (500 kcal daily deficit).</p>
      </div>

      <div className="wi-slider-wrap">
        <div className="wi-slider-meta">
          <span>Current · <b>{input.weightKg} kg</b></span>
          <span className="wi-target">Target · <b>{p.newWeight} kg</b></span>
        </div>
        <input
          type="range"
          min="1"
          max={maxLoss}
          step="0.5"
          value={kgLost}
          onChange={(e) => setKgLost(Number(e.target.value))}
          className="wi-slider"
          style={{ '--pct': `${kgLost / maxLoss * 100}%` }} />
        
        <div className="wi-slider-ticks">
          <span>−1 kg</span>
          <span>−{Math.round(maxLoss / 2)} kg</span>
          <span>−{maxLoss} kg</span>
        </div>
      </div>

      <div className="wi-projections">
        <div className="wi-row">
          <div className="wi-label">BMI</div>
          <div className="wi-old">{results.bmi}</div>
          {formatArrow(results.bmi, p.newBMI)}
          <div className="wi-new">{p.newBMI}</div>
          <div className="wi-tag">{p.newBMI < 23 ? 'Healthy' : p.newBMI < 25 ? 'Overweight' : 'Obese'}</div>
        </div>
        <div className="wi-row">
          <div className="wi-label">Body Fat</div>
          <div className="wi-old">{results.bodyFat}%</div>
          {formatArrow(results.bodyFat, p.newBF)}
          <div className="wi-new">{p.newBF}%</div>
          <div className="wi-tag">{p.newBF <= healthyBF[1] ? 'Healthy' : 'Still high'}</div>
        </div>
        <div className="wi-row">
          <div className="wi-label">Waist</div>
          <div className="wi-old">{input.waistCm} cm</div>
          {formatArrow(input.waistCm, p.newWaist)}
          <div className="wi-new">{p.newWaist} cm</div>
          <div className="wi-tag">{p.newWhr <= 0.5 ? 'Low risk' : 'Watch'}</div>
        </div>
        <div className="wi-row">
          <div className="wi-label">Metabolic Age</div>
          <div className="wi-old">{results.metAge} yrs</div>
          {formatArrow(results.metAge, p.newMetAge)}
          <div className="wi-new">{p.newMetAge} yrs</div>
          <div className="wi-tag">{p.newMetAge <= input.age ? 'Aligned' : `+${p.newMetAge - input.age} over`}</div>
        </div>
      </div>

      <div className="wi-time">
        <div className="wi-time-num">{p.weeks}</div>
        <div className="wi-time-text">
          <b>weeks</b><br />to reach this — sustainably
        </div>
        <div className="wi-time-divider"></div>
        <div className="wi-time-text wi-time-est">
          That's roughly <b>{Math.ceil(p.weeks / 4)} months</b><br />at 500 kcal/day deficit
        </div>
      </div>

      <div className="wi-wins">
        <div className="wi-wins-head">What changes for your body</div>
        <ul>
          {wins.slice(0, 5).map((w, i) =>
          <li key={i}><span className="wi-tick">{w.icon}</span>{w.text}</li>
          )}
        </ul>
      </div>
    </div>);

}

/* ───────── RESULT VIEW ───────── */
function ResultView({ input, results, onRestart }) {
  const avg = avgIndian(input.age, input.gender);
  const cardRef = useRef(null);

  const downloadCard = async () => {
    // Build a PNG via canvas
    const cvs = document.createElement('canvas');
    const W = 1000,H = 1400,dpr = 2;
    cvs.width = W * dpr;cvs.height = H * dpr;
    cvs.style.width = W + 'px';cvs.style.height = H + 'px';
    const ctx = cvs.getContext('2d');
    ctx.scale(dpr, dpr);

    // bg
    ctx.fillStyle = '#f8f4ee';ctx.fillRect(0, 0, W, H);
    // header
    ctx.fillStyle = '#0b1a0c';ctx.fillRect(0, 0, W, 180);
    ctx.fillStyle = '#f4622a';
    ctx.font = '700 14px DM Sans, sans-serif';
    ctx.fillText('NUTRI PHYSICIAN · YOUR HEALTH CARD', 60, 70);
    ctx.fillStyle = '#fdfaf7';
    ctx.font = '700 40px "Playfair Display", Georgia, serif';
    ctx.fillText(results.verdict.headline, 60, 130);

    // verdict tone bar
    const toneCol = results.verdict.tone === 'green' ? '#2d6e31' : results.verdict.tone === 'amber' ? '#f5a623' : '#e04d18';
    ctx.fillStyle = toneCol;ctx.fillRect(0, 180, W, 8);

    // metrics grid
    const metrics = [
    { label: 'BMI', v: results.bmi, sub: results.bmiBand.name },
    { label: 'Body Fat', v: results.bodyFat + '%', sub: `Healthy ${results.bfHealthy[0]}-${results.bfHealthy[1]}%` },
    { label: 'Ideal Weight', v: results.ibw + ' kg', sub: '(Broca·Indian)' },
    { label: 'Waist-to-Height', v: results.whr, sub: results.whrBand === 'healthy' ? 'Healthy' : 'Watch' },
    { label: 'BMR', v: results.bmr + ' kcal', sub: 'At rest / day' },
    { label: 'Metabolic Age', v: results.metAge + ' yrs', sub: `Actual ${input.age} yrs` }];

    const startY = 240,cellW = 290,cellH = 130,gap = 20,cols = 3;
    metrics.forEach((m, i) => {
      const col = i % cols,row = Math.floor(i / cols);
      const x = 60 + col * (cellW + gap),y = startY + row * (cellH + gap);
      ctx.fillStyle = '#fdfaf7';ctx.fillRect(x, y, cellW, cellH);
      ctx.strokeStyle = '#ede8e0';ctx.lineWidth = 1.5;ctx.strokeRect(x, y, cellW, cellH);
      ctx.fillStyle = '#7a6e5f';
      ctx.font = '500 12px DM Sans, sans-serif';
      ctx.fillText(m.label.toUpperCase(), x + 22, y + 30);
      ctx.fillStyle = '#1a1208';
      ctx.font = '700 36px "Playfair Display", Georgia, serif';
      ctx.fillText(m.v, x + 22, y + 78);
      ctx.fillStyle = '#4a3f2e';
      ctx.font = '400 13px DM Sans, sans-serif';
      ctx.fillText(m.sub, x + 22, y + 105);
    });

    // Calories & macros
    const macY = 540;
    ctx.fillStyle = '#0b1a0c';ctx.fillRect(60, macY, W - 120, 200);
    ctx.fillStyle = '#f4622a';
    ctx.font = '700 12px DM Sans, sans-serif';
    ctx.fillText('YOUR DAILY TARGETS · ICMR-NIN 2020', 90, macY + 38);
    ctx.fillStyle = '#fdfaf7';
    ctx.font = '700 56px "Playfair Display", Georgia, serif';
    ctx.fillText(results.targetCals + ' kcal', 90, macY + 100);
    ctx.font = '400 14px DM Sans, sans-serif';
    ctx.fillStyle = 'rgba(255,255,255,0.7)';
    ctx.fillText(`Goal: ${results.goalLabel}`, 90, macY + 125);

    const macros = [
    { l: 'Protein', v: results.proteinG + ' g', c: '#f4622a' },
    { l: 'Carbs', v: results.carbG + ' g', c: '#02e37a' },
    { l: 'Fats', v: results.fatG + ' g', c: '#f5a623' },
    { l: 'Fibre', v: results.fiberG + ' g', c: '#5fa3d8' }];

    macros.forEach((m, i) => {
      const x = 500 + i % 2 * 210,y = macY + 45 + Math.floor(i / 2) * 75;
      ctx.fillStyle = m.c;
      ctx.fillRect(x, y, 6, 50);
      ctx.fillStyle = 'rgba(255,255,255,0.55)';
      ctx.font = '500 11px DM Sans, sans-serif';
      ctx.fillText(m.l.toUpperCase(), x + 18, y + 18);
      ctx.fillStyle = '#fdfaf7';
      ctx.font = '700 28px "Playfair Display", Georgia, serif';
      ctx.fillText(m.v, x + 18, y + 48);
    });

    // Water
    const wY = 780;
    ctx.fillStyle = '#1a1208';
    ctx.font = '500 12px DM Sans, sans-serif';
    ctx.fillText('DAILY WATER TARGET', 60, wY);
    ctx.fillStyle = '#1a1208';
    ctx.font = '700 32px "Playfair Display", Georgia, serif';
    ctx.fillText(`${(results.waterMl / 1000).toFixed(1)} L  ·  ~${results.waterGlasses} glasses`, 60, wY + 38);

    // Verdict text
    const vY = 900;
    ctx.fillStyle = '#1a1208';
    ctx.font = '700 24px "Playfair Display", Georgia, serif';
    ctx.fillText('Here\'s what to focus on', 60, vY);
    ctx.fillStyle = '#4a3f2e';
    ctx.font = '400 16px DM Sans, sans-serif';
    wrapText(ctx, results.verdict.sub, 60, vY + 34, W - 120, 24);

    // Footer
    ctx.fillStyle = '#0b1a0c';ctx.fillRect(0, H - 130, W, 130);
    ctx.fillStyle = '#fdfaf7';
    ctx.font = '700 22px "Playfair Display", Georgia, serif';
    ctx.fillText('Want a real plan for these numbers?', 60, H - 78);
    ctx.fillStyle = '#f4622a';
    ctx.font = '500 14px DM Sans, sans-serif';
    ctx.fillText('Book a free consultation · nutriphysician.in', 60, H - 46);
    ctx.fillStyle = 'rgba(255,255,255,0.4)';
    ctx.font = '400 11px DM Sans, sans-serif';
    ctx.fillText('Indicative only. Based on ICMR-NIN 2020 guidelines for Indian adults.', 60, H - 20);

    // POWERED BY ICMR stamp — top right circle
    const sx = W - 110,sy = 100;
    ctx.save();
    ctx.translate(sx, sy);
    // outer ring
    ctx.beginPath();
    ctx.arc(0, 0, 56, 0, Math.PI * 2);
    ctx.strokeStyle = '#f4622a';
    ctx.lineWidth = 2;
    ctx.stroke();
    // inner ring
    ctx.beginPath();
    ctx.arc(0, 0, 48, 0, Math.PI * 2);
    ctx.strokeStyle = 'rgba(244,98,42,0.4)';
    ctx.lineWidth = 1;
    ctx.stroke();
    // curved "POWERED BY" along top
    ctx.fillStyle = 'rgba(255,255,255,0.92)';
    ctx.font = '600 8px DM Sans, sans-serif';
    const topText = 'POWERED BY · POWERED BY ·';
    const topR = 42;
    const topLen = topText.length;
    for (let i = 0; i < topLen; i++) {
      const a = i / topLen * Math.PI * 2 - Math.PI / 2;
      ctx.save();
      ctx.rotate(a + Math.PI / 2);
      ctx.translate(0, -topR);
      ctx.textAlign = 'center';
      ctx.fillText(topText[i], 0, 0);
      ctx.restore();
    }
    // center ICMR
    ctx.fillStyle = '#f4622a';
    ctx.font = '800 18px "Playfair Display", Georgia, serif';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.fillText('ICMR', 0, -4);
    ctx.fillStyle = 'rgba(255,255,255,0.7)';
    ctx.font = '500 7px DM Sans, sans-serif';
    ctx.fillText('NIN · 2020', 0, 12);
    ctx.restore();

    // Download
    cvs.toBlob((blob) => {
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = 'nutri-physician-health-card.png';
      a.click();
      setTimeout(() => URL.revokeObjectURL(url), 1000);
    }, 'image/png');
  };

  const shareWA = () => {
    const msg = encodeURIComponent(
      `Hi! I just took the Nutri Physician health audit.\n\n` +
      `• BMI: ${results.bmi} (${results.bmiBand.name})\n` +
      `• Body Fat: ${results.bodyFat}%\n` +
      `• Waist-Height: ${results.whr}\n` +
      `• Metabolic Age: ${results.metAge} yrs (actual ${input.age})\n` +
      `• Daily target: ${results.targetCals} kcal · ${results.proteinG}g protein\n\n` +
      `I'd like to discuss a plan.`
    );
    window.open(`https://wa.me/message/OU2ASOWIY226K1?text=${msg}`, '_blank');
  };

  const toneClass = `verdict-${results.verdict.tone}`;

  return (
    <div className="ha-result" ref={cardRef}>
      {/* Verdict */}
      <div className={`ha-verdict ${toneClass}`}>
        <span className="ha-verdict-tag">Your Audit · {input.gender === 'male' ? 'Male' : 'Female'} · {input.age} yrs</span>
        <h3>{results.verdict.headline}</h3>
        <p>{results.verdict.sub}</p>
        <div className="icmr-stamp" style={{ marginTop: '1rem', marginBottom: 0, color: "rgb(4, 162, 88)" }}>
          <span className="icmr-stamp-ring" style={{ color: "rgb(4, 162, 88)" }}>ICMR</span>
          BASED ON ICMR-NIN 2020 GUIDELINES
        </div>
      </div>

      {/* Key metric tiles */}
      <div className="ha-tiles">
        <div className="ha-tile ha-tile-bmi">
          <div className="ha-tile-label">BMI</div>
          <BMIGauge bmi={results.bmi} band={results.bmiBand} />
          <div className={`ha-tile-band band-${results.bmiBand.tone}`}>{results.bmiBand.name}</div>
        </div>

        <div className="ha-tile">
          <div className="ha-tile-label">Body Fat</div>
          <div className="ha-tile-big">{results.bodyFat}<span>%</span></div>
          <BodyFatBar value={results.bodyFat} healthy={results.bfHealthy} band={results.bfBand} />
          <div className="ha-tile-foot">Healthy range {results.bfHealthy[0]}–{results.bfHealthy[1]}%</div>
        </div>

        <div className="ha-tile">
          <div className="ha-tile-label">Ideal Weight</div>
          <div className="ha-tile-big">{results.ibw}<span>kg</span></div>
          <div className="ha-tile-foot">
            {input.weightKg > results.ibw + 2 ?
            `${round(input.weightKg - results.ibw, 1)} kg above ideal` :
            input.weightKg < results.ibw - 2 ?
            `${round(results.ibw - input.weightKg, 1)} kg below ideal` :
            'You\'re right at your ideal'}
          </div>
        </div>

        <div className="ha-tile">
          <div className="ha-tile-label">Waist-to-Height</div>
          <div className="ha-tile-big">{results.whr}</div>
          <div className="whr-bar">
            <div className="whr-track">
              <div className="whr-zone z-h" />
              <div className="whr-pin" style={{ left: `${Math.min(100, results.whr / 0.7 * 100)}%` }} />
            </div>
            <div className="whr-ticks"><span>0.4</span><span>0.5</span><span>0.6</span><span>0.7+</span></div>
          </div>
          <div className="ha-tile-foot">{results.whrBand === 'healthy' ? 'Healthy (below 0.5)' : results.whrBand === 'low' ? 'Below typical' : 'Above 0.5 — T2D risk band'}</div>
        </div>

        <div className="ha-tile">
          <div className="ha-tile-label">Metabolic Age</div>
          <div className="metage">
            <div className="metage-block">
              <div className="metage-num">{results.metAge}</div>
              <div className="metage-tag">Your body</div>
            </div>
            <div className="metage-vs">vs</div>
            <div className="metage-block">
              <div className="metage-num actual">{input.age}</div>
              <div className="metage-tag">Actual age</div>
            </div>
          </div>
          <div className="ha-tile-foot">
            {results.metAge > input.age + 2 ?
            `Body running ${results.metAge - input.age} yrs older — reversible` :
            results.metAge < input.age - 2 ?
            `Body running ${input.age - results.metAge} yrs younger — excellent` :
            'Aligned with your years'}
          </div>
        </div>

        <div className="ha-tile">
          <div className="ha-tile-label">Daily Water</div>
          <div className="ha-tile-big">{(results.waterMl / 1000).toFixed(1)}<span>L</span></div>
          <WaterRow glasses={results.waterGlasses} />
          <div className="ha-tile-foot">~ {results.waterGlasses} glasses · 35 ml per kg</div>
        </div>
      </div>

      {/* Calories + Macros wide card */}
      <div className="ha-cals-card">
        <div className="ha-cals-left">
          <span className="ha-section-tag">Daily Targets · ICMR-NIN 2020</span>
          <div className="ha-cals-big">{results.targetCals}<span>kcal</span></div>
          <div className="ha-cals-sub">
            Goal: <b>{results.goalLabel}</b> · BMR {results.bmr} kcal · TDEE {results.tdee} kcal
          </div>
          <MacroDonut p={results.proteinG} c={results.carbG} f={results.fatG} cals={results.targetCals} />
        </div>
        <div className="ha-cals-right">
          <div className="macro-row">
            <div className="macro-swatch" style={{ background: '#f4622a' }} />
            <div className="macro-info">
              <div className="macro-label">Protein</div>
              <div className="macro-value">{results.proteinG}<span>g</span></div>
              <div className="macro-note">{round(results.proteinG * 4)} kcal · ICMR safe</div>
            </div>
          </div>
          <div className="macro-row">
            <div className="macro-swatch" style={{ background: '#2d6e31' }} />
            <div className="macro-info">
              <div className="macro-label">Carbs</div>
              <div className="macro-value">{results.carbG}<span>g</span></div>
              <div className="macro-note">{round(results.carbG * 4)} kcal · 58% of total</div>
            </div>
          </div>
          <div className="macro-row">
            <div className="macro-swatch" style={{ background: '#f5a623' }} />
            <div className="macro-info">
              <div className="macro-label">Fats</div>
              <div className="macro-value">{results.fatG}<span>g</span></div>
              <div className="macro-note">{round(results.fatG * 9)} kcal · 27% of total</div>
            </div>
          </div>
          <div className="macro-row">
            <div className="macro-swatch" style={{ background: '#5fa3d8' }} />
            <div className="macro-info">
              <div className="macro-label">Fibre</div>
              <div className="macro-value">{results.fiberG}<span>g</span></div>
              <div className="macro-note">40 g per 2000 kcal · ICMR</div>
            </div>
          </div>
        </div>
      </div>

      {/* Comparison */}
      <div className="ha-compare-card">
        <span className="ha-section-tag">How you compare</span>
        <h4>You vs. the average urban Indian, age {input.age}</h4>
        <CompareBar label="BMI" you={results.bmi} avg={avg.bmi} suffix="" betterLower={true} />
        <CompareBar label="Waist" you={input.waistCm} avg={avg.waist} suffix=" cm" betterLower={true} />
        <CompareBar label="Body Fat" you={results.bodyFat} avg={avg.bf} suffix="%" betterLower={true} />
        <div className="ha-compare-note">National benchmark drawn from NFHS-5 &amp; ICMR-INDIAB urban cohort averages.</div>
      </div>

      {/* What-If projection */}
      <WhatIfPanel input={input} results={results} />

      {/* CTA strip */}
      <div className="ha-cta-strip">
        <div className="ha-cta-copy">
          <h4>Numbers are a snapshot. A plan is the change.</h4>
          <p>Get a personalised 12-week dietary protocol built around your numbers, your kitchen, and your goals — no supplements, just real Indian food.</p>
        </div>
        <div className="ha-cta-actions">
          <a href="Health-Declaration-Form.html" className="ha-btn-primary big">
            Start My Plan <span>→</span>
          </a>
          <button className="ha-btn-ghost" onClick={shareWA}>
            <svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor"><path d="M17.5 14.4c-.3-.1-1.7-.8-2-.9-.3-.1-.4-.1-.6.1-.2.3-.7.9-.9 1.1-.2.2-.3.2-.6.1-.3-.1-1.2-.5-2.3-1.4-.9-.8-1.4-1.8-1.6-2.1-.2-.3 0-.5.1-.6.1-.1.3-.3.4-.5.1-.2.2-.3.3-.5.1-.2 0-.4 0-.5 0-.1-.6-1.4-.8-2-.2-.5-.4-.4-.6-.4h-.5c-.2 0-.5.1-.7.4-.2.3-.9.9-.9 2.2 0 1.3.9 2.5 1 2.7.1.2 1.8 2.7 4.3 3.8.6.3 1.1.4 1.4.5.6.2 1.2.2 1.6.1.5-.1 1.5-.6 1.7-1.2.2-.6.2-1.1.1-1.2 0-.1-.2-.2-.5-.3z" /><path d="M12 2A10 10 0 0 0 3.6 17.7L2 22l4.4-1.6A10 10 0 1 0 12 2zm0 18.2c-1.6 0-3.1-.4-4.4-1.2l-.3-.2-3.1 1.1 1-3-.2-.3A8.3 8.3 0 1 1 20.3 12 8.3 8.3 0 0 1 12 20.2z" /></svg>
            WhatsApp My Results
          </button>
          <a href="tel:+919980599949" className="ha-btn-ghost">
            <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.36 1.9.7 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.34 1.85.57 2.81.7A2 2 0 0 1 22 16.92z" /></svg>
            Call Us
          </a>
        </div>
      </div>

      {/* Tools row */}
      <div className="ha-tools-row">
        <button className="ha-tool-btn" onClick={downloadCard}>
          <svg viewBox="0 0 24 24" width="16" height="16"><path d="M12 3v12m0 0l-4-4m4 4l4-4M5 21h14" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" /></svg>
          Download Health Card
        </button>
        <button className="ha-tool-btn" onClick={onRestart}>
          <svg viewBox="0 0 24 24" width="16" height="16"><path d="M3 12a9 9 0 1 0 3-6.7M3 4v5h5" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" /></svg>
          Recalculate
        </button>
      </div>

      <div className="ha-source">
        Formulas based on <b>ICMR-NIN 2020</b> Indian RDA · BMI cutoffs per WHO Asia-Pacific · BMR by Mifflin–St Jeor · Body Fat by Deurenberg. Indicative only — not a medical diagnosis.
      </div>
    </div>);

}

/* canvas text wrap helper */
function wrapText(ctx, text, x, y, maxW, lineH) {
  const words = text.split(' ');
  let line = '';
  for (let i = 0; i < words.length; i++) {
    const test = line + words[i] + ' ';
    if (ctx.measureText(test).width > maxW && i > 0) {
      ctx.fillText(line, x, y);
      line = words[i] + ' ';
      y += lineH;
    } else {
      line = test;
    }
  }
  ctx.fillText(line, x, y);
}

/* ───────── MAIN ───────── */
function HealthAudit() {
  const [step, setStep] = useState(0); // 0,1,2 = wizard, 3 = result
  const [data, setData] = useState({
    gender: 'male', age: 32,
    heightCm: 170, weightKg: 75,
    waistCm: 86,
    activityId: 'light', goalId: 'maintain'
  });
  const [results, setResults] = useState(null);
  const set = (patch) => setData((d) => ({ ...d, ...patch }));

  const submit = () => {
    const r = computeResults(data);
    setResults(r);
    setStep(3);
    setTimeout(() => {
      const el = document.getElementById('audit');
      if (el) {
        const top = el.getBoundingClientRect().top + window.scrollY - 80;
        window.scrollTo({ top, behavior: 'smooth' });
      }
    }, 50);
  };
  const restart = () => {setResults(null);setStep(0);};

  // Slide transform — only for wizard steps
  const showingResult = step === 3 && results;

  return (
    <div className="ha-wrap">
      {!showingResult &&
      <>
          <ProgressDots step={step} total={3} />
          <div className="ha-track-wrap">
            <div className="ha-track" style={{ transform: `translateX(-${step * 100}%)` }}>
              <div className="ha-slide">
                <Step1 data={data} set={set} onNext={() => setStep(1)} />
              </div>
              <div className="ha-slide">
                <Step2 data={data} set={set} onNext={() => setStep(2)} onBack={() => setStep(0)} />
              </div>
              <div className="ha-slide">
                <Step3 data={data} set={set} onSubmit={submit} onBack={() => setStep(1)} />
              </div>
            </div>
          </div>
        </>
      }
      {showingResult &&
      <ResultView input={data} results={results} onRestart={restart} />
      }
    </div>);

}

/* ───────── MOUNT ───────── */
const auditEl = document.getElementById('audit-widget');
if (auditEl) ReactDOM.createRoot(auditEl).render(<HealthAudit />);