// LAZY LEGEND — main app
// Screens: start → selector → workout → complete

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

// ---- Storage helpers ----
const STORAGE_KEY = "lazy_legend_state_v1";
const loadState = () => {
  try { return JSON.parse(localStorage.getItem(STORAGE_KEY)) || {}; }
  catch { return {}; }
};
const saveState = (s) => { try { localStorage.setItem(STORAGE_KEY, JSON.stringify(s)); } catch {} };

// ---- Workout generator ----
function generateWorkout(levelKey) {
  const lvl = LEVELS[levelKey];
  const pool = EXERCISES.filter((e) => lvl.pool.includes(e.tier));
  // Shuffle
  const shuffled = [...pool].sort(() => Math.random() - 0.5);
  // Pick first N moves; ensure each move duration averages to fit minutes.
  const moves = shuffled.slice(0, lvl.moves).map((m) => ({ ...m }));
  // Total work seconds available
  const totalSec = lvl.minutes * 60;
  // Subtract rest gaps (5s between moves, but not after last)
  const restSec = (moves.length - 1) * 5;
  let workSec = totalSec - restSec;
  // Distribute time per move using each move's natural duration as a weight
  const weights = moves.map((m) => m.time || 30);
  const wSum = weights.reduce((a, b) => a + b, 0);
  moves.forEach((m, i) => {
    const t = Math.max(15, Math.round((weights[i] / wSum) * workSec));
    m.duration = t;
  });
  // Fix off-by-one to match exact total
  const used = moves.reduce((a, m) => a + m.duration, 0);
  const diff = workSec - used;
  if (diff !== 0) moves[0].duration += diff;
  return {
    name: WORKOUT_NAMES[Math.floor(Math.random() * WORKOUT_NAMES.length)],
    levelKey,
    moves,
    totalSec,
  };
}

// ============================================================
// START SCREEN
// ============================================================
function StartScreen({ onStart, total }) {
  const benefits = [
    { icon: "brain", h: "INSTANT MOOD BOOST", b: "Even 5 minutes of movement releases endorphins. You'll feel better. Science says so." },
    { icon: "bolt",  h: "MORE ENERGY, NOT LESS", b: "Sounds backwards but moving more = feeling less tired. Your body wakes up." },
    { icon: "moon",  h: "BETTER SLEEP", b: "Daily movement = deeper sleep. You'll actually wake up rested instead of foggy." },
    { icon: "heart", h: "STRONGER HEART", b: "Bodyweight workouts add years to your life and life to your years. Free upgrade." },
    { icon: "spark", h: "SHARPER FOCUS", b: "Exercise grows your brain, literally. Better memory, better focus, better output." },
    { icon: "flame", h: "BUILDS THE HABIT", b: "5 minutes today = 10 mins tomorrow = a full life upgrade. Each one makes the next easier." },
  ];
  return (
    <div className="screen start screen-enter">
      <div className="topbar">
        <div className="left"><span className="dot" /><span className="logo">LAZY LEGEND</span></div>
        <div>FITNESS, KIND OF</div>
      </div>
      <div className="wrap">
        <h1 className="title">LAZY<br />LEGEND</h1>
        <p className="subtitle">Workouts for people who'd rather not.</p>
        <div className="mascot-stage"><FlexMascot size={260} expression="curl" /></div>
        <button className="chunky" onClick={() => { sfx.start(); onStart(); }}>START</button>
        <div style={{ marginTop: 18, fontFamily: "var(--mono)", fontSize: 12, letterSpacing: "0.22em", color: "var(--ink-mute)", textTransform: "uppercase" }}>
          ↓ SCROLL FOR WHY YOU SHOULD ↓
        </div>
      </div>

      <section className="benefits">
        <div className="mascot-corner">
          <FlexMascot size={140} expression="proud" />
          <div className="thumbs">▲ THUMBS UP</div>
        </div>
        <div className="head">
          <div className="eyebrow">— THE PEP TALK —</div>
          <h2>WHY EVEN <span className="lime">BOTHER?</span></h2>
        </div>
        <div className="grid">
          {benefits.map((b) => (
            <div className="b-card" key={b.h} onMouseEnter={() => sfx.click()}>
              <BenefitIcon name={b.icon} />
              <div className="b-headline">{b.h}</div>
              <div className="b-body">{b.b}</div>
            </div>
          ))}
        </div>
        <div className="tagline">
          Lazy Legend = <span className="lime">bare minimum effort</span>, maximum gains. No gym needed.
        </div>
      </section>

      <div className="footer">
        <span>WORKOUTS COMPLETED · <b>{String(total).padStart(2, "0")}</b></span>
        <span>v1.0 · NO PLANS · NO STREAKS</span>
      </div>
    </div>
  );
}

