const { useState, useEffect, useRef } = React;

/* ============ safe persistence: localStorage when available, memory fallback ============ */
const MEM = {};
const store = {
  get(k, d) {
    try { const v = localStorage.getItem("fitpulse:" + k); if (v != null) return JSON.parse(v); } catch (e) {}
    return k in MEM ? MEM[k] : d;
  },
  set(k, v) {
    MEM[k] = v;
    try { localStorage.setItem("fitpulse:" + k, JSON.stringify(v)); } catch (e) {}
  },
  clear() {
    Object.keys(MEM).forEach(k => delete MEM[k]);
    try { Object.keys(localStorage).filter(k => k.startsWith("fitpulse:")).forEach(k => localStorage.removeItem(k)); } catch (e) {}
  }
};

/* ============ icons (lucide-style strokes) ============ */
const ICONS = {
  home: <><path d="M3 10.5 12 3l9 7.5"/><path d="M5 9.5V21h14V9.5"/></>,
  calendar: <><rect x="3" y="4" width="18" height="17" rx="3"/><path d="M16 2v4M8 2v4M3 10h18"/></>,
  trending: <><path d="M22 7 13.5 15.5 8.5 10.5 2 17"/><path d="M16 7h6v6"/></>,
  chat: <path d="M7.9 20A9 9 0 1 0 4 16.1L2 22z"/>,
  flame: <path d="M8.5 14.5A2.5 2.5 0 0 0 11 12c0-1.38-.5-2-1-3-1.072-2.143-.224-4.054 2-6 .5 2.5 2 4.9 4 6.5 2 1.6 3 3.5 3 5.5a7 7 0 1 1-14 0c0-1.153.433-2.294 1-3a2.5 2.5 0 0 0 2.5 2.5z"/>,
  activity: <path d="M22 12h-4l-3 9L9 3l-3 9H2"/>,
  zap: <path d="M13 2 3 14h9l-1 8 10-12h-9l1-8z"/>,
  check: <path d="M20 6 9 17l-5-5"/>,
  play: <path d="m6 4 14 8-14 8V4z"/>,
  left: <path d="m15 18-6-6 6-6"/>,
  right: <path d="m9 18 6-6-6-6"/>,
  arrow: <><path d="M5 12h14"/><path d="m12 5 7 7-7 7"/></>,
  clock: <><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3.5 2"/></>,
  x: <path d="M18 6 6 18M6 6l12 12"/>,
  sparkles: <><path d="m12 3-1.6 5a2 2 0 0 1-1.4 1.4L4 11l5 1.6a2 2 0 0 1 1.4 1.4L12 19l1.6-5a2 2 0 0 1 1.4-1.4L20 11l-5-1.6a2 2 0 0 1-1.4-1.4z"/><path d="M19 3v3M20.5 4.5h-3"/></>,
  moon: <path d="M12 3a7 7 0 0 0 9.5 9.5A9 9 0 1 1 12 3z"/>,
  send: <><path d="m22 2-7 20-4-9-9-4z"/><path d="M22 2 11 13"/></>,
  dumbbell: <><path d="m6.5 6.5 11 11"/><path d="m21 21-1-1"/><path d="m3 3 1 1"/><path d="m18 22 4-4"/><path d="m2 6 4-4"/><path d="m3 10 7-7"/><path d="m14 21 7-7"/></>,
  skip: <><path d="m5 4 10 8-10 8V4z"/><path d="M19 5v14"/></>,
  target: <><circle cx="12" cy="12" r="9"/><circle cx="12" cy="12" r="4"/><circle cx="12" cy="12" r="1"/></>,
  wind: <path d="M17.7 7.7a2.5 2.5 0 1 1 1.8 4.3H2M9.6 4.6A2 2 0 1 1 11 8H2M12.6 19.4A2 2 0 1 0 14 16H2"/>,
  refresh: <><path d="M3 12a9 9 0 1 0 2.6-6.4L3 8"/><path d="M3 3v5h5"/></>,
  heart: <path d="M19 14c1.5-1.5 3-3.3 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.8 0-3.4 1-4.5 2.5C10.9 4 9.3 3 7.5 3A5.5 5.5 0 0 0 2 8.5c0 2.2 1.5 4 3 5.5l7 7z"/>,
  timer: <><path d="M10 2h4"/><path d="M12 14v-4"/><circle cx="12" cy="14" r="8"/></>,
};
const Ico = ({ n, s = 20, c = "", w = 2 }) => (
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor"
    strokeWidth={w} strokeLinecap="round" strokeLinejoin="round" className={c}>{ICONS[n]}</svg>
);

/* ============ mock data ============ */
const GOALS = [
  { id: "fitness", label: "Improve fitness", icon: "activity" },
  { id: "strength", label: "Build strength", icon: "dumbbell" },
  { id: "endurance", label: "Improve endurance", icon: "wind" },
  { id: "active", label: "Stay active", icon: "heart" },
  { id: "muscle", label: "Build muscle", icon: "zap" },
];
const EXPERIENCE = ["Beginner", "Intermediate", "Advanced"];
const DAY_OPTS = [2, 3, 4, 5, 6];
const TIME_OPTS = ["15 min", "30 min", "45 min", "60+ min"];
const LOCATIONS = ["Home", "Gym", "Outdoor", "Mixed"];
const EQUIPMENT = [
  { id: "none", label: "None", desc: "Bodyweight only" },
  { id: "dumbbells", label: "Dumbbells", desc: "A pair, any weight" },
  { id: "bands", label: "Resistance bands", desc: "Light & portable" },
  { id: "gym", label: "Full gym", desc: "Everything available" },
  { id: "other", label: "Other", desc: "Tell your coach later" },
];