// Tiny icon set for benefit cards
function BenefitIcon({ name }) {
  const common = { className: "b-icon", viewBox: "0 0 64 64", fill: "none", stroke: "currentColor", strokeWidth: 3, strokeLinecap: "round", strokeLinejoin: "round" };
  switch (name) {
    case "brain":
      return (
        <svg {...common}>
          <path d="M22 16c-5 0-9 4-9 9 0 2 1 4 2 5-2 1-3 4-3 6 0 4 3 7 7 7 1 3 4 5 7 5h6V14h-6c-2 0-4 1-4 2z"/>
          <path d="M42 16c5 0 9 4 9 9 0 2-1 4-2 5 2 1 3 4 3 6 0 4-3 7-7 7-1 3-4 5-7 5"/>
          <path d="M32 14v34" />
          <path d="M22 28h6M36 28h6M22 36h6M36 36h6" />
        </svg>
      );
    case "bolt":
      return (
        <svg {...common}>
          <path d="M36 6 L18 36 H30 L26 58 L46 26 H32 L36 6 Z" fill="currentColor" stroke="currentColor" />
        </svg>
      );
    case "moon":
      return (
        <svg {...common}>
          <path d="M44 38a18 18 0 1 1-18-30 14 14 0 0 0 18 30z" fill="currentColor" stroke="currentColor" />
          <circle cx="48" cy="14" r="2" fill="currentColor" />
          <circle cx="54" cy="22" r="1.5" fill="currentColor" />
        </svg>
      );
    case "heart":
      return (
        <svg {...common}>
          <path d="M32 54 L10 32 a10 10 0 0 1 14-14 l8 8 8-8 a10 10 0 0 1 14 14 z" fill="currentColor" stroke="currentColor" />
          <path d="M14 30 H22 L26 24 L30 36 L34 28 H50" stroke="#0B0B0D" strokeWidth="2.5" fill="none" />
        </svg>
      );
    case "spark":
      return (
        <svg {...common}>
          <path d="M32 6 L36 26 L56 32 L36 38 L32 58 L28 38 L8 32 L28 26 Z" fill="currentColor" stroke="currentColor" />
        </svg>
      );
    case "flame":
      return (
        <svg {...common}>
          <path d="M32 58 c-10 0-16-7-16-15 0-7 6-12 8-18 1-4 0-9 0-13 6 4 12 11 12 17 4-2 6-6 6-10 6 6 10 14 10 22 0 11-8 17-20 17z" fill="currentColor" stroke="currentColor" />
        </svg>
      );
    default: return <svg {...common}><circle cx="32" cy="32" r="24" /></svg>;
  }
}

// ============================================================
// SELECTOR SCREEN
// ============================================================
function SelectorScreen({ onPick, onBack }) {
  const order = ["barely", "meh", "bothered", "unhinged"];
  const sampleAnims = { barely: "armCircles", meh: "jumpingJacks", bothered: "squat", unhinged: "burpee" };
  return (
    <div className="screen selector screen-enter">
      <div className="topbar">
        <div className="left"><span className="dot" /><span className="logo">LAZY LEGEND</span></div>
        <button className="back-btn" onClick={() => { sfx.click(); onBack(); }}>← BACK</button>
      </div>
      <div className="header">
        <h1>How lazy are you right now? <span className="pink">Be honest.</span></h1>
        <div className="sub">Pick a card. We'll do the rest. Mostly.</div>
      </div>
      <div className="cards">
        {order.map((k) => {
          const lvl = LEVELS[k];
          return (
            <div
              key={k}
              className="lz-card"
              onClick={() => { sfx.thunder(); onPick(k); }}
              onMouseEnter={() => sfx.click()}
            >
              <div className="lz-meta">
                <span className="lz-time">{lvl.minutes} MIN</span>
                <span className="lz-bolts">
                  {[1, 2, 3, 4].map((i) => <Bolt key={i} filled={i <= lvl.bolts} size={16} />)}
                </span>
              </div>
              <div className="lz-name">{lvl.label}</div>
              <div className="lz-blurb">{lvl.blurb}</div>
              <div className="lz-figure">
                <Figure anim={sampleAnims[k]} pose={figurePose(sampleAnims[k])} />
              </div>
              <div className="lz-foot">
                <span>{lvl.moves} MOVES</span>
                <span>SHUFFLED</span>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ============================================================
// WORKOUT SCREEN
// ============================================================
function WorkoutScreen({ workout, onComplete, onBack }) {
  const [moveIdx, setMoveIdx] = useState(0);
  const [secondsLeft, setSecondsLeft] = useState(workout.moves[0].duration);
  const [paused, setPaused] = useState(false);
  const [resting, setResting] = useState(false);
  const [restLeft, setRestLeft] = useState(0);
  const [shout, setShout] = useState(null);
  const [totalRemaining, setTotalRemaining] = useState(() => {
    const moveSum = workout.moves.reduce((a, m) => a + m.duration, 0);
    const restSum = (workout.moves.length - 1) * 5;
    return moveSum + restSum;
  });

  const move = workout.moves[moveIdx];
  const tier = move.tier;

  // Random shout occasionally
  useEffect(() => {
    if (paused || resting) return;
    const t = setInterval(() => {
      if (Math.random() < 0.55) {
        const s = SHOUTS[Math.floor(Math.random() * SHOUTS.length)];
        setShout(s);
        setTimeout(() => setShout(null), 2400);
      }
    }, 7000);
    return () => clearInterval(t);
  }, [paused, resting, moveIdx]);

  // Main timer
  useEffect(() => {
    if (paused) return;
    const t = setInterval(() => {
      if (resting) {
        setRestLeft((r) => {
          if (r <= 1) {
            setResting(false);
            sfx.start();
            return 0;
          }
          if (r <= 4) sfx.beep();
          return r - 1;
        });
        setTotalRemaining((x) => Math.max(0, x - 1));
      } else {
        setSecondsLeft((s) => {
          if (s <= 1) {
            // Move complete
            sfx.ding();
            const next = moveIdx + 1;
            if (next >= workout.moves.length) {
              // Workout done
              setTimeout(() => onComplete(), 600);
              return 0;
            }
            // Start rest
            setResting(true);
            setRestLeft(5);
            setMoveIdx(next);
            return workout.moves[next].duration;
          }
          if (s <= 4) sfx.beep();
          return s - 1;
        });
        setTotalRemaining((x) => Math.max(0, x - 1));
      }
    }, 1000);
    return () => clearInterval(t);
  }, [paused, resting, moveIdx, onComplete, workout]);

  const onSkip = () => {
    sfx.click();
    if (resting) {
      setResting(false);
      setRestLeft(0);
      return;
    }
    const next = moveIdx + 1;
    if (next >= workout.moves.length) { onComplete(); return; }
    setResting(true);
    setRestLeft(5);
    setMoveIdx(next);
    setSecondsLeft(workout.moves[next].duration);
  };
  const onPause = () => { sfx.click(); setPaused((p) => !p); };
  const onEnd = () => { sfx.click(); onComplete(true); };

  // Timer ring math
  const total = move.duration;
  const pct = total > 0 ? secondsLeft / total : 0;
  const R = 96;
  const C = 2 * Math.PI * R;
  const offset = C * (1 - pct);
  const urgent = !resting && secondsLeft <= 3;

  const formatTotal = (s) => {
    const m = Math.floor(s / 60);
    const r = s % 60;
    return `${m}:${String(r).padStart(2, "0")}`;
  };
  const targetText = move.reps ? `${move.reps} REPS` : `${move.duration}S`;

  return (
    <div className="screen workout screen-enter">
      <div className="top">
        <div className="name">{workout.name}</div>
        <div className="center">
          MOVE {String(moveIdx + 1).padStart(2, "0")} / {String(workout.moves.length).padStart(2, "0")}
        </div>
        <div className="right">
          <span>TIME LEFT · </span>{formatTotal(totalRemaining)}
        </div>
      </div>

      <div className="body">
        <div className="stage-l">
          <div className={`tier-pill tier-${tier}`}>{tier.toUpperCase()}</div>
          <Figure anim={move.anim} pose={figurePose(move.anim)} />
          <div className="floor" />
          {shout && !resting && (
            <div className={`shout visible`}>{shout}</div>
          )}
        </div>

        <div className="stage-r">
          <h2 className="move-name">{move.name.toUpperCase()}</h2>
          <p className="move-instruction">{move.instruction}</p>
          <div className="move-target">{targetText}</div>

          <div className={`timer-wrap ${urgent ? "urgent" : ""}`}>
            <svg viewBox="0 0 220 220">
              <circle className="ring-bg" cx="110" cy="110" r={R} fill="none" strokeWidth="14" />
              <circle
                className="ring-fg"
                cx="110" cy="110" r={R}
                fill="none"
                strokeWidth="14"
                strokeDasharray={C}
                strokeDashoffset={offset}
                strokeLinecap="round"
              />
            </svg>
            <div className="num">{secondsLeft}</div>
          </div>
        </div>
      </div>

      <div className="controls">
        <button className="chunky btn-sm ghost" onClick={onPause}>{paused ? "RESUME" : "PAUSE"}</button>
        <button className="chunky btn-sm" onClick={onSkip}>SKIP</button>
        <button className="chunky btn-sm pink" onClick={onEnd}>END EARLY</button>
        <button className="back-btn" onClick={() => { sfx.click(); onBack(); }}>← LEAVE</button>
      </div>

      {resting && (
        <div className="rest-overlay">
          <div className="word">REST</div>
          <div className="next">UP NEXT · <b>{workout.moves[moveIdx].name}</b></div>
          <div className="countdown">{restLeft}</div>
        </div>
      )}
      {paused && !resting && (
        <div className="rest-overlay">
          <div className="word" style={{ color: "var(--lime)" }}>PAUSED</div>
          <div className="next">CLICK RESUME WHEN READY</div>
        </div>
      )}
    </div>
  );
}

// ============================================================
// COMPLETION SCREEN
// ============================================================
function CompleteScreen({ workout, endedEarly, onAnother, onHome }) {
  useEffect(() => { sfx.finish(); }, []);
  const lvl = LEVELS[workout.levelKey];
  const minutes = endedEarly ? Math.max(1, Math.round(lvl.minutes * 0.6)) : lvl.minutes;
  const kcal = Math.round(minutes * KCAL_PER_MIN[workout.levelKey]);
  const titlePool = ACHIEVEMENTS[workout.levelKey];
  const title = titlePool[Math.floor(Math.random() * titlePool.length)];
  const [meterFill, setMeterFill] = useState(0);
  useEffect(() => {
    const t = setTimeout(() => setMeterFill(endedEarly ? 65 : 100), 200);
    return () => clearTimeout(t);
  }, []);
  return (
    <div className="screen complete screen-enter">
      <ConfettiBurst count={70} />
      <div className="topbar">
        <div className="left"><span className="dot" /><span className="logo">LAZY LEGEND</span></div>
        <div>{endedEarly ? "ENDED EARLY · STILL COUNTS" : "MISSION ACCOMPLISHED"}</div>
      </div>
      <div className="inner">
        <FlexMascot size={170} expression="dance" />
        <h1 className="you-finished">{endedEarly ? "GOOD ENOUGH" : "YOU FINISHED"}</h1>
        <div className="achievement">ACHIEVEMENT · {title.toUpperCase()}</div>

        <div className="stats">
          <div>
            <div className="stat-v">{minutes}:00</div>
            <div className="stat-l">TOTAL TIME</div>
          </div>
          <div>
            <div className="stat-v">~{kcal}</div>
            <div className="stat-l">KCAL BURNED</div>
          </div>
          <div>
            <div className="stat-v">+1</div>
            <div className="stat-l">LEGEND POINT</div>
          </div>
        </div>

        <div className="meter">
          <div className="lbl"><span>LAZINESS DEFEATED</span><span>{meterFill}%</span></div>
          <div className="bar"><div className="fill" style={{ width: `${meterFill}%` }} /></div>
        </div>

        <div className="actions">
          <button className="chunky" onClick={() => { sfx.start(); onAnother(); }}>ANOTHER ONE</button>
          <button className="chunky ghost" onClick={() => { sfx.click(); onHome(); }}>BACK TO START</button>
        </div>
      </div>
    </div>
  );
}

// ============================================================
// APP SHELL
// ============================================================
function App() {
  const [route, setRoute] = useState("start"); // start | selector | workout | complete
  const [workout, setWorkout] = useState(null);
  const [endedEarly, setEndedEarly] = useState(false);
  const [total, setTotal] = useState(() => loadState().total || 0);

  // Persist counter
  useEffect(() => { saveState({ total }); }, [total]);

  const goStart = () => setRoute("start");
  const goSelector = () => setRoute("selector");
  const startLevel = (key) => {
    const w = generateWorkout(key);
    setWorkout(w);
    setEndedEarly(false);
    setRoute("workout");
  };
  const finish = (early = false) => {
    setEndedEarly(early);
    setTotal((t) => t + (early ? 0 : 1));
    setRoute("complete");
  };
  const another = () => {
    if (!workout) { goSelector(); return; }
    const w = generateWorkout(workout.levelKey);
    setWorkout(w);
    setEndedEarly(false);
    setRoute("workout");
  };

  return (
    <>
      <div className="grain" />
      <div className="vignette" />
      {route === "start"    && <StartScreen onStart={goSelector} total={total} />}
      {route === "selector" && <SelectorScreen onPick={startLevel} onBack={goStart} />}
      {route === "workout"  && workout && (
        <WorkoutScreen
          key={workout.name + workout.moves[0].key}
          workout={workout}
          onComplete={finish}
          onBack={goStart}
        />
      )}
      {route === "complete" && workout && (
        <CompleteScreen
          workout={workout}
          endedEarly={endedEarly}
          onAnother={another}
          onHome={goStart}
        />
      )}
    </>
  );
}

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