const EXERCISES = [
  { name: "Goblet Squat", sets: 3, reps: "10", eq: "dumbbells", focus: "lower", instr: "Hold the dumbbell at your chest and lower with control." },
  { name: "Push-ups", sets: 3, reps: "8–12", eq: "none", focus: "upper", instr: "Keep a straight line from head to heels, elbows at 45°." },
  { name: "Bodyweight Squat", sets: 3, reps: "12", eq: "none", focus: "lower", instr: "Chest up, knees tracking over your toes." },
  { name: "Dumbbell Row", sets: 3, reps: "10", eq: "dumbbells", focus: "upper", instr: "Hinge at the hips, pull to your hip and squeeze your back." },
  { name: "Plank", sets: 3, reps: "30 sec", eq: "none", focus: "core", instr: "Brace your core, glutes tight, keep breathing." },
  { name: "Mountain Climbers", sets: 3, reps: "40 sec", eq: "none", focus: "cardio", instr: "Drive your knees toward your chest, hips low." },
  { name: "Jumping Jacks", sets: 3, reps: "40 sec", eq: "none", focus: "cardio", instr: "Stay light and bouncy, full range on every rep." },
  { name: "Shoulder Press", sets: 3, reps: "10", eq: "dumbbells", focus: "upper", instr: "Press overhead without arching your lower back." },
  { name: "Glute Bridge", sets: 3, reps: "12", eq: "none", focus: "lower", instr: "Drive through your heels and squeeze at the top." },
  { name: "Band Pull-apart", sets: 3, reps: "15", eq: "bands", focus: "upper", instr: "Pull the band apart at chest height, slow return." },
  { name: "Dead Bug", sets: 3, reps: "8 / side", eq: "none", focus: "core", instr: "Lower opposite arm and leg slowly, back flat." },
  { name: "High Knees", sets: 3, reps: "40 sec", eq: "none", focus: "cardio", instr: "Sprint in place, knees above hip height." },
  { name: "Russian Twists", sets: 3, reps: "20", eq: "none", focus: "core", instr: "Rotate from the ribs, not the arms." },
  { name: "Calf Raises", sets: 3, reps: "15", eq: "none", focus: "lower", instr: "Rise slowly, pause at the top, lower with control." },
  { name: "Band Overhead Press", sets: 3, reps: "10", eq: "bands", focus: "upper", instr: "Stand on the band, press up, wrists strong." },
  { name: "Cat–Cow Flow", sets: 2, reps: "8", eq: "none", focus: "recovery", instr: "Move with your breath — round and arch slowly." },
  { name: "World's Greatest Stretch", sets: 2, reps: "5 / side", eq: "none", focus: "recovery", instr: "Lunge, rotate open, breathe into the stretch." },
  { name: "Deep Squat Hold", sets: 2, reps: "40 sec", eq: "none", focus: "recovery", instr: "Sink into the squat, heels down, relax and breathe." },
  { name: "Hamstring Stretch", sets: 2, reps: "40 sec", eq: "none", focus: "recovery", instr: "Hinge forward with a flat back, ease into it." },
  { name: "Child's Pose", sets: 2, reps: "45 sec", eq: "none", focus: "recovery", instr: "Knees wide, arms long, slow deep breaths." },
];

const WEEK_TYPES = ["Full Body Strength", "Cardio Blast", "Upper Body", "Lower Body", "Recovery + Mobility", "Full Body Power"];
const PATTERNS = {
  2: [0, "rest", "rest", 1, "rest", 0, "rest"],
  3: [0, 1, "rest", 2, 4, 0, "rest"],
  4: [0, 1, 2, "rest", 3, 4, "rest"],
  5: [0, 1, 2, 3, 4, 0, "rest"],
  6: [0, 1, 2, 3, 0, 4, "rest"],
};
const DAY_NAMES = ["MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"];

function pickExercises(typeIdx, eq) {
  const wants =
    typeIdx === 1 ? ["cardio"] :
    typeIdx === 4 ? ["recovery"] :
    typeIdx === 2 ? ["upper", "core", "cardio"] :
    typeIdx === 3 ? ["lower", "core", "cardio"] :
    ["lower", "upper", "core"];
  const pool = EXERCISES.filter(e => wants.includes(e.focus) && (e.eq === "none" || eq === "gym" || eq === e.eq));
  const picks = [];
  wants.forEach(f => pool.filter(e => e.focus === f).forEach(e => { if (!picks.includes(e)) picks.push(e); }));
  pool.filter(e => !picks.includes(e)).forEach(e => picks.push(e));
  return picks.slice(0, typeIdx === 4 ? 5 : 8).map(e => ({ ...e }));
}

function buildPlan(user) {
  const pattern = PATTERNS[user.days] || PATTERNS[3];
  const baseMin = { "15 min": 20, "30 min": 30, "45 min": 40, "60+ min": 50 }[user.time] || 30;
  const jitter = [0, 2, -2, 3, 0, -3, 1];
  let todaySet = false;
  return pattern.map((slot, i) => {
    if (slot === "rest") return { day: DAY_NAMES[i], type: "Rest", typeIdx: null, minutes: 0, status: "rest" };
    let status = "todo";
    if (i < 2) status = "done";
    else if (!todaySet) { status = "today"; todaySet = true; }
    return { day: DAY_NAMES[i], type: WEEK_TYPES[slot], typeIdx: slot, minutes: Math.max(15, baseMin + jitter[i % 7]), status };
  });
}

const seedLogs = () => ({
  workouts: 18, minutes: 642, consistency: 82, streak: 6,
  week: [35, 30, 0, 32, 25, 40, 0],
});

const RATINGS = [
  { id: "easy", emoji: "😌", label: "Easy" },
  { id: "good", emoji: "🙂", label: "Good" },
  { id: "hard", emoji: "😐", label: "Hard" },
  { id: "veryhard", emoji: "🥵", label: "Very hard" },
];

function coachReply(text) {
  const t = text.toLowerCase();
  if (t.includes("tired")) return "Got it. I've scaled today's session down to the essentials — about 15 minutes. Quality over quantity. 💪";
  if (t.includes("missed")) return "No stress — consistency is a long game, not a perfect one. I've shifted the missed session to tomorrow and kept the rest of your week intact.";
  if (t.includes("equipment")) return "No problem. I've swapped in bodyweight alternatives you can do anywhere — same training effect.";
  if (t.includes("short")) return "Done. I've shortened today's workout while keeping the main training objective.";
  if (t.includes("sore") || t.includes("pain")) return "Thanks for telling me. I've reduced intensity for the next session and added mobility work. If pain persists, see a professional.";
  if (t.includes("thank") || t.includes("great")) return "You're doing the work — I just make sure it fits your life. See you at the next session. 🔥";
  return "Noted — I'll factor that into your next adaptation. Anything else? Energy, soreness, schedule changes — I'm listening.";
}

/* ============ shared UI ============ */
const GLASS = "bg-white/[0.06] backdrop-blur-xl border border-white/10";
const Btn = ({ children, onClick, variant = "primary", className = "", disabled }) => {
  const styles = {
    primary: "bg-gradient-to-r from-cyan-400 to-blue-600 text-navy font-bold shadow-[0_10px_30px_-8px_rgba(34,211,238,.55)] hover:brightness-110",
    ghost: "bg-white/[0.07] border border-white/10 text-white/80 hover:bg-white/[0.12]",
    cyan: "bg-transparent border border-cyan-400/40 text-cyan-300 hover:bg-cyan-400/10",
  };
  return (
    <button disabled={disabled} onClick={onClick}
      className={`rounded-2xl px-6 py-4 text-sm tracking-wide font-semibold transition-all duration-200 w-full active:scale-[.98] ${styles[variant]} ${disabled ? "opacity-40 pointer-events-none" : ""} ${className}`}>
      {children}
    </button>
  );
};
const Dots = ({ total, current }) => (
  <div className="flex items-center gap-2">
    {Array.from({ length: total }).map((_, i) => (
      <span key={i} className={`rounded-full transition-all duration-300 ${i === current ? "w-6 h-2 bg-cyan-400" : i < current ? "w-2 h-2 bg-cyan-400/70" : "w-2 h-2 bg-white/20"}`} />
    ))}
  </div>
);

/* ============ Screen 1 · Landing ============ */
function Landing({ onBuild, onExisting }) {
  return (
    <div className="min-h-screen px-6 pt-10 pb-12 max-w-md mx-auto w-full">
      <div className="fade-up flex items-center gap-2 mb-10">
        <div className="w-9 h-9 rounded-xl bg-gradient-to-br from-cyan-400 to-blue-600 flex items-center justify-center text-navy"><Ico n="zap" s={18} w={2.5} /></div>
        <span className="font-disp font-bold tracking-[0.25em]">FITPULSE</span>
      </div>
      <div className="fade-up" style={{ animationDelay: ".05s" }}>
        <h1 className="font-disp text-4xl leading-[1.15]">
          Your fitness plan,<br />
          <span className="bg-gradient-to-r from-cyan-300 to-blue-500 bg-clip-text text-transparent">built around your life.</span>
        </h1>
        <p className="text-white/55 mt-4 text-[15px] leading-relaxed">
          Personalized workouts. Real progress. A coach that adjusts with you.
        </p>
      </div>
      <div className="mt-8 space-y-3 fade-up" style={{ animationDelay: ".15s" }}>
        <Btn onClick={onBuild}>BUILD MY PLAN <Ico n="arrow" s={15} c="inline ml-1" /></Btn>
        <Btn onClick={onExisting} variant="ghost">I already have an account</Btn>
      </div>

      <div className="mt-14 fade-up" style={{ animationDelay: ".25s" }}>
        <h2 className="font-disp text-xs tracking-[0.3em] text-white/35 mb-4">HOW IT WORKS</h2>
        {[["01","Tell us about yourself","Goal, schedule, experience, equipment."],
          ["02","Get your plan","A realistic week built around your life."],
          ["03","Train","Guided sessions that fit your time."],
          ["04","FitPulse adapts","Your plan changes when life changes."]].map(([n,t,d]) => (
          <div key={n} className="flex gap-4 py-3 border-b border-white/[0.06]">
            <span className="font-disp text-cyan-400/80 text-sm pt-0.5">{n}</span>
            <div><div className="font-semibold text-[15px]">{t}</div><div className="text-white/40 text-[13px] mt-0.5">{d}</div></div>
          </div>
        ))}
      </div>

      <div className="mt-10 fade-up" style={{ animationDelay: ".3s" }}>
        <h2 className="font-disp text-xs tracking-[0.3em] text-white/35 mb-4">WHY FITPULSE?</h2>
        <div className="grid grid-cols-2 gap-3">
          {[["target","Personalized","Built around your schedule."],
            ["refresh","Adaptive","Changes when circumstances change."],
            ["zap","Simple","No complicated dashboards."],
            ["send","Your coach","Guidance whenever you need it."]].map(([ic,t,d]) => (
            <div key={t} className={`${GLASS} rounded-2xl p-4`}>
              <span className="text-cyan-300 block mb-2"><Ico n={ic} s={18} /></span>
              <div className="font-semibold text-sm">{t}</div>
              <div className="text-white/40 text-xs mt-1 leading-relaxed">{d}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

/* ============ Screen 2 · Onboarding ============ */
const OB_KEYS = ["goal","experience","days","time","location","equipment"];
function Onboarding({ onDone, onBack }) {
  const [step, setStep] = useState(0);
  const [ans, setAns] = useState({});
  const cur = OB_KEYS[step];
  const pick = (v) => {
    const next = { ...ans, [cur]: v };
    setAns(next);
    setTimeout(() => {
      if (step < 5) setStep(step + 1);
      else onDone({ name: "Michael", goal: next.goal, experience: next.experience, days: next.days, time: next.time, location: next.location, equipment: next.equipment });
    }, 260);
  };
  const Q = {
    goal: { t: "What's your goal?", o: GOALS.map(g => ({ v: g.id, label: g.label, icon: g.icon })) },
    experience: { t: "What's your experience?", o: EXPERIENCE.map(e => ({ v: e, label: e })) },
    days: { t: "How many days can you train?", o: DAY_OPTS.map(d => ({ v: d, label: String(d), big: true })), grid: "grid-cols-3" },
    time: { t: "How much time do you have?", o: TIME_OPTS.map(t => ({ v: t, label: t })) },
    location: { t: "Where do you train?", o: LOCATIONS.map(l => ({ v: l, label: l })) },
    equipment: { t: "What equipment do you have?", o: EQUIPMENT.map(e => ({ v: e.id, label: e.label, desc: e.desc })) },
  }[cur];
  return (
    <div className="min-h-screen flex flex-col px-6 max-w-md mx-auto w-full">
      <div className="flex items-center justify-between pt-6">
        <button onClick={() => step === 0 ? onBack() : setStep(step - 1)} className="text-white/60 p-2 -ml-2 hover:text-white"><Ico n="left" s={22} /></button>
        <Dots total={6} current={step} />
        <span className="text-white/30 text-xs w-10 text-right">{step + 1} / 6</span>
      </div>
      <div className="flex-1 flex flex-col justify-center py-10">
        <div key={step} className="fade-up">
          <h2 className="font-disp text-3xl leading-tight mb-8">{Q.t}</h2>
          <div className={`grid gap-3 ${Q.grid || "grid-cols-1"}`}>
            {Q.o.map(o => (
              <button key={String(o.v)} onClick={() => pick(o.v)}
                className={`${GLASS} rounded-2xl px-5 py-4 text-left hover:bg-white/[0.12] hover:border-cyan-400/40 active:scale-[.98] transition-all duration-200 ${ans[cur] === o.v ? "!border-cyan-400/70 !bg-cyan-400/10" : ""}`}>
                <div className="flex items-center gap-3">
                  {o.icon && <span className="text-cyan-300"><Ico n={o.icon} s={18} /></span>}
                  <span className={`font-semibold ${o.big ? "text-2xl font-disp flex-1 text-center" : "text-[15px]"}`}>{o.label}</span>
                </div>
                {o.desc && <div className="text-white/40 text-xs mt-1">{o.desc}</div>}
              </button>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

/* ============ Screen 3 · Plan generation ============ */
function PlanGeneration({ onDone }) {
  const STEPS = ["Analyzing your goals", "Planning your workouts", "Balancing your week", "Personalizing intensity"];
  const [done, setDone] = useState(0);
  useEffect(() => {
    if (done < STEPS.length) { const t = setTimeout(() => setDone(d => d + 1), done === 0 ? 650 : 800); return () => clearTimeout(t); }
    const t = setTimeout(onDone, 1500);
    return () => clearTimeout(t);
  }, [done]);
  const ready = done === STEPS.length;
  return (
    <div className="min-h-screen flex flex-col items-center justify-center px-8 max-w-md mx-auto w-full text-center">
      <div className={`w-24 h-24 rounded-full border-2 border-cyan-400/25 flex items-center justify-center mb-12 ${ready ? "" : "glow"}`}>
        <div className="w-16 h-16 rounded-full bg-gradient-to-br from-cyan-400 to-blue-600 flex items-center justify-center text-navy float-y">
          <Ico n={ready ? "check" : "activity"} s={28} w={2.5} />
        </div>
      </div>
      <div className="w-full space-y-4">
        {STEPS.map((s, i) => {
          const isDone = i < done, active = i === done;
          return (
            <div key={s} className={`flex items-center gap-3 text-left transition-all duration-500 ${isDone ? "opacity-100" : active ? "opacity-90" : "opacity-25"}`}>
              <span className={`w-6 h-6 rounded-full flex items-center justify-center shrink-0 ${isDone ? "bg-cyan-400/20 text-cyan-300" : active ? "border border-cyan-400/40" : "border border-white/15"}`}>
                {isDone ? <Ico n="check" s={13} w={3} /> : active ? <span className="w-2 h-2 rounded-full bg-cyan-400 animate-ping block"></span> : <span className="w-1.5 h-1.5 rounded-full bg-white/30 block"></span>}
              </span>
              <span className="text-[15px]">{s}{isDone && <span className="text-cyan-300 ml-2">✓</span>}</span>
            </div>
          );
        })}
      </div>
      <div className={`mt-14 transition-all duration-700 ${ready ? "opacity-100 translate-y-0" : "opacity-0 translate-y-3"}`}>
        <div className="font-disp text-2xl bg-gradient-to-r from-cyan-300 to-blue-500 bg-clip-text text-transparent">Your plan is ready.</div>
      </div>
    </div>
  );
}

/* ============ Screen 4 · Home ============ */
function Home({ user, plan, onStart, goTab }) {
  const todayIdx = plan.findIndex(d => d.status === "today");
  const today = plan[todayIdx] || plan.find(d => d.status === "todo");
  const prev = plan[todayIdx - 1];
  const focusText = (d) => d.typeIdx === 1 ? "conditioning and heart rate" : d.typeIdx === 4 ? "mobility and easy movement" :
    d.typeIdx === 2 ? "upper body and core" : d.typeIdx === 3 ? "lower body and core" : "full-body strength";
  const doneCount = plan.filter(d => d.status === "done").length;
  const trainable = plan.filter(d => d.status !== "rest").length;
  const h = new Date().getHours();
  const greet = h < 12 ? "Good morning" : h < 17 ? "Good afternoon" : "Good evening";
  return (
    <div className="px-5 pt-6 pb-4 space-y-5 max-w-md mx-auto w-full">
      <div className="flex items-start justify-between">
        <div>
          <div className="font-disp text-2xl">{greet} 👋 <span className="text-cyan-300">{user.name}</span></div>
          <div className="text-white/40 text-sm mt-1">Monday · Week 1</div>
        </div>
        <div className="w-10 h-10 rounded-full bg-gradient-to-br from-cyan-400/30 to-blue-600/30 border border-white/10 flex items-center justify-center font-disp font-bold text-cyan-200">{user.name[0]}</div>
      </div>

      <div className={`${GLASS} rounded-3xl p-5 relative overflow-hidden fade-up`}>
        <div className="absolute -top-16 -right-16 w-44 h-44 rounded-full bg-cyan-500/20 blur-3xl pointer-events-none"></div>
        <div className="text-[11px] tracking-[0.25em] text-cyan-300/80 font-bold mb-3">TODAY'S WORKOUT</div>
        <div className="font-disp text-3xl leading-tight">{today?.type || "Rest Day"}</div>
        <div className="flex items-center gap-2.5 mt-3 text-white/55 text-[13px]">
          <Ico n="clock" s={14} /> {today?.minutes || 0} min <span>·</span> {user.experience} <span>·</span>
          <span className="capitalize">{user.equipment === "none" ? "No equipment" : user.equipment}</span>
        </div>
        <div className="mt-4 bg-white/[0.05] border border-white/[0.07] rounded-2xl p-3.5">
          <div className="text-[11px] tracking-widest text-white/35 font-bold mb-1">WHY TODAY?</div>
          <div className="text-white/70 text-[13px] leading-relaxed">
            {prev && prev.status === "done"
              ? `You trained ${prev.type.split(" ")[0].toLowerCase()} body this week, so today's session focuses on ${focusText(today)}.`
              : "A fresh week — today's session sets the tone and builds momentum."}
          </div>
        </div>
        <div className="mt-5"><Btn onClick={onStart}>START WORKOUT <Ico n="arrow" s={15} c="inline ml-1" /></Btn></div>
      </div>

      <div className={`${GLASS} rounded-3xl p-5 fade-up`} style={{ animationDelay: ".1s" }}>
        <div className="flex items-center justify-between mb-4">
          <span className="text-[11px] tracking-[0.25em] text-white/35 font-bold">WEEKLY PROGRESS</span>
          <button onClick={() => goTab("plan")} className="text-cyan-300 text-xs font-semibold">View plan →</button>
        </div>
        <div className="flex justify-between px-0.5">
          {plan.map((d, i) => (
            <div key={i} className="flex flex-col items-center gap-2">
              <span className="text-[10px] text-white/35 font-bold">{d.day.slice(0, 1) + d.day.slice(1, 2).toLowerCase()}</span>
              <span className={`w-9 h-9 rounded-xl flex items-center justify-center ${
                d.status === "done" ? "bg-cyan-400/20 text-cyan-300 border border-cyan-400/30" :
                d.status === "today" ? "bg-gradient-to-br from-cyan-400 to-blue-600 text-navy" :
                d.status === "rest" ? "text-white/25" : "text-white/40 border border-white/10"}`}>
                {d.status === "done" ? <Ico n="check" s={14} w={3} /> : d.status === "rest" ? <Ico n="moon" s={13} /> :
                 d.status === "today" ? <span className="w-2 h-2 rounded-full bg-navy block"></span> : <span className="w-2 h-2 rounded-full border border-white/40 block"></span>}
              </span>
            </div>
          ))}
        </div>
        <div className="text-white/50 text-[13px] mt-4">{doneCount} / {trainable} completed</div>
      </div>

      <div className="flex items-start gap-3 px-1 fade-up" style={{ animationDelay: ".18s" }}>
        <span className="text-cyan-300 mt-0.5"><Ico n="sparkles" s={15} /></span>
        <p className="text-white/60 text-[13px] leading-relaxed">
          {doneCount >= 2 ? "You're building consistency this week. Keep going." : "Every session counts. Today's workout is ready when you are."}
        </p>
      </div>
    </div>
  );
}

/* ============ Screen 5 · Plan ============ */
function PlanPage({ plan, onOpenDay }) {
  return (
    <div className="px-5 pt-6 pb-4 max-w-md mx-auto w-full">
      <div className="flex items-end justify-between mb-1">
        <h1 className="font-disp text-2xl">Your Plan</h1>
        <span className="text-white/30 text-xs mb-1">Week 1</span>
      </div>
      <p className="text-white/40 text-[13px] mb-6">Tap a session to see details or start it.</p>
      <div className="space-y-3">
        {plan.map((d, i) => {
          const clickable = d.status === "today" || d.status === "todo";
          return (
            <button key={i} disabled={!clickable} onClick={() => onOpenDay(i)}
              className={`${GLASS} w-full rounded-2xl p-4 flex items-center gap-4 text-left transition-all duration-200
                ${d.status === "today" ? "!border-cyan-400/50 !bg-cyan-400/[0.08]" : ""} ${clickable ? "hover:bg-white/[0.1] active:scale-[.99]" : "opacity-60"}`}>
              <div className="w-14 shrink-0 text-center">
                <div className="text-[10px] tracking-widest text-white/35 font-bold">{d.day}</div>
                <div className={`w-10 h-10 mx-auto mt-1 rounded-xl flex items-center justify-center ${d.status === "today" ? "bg-gradient-to-br from-cyan-400 to-blue-600 text-navy" : "bg-white/[0.06] text-white/60"}`}>
                  {d.status === "done" ? <Ico n="check" s={16} w={3} c="text-cyan-300" /> :
                   d.status === "today" ? <span className="text-[9px] font-disp font-bold tracking-wider">NOW</span> :
                   d.status === "rest" ? <Ico n="moon" s={16} c="text-white/30" /> : <Ico n="play" s={13} c="text-white/40" />}
                </div>
              </div>
              <div className="flex-1 min-w-0">
                <div className="font-semibold text-[15px]">{d.type}</div>
                <div className="text-white/40 text-xs mt-0.5">
                  {d.status === "rest" ? "Recover — you've earned it." :
                   d.status === "done" ? `${d.minutes} min · Completed ✓` :
                   d.status === "today" ? `${d.minutes} min · Ready now` : `${d.minutes} min · Upcoming`}
                </div>
              </div>
              {clickable && <Ico n="right" s={16} c="text-white/30" />}
            </button>
          );
        })}
      </div>
    </div>
  );
}

/* ============ Screen 6 · Workout player ============ */
function WorkoutPlayer({ day, eq, onExit, onFinish }) {
  const [exs] = useState(() => pickExercises(day.typeIdx, day.typeIdx === 4 ? "none" : eq));
  const totalSets = exs.reduce((a, e) => a + e.sets, 0);
  const [ei, setEi] = useState(0);
  const [set, setSet] = useState(0);
  const [phase, setPhase] = useState("work");
  const [left, setLeft] = useState(0);
  const [setsDone, setSetsDone] = useState(0);
  const [nextLabel, setNextLabel] = useState("");
  const start = useRef(Date.now());
  const pending = useRef(null);
  const ex = exs[ei];

  const completeSet = () => {
    if (set + 1 < ex.sets) {
      pending.current = () => setSet(s => s + 1);
      setNextLabel(`${ex.name} · Set ${set + 2} of ${ex.sets}`);
      setLeft(60); setPhase("rest");
    } else if (ei + 1 < exs.length) {
      pending.current = () => { setEi(e => e + 1); setSet(0); };
      setNextLabel(exs[ei + 1].name);
      setLeft(45); setPhase("rest");
    } else {
      onFinish(Math.max(60, Math.round((Date.now() - start.current) / 1000)), setsDone + 1, exs.length);
    }
  };
  const endRest = () => {
    if (pending.current) { const fn = pending.current; pending.current = null; fn(); }
    setPhase("work");
  };

  useEffect(() => {
    if (phase !== "rest") return;
    const t = setInterval(() => setLeft(l => l - 1), 1000);
    return () => clearInterval(t);
  }, [phase, ei, set]);
  useEffect(() => { if (phase === "rest" && left <= 0) endRest(); }, [left, phase]);

  const mm = String(Math.floor(Math.max(0, left) / 60)).padStart(2, "0");
  const ss = String(Math.max(0, left) % 60).padStart(2, "0");

  return (
    <div className="min-h-screen flex flex-col px-5 pt-5 pb-6 max-w-md mx-auto w-full">
      <div className="flex items-center justify-between mb-4">
        <button onClick={onExit} className="text-white/60 p-2 -ml-2 hover:text-white"><Ico n="x" s={20} /></button>
        <span className="text-[11px] tracking-[0.25em] text-white/40 font-bold">{day.type.toUpperCase()}</span>
        <span className="text-white/50 text-xs font-disp font-semibold">{String(ei + 1).padStart(2, "0")} / {String(exs.length).padStart(2, "0")}</span>
      </div>
      <div className="h-1.5 rounded-full bg-white/[0.07] mb-8 overflow-hidden">
        <div className="h-full rounded-full bg-gradient-to-r from-cyan-400 to-blue-500 transition-all duration-500"
          style={{ width: `${Math.min(100, Math.round((setsDone / totalSets) * 100))}%` }} />
      </div>

      {phase === "rest" ? (
        <div className="flex-1 flex flex-col items-center justify-center text-center pop-in" key={"rest" + ei + set}>
          <span className="text-cyan-300/70 mb-4"><Ico n="timer" s={36} w={1.6} /></span>
          <div className="text-[11px] tracking-[0.3em] text-white/40 font-bold mb-2">REST</div>
          <div className="font-disp text-6xl tabular-nums bg-gradient-to-r from-cyan-300 to-blue-500 bg-clip-text text-transparent">{mm}:{ss}</div>
          <div className="mt-8 text-white/50 text-sm">Up next · <span className="text-white/95 font-semibold">{nextLabel}</span></div>
          <div className="w-full mt-10"><Btn variant="cyan" onClick={endRest}>START SET <Ico n="play" s={13} c="inline ml-1" /></Btn></div>
        </div>
      ) : (
        <div className="flex-1 flex flex-col fade-up" key={"work" + ei + set}>
          <div className="flex-1 flex flex-col items-center justify-center text-center">
            <div className="text-[11px] tracking-[0.3em] text-cyan-300/80 font-bold mb-3">{String(ei + 1).padStart(2, "0")} / {String(exs.length).padStart(2, "0")}</div>
            <div className="w-40 h-40 rounded-3xl bg-gradient-to-br from-cyan-400/15 to-blue-600/15 border border-white/10 flex items-center justify-center mb-6 float-y">
              <span className="text-cyan-300/80"><Ico n="dumbbell" s={52} w={1.5} /></span>
            </div>
            <h2 className="font-disp text-3xl">{ex.name}</h2>
            <div className="text-white/50 mt-2 text-lg font-disp font-semibold">{ex.sets} × {ex.reps}</div>
            <div className="text-[10px] tracking-widest text-white/30 font-bold mt-1 mb-4">SET {set + 1} / {ex.sets}</div>
            <p className="text-white/60 text-sm leading-relaxed max-w-xs">{ex.instr}</p>
          </div>
          <div className="space-y-2">
            <Btn onClick={() => { setSetsDone(d => d + 1); completeSet(); }}><Ico n="check" s={14} c="inline mr-1.5" />COMPLETE SET</Btn>
            <button onClick={completeSet} className="w-full text-center text-white/40 text-[13px] py-2.5 hover:text-white/70 transition-colors">
              Skip <Ico n="skip" s={12} c="inline ml-1" />
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

/* ============ Screen 7 · Complete + check-in ============ */
function WorkoutComplete({ elapsed, exCount, setCount, onRate }) {
  const t = `${Math.floor(elapsed / 60)}:${String(elapsed % 60).padStart(2, "0")}`;
  return (
    <div className="min-h-screen flex flex-col items-center justify-center px-6 max-w-md mx-auto w-full text-center">
      <div className="pop-in">
        <div className="text-6xl mb-4">🎉</div>
        <h1 className="font-disp text-3xl bg-gradient-to-r from-cyan-300 to-blue-500 bg-clip-text text-transparent">WORKOUT COMPLETE</h1>
        <div className="font-disp text-6xl mt-6 tabular-nums">{t}</div>
        <div className="text-white/40 text-sm mt-2">{exCount} exercises · {setCount} sets completed</div>
      </div>
      <div className="w-full mt-12 fade-up" style={{ animationDelay: ".2s" }}>
        <div className="text-white/60 text-sm mb-4">How did it feel?</div>
        <div className="grid grid-cols-4 gap-2">
          {RATINGS.map(r => (
            <button key={r.id} onClick={() => onRate(r.id)}
              className={`${GLASS} rounded-2xl py-4 flex flex-col items-center gap-1.5 hover:!border-cyan-400/50 hover:!bg-cyan-400/10 active:scale-95 transition-all duration-200`}>
              <span className="text-2xl">{r.emoji}</span>
              <span className="text-[11px] text-white/60 font-semibold">{r.label}</span>
            </button>
          ))}
        </div>
        <div className="mt-8"><Btn variant="ghost" onClick={() => onRate("good")}>CONTINUE <Ico n="arrow" s={14} c="inline ml-1" /></Btn></div>
      </div>
    </div>
  );
}

/* ============ Screen 8 · AI Adaptation ============ */
function Adaptation({ rating, nextDay, onView }) {
  const reduce = rating === "hard" || rating === "veryhard";
  const msg = rating === "easy"
    ? "That felt easy — good sign. I've added a little intensity to tomorrow's session so you keep progressing."
    : rating === "good"
    ? "Great session. Tomorrow's plan stays on track — you're right where you should be."
    : rating === "veryhard"
    ? "Today was a big effort. I've replaced tomorrow's session with light recovery work so you come back stronger."
    : "Today's workout was harder than expected. I've adjusted tomorrow's session to reduce intensity and give you more recovery.";
  const type = reduce ? "Recovery + Mobility" : nextDay.type;
  const min = reduce ? Math.max(15, nextDay.minutes - 10) : rating === "easy" ? nextDay.minutes + 5 : nextDay.minutes;
  return (
    <div className="min-h-screen flex flex-col items-center justify-center px-6 max-w-md mx-auto w-full text-center">
      <div className="pop-in w-full">
        <div className="inline-flex items-center gap-2 text-cyan-300 text-[11px] tracking-[0.3em] font-bold mb-6">
          <Ico n="sparkles" s={15} /> FITPULSE COACH
        </div>
        <h1 className="font-disp text-3xl mb-3">Plan updated ✨</h1>
        <p className="text-white/60 text-[15px] leading-relaxed max-w-sm mx-auto">{msg}</p>

        <div className={`${GLASS} rounded-3xl p-5 mt-8 text-left max-w-sm mx-auto`}>
          <div className="text-[11px] tracking-[0.25em] text-white/35 font-bold mb-3">TOMORROW</div>
          <div className="font-disp text-xl">{type}</div>
          <div className="text-white/40 text-[13px] mt-1">{min} minutes · {reduce ? "Light, restorative movement" : rating === "easy" ? "A step up from today" : "Same objective, right intensity"}</div>
        </div>

        <div className="mt-8 max-w-sm mx-auto"><Btn onClick={onView}>VIEW UPDATED PLAN</Btn></div>
      </div>
    </div>
  );
}

/* ============ Screen 9 · Progress ============ */
function ProgressPage({ logs }) {
  const max = Math.max(...logs.week, 40);
  const days = ["M", "T", "W", "T", "F", "S", "S"];
  return (
    <div className="px-5 pt-6 pb-4 space-y-5 max-w-md mx-auto w-full">
      <h1 className="font-disp text-2xl">Your Progress</h1>

      <div className="grid grid-cols-3 gap-3">
        {[["WORKOUTS", logs.workouts], ["MINUTES", logs.minutes], ["CONSISTENCY", logs.consistency + "%"]].map(([l, v]) => (
          <div key={l} className={`${GLASS} rounded-2xl p-4 text-center`}>
            <div className="font-disp text-2xl text-cyan-300">{v}</div>
            <div className="text-[9px] tracking-[0.15em] text-white/35 font-bold mt-1">{l}</div>
          </div>
        ))}
      </div>

      <div className={`${GLASS} rounded-3xl p-5 flex items-center gap-4`}>
        <div className="w-12 h-12 rounded-2xl bg-gradient-to-br from-orange-400/30 to-red-500/30 border border-orange-400/30 flex items-center justify-center text-orange-300"><Ico n="flame" s={22} /></div>
        <div>
          <div className="text-[11px] tracking-[0.2em] text-white/35 font-bold">CURRENT STREAK</div>
          <div className="font-disp text-2xl">{logs.streak} days <span className="text-xl">🔥</span></div>
        </div>
      </div>

      <div className={`${GLASS} rounded-3xl p-5`}>
        <div className="text-[11px] tracking-[0.25em] text-white/35 font-bold mb-5">WEEKLY ACTIVITY</div>
        <div className="flex items-end justify-between gap-2 h-32">
          {logs.week.map((m, i) => (
            <div key={i} className="flex-1 flex flex-col items-center gap-2 h-full justify-end">
              <div className="w-full rounded-lg bg-gradient-to-t from-cyan-500/40 to-cyan-300/80 transition-all duration-700"
                style={{ height: m === 0 ? "4px" : `${Math.max(8, (m / max) * 100)}%`, opacity: m === 0 ? 0.25 : 1 }}
                title={m + " min"}></div>
              <span className="text-[9px] text-white/30 font-bold">{days[i]}</span>
            </div>
          ))}
        </div>
      </div>

      <div className={`${GLASS} rounded-3xl p-5 flex items-start gap-3`}>
        <span className="text-cyan-300 mt-0.5"><Ico n="sparkles" s={15} /></span>
        <div>
          <div className="text-[11px] tracking-[0.2em] text-white/35 font-bold mb-1">COACH INSIGHT</div>
          <p className="text-white/70 text-[13px] leading-relaxed">You're most consistent when your workouts are under 40 min. I'll keep sessions tight.</p>
        </div>
      </div>

      <button onClick={() => { store.clear(); location.reload(); }}
        className="w-full text-center text-white/25 text-[11px] py-3 hover:text-white/50 transition-colors">
        <Ico n="refresh" s={12} c="inline mr-1" /> Reset demo data
      </button>
    </div>
  );
}

/* ============ Screen 10 · Coach ============ */
function CoachPage() {
  const [msgs, setMsgs] = useState(() => store.get("coach", [
    { role: "coach", text: "Hey Michael 👋 I'm your FitPulse coach. Tell me how you're feeling, what life looks like today, and I'll adjust your plan in real time." },
  ]));
  const [input, setInput] = useState("");
  const [typing, setTyping] = useState(false);
  useEffect(() => { store.set("coach", msgs); }, [msgs]);

  const send = (text) => {
    const t = text.trim();
    if (!t || typing) return;
    setMsgs(m => [...m, { role: "user", text: t }]);
    setInput("");
    setTyping(true);
    setTimeout(() => {
      setTyping(false);
      setMsgs(m => [...m, { role: "coach", text: coachReply(t) }]);
    }, 1100);
  };

  return (
    <div className="flex flex-col h-[calc(100vh-76px)] max-w-md mx-auto w-full">
      <div className="px-5 pt-6 pb-3 flex items-center gap-3 border-b border-white/[0.07]">
        <div className="relative">
          <div className="w-10 h-10 rounded-full bg-gradient-to-br from-cyan-400 to-blue-600 flex items-center justify-center text-navy"><Ico n="sparkles" s={18} /></div>
          <span className="absolute -bottom-0.5 -right-0.5 w-3 h-3 rounded-full bg-emerald-400 border-2 border-navy"></span>
        </div>
        <div>
          <div className="font-disp font-bold">FITPULSE COACH</div>
          <div className="text-[11px] text-emerald-400/80 flex items-center gap-1.5"><span className="w-1.5 h-1.5 rounded-full bg-emerald-400 block"></span>Online</div>
        </div>
      </div>

      <div className="flex-1 overflow-y-auto px-5 py-4 space-y-3 no-scrollbar">
        {msgs.map((m, i) => (
          <div key={i} className={`flex ${m.role === "user" ? "justify-end" : "justify-start"} fade-up`}>
            <div className={`max-w-[80%] rounded-2xl px-4 py-3 text-[14px] leading-relaxed ${
              m.role === "user" ? "bg-gradient-to-br from-cyan-500 to-blue-600 text-white rounded-br-md" :
              GLASS + " rounded-bl-md"}`}>
              {m.text}
            </div>
          </div>
        ))}
        {typing && (
          <div className="flex justify-start"><div className={`${GLASS} rounded-2xl rounded-bl-md px-4 py-3 flex gap-1.5 items-center`}>
            <span className="w-1.5 h-1.5 rounded-full bg-cyan-300 dot1 block"></span>
            <span className="w-1.5 h-1.5 rounded-full bg-cyan-300 dot2 block"></span>
            <span className="w-1.5 h-1.5 rounded-full bg-cyan-300 dot3 block"></span>
          </div></div>
        )}
      </div>

      <div className="px-5 pb-2">
        <div className="flex gap-2 overflow-x-auto no-scrollbar pb-3">
          {["I'm tired", "I missed a workout", "No equipment today", "Make it shorter"].map(p => (
            <button key={p} onClick={() => send(p)}
              className="shrink-0 text-[12px] font-semibold px-3.5 py-2 rounded-full bg-white/[0.06] border border-white/10 text-white/70 hover:!border-cyan-400/40 hover:text-cyan-300 transition-all">
              {p}
            </button>
          ))}
        </div>
        <form onSubmit={(e) => { e.preventDefault(); send(input); }} className="flex items-center gap-2">
          <input value={input} onChange={e => setInput(e.target.value)} placeholder="Ask your coach..."
            className="flex-1 bg-white/[0.06] border border-white/10 rounded-2xl px-4 py-3.5 text-sm placeholder-white/30 outline-none focus:border-cyan-400/50 transition-colors" />
          <button type="submit" className="w-11 h-11 rounded-2xl bg-gradient-to-br from-cyan-400 to-blue-600 text-navy flex items-center justify-center shrink-0 active:scale-95 transition-transform">
            <Ico n="send" s={17} />
          </button>
        </form>
      </div>
    </div>
  );
}

/* ============ bottom navigation ============ */
function BottomNav({ tab, setTab }) {
  const items = [["home", "Home", "home"], ["plan", "Plan", "calendar"], ["progress", "Progress", "trending"], ["coach", "Coach", "chat"]];
  return (
    <div className="fixed bottom-0 left-1/2 -translate-x-1/2 w-full max-w-md px-4 pb-4 z-40">
      <div className={`${GLASS} rounded-3xl px-2 py-2 flex justify-around shadow-[0_20px_60px_-15px_rgba(0,0,0,.8)]`}>
        {items.map(([id, label, icon]) => (
          <button key={id} onClick={() => setTab(id)}
            className={`flex flex-col items-center gap-1 px-4 py-2 rounded-2xl transition-all duration-200 ${tab === id ? "text-cyan-300 bg-cyan-400/10" : "text-white/40 hover:text-white/70"}`}>
            <Ico n={icon} s={19} />
            <span className="text-[10px] font-semibold">{label}</span>
          </button>
        ))}
      </div>
    </div>
  );
}

/* ============ App ============ */
function App() {
  const [phase, setPhase] = useState(() => store.get("onboarded") ? "app" : "landing");
  const [user, setUser] = useState(() => store.get("user", null));
  const [plan, setPlan] = useState(() => store.get("plan", null));
  const [logs, setLogs] = useState(() => store.get("logs", null) || seedLogs());
  const [tab, setTab] = useState("home");
  const [flow, setFlow] = useState(null); // {stage:'workout'|'complete'|'adapt', dayIdx, elapsed, setCount, exCount, rating, nextIdx}

  useEffect(() => {
    if (user) store.set("user", user);
    if (plan) store.set("plan", plan);
    store.set("logs", logs);
    store.set("onboarded", phase === "app" && !!user);
  }, [user, plan, logs, phase]);

  const finishOnboarding = (u) => {
    setUser(u);
    setPlan(buildPlan(u));
    setPhase("generating");
  };
  const enterDemo = () => {
    if (!store.get("user")) {
      const u = { name: "Michael", goal: "strength", experience: "Beginner", days: 3, time: "30 min", location: "Home", equipment: "dumbbells" };
      setUser(u); setPlan(buildPlan(u));
    }
    setPhase("app"); setTab("home");
  };

  const openDay = (idx) => setFlow({ stage: "workout", dayIdx: idx });
  const startToday = () => {
    const idx = plan.findIndex(d => d.status === "today");
    openDay(idx >= 0 ? idx : plan.findIndex(d => d.status === "todo"));
  };

  const rate = (r) => {
    const f = flow;
    const p = plan.map(d => ({ ...d }));
    const todayIdx = f.dayIdx;
    p[todayIdx].status = "done";
    const nextIdx = p.findIndex((d, i) => i > todayIdx && d.status === "todo" && d.status !== "rest");
    if (nextIdx >= 0) {
      if (r === "hard" || r === "veryhard") { p[nextIdx].type = "Recovery + Mobility"; p[nextIdx].typeIdx = 4; p[nextIdx].minutes = Math.max(15, p[nextIdx].minutes - 10); }
      else if (r === "easy") { p[nextIdx].minutes = p[nextIdx].minutes + 5; }
    }
    setPlan(p);
    setLogs(l => ({
      ...l,
      workouts: l.workouts + 1,
      minutes: l.minutes + p[todayIdx].minutes,
      streak: l.streak + 1,
      week: l.week.map((v, i) => (i === (new Date().getDay() + 6) % 7 ? v + p[todayIdx].minutes : v)),
    }));
    setFlow({ ...f, stage: "adapt", rating: r, nextIdx: nextIdx >= 0 ? nextIdx : todayIdx });
  };

  /* ---- full-screen flows ---- */
  if (phase === "landing") return <Landing onBuild={() => setPhase("onboarding")} onExisting={enterDemo} />;
  if (phase === "onboarding") return <Onboarding onDone={finishOnboarding} onBack={() => setPhase("landing")} />;
  if (phase === "generating") return <PlanGeneration onDone={() => setPhase("app")} />;
  if (flow?.stage === "workout") {
    const day = plan[flow.dayIdx];
    return <WorkoutPlayer day={day} eq={user.equipment}
      onExit={() => setFlow(null)}
      onFinish={(elapsed, setCount, exCount) => setFlow({ ...flow, stage: "complete", elapsed, setCount, exCount })} />;
  }
  if (flow?.stage === "complete") {
    return <WorkoutComplete elapsed={flow.elapsed} exCount={flow.exCount} setCount={flow.setCount} onRate={rate} />;
  }
  if (flow?.stage === "adapt") {
    return <Adaptation rating={flow.rating} nextDay={plan[flow.nextIdx]} onView={() => { setTab("plan"); setFlow(null); }} />;
  }

  /* ---- tabbed app ---- */
  return (
    <div className="min-h-screen pb-28">
      {tab === "home" && <Home user={user} plan={plan} onStart={startToday} goTab={setTab} />}
      {tab === "plan" && <PlanPage plan={plan} onOpenDay={openDay} />}
      {tab === "progress" && <ProgressPage logs={logs} />}
      {tab === "coach" && <CoachPage />}
      {tab !== "coach" && <BottomNav tab={tab} setTab={setTab} />}
      {tab === "coach" && (
        <div className="fixed bottom-0 left-1/2 -translate-x-1/2 w-full max-w-md px-4 pb-4 z-40">
          <div className={`${GLASS} rounded-3xl px-2 py-2 flex justify-around`}>
            {[["home", "Home", "home"], ["plan", "Plan", "calendar"], ["progress", "Progress", "trending"], ["coach", "Coach", "chat"]].map(([id, label, icon]) => (
              <button key={id} onClick={() => setTab(id)}
                className={`flex flex-col items-center gap-1 px-4 py-2 rounded-2xl transition-all ${tab === id ? "text-cyan-300 bg-cyan-400/10" : "text-white/40 hover:text-white/70"}`}>
                <Ico n={icon} s={19} /><span className="text-[10px] font-semibold">{label}</span>
              </button>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);