Skip to content
VibeCodeBench
Back to the app

The code

Why the Moon Has Phases by Claude Opus 5.5

Exactly as the AI wrote it. Shown as text, so nothing runs on this page.

Try 1 · index.html

worksshown54.7 KB · 863 lines · no libraries
Download
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>Why Does the Moon Have Phases?</title>
<style>
:root{
  --bg:#070b18; --panel:#10172c; --panel2:#18213d; --line:#2a3560; --text:#eef1fb; --muted:#a9b3d6;
  --sun:#ffcf5a; --sky:#5fd3ff; --good:#5be3a0; --bad:#ff7d7d; --you:#ff9f43;
}
*{box-sizing:border-box}
html,body{margin:0;background:var(--bg);color:var(--text);font-family:system-ui,-apple-system,"Segoe UI",Roboto,Ubuntu,"Helvetica Neue",Arial,sans-serif;-webkit-text-size-adjust:100%}
body{min-height:100vh;display:flex;flex-direction:column}
button{font:inherit;color:inherit}
header{display:flex;align-items:center;gap:8px;padding:10px 16px;flex-wrap:wrap}
header h1{font-size:clamp(18px,2.3vw,24px);margin:0;flex:1 1 220px;letter-spacing:.2px;line-height:1.2}
header h1 span{color:var(--sun)}
.btn{min-height:44px;min-width:44px;padding:0 14px;border-radius:12px;border:1px solid var(--line);background:var(--panel2);cursor:pointer;display:inline-flex;align-items:center;justify-content:center;gap:8px;font-weight:650;font-size:15px;touch-action:manipulation;user-select:none;-webkit-user-select:none;-webkit-tap-highlight-color:transparent}
.btn:active{transform:translateY(1px)}
.btn.primary{background:var(--sun);color:#221800;border-color:transparent}
.btn.ghost{background:transparent;border-color:transparent;color:var(--muted)}
.btn.small{font-size:14px;font-weight:600}
.btn:disabled{opacity:.4;cursor:default}
.btn:focus-visible,.switch:focus-visible,#scrub:focus-visible,.tick:focus-visible,.opt:focus-visible{outline:3px solid var(--sky);outline-offset:2px}
.icon{width:20px;height:20px;flex:none}
main{flex:1;display:grid;gap:12px;padding:0 16px 16px;grid-template-columns:minmax(0,1fr);min-height:0}
.card{background:var(--panel);border:1px solid var(--line);border-radius:18px}
.view{position:relative;overflow:hidden}
.view canvas{position:absolute;inset:0;width:100%;height:100%;display:block}
#orbitPanel{height:min(96vw,460px)}
#orbitCv{touch-action:none;cursor:grab}
.vlabel{position:absolute;left:10px;top:8px;font-size:11px;font-weight:750;letter-spacing:.6px;text-transform:uppercase;color:var(--muted);background:rgba(7,11,24,.66);padding:5px 8px;border-radius:8px;pointer-events:none;max-width:calc(100% - 20px)}
.vlabel.r{left:auto;right:10px}
.legend{position:absolute;left:10px;bottom:8px;display:flex;flex-wrap:wrap;gap:4px 10px;font-size:12px;color:var(--text);background:rgba(7,11,24,.66);padding:5px 9px;border-radius:8px;pointer-events:none;max-width:calc(100% - 20px)}
.legend i{display:inline-block;width:14px;height:4px;border-radius:2px;vertical-align:middle;margin-right:5px}
.lg-sun{background:var(--sun)} .lg-face{background:var(--sky)} .lg-you{background:var(--you)}
#moonPanel{display:flex;flex-direction:column;overflow:hidden}
#moonView{height:240px;flex:none}
#eclBadge{position:absolute;left:50%;bottom:10px;transform:translateX(-50%);background:rgba(150,40,20,.85);color:#fff;font-weight:750;font-size:13px;padding:5px 10px;border-radius:999px;pointer-events:none;white-space:nowrap}
#eclBadge[hidden]{display:none}
.readout{padding:12px 14px 14px}
.readout p{margin:0 0 6px;line-height:1.45}
#phaseName{font-size:clamp(22px,2.8vw,30px);font-weight:850;margin:0 0 2px;color:#fff}
.meta{color:var(--muted);font-size:14px}
.when{font-size:14px;color:#cfe7ff}
.snote{font-size:14px;padding:8px 10px;border-radius:10px;background:rgba(95,211,255,.08);border:1px solid rgba(95,211,255,.3)}
.snote.ecl{background:rgba(200,70,40,.14);border-color:rgba(255,120,90,.45)}
.snote[hidden]{display:none}
#scrubPanel{padding:10px 12px}
.scrubgrid{display:grid;gap:8px;align-items:center;grid-template-columns:auto auto minmax(0,1fr) auto;grid-template-areas:"scrub scrub scrub scrub" "play prev day next" "ticks ticks ticks ticks"}
#playBtn{grid-area:play;min-width:96px}
#prevDay{grid-area:prev}
#nextDay{grid-area:next}
#dayChip{grid-area:day;text-align:center;font-weight:700;color:var(--muted);font-size:14px}
#scrub{grid-area:scrub;position:relative;height:52px;touch-action:none;cursor:pointer;border-radius:12px}
.rail{position:absolute;left:24px;right:24px;top:0;bottom:0}
.track{position:absolute;left:0;right:0;top:21px;height:10px;border-radius:5px;background:linear-gradient(90deg,#1c2444 0%,#8d8a7c 25%,#f3eedc 50%,#8d8a7c 75%,#1c2444 100%);box-shadow:inset 0 0 0 1px rgba(255,255,255,.14)}
.thumb{position:absolute;top:4px;width:44px;height:44px;margin-left:-22px;border-radius:50%;background:#0d1328;border:3px solid var(--sun);box-shadow:0 2px 10px rgba(0,0,0,.55);display:flex;align-items:center;justify-content:center;pointer-events:none}
.thumb svg{display:block}
.ticks{grid-area:ticks}
.tickrail{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:6px}
.tick{min-height:44px;display:flex;align-items:center;gap:6px;padding:4px 6px;border-radius:10px;border:1px solid var(--line);background:transparent;cursor:pointer;font-size:12px;line-height:1.15;color:var(--muted);text-align:left;touch-action:manipulation;-webkit-tap-highlight-color:transparent}
.tick svg{flex:none}
.tick.on{border-color:var(--sun);color:#fff;background:rgba(255,207,90,.1)}
.tick.tick-end{display:none}
#side{display:flex;flex-direction:column;gap:12px;min-height:0}
#guide{padding:16px}
#guide h2{font-size:20px;margin:2px 0 8px;line-height:1.25}
#guide p{line-height:1.5;margin:0 0 10px}
.kicker{font-size:12px;text-transform:uppercase;letter-spacing:.7px;color:var(--sun);font-weight:800;margin:0 0 4px!important}
.dots{display:flex;gap:6px;margin-bottom:10px}
.dot{width:26px;height:6px;border-radius:3px;background:#2a3358}
.dot.done{background:#7d6a2d}
.dot.on{background:var(--sun)}
.try{background:rgba(95,211,255,.08);border-left:4px solid var(--sky);padding:8px 10px;border-radius:8px}
.navrow{display:flex;gap:8px;flex-wrap:wrap;margin-top:12px}
.navrow .btn{flex:1 1 120px}
.extra{margin:4px 0 6px}
.tips{margin:0 0 10px;padding-left:20px;line-height:1.5}
.words{font-size:14px;color:var(--muted)}
.opts{display:flex;flex-direction:column;gap:8px;margin:8px 0}
.opt{min-height:48px;padding:10px 12px;border-radius:12px;border:1px solid var(--line);background:var(--panel2);text-align:left;cursor:pointer;line-height:1.35;font-size:15px;touch-action:manipulation}
.opt:disabled{cursor:default;opacity:.65}
.opt.right{border-color:var(--good);background:rgba(91,227,160,.14);opacity:1}
.opt.wrong{border-color:var(--bad);background:rgba(255,125,125,.14);opacity:1}
.fb{padding:10px 12px;border-radius:12px;line-height:1.45;font-size:15px}
.fb.ok{background:rgba(91,227,160,.12);border:1px solid rgba(91,227,160,.5)}
.fb.no{background:rgba(255,125,125,.1);border:1px solid rgba(255,125,125,.45)}
.bigscore{font-size:44px;font-weight:900;color:var(--sun);margin:4px 0}
#switchCard{padding:14px 16px;display:flex;flex-direction:column;gap:10px}
#switchCard h2{font-size:14px;text-transform:uppercase;letter-spacing:.7px;color:var(--muted);margin:0}
.switch{display:flex;align-items:center;justify-content:space-between;gap:12px;width:100%;min-height:56px;padding:8px 12px;border-radius:14px;border:1px solid var(--line);background:var(--panel2);cursor:pointer;text-align:left;touch-action:manipulation;-webkit-tap-highlight-color:transparent}
.swtext{display:flex;flex-direction:column}
.swname{font-weight:750;display:flex;align-items:center;gap:6px}
.swval{font-size:13px;color:var(--muted)}
.swtrack{position:relative;width:54px;height:30px;border-radius:15px;background:#2a3358;flex:none;transition:background .2s}
.swknob{position:absolute;top:3px;left:3px;width:24px;height:24px;border-radius:50%;background:#fff;transition:transform .2s}
.switch[aria-checked="true"] .swtrack{background:var(--sky)}
.switch[aria-checked="true"] .swknob{transform:translateX(24px)}
.switch:disabled{opacity:.45;cursor:not-allowed}
.lock{display:none;width:14px;height:14px}
.switch:disabled .lock{display:inline-block}
.switch.pulse{animation:pulse 1.4s ease-in-out infinite}
@keyframes pulse{0%,100%{box-shadow:0 0 0 0 rgba(95,211,255,0)}50%{box-shadow:0 0 0 5px rgba(95,211,255,.45)}}
.lockmsg{font-size:13px;color:var(--muted);margin:0}
#toast{position:fixed;left:50%;bottom:22px;transform:translate(-50%,20px);background:#1d2a52;border:1px solid var(--sun);color:#fff;padding:12px 16px;border-radius:14px;font-weight:700;opacity:0;pointer-events:none;transition:opacity .25s,transform .25s;z-index:900;max-width:calc(100% - 32px);text-align:center}
#toast.show{opacity:1;transform:translate(-50%,0)}
#demoBanner{position:fixed;top:8px;left:50%;transform:translateX(-50%);z-index:950;background:rgba(255,207,90,.95);color:#221800;font-weight:800;font-size:13px;padding:6px 12px;border-radius:999px;pointer-events:none;white-space:nowrap}
#demoBanner[hidden],#demoPtr[hidden]{display:none}
#demoPtr{position:fixed;left:0;top:0;z-index:1000;pointer-events:none;width:30px;height:30px;transition:none}
#demoPtr svg{transition:transform .12s;transform-origin:3px 3px}
#demoPtr.down svg{transform:scale(.85)}
.ripple{position:fixed;width:46px;height:46px;margin:-23px 0 0 -23px;border-radius:50%;border:3px solid var(--sky);pointer-events:none;z-index:999;animation:rip .5s ease-out forwards}
@keyframes rip{from{transform:scale(.3);opacity:1}to{transform:scale(1.4);opacity:0}}

@media (min-width:700px){
  main{grid-template-columns:minmax(0,1.15fr) minmax(0,1fr)}
  #orbitPanel{height:min(62vh,540px)}
  #moonView{flex:1 1 auto;height:auto;min-height:190px}
  #scrubPanel{grid-column:1/-1}
  #side{grid-column:1/-1;display:grid;grid-template-columns:minmax(0,1.5fr) minmax(0,1fr);align-items:start}
  .scrubgrid{grid-template-columns:auto auto minmax(0,1fr) auto;grid-template-areas:"play prev scrub next" ". . ticks ."}
  #dayChip{display:none}
  .ticks{padding:0 24px}
  .tickrail{display:block;position:relative;height:60px}
  .tick{position:absolute;top:0;left:calc(var(--f) * 100%);transform:translateX(-50%);width:54px;min-height:58px;flex-direction:column;justify-content:flex-start;gap:3px;padding:4px 2px;font-size:10.5px;text-align:center;border-color:transparent}
  .tick.tick-end{display:flex}
}
@media (min-width:1080px) and (min-height:620px){
  body{height:100vh;overflow:hidden}
  main{grid-template-columns:minmax(0,1.2fr) minmax(0,1fr) 360px;grid-template-rows:minmax(0,1fr) auto}
  #orbitPanel{grid-column:1;grid-row:1;height:auto;min-height:0}
  #moonPanel{grid-column:2;grid-row:1;min-height:0}
  #scrubPanel{grid-column:1/3;grid-row:2}
  #side{grid-column:3;grid-row:1/3;display:flex;flex-direction:column;overflow:auto;padding-bottom:4px}
}
</style>
</head>
<body>
<header>
  <h1>Why does the Moon have <span>phases</span>?</h1>
  <button class="btn" id="muteBtn" aria-pressed="false"></button>
  <button class="btn" id="restartBtn" aria-label="Restart from the beginning">
    <svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 12a9 9 0 1 0 3-6.7"/><path d="M3 4v5h5"/></svg><span>Restart</span>
  </button>
</header>
<main>
  <section id="orbitPanel" class="card view" aria-label="Top-down orbit diagram. Drag the Moon to move it around Earth.">
    <canvas id="orbitCv"></canvas>
    <span class="vlabel">Top view from above the North Pole (not to scale)</span>
    <div class="legend"><span><i class="lg-sun"></i>Sunlit half</span><span id="lgFace"><i class="lg-face"></i>Half facing Earth</span><span><i class="lg-you"></i>You</span></div>
  </section>

  <section id="moonPanel" class="card">
    <div id="moonView" class="view">
      <canvas id="moonCv"></canvas>
      <span class="vlabel">What you see from Earth</span>
      <span class="vlabel r" id="hemiChip">Northern Hemisphere</span>
      <div id="eclBadge" hidden>Lunar eclipse!</div>
    </div>
    <div class="readout">
      <p id="phaseName" aria-live="polite">Waxing crescent</p>
      <p class="meta"><span id="dayTxt"></span> &middot; <span id="illumTxt"></span></p>
      <p id="noteTxt"></p>
      <p id="whenTxt" class="when"></p>
      <p id="shadowNote" class="snote" hidden></p>
    </div>
  </section>

  <section id="scrubPanel" class="card" aria-label="Timeline: one lunar month">
    <div class="scrubgrid">
      <button class="btn" id="playBtn"></button>
      <button class="btn" id="prevDay" aria-label="Back one day">&minus;1 day</button>
      <div id="scrub" role="slider" tabindex="0" aria-label="Day of the lunar month" aria-valuemin="0" aria-valuemax="29.5" aria-valuenow="0">
        <div class="rail" id="rail"><div class="track"></div><div class="thumb" id="thumb"></div></div>
      </div>
      <button class="btn" id="nextDay" aria-label="Forward one day">+1 day</button>
      <span id="dayChip"></span>
      <div class="ticks"><div class="tickrail" id="ticks"></div></div>
    </div>
  </section>

  <aside id="side">
    <section id="guide" class="card"><div id="guideBody"></div></section>
    <section id="switchCard" class="card">
      <h2>Switches</h2>
      <button class="switch" id="hemiSw" role="switch" aria-checked="false">
        <span class="swtext"><span class="swname"><svg class="lock" viewBox="0 0 24 24" fill="currentColor"><path d="M7 10V7a5 5 0 0 1 10 0v3h1a1 1 0 0 1 1 1v10a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V11a1 1 0 0 1 1-1h1zm2 0h6V7a3 3 0 0 0-6 0v3z"/></svg>Hemisphere</span><span class="swval" id="hemiVal">North</span></span>
        <span class="swtrack"><span class="swknob"></span></span>
      </button>
      <button class="switch" id="shadowSw" role="switch" aria-checked="false">
        <span class="swtext"><span class="swname"><svg class="lock" viewBox="0 0 24 24" fill="currentColor"><path d="M7 10V7a5 5 0 0 1 10 0v3h1a1 1 0 0 1 1 1v10a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V11a1 1 0 0 1 1-1h1zm2 0h6V7a3 3 0 0 0-6 0v3z"/></svg>Show Earth's shadow</span><span class="swval" id="shadowVal">Off</span></span>
        <span class="swtrack"><span class="swknob"></span></span>
      </button>
      <p class="lockmsg" id="lockMsg"></p>
    </section>
  </aside>
</main>
<div id="toast" role="status" aria-live="polite"></div>
<div id="demoBanner" hidden>Demo &middot; tap anywhere to explore on your own</div>
<div id="demoPtr" hidden><svg width="30" height="30" viewBox="0 0 30 30"><path d="M3 3 L3 24 L9 18.5 L13 27 L17 25.2 L13 16.8 L21 16.8 Z" fill="#fff" stroke="#111" stroke-width="2" stroke-linejoin="round"/></svg></div>

<script>
(() => {
'use strict';
const P = 29.530588;          // days in a lunar month
const TAU = Math.PI * 2;
const SPEED = 2.6;            // days per second while playing
// Diagram proportions (fractions of view size). Not to scale, but used consistently in both views.
const RO = 0.36, RE = 0.075, RM = 0.03, PEN = 0.12;

const $ = s => document.querySelector(s);
const PHASES = [
  {name:'New moon', short:'New', when:'Where to look: it is up in the daytime sky close to the Sun, lost in the glare.', note:'The sunlit half faces away from Earth, so the side we see is dark.'},
  {name:'Waxing crescent', short:'Waxing crescent', when:'Where to look: low in the west just after sunset.', note:'Waxing means growing. Crescent means less than half lit.'},
  {name:'First quarter', short:'First quarter', when:'Where to look: it rises around noon and is high in the sky at sunset.', note:'Half of the side we see is lit. The Moon is a quarter of the way around its orbit.'},
  {name:'Waxing gibbous', short:'Waxing gibbous', when:'Where to look: it rises in the afternoon and shines all evening.', note:'Gibbous means more than half lit. It is still growing.'},
  {name:'Full moon', short:'Full', when:'Where to look: it rises at sunset and shines all night long.', note:'The whole sunlit half faces Earth.'},
  {name:'Waning gibbous', short:'Waning gibbous', when:'Where to look: it rises mid-evening and is high before dawn.', note:'Waning means shrinking. Still more than half lit.'},
  {name:'Last quarter', short:'Last quarter', when:'Where to look: it rises around midnight and is high in the morning sky.', note:'Half lit again, but now it is the other half.'},
  {name:'Waning crescent', short:'Waning crescent', when:'Where to look: low in the east just before sunrise.', note:'A thin sliver, about to disappear into the next new moon.'}
];

// ---------- seeded randomness ----------
function mulberry32(a){return function(){a|=0;a=a+0x6D2B79F5|0;let t=Math.imul(a^a>>>15,1|a);t=t+Math.imul(t^t>>>7,61|t)^t;return((t^t>>>14)>>>0)/4294967296;};}
const rnd = mulberry32(29530588);
const STARS_O = Array.from({length:150},()=>({x:rnd(),y:rnd(),s:rnd()<0.85?1:1.8,a:0.2+rnd()*0.6,sp:0.4+rnd()*1.8,ph:rnd()*TAU}));
const STARS_M = Array.from({length:100},()=>({x:rnd(),y:rnd()*0.82,s:rnd()<0.85?1:1.7,a:0.25+rnd()*0.65,sp:0.5+rnd()*2,ph:rnd()*TAU}));
const CONTINENTS = Array.from({length:6},()=>{const a=rnd()*TAU,d=0.25+rnd()*0.5;return Array.from({length:4},()=>({x:Math.cos(a)*d+(rnd()-0.5)*0.4,y:Math.sin(a)*d+(rnd()-0.5)*0.4,r:0.1+rnd()*0.16}));});
const MARIA = Array.from({length:7},()=>{const a=rnd()*TAU,d=rnd()*0.55;const cx=Math.cos(a)*d,cy=Math.sin(a)*d-0.12;return Array.from({length:5},()=>({x:cx+(rnd()-0.5)*0.35,y:cy+(rnd()-0.5)*0.3,r:0.08+rnd()*0.14}));});
const CRATERS = Array.from({length:46},()=>{const a=rnd()*TAU,d=Math.sqrt(rnd())*0.92;return {x:Math.cos(a)*d,y:Math.sin(a)*d,r:0.015+Math.pow(rnd(),2.2)*0.09};});
const HILLS = Array.from({length:16},()=>rnd());

// ---------- state ----------
const state = {day:3.7, playing:false, hemi:'N', hemiRot:0, shadow:false, unlocked:false, mode:'tour', step:0, quiz:null};
let dirty = true;
const theta = () => state.day / P * TAU;
const phaseIndex = () => Math.round(state.day / (P/8)) % 8;
function setDay(d){ state.day = ((d % P) + P) % P; dirty = true; }

// lit region of the Moon's disc as a polygon, northern-hemisphere orientation, centered at 0,0
function litPoly(th, r, n){
  const c = Math.cos(th), s = Math.sin(th) >= 0 ? 1 : -1, pts = [];
  for(let i=0;i<=n;i++){const a=-Math.PI/2+Math.PI*i/n; pts.push([s*r*Math.cos(a), r*Math.sin(a)]);}
  for(let i=0;i<=n;i++){const a=Math.PI/2-Math.PI*i/n; pts.push([s*c*r*Math.cos(a), r*Math.sin(a)]);}
  return pts;
}
function moonIcon(th, size, south){
  const r=size/2-1.5, m=size/2;
  const pts=litPoly(th,r,20).map(([x,y])=>south?[-x,-y]:[x,y]).map(([x,y])=>(m+x).toFixed(2)+','+(m+y).toFixed(2)).join(' ');
  return `<svg width="${size}" height="${size}" viewBox="0 0 ${size} ${size}" aria-hidden="true"><circle cx="${m}" cy="${m}" r="${r}" fill="#262d4a" stroke="#56618c" stroke-width="1"/><polygon points="${pts}" fill="#f4efdc"/></svg>`;
}

// ---------- sound ----------
const Sound = {
  ctx:null, master:null, muted:false, lastChime:0,
  unlock(){
    try{
      if(!this.ctx){
        const AC = window.AudioContext || window.webkitAudioContext; if(!AC) return;
        this.ctx = new AC(); this.master = this.ctx.createGain();
        this.master.gain.value = this.muted ? 0 : 0.9; this.master.connect(this.ctx.destination);
      }
      if(this.ctx.state === 'suspended') this.ctx.resume();
    }catch(e){}
  },
  setMuted(m){
    this.muted = m;
    try{ if(this.master) this.master.gain.setTargetAtTime(m?0:0.9, this.ctx.currentTime, 0.02); }catch(e){}
    try{ localStorage.setItem('moonPhases.muted', m?'1':'0'); }catch(e){}
  },
  tone(f, dur, type, vol, delay){
    const ctx=this.ctx; if(!ctx || this.muted) return;
    try{
      const t=ctx.currentTime+(delay||0), o=ctx.createOscillator(), g=ctx.createGain();
      o.type=type||'sine'; o.frequency.setValueAtTime(f,t);
      g.gain.setValueAtTime(0.0001,t); g.gain.exponentialRampToValueAtTime(vol||0.06,t+0.012); g.gain.exponentialRampToValueAtTime(0.0001,t+dur);
      o.connect(g); g.connect(this.master); o.start(t); o.stop(t+dur+0.05);
    }catch(e){}
  },
  click(){ this.tone(700,0.07,'triangle',0.04); },
  chime(i){ const now=performance.now(); if(now-this.lastChime<90) return; this.lastChime=now;
    const f=[392,440,494,587,659,587,494,440][i]; this.tone(f,0.55,'sine',0.06); this.tone(f*2,0.35,'sine',0.02,0.01); },
  good(){ this.tone(523,0.2,'sine',0.08); this.tone(784,0.35,'sine',0.08,0.12); },
  bad(){ this.tone(240,0.25,'triangle',0.07); this.tone(190,0.32,'triangle',0.06,0.13); },
  fanfare(){ [523,659,784,1046].forEach((f,i)=>this.tone(f,0.35,'sine',0.06,i*0.1)); }
};
try{ Sound.muted = localStorage.getItem('moonPhases.muted') === '1'; }catch(e){}

// ---------- canvases ----------
const orbitCv=$('#orbitCv'), moonCv=$('#moonCv');
const V = { o:{cv:orbitCv, ctx:orbitCv.getContext('2d'), w:1,h:1,dpr:1}, m:{cv:moonCv, ctx:moonCv.getContext('2d'), w:1,h:1,dpr:1} };
let quality = 2; const DPR_CAPS=[1,1.5,2];
let moonTex = null;
function sizeView(v){
  const r=v.cv.parentElement.getBoundingClientRect();
  const w=Math.max(1,r.width), h=Math.max(1,r.height);
  const dpr=Math.min(window.devicePixelRatio||1, DPR_CAPS[quality]);
  v.w=w; v.h=h; v.dpr=dpr; v.cv.width=Math.max(1,Math.round(w*dpr)); v.cv.height=Math.max(1,Math.round(h*dpr));
}
function resizeAll(){ sizeView(V.o); sizeView(V.m); moonTex=null; }

function buildMoonTex(r, dpr){
  const D=Math.ceil(2*r*dpr)+2, cv=document.createElement('canvas'); cv.width=cv.height=D;
  const c=cv.getContext('2d'), R=D/2;
  c.save(); c.beginPath(); c.arc(R,R,R-1,0,TAU); c.clip();
  const g=c.createRadialGradient(R*0.8,R*0.75,R*0.1,R,R,R); g.addColorStop(0,'#f8f5ea'); g.addColorStop(1,'#d3cebd');
  c.fillStyle=g; c.fillRect(0,0,D,D);
  c.fillStyle='rgba(112,110,106,0.30)';
  for(const m of MARIA) for(const b of m){ c.beginPath(); c.arc(R+b.x*R,R+b.y*R,b.r*R,0,TAU); c.fill(); }
  for(const k of CRATERS){
    const x=R+k.x*R, y=R+k.y*R, rr=Math.max(0.8,k.r*R);
    c.beginPath(); c.arc(x,y,rr,0,TAU); c.fillStyle='rgba(125,120,112,0.32)'; c.fill();
    c.beginPath(); c.arc(x,y,rr,Math.PI*0.85,Math.PI*1.85); c.strokeStyle='rgba(255,255,248,0.4)'; c.lineWidth=Math.max(0.6,rr*0.22); c.stroke();
  }
  const lg=c.createRadialGradient(R,R,R*0.72,R,R,R); lg.addColorStop(0,'rgba(0,0,0,0)'); lg.addColorStop(1,'rgba(70,62,50,0.28)');
  c.fillStyle=lg; c.fillRect(0,0,D,D);
  c.restore();
  return {cv, r, dpr};
}

function eclipseInfo(th){
  if(!state.shadow || Math.cos(th) >= 0) return null;
  const a=Math.abs(RO*Math.sin(th)/RM), Ru=RE/RM, Rp=(RE+RO*PEN)/RM;
  if(a <= Ru-1) return 'total';
  if(a < Ru+1) return 'partial';
  if(a < Rp+1) return 'penumbral';
  return null;
}
const showFacing = () => state.unlocked || state.mode!=='tour' || state.step>=2;

// ---------- orbit view ----------
let og = {cx:0,cy:0,S:1,ro:1,rm:1,mx:0,my:0};
function drawOrbit(t){
  const v=V.o, c=v.ctx, w=v.w, h=v.h;
  c.setTransform(v.dpr,0,0,v.dpr,0,0);
  c.fillStyle='#050916'; c.fillRect(0,0,w,h);
  const ns = quality===0 ? 60 : STARS_O.length;
  for(let i=0;i<ns;i++){ const s=STARS_O[i]; c.fillStyle='rgba(255,255,255,'+(s.a*(0.7+0.3*Math.sin(t*s.sp+s.ph))).toFixed(3)+')'; c.fillRect(s.x*w,s.y*h,s.s,s.s); }
  const S=Math.min(w,h)*0.92, cx=w/2, cy=h/2, ro=RO*S, Re=RE*S, rm=Math.max(5,RM*S);
  const th=theta(), u={x:Math.cos(th), y:-Math.sin(th)};
  const mx=cx+u.x*ro, my=cy+u.y*ro;
  og={cx,cy,S,ro,rm,mx,my};
  const fs=Math.max(10,Math.min(14,S*0.034));

  // Sun glow on the right edge
  const sg=c.createRadialGradient(w+S*0.06,cy,0,w+S*0.06,cy,S*0.5);
  sg.addColorStop(0,'rgba(255,214,110,0.6)'); sg.addColorStop(0.3,'rgba(255,190,80,0.2)'); sg.addColorStop(1,'rgba(255,190,80,0)');
  c.fillStyle=sg; c.fillRect(0,0,w,h);
  // Parallel sunlight rays travelling right-to-left
  const sp=Math.max(18,S*0.085);
  c.save(); c.strokeStyle='rgba(255,214,102,0.2)'; c.lineWidth=Math.max(1,S*0.004);
  const dl=S*0.05, gp=S*0.035; c.setLineDash([dl,gp]); c.lineDashOffset=-((t*S*0.14)%(dl+gp));
  c.beginPath();
  for(let y=cy-Math.floor(cy/sp)*sp; y<h; y+=sp){ c.moveTo(w,y); c.lineTo(0,y); }
  c.stroke(); c.restore();
  c.font=`700 ${fs}px system-ui,sans-serif`; c.textAlign='right'; c.textBaseline='middle';
  c.fillStyle='rgba(255,214,102,0.95)'; c.fillText('← Sunlight from the Sun', w-12, Math.max(44, cy-ro-S*0.13));

  // Orbit path
  c.save(); c.setLineDash([4,6]); c.strokeStyle='rgba(160,180,255,0.38)'; c.lineWidth=1.5;
  c.beginPath(); c.arc(cx,cy,ro,0,TAU); c.stroke(); c.restore();
  // direction arrows (counter-clockwise)
  for(const a of [Math.PI*0.75, Math.PI*1.75]){
    const px=cx+Math.cos(a)*ro, py=cy-Math.sin(a)*ro, dx=-Math.sin(a), dy=-Math.cos(a), nx=-dy, ny=dx, L=Math.max(6,S*0.02);
    c.beginPath(); c.moveTo(px+dx*L,py+dy*L); c.lineTo(px-dx*L*0.6+nx*L*0.7,py-dy*L*0.6+ny*L*0.7); c.lineTo(px-dx*L*0.6-nx*L*0.7,py-dy*L*0.6-ny*L*0.7); c.closePath();
    c.fillStyle='rgba(160,180,255,0.7)'; c.fill();
  }
  // phase position dots + labels
  const idx=phaseIndex();
  for(let k=0;k<8;k++){ const a=k*Math.PI/4; c.beginPath(); c.arc(cx+Math.cos(a)*ro, cy-Math.sin(a)*ro, k===idx?3.5:2.5, 0, TAU); c.fillStyle=k===idx?'#ffcf5a':'rgba(190,200,255,0.55)'; c.fill(); }
  const lr=ro+S*0.075, labs=[['New moon',cx+lr,cy,'left'],['First quarter',cx,cy-lr,'center'],['Full moon',cx-lr,cy,'right'],['Last quarter',cx,cy+lr,'center']];
  c.font=`600 ${fs}px system-ui,sans-serif`; c.textBaseline='middle';
  labs.forEach((L,k)=>{
    let d=Math.abs(((th-k*Math.PI/2)%TAU+TAU)%TAU); d=Math.min(d,TAU-d);
    c.globalAlpha = d<0.5 ? 0.15 : 0.85; c.textAlign=L[3]; c.fillStyle= idx===k*2 ? '#ffffff' : '#b8c2e8'; c.fillText(L[0],L[1],L[2]);
  });
  c.globalAlpha=1;

  // Moon (top view): always half lit, on the Sun's side
  c.beginPath(); c.arc(mx,my,rm,0,TAU); c.fillStyle='#2a3048'; c.fill();
  c.beginPath(); c.arc(mx,my,rm,-Math.PI/2,Math.PI/2); c.closePath(); c.fillStyle='#f3efde'; c.fill();

  // Earth's shadow
  if(state.shadow){
    const L=cx+20;
    c.beginPath(); c.moveTo(cx,cy-Re); c.lineTo(cx-L,cy-Re-L*PEN); c.lineTo(cx-L,cy+Re+L*PEN); c.lineTo(cx,cy+Re); c.closePath();
    c.fillStyle='rgba(0,0,10,0.3)'; c.fill();
    const ug=c.createLinearGradient(cx,0,0,0); ug.addColorStop(0,'rgba(0,0,6,0.78)'); ug.addColorStop(1,'rgba(0,0,6,0.5)');
    c.fillStyle=ug; c.fillRect(0,cy-Re,cx,2*Re);
    c.save(); c.font=`700 ${Math.max(9,fs-1)}px system-ui,sans-serif`; c.textAlign='center'; c.textBaseline='middle'; c.fillStyle='rgba(220,225,255,0.75)';
    c.fillText("Earth's shadow", cx-(Re+ro)/2-rm*0.3, cy); c.restore();
  }

  // Earth
  c.save(); c.beginPath(); c.arc(cx,cy,Re,0,TAU); c.clip();
  c.fillStyle='#2a6fd1'; c.fillRect(cx-Re,cy-Re,2*Re,2*Re);
  c.fillStyle='#3fae6a';
  for(const blob of CONTINENTS) for(const b of blob){ c.beginPath(); c.arc(cx+b.x*Re,cy+b.y*Re,b.r*Re,0,TAU); c.fill(); }
  c.fillStyle='rgba(240,248,255,0.92)'; c.beginPath(); c.arc(cx,cy,Re*0.22,0,TAU); c.fill();
  c.fillStyle='rgba(2,5,18,0.74)'; c.fillRect(cx-Re-1,cy-Re-1,Re+1,2*Re+2);
  c.restore();
  c.beginPath(); c.arc(cx,cy,Re+1,0,TAU); c.strokeStyle='rgba(120,190,255,0.6)'; c.lineWidth=1.5; c.stroke();
  c.font=`700 ${fs}px system-ui,sans-serif`; c.textAlign='center'; c.textBaseline='middle'; c.fillStyle='rgba(200,225,255,0.9)';
  const elx = cx - u.x*(Re+S*0.05), ely = cy - u.y*(Re+S*0.05);
  c.fillText('Earth', elx, ely);

  // Observer + sight line
  const bx=cx+u.x*Re, by=cy+u.y*Re, hx=cx+u.x*(Re+S*0.036), hy=cy+u.y*(Re+S*0.036);
  if(showFacing()){
    c.save(); c.setLineDash([2,5]); c.strokeStyle='rgba(95,211,255,0.55)'; c.lineWidth=1.5;
    c.beginPath(); c.moveTo(hx,hy); c.lineTo(mx-u.x*rm*1.3,my-u.y*rm*1.3); c.stroke(); c.restore();
  }
  c.strokeStyle='#ff9f43'; c.fillStyle='#ff9f43'; c.lineWidth=Math.max(2,S*0.006); c.lineCap='round';
  c.beginPath(); c.moveTo(bx,by); c.lineTo(bx+u.x*S*0.026,by+u.y*S*0.026);
  const ax=bx+u.x*S*0.018, ay=by+u.y*S*0.018, al=S*0.012;
  c.moveTo(ax-u.y*al,ay+u.x*al); c.lineTo(ax+u.y*al,ay-u.x*al); c.stroke();
  c.beginPath(); c.arc(hx,hy,Math.max(2.5,S*0.008),0,TAU); c.fill();

  // Edge arcs: sunlit half (yellow) and half facing Earth (blue)
  const pulse=0.5+0.5*Math.sin(t*5);
  const litR=rm+Math.max(3,S*0.009), faceR=rm+Math.max(7,S*0.02);
  const litW=2.5+((state.mode==='tour'&&state.step===0)?pulse*2.5:0);
  c.lineCap='round';
  c.beginPath(); c.arc(mx,my,litR,-Math.PI/2,Math.PI/2); c.strokeStyle='#ffcf5a'; c.lineWidth=litW; c.stroke();
  if(showFacing()){
    const phi=Math.atan2(cy-my,cx-mx);
    c.beginPath(); c.arc(mx,my,faceR,phi-Math.PI/2,phi+Math.PI/2); c.strokeStyle='#5fd3ff';
    c.lineWidth=2.5+((state.mode==='tour'&&state.step===2)?pulse*2.5:0); c.stroke();
  }
  c.font=`800 ${fs}px system-ui,sans-serif`; c.textAlign='center'; c.textBaseline='middle'; c.fillStyle='#ffffff';
  c.fillText('Moon', mx+u.x*(rm+S*0.065), my+u.y*(rm+S*0.065));
  c.lineCap='butt';
}

// ---------- "what you see" view ----------
function drawMoonView(t){
  const v=V.m, c=v.ctx, w=v.w, h=v.h;
  c.setTransform(v.dpr,0,0,v.dpr,0,0);
  const sky=c.createLinearGradient(0,0,0,h); sky.addColorStop(0,'#040920'); sky.addColorStop(1,'#17244e');
  c.fillStyle=sky; c.fillRect(0,0,w,h);
  const ns = quality===0 ? 45 : STARS_M.length;
  for(let i=0;i<ns;i++){ const s=STARS_M[i]; c.fillStyle='rgba(255,255,255,'+(s.a*(0.65+0.35*Math.sin(t*s.sp+s.ph))).toFixed(3)+')'; c.fillRect(s.x*w,s.y*h,s.s,s.s); }

  const th=theta(), k=(1-Math.cos(th))/2;
  const r=Math.max(12,Math.min(w*0.27,h*0.3)), mx=w/2, my=h*0.46;
  if(!moonTex || Math.abs(moonTex.r-r)>0.5 || moonTex.dpr!==v.dpr) moonTex=buildMoonTex(r,v.dpr);
  const ecl=eclipseInfo(th);
  const haloA=0.24*k*((ecl==='total')?0.15:(ecl==='partial'?0.5:1));
  if(haloA>0.01){ const hg=c.createRadialGradient(mx,my,r*0.9,mx,my,r*2.3); hg.addColorStop(0,'rgba(255,250,225,'+haloA.toFixed(3)+')'); hg.addColorStop(1,'rgba(255,250,225,0)'); c.fillStyle=hg; c.fillRect(0,0,w,h); }

  c.save(); c.translate(mx,my); c.rotate(state.hemiRot);
  c.drawImage(moonTex.cv,-r,-r,2*r,2*r);
  // unlit part = disc minus lit polygon
  const pts=litPoly(th,r,56);
  c.beginPath(); c.arc(0,0,r+0.6,0,TAU);
  c.moveTo(pts[0][0],pts[0][1]); for(let i=1;i<pts.length;i++) c.lineTo(pts[i][0],pts[i][1]); c.closePath();
  c.fillStyle='rgba(5,8,22,0.9)'; c.fill('evenodd');
  // eclipse overlay (Earth's shadow on the Moon)
  if(ecl){
    const off=-(RO*Math.sin(th))/RM*r, Ru=RE/RM*r, Rp=(RE+RO*PEN)/RM*r;
    c.save(); c.beginPath(); c.arc(0,0,r+0.6,0,TAU); c.clip();
    const pg=c.createRadialGradient(off,0,Ru*0.96,off,0,Rp); pg.addColorStop(0,'rgba(0,0,0,0.42)'); pg.addColorStop(1,'rgba(0,0,0,0)');
    c.fillStyle=pg; c.fillRect(-r-1,-r-1,2*r+2,2*r+2);
    c.globalCompositeOperation='multiply';
    c.beginPath(); c.arc(off,0,Ru,0,TAU); c.fillStyle='#8a3418'; c.fill();
    c.globalCompositeOperation='source-over';
    c.restore();
  }
  c.restore();

  // which side the Sun is on (from this observer's point of view)
  const sideN=(Math.sin(th)>=0?1:-1), cr=Math.cos(state.hemiRot);
  const aA=Math.min(1,Math.abs(Math.sin(th))*1.6)*Math.abs(cr);
  if(aA>0.12){
    const side=sideN*Math.sign(cr||1), ax=mx+side*(r+Math.max(18,r*0.32)), L=Math.max(10,r*0.18);
    c.globalAlpha=aA*0.85; c.strokeStyle='#ffcf5a'; c.fillStyle='#ffcf5a'; c.lineWidth=2;
    c.beginPath(); c.moveTo(ax-side*L*0.6,my); c.lineTo(ax+side*L,my); c.stroke();
    c.beginPath(); c.moveTo(ax+side*(L+6),my); c.lineTo(ax+side*L,my-5); c.lineTo(ax+side*L,my+5); c.closePath(); c.fill();
    c.font=`700 ${Math.max(10,Math.min(13,r*0.16))}px system-ui,sans-serif`; c.textAlign='center'; c.textBaseline='top';
    c.fillText('Sun side', ax+side*L*0.2, my+9);
    c.globalAlpha=1;
  }

  // hills + tiny observer
  const base=h*0.87, amp=h*0.06;
  c.beginPath(); c.moveTo(0,h);
  for(let i=0;i<HILLS.length;i++){ const x=i/(HILLS.length-1)*w, y=base-HILLS[i]*amp; if(i===0) c.lineTo(x,y); else { const px=(i-1)/(HILLS.length-1)*w, py=base-HILLS[i-1]*amp; c.quadraticCurveTo(px,py,(px+x)/2,(py+y)/2); } }
  c.lineTo(w,base-HILLS[HILLS.length-1]*amp); c.lineTo(w,h); c.closePath();
  c.fillStyle='#070c1c'; c.fill();
  const ox=w*0.16, oy=base-HILLS[2]*amp-2, sc=Math.max(0.8,Math.min(1.4,h/260));
  c.strokeStyle='#ff9f43'; c.fillStyle='#ff9f43'; c.lineWidth=2*sc; c.lineCap='round';
  c.beginPath(); c.moveTo(ox,oy); c.lineTo(ox,oy-14*sc); c.moveTo(ox-5*sc,oy-9*sc); c.lineTo(ox+6*sc,oy-15*sc); c.stroke();
  c.beginPath(); c.arc(ox,oy-18*sc,3.4*sc,0,TAU); c.fill(); c.lineCap='butt';
}

// ---------- DOM refs ----------
const phaseNameEl=$('#phaseName'), dayTxt=$('#dayTxt'), illumTxt=$('#illumTxt'), noteTxt=$('#noteTxt'), whenTxt=$('#whenTxt'), shadowNote=$('#shadowNote');
const eclBadge=$('#eclBadge'), thumb=$('#thumb'), scrub=$('#scrub'), rail=$('#rail'), dayChip=$('#dayChip'), ticksEl=$('#ticks');
const hemiSw=$('#hemiSw'), shadowSw=$('#shadowSw'), hemiVal=$('#hemiVal'), shadowVal=$('#shadowVal'), lockMsg=$('#lockMsg'), hemiChip=$('#hemiChip');
const guideBody=$('#guideBody'), playBtn=$('#playBtn'), muteBtn=$('#muteBtn'), lgFace=$('#lgFace');

// ticks (phase buttons)
const tickBtns=[];
for(let i=0;i<9;i++){
  const b=document.createElement('button'); b.type='button'; b.className='tick'+(i===8?' tick-end':'');
  b.style.setProperty('--f', String(i/8)); b.dataset.i=String(i);
  b.setAttribute('aria-label','Jump to '+PHASES[i%8].name);
  b.addEventListener('click',()=>{ Sound.click(); state.playing=false; setDay(i===8 ? P-0.001 : i*P/8); });
  ticksEl.appendChild(b); tickBtns.push(b);
}
let tickHemi='';
function renderTicks(){
  if(tickHemi===state.hemi) return; tickHemi=state.hemi;
  tickBtns.forEach((b,i)=>{ b.innerHTML=moonIcon(i*Math.PI/4,22,state.hemi==='S')+'<span>'+PHASES[i%8].short+'</span>'; });
}

let thumbKey='';
function updateReadout(){
  const th=theta(), idx=phaseIndex(), ph=PHASES[idx], k=(1-Math.cos(th))/2;
  phaseNameEl.textContent=ph.name;
  dayTxt.textContent='Day '+state.day.toFixed(1)+' of 29.5';
  illumTxt.textContent=Math.round(k*100)+'% of the side facing us is lit';
  noteTxt.textContent=ph.note;
  whenTxt.textContent=ph.when;
  dayChip.textContent='Day '+state.day.toFixed(1);
  const ecl=eclipseInfo(th);
  if(state.shadow){
    shadowNote.hidden=false;
    if(ecl){
      shadowNote.classList.add('ecl');
      shadowNote.textContent = (ecl==='total' ? "Total lunar eclipse! Earth's shadow covers the whole Moon. A little sunlight bends through Earth's air and paints it a coppery red."
        : ecl==='partial' ? "Partial lunar eclipse: Earth's dark shadow is taking a bite out of the Moon."
        : "The Moon is in the faint outer edge of Earth's shadow. It looks only slightly dimmer.")
        + " In real life this only happens when the Sun, Earth and Moon line up exactly, a few times a year.";
      eclBadge.hidden = ecl==='penumbral'; eclBadge.textContent = ecl==='total' ? 'Total lunar eclipse' : 'Partial lunar eclipse';
    } else {
      shadowNote.classList.remove('ecl');
      shadowNote.textContent = k>0.97 ? "Full moon, but not touching the shadow. Most months the tilted orbit carries the Moon just above or below it."
        : "Earth's shadow points away from the Sun and is not touching the Moon right now. The dark part you see is simply the Moon's own night side.";
      eclBadge.hidden=true;
    }
  } else { shadowNote.hidden=true; eclBadge.hidden=true; }
  thumb.style.left=(state.day/P*100)+'%';
  const key=Math.round(state.day*3)+state.hemi;
  if(key!==thumbKey){ thumbKey=key; thumb.innerHTML=moonIcon(th,30,state.hemi==='S'); }
  scrub.setAttribute('aria-valuenow',state.day.toFixed(1));
  scrub.setAttribute('aria-valuetext','Day '+state.day.toFixed(1)+', '+ph.name);
  tickBtns.forEach((b,i)=>b.classList.toggle('on', (i%8)===idx && (i<8 ? !(i===0 && state.day>P*0.75) : state.day>P*0.75)));
  lgFace.style.display = showFacing() ? '' : 'none';
}

const ICON_PLAY='<svg class="icon" viewBox="0 0 24 24" fill="currentColor"><path d="M7 4.5v15l13-7.5z"/></svg>';
const ICON_PAUSE='<svg class="icon" viewBox="0 0 24 24" fill="currentColor"><rect x="6" y="4.5" width="4.2" height="15" rx="1"/><rect x="13.8" y="4.5" width="4.2" height="15" rx="1"/></svg>';
let shownPlaying=null;
function updatePlayBtn(){ shownPlaying=state.playing; playBtn.innerHTML=(state.playing?ICON_PAUSE:ICON_PLAY)+'<span>'+(state.playing?'Pause':'Play')+'</span>'; playBtn.setAttribute('aria-label',state.playing?'Pause the month':'Play the month'); }
function updateMuteBtn(){
  muteBtn.innerHTML = Sound.muted
    ? '<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 9h4l5-4v14l-5-4H4z"/><path d="M17 9l5 6M22 9l-5 6"/></svg><span>Sound off</span>'
    : '<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 9h4l5-4v14l-5-4H4z"/><path d="M16.5 8.5a5 5 0 0 1 0 7M19 6a8.5 8.5 0 0 1 0 12"/></svg><span>Sound on</span>';
  muteBtn.setAttribute('aria-pressed', Sound.muted?'true':'false');
}

// ---------- switches ----------
function syncSwitches(){
  const hemiOpen = state.unlocked || (state.mode==='tour' && state.step>=5);
  const shadowOpen = state.unlocked || (state.mode==='tour' && state.step>=4);
  if(!hemiOpen) state.hemi='N';
  if(!shadowOpen) state.shadow=false;
  hemiSw.disabled=!hemiOpen; shadowSw.disabled=!shadowOpen;
  hemiSw.setAttribute('aria-checked', state.hemi==='S'?'true':'false');
  shadowSw.setAttribute('aria-checked', state.shadow?'true':'false');
  hemiVal.textContent = state.hemi==='S' ? 'South (Australia, Argentina...)' : 'North (Europe, USA, Mexico...)';
  shadowVal.textContent = state.shadow ? 'On' : 'Off';
  hemiChip.textContent = state.hemi==='S' ? 'Southern Hemisphere' : 'Northern Hemisphere';
  lockMsg.textContent = (hemiOpen && shadowOpen) ? '' : 'Locked switches open up as you go through the tour.';
  shadowSw.classList.toggle('pulse', state.mode==='tour' && state.step===4 && !state.shadow);
  hemiSw.classList.toggle('pulse', state.mode==='tour' && state.step===5 && state.hemi==='N');
  renderTicks();
  dirty=true;
}
hemiSw.addEventListener('click',()=>{ if(hemiSw.disabled) return; Sound.click(); state.hemi = state.hemi==='N'?'S':'N'; syncSwitches(); });
shadowSw.addEventListener('click',()=>{ if(shadowSw.disabled) return; Sound.click(); state.shadow=!state.shadow; syncSwitches(); });

// ---------- guided tour ----------
const STEPS = [
  {t:'Sunlight comes from one side',
   p:["You're looking down on Earth from far above the North Pole. Sunlight pours in from the right. The Sun is so far away that its rays arrive almost side by side.",
      "Look at the yellow edge: the Sun always lights exactly half of the Moon, the half facing the Sun. Earth is the same: one half has day, the other half has night."],
   tryit:'Drag the Moon around its circle in the top view. The yellow, sunlit half always stays on the Sun’s side.',
   scene(){ state.playing=false; setDay(3.7); }},
  {t:'The Moon circles Earth',
   p:["The Moon travels all the way around Earth in about 29.5 days. That's one lunar month (the word “month” comes from “Moon”).",
      "Watch it go around. The sunlit half keeps pointing at the Sun the whole time."],
   tryit:'Press Pause whenever you like, or drag the slider under the pictures.',
   scene(){ state.playing=true; }},
  {t:'You only see the half facing you',
   p:["From Earth you can only see the half of the Moon that faces Earth: the blue edge. The orange stick figure is you.",
      "A phase is simply how much of that blue half is also sunlit. Where the yellow and blue edges overlap is the bright part you see in the sky."],
   tryit:'Move the Moon and watch the “What you see from Earth” picture change.',
   scene(){ state.playing=false; setDay(5.5); }},
  {t:'From new moon to full moon and back',
   p:["At new moon the Moon is between Earth and the Sun, so its lit half faces away and we see almost nothing. About a week later we see half of the lit half: first quarter.",
      "At full moon the whole lit half faces us. Then it shrinks again. Growing is called waxing, shrinking is waning."],
   tryit:'Drag the slider from start to end and watch each phase name appear.',
   scene(){ state.playing=false; setDay(0.4); }},
  {t:'Myth buster: is it Earth’s shadow?',
   p:["Lots of people think Earth's shadow causes the phases. Turn on <b>Show Earth's shadow</b> and check.",
      "At first quarter the shadow points away from the Sun, nowhere near the Moon, yet half the Moon is dark! That dark part is just the Moon's own night side.",
      "The shadow only reaches the Moon near full moon, and only when everything lines up exactly. That's a lunar eclipse. The Moon's orbit is tilted a little, so most months it slips just above or below the shadow."],
   tryit:'Switch the shadow on, then tap the button below to see an eclipse.',
   extra:'<div class="extra"><button class="btn" data-act="eclipse" type="button">Show me a lunar eclipse</button></div>',
   scene(){ state.playing=false; setDay(7.38); }},
  {t:'Upside down Down Under',
   p:["Everyone on Earth sees the same phase on the same night, but not the same way up.",
      "People in the Southern Hemisphere stand “upside down” compared with people in the north, so the Moon looks rotated. A first-quarter Moon lit on the right in the north is lit on the left in the south."],
   tryit:'Flip the Hemisphere switch and watch the Moon turn.',
   scene(){ state.playing=false; setDay(7.38); }}
];

const QUIZ = [
  {q:"What really causes the Moon's phases?",
   o:["Earth's shadow covers part of the Moon","We see different amounts of the Moon's sunlit half as it orbits Earth","The Moon's sunlit half grows and shrinks","Clouds in space block part of the Moon"],
   a:1, why:"The Sun always lights half of the Moon. As the Moon goes around Earth, we see more or less of that lit half. Look: at first quarter Earth's shadow is nowhere near the Moon.",
   show(){ state.playing=false; state.shadow=true; setDay(7.38); syncSwitches(); }},
  {q:"At full moon, where is the Moon?",
   o:["Between the Sun and Earth","On the far side of Earth, opposite the Sun","Off to the side, at a right angle to the Sun"],
   a:1, why:"At full moon Earth sits between the Sun and the Moon, so the whole sunlit half faces us. That's why a full Moon rises just as the Sun sets.",
   show(){ state.playing=false; state.shadow=false; setDay(P/2+1.1); syncSwitches(); }},
  {q:"A friend in the north sees a first-quarter Moon lit on the right. What does a friend in the Southern Hemisphere see that same night?",
   o:["Also lit on the right","Lit on the left","A full Moon"],
   a:1, why:"Same phase, flipped view! From the Southern Hemisphere the Moon looks rotated, so the lit half appears on the left.",
   show(){ state.playing=false; state.hemi='S'; setDay(7.38); syncSwitches(); }}
];

function renderGuide(){
  const hadFocus = guideBody.contains(document.activeElement);
  let html='';
  if(state.mode==='tour'){
    const s=STEPS[state.step];
    html = `<div class="dots" aria-hidden="true">${STEPS.map((_,i)=>`<span class="dot${i===state.step?' on':(i<state.step?' done':'')}"></span>`).join('')}</div>
      <p class="kicker">Step ${state.step+1} of ${STEPS.length}</p>
      <h2>${s.t}</h2>
      ${s.p.map(x=>`<p>${x}</p>`).join('')}
      <p class="try"><b>Try it:</b> ${s.tryit}</p>
      ${s.extra||''}
      <div class="navrow">
        <button class="btn" type="button" data-act="back" ${state.step===0?'disabled':''}>Back</button>
        <button class="btn primary" type="button" data-act="next">${state.step===STEPS.length-1?'Start free play':'Next'}</button>
      </div>
      <div class="navrow"><button class="btn ghost small" type="button" data-act="skip">${state.unlocked?'Back to free play':'Skip the tour'}</button></div>`;
  } else if(state.mode==='free'){
    html = `<p class="kicker">Free play unlocked</p>
      <h2>Explore on your own</h2>
      <ul class="tips">
        <li>Drag the Moon in the top view, or use the slider and the phase buttons.</li>
        <li>Press Play to watch a whole month in a few seconds.</li>
        <li>Turn on Earth's shadow and find the eclipse near full moon.</li>
        <li>Flip the hemisphere at a crescent Moon.</li>
      </ul>
      <p class="words"><b>Moon words:</b> waxing = growing &middot; waning = shrinking &middot; crescent = less than half lit &middot; gibbous = more than half lit</p>
      <div class="navrow">
        <button class="btn primary" type="button" data-act="quiz">Take the 3-question quiz</button>
        <button class="btn" type="button" data-act="tour">Replay the tour</button>
      </div>`;
  } else if(state.mode==='quiz'){
    const qz=state.quiz;
    if(qz.i>=QUIZ.length){
      const msg = qz.score===3 ? 'Perfect! You really get how phases work.' : qz.score===2 ? 'Great job! Just one slipped by.' : 'Good try! Play with the model a bit and try again.';
      html = `<p class="kicker">Quiz complete</p><h2>Your score</h2>
        <p class="bigscore">${qz.score} / ${QUIZ.length}</p><p>${msg}</p>
        <div class="navrow"><button class="btn primary" type="button" data-act="quiz">Try again</button><button class="btn" type="button" data-act="qdone">Back to free play</button></div>`;
    } else {
      const q=QUIZ[qz.i];
      html = `<p class="kicker">Quiz &middot; Question ${qz.i+1} of ${QUIZ.length} &middot; Score ${qz.score}</p>
        <h2>${q.q}</h2>
        <div class="opts">${q.o.map((o,j)=>{
          let cls='opt'; if(qz.answered){ if(j===q.a) cls+=' right'; else if(j===qz.picked) cls+=' wrong'; }
          return `<button class="${cls}" type="button" data-act="ans" data-i="${j}" ${qz.answered?'disabled':''}>${o}</button>`; }).join('')}</div>
        ${qz.answered?`<div class="fb ${qz.picked===q.a?'ok':'no'}" role="status"><b>${qz.picked===q.a?'Correct!':'Not quite.'}</b> ${q.why}</div>
        <div class="navrow"><button class="btn primary" type="button" data-act="qnext">${qz.i<QUIZ.length-1?'Next question':'See my score'}</button></div>`:''}
        <div class="navrow"><button class="btn ghost small" type="button" data-act="qdone">Leave the quiz</button></div>`;
    }
  }
  guideBody.innerHTML=html;
  if(hadFocus){ const f=guideBody.querySelector('.btn.primary:not([disabled]), .opt:not([disabled]), .btn:not([disabled])'); if(f) f.focus({preventScroll:true}); }
}

function setStep(i){
  state.mode='tour'; state.step=Math.max(0,Math.min(STEPS.length-1,i));
  STEPS[state.step].scene();
  syncSwitches(); renderGuide();
}
let toastT=0;
function toast(msg){ const el=$('#toast'); el.textContent=msg; el.classList.add('show'); clearTimeout(toastT); toastT=setTimeout(()=>el.classList.remove('show'),2800); }
function unlockFree(){
  const first=!state.unlocked; state.unlocked=true; state.mode='free'; state.quiz=null;
  syncSwitches(); renderGuide();
  if(first){ toast('Free play unlocked! Every control is yours now.'); Sound.fanfare(); }
}
function startQuiz(){ state.mode='quiz'; state.quiz={i:0,score:0,answered:false,picked:-1}; renderGuide(); }

guideBody.addEventListener('click', e=>{
  const b=e.target.closest('[data-act]'); if(!b || b.disabled) return;
  const act=b.dataset.act;
  if(act!=='ans') Sound.click();
  switch(act){
    case 'next': if(state.step<STEPS.length-1) setStep(state.step+1); else unlockFree(); break;
    case 'back': setStep(state.step-1); break;
    case 'skip': unlockFree(); break;
    case 'eclipse': state.playing=false; state.shadow=true; setDay(P/2); syncSwitches(); break;
    case 'quiz': startQuiz(); break;
    case 'tour': setStep(0); break;
    case 'ans': {
      const qz=state.quiz; if(!qz || qz.answered) break;
      const j=+b.dataset.i, q=QUIZ[qz.i]; qz.answered=true; qz.picked=j;
      if(j===q.a){ qz.score++; Sound.good(); } else Sound.bad();
      q.show(); renderGuide(); break;
    }
    case 'qnext': { const qz=state.quiz; qz.i++; qz.answered=false; qz.picked=-1; if(qz.i>=QUIZ.length && qz.score===QUIZ.length) Sound.fanfare(); renderGuide(); break; }
    case 'qdone': state.mode='free'; state.quiz=null; renderGuide(); break;
  }
});

function resetAll(){
  state.day=3.7; state.playing=false; state.hemi='N'; state.hemiRot=0; state.shadow=false;
  state.unlocked=false; state.quiz=null; state.mode='tour';
  setStep(0); dirty=true;
}

// ---------- controls ----------
playBtn.addEventListener('click',()=>{ Sound.click(); state.playing=!state.playing; });
$('#prevDay').addEventListener('click',()=>{ Sound.click(); state.playing=false; setDay(state.day-1); });
$('#nextDay').addEventListener('click',()=>{ Sound.click(); state.playing=false; setDay(state.day+1); });
muteBtn.addEventListener('click',()=>{ Sound.unlock(); Sound.setMuted(!Sound.muted); updateMuteBtn(); Sound.click(); });
$('#restartBtn').addEventListener('click',()=>{ Sound.click(); resetAll(); try{ window.scrollTo(0,0); }catch(e){} toast('Restarted from step 1'); });

// scrubber (Pointer Events)
let scrubbing=false;
function dayFromX(x){ const r=rail.getBoundingClientRect(); const f=Math.max(0,Math.min(1,(x-r.left)/r.width)); return Math.min(f*P, P-0.001); }
scrub.addEventListener('pointerdown',e=>{ scrubbing=true; state.playing=false; try{scrub.setPointerCapture(e.pointerId);}catch(_){} setDay(dayFromX(e.clientX)); e.preventDefault(); });
scrub.addEventListener('pointermove',e=>{ if(scrubbing) setDay(dayFromX(e.clientX)); });
const endScrub=()=>{ scrubbing=false; };
scrub.addEventListener('pointerup',endScrub); scrub.addEventListener('pointercancel',endScrub); scrub.addEventListener('lostpointercapture',endScrub);
scrub.addEventListener('keydown',e=>{
  let d=null; const k=e.key, step=P/8;
  if(k==='ArrowRight'||k==='ArrowUp') d=state.day+0.5;
  else if(k==='ArrowLeft'||k==='ArrowDown') d=state.day-0.5;
  else if(k==='PageUp') d=(Math.round(state.day/step)+1)*step;
  else if(k==='PageDown') d=(Math.round(state.day/step)-1)*step;
  else if(k==='Home') d=0; else if(k==='End') d=P-0.001;
  if(d!==null){ e.preventDefault(); state.playing=false; setDay(d); }
});
document.addEventListener('keydown',e=>{
  if((e.key===' '||e.code==='Space') && !(e.target.closest && e.target.closest('button,[role=slider],input,textarea'))){ e.preventDefault(); state.playing=!state.playing; }
});

// drag the Moon in the orbit view
let dragMoon=false;
function localPt(e){ const r=orbitCv.getBoundingClientRect(); return {x:e.clientX-r.left, y:e.clientY-r.top}; }
function setFromPoint(p){ let a=Math.atan2(-(p.y-og.cy), p.x-og.cx); if(a<0) a+=TAU; setDay(a/TAU*P); }
orbitCv.addEventListener('pointerdown',e=>{
  const p=localPt(e), dist=Math.hypot(p.x-og.cx,p.y-og.cy), dm=Math.hypot(p.x-og.mx,p.y-og.my);
  if(dm<Math.max(32,og.rm*2.8) || Math.abs(dist-og.ro)<Math.max(28,og.S*0.07)){
    dragMoon=true; state.playing=false; try{orbitCv.setPointerCapture(e.pointerId);}catch(_){}
    orbitCv.style.cursor='grabbing'; setFromPoint(p); e.preventDefault();
  }
});
orbitCv.addEventListener('pointermove',e=>{ if(dragMoon) setFromPoint(localPt(e)); });
const endDrag=()=>{ dragMoon=false; orbitCv.style.cursor='grab'; };
orbitCv.addEventListener('pointerup',endDrag); orbitCv.addEventListener('pointercancel',endDrag); orbitCv.addEventListener('lostpointercapture',endDrag);

// ---------- demo mode ----------
const isDemo = /#demo$/.test(location.href);
const demo={active:false};
const ptr=$('#demoPtr'), banner=$('#demoBanner');
let ptrX=window.innerWidth/2, ptrY=window.innerHeight/2;
function placePtr(){ ptr.style.transform=`translate(${ptrX}px,${ptrY}px)`; }
function stopErr(){ return new Error('demo-stopped'); }
function tween(ms,fn){ return new Promise((res,rej)=>{ const t0=performance.now(); function f(now){ if(!demo.active) return rej(stopErr()); const p=Math.min(1,(now-t0)/ms); fn(p); if(p>=1) res(); else requestAnimationFrame(f); } requestAnimationFrame(f); }); }
const dwait = ms => tween(ms,()=>{});
const ease = p => p<0.5 ? 2*p*p : 1-Math.pow(-2*p+2,2)/2;
async function movePtr(x,y,ms){ const x0=ptrX,y0=ptrY; await tween(ms,p=>{ const e=ease(p); ptrX=x0+(x-x0)*e; ptrY=y0+(y-y0)*e; placePtr(); }); }
function ensureVisible(el){ const r=el.getBoundingClientRect(); if(r.top<50 || r.bottom>window.innerHeight-10){ try{ el.scrollIntoView({block:'center'}); }catch(e){ el.scrollIntoView(); } } }
function ripple(){ const d=document.createElement('div'); d.className='ripple'; d.style.left=ptrX+'px'; d.style.top=ptrY+'px'; document.body.appendChild(d); setTimeout(()=>d.remove(),550); }
async function tapEl(get){
  let el=get(); if(!el) return; ensureVisible(el); await dwait(120);
  el=get(); if(!el) return; const r=el.getBoundingClientRect();
  await movePtr(r.left+r.width/2, r.top+r.height/2, 600);
  ptr.classList.add('down'); ripple(); await dwait(120); ptr.classList.remove('down');
  if(!demo.active) throw stopErr();
  el.click(); await dwait(280);
}
async function dragDays(d0,d1,ms){
  ensureVisible(scrub); await dwait(100); state.playing=false;
  let r=rail.getBoundingClientRect();
  await movePtr(r.left+d0/P*r.width, r.top+r.height/2, 600);
  setDay(d0); ptr.classList.add('down'); ripple();
  await tween(ms,p=>{ const d=d0+(d1-d0)*ease(p); setDay(d); r=rail.getBoundingClientRect(); ptrX=r.left+d/P*r.width; ptrY=r.top+r.height/2; placePtr(); });
  ptr.classList.remove('down');
}
const q = s => guideBody.querySelector(s);
async function demoScript(){
  while(demo.active){
    resetAll(); try{ window.scrollTo(0,0); }catch(e){}
    await dwait(600);
    await tapEl(()=>q('[data-act=next]'));          // step 2: orbit plays
    await dwait(1800);
    await tapEl(()=>q('[data-act=next]'));          // step 3
    await dwait(700);
    await tapEl(()=>q('[data-act=next]'));          // step 4
    await dragDays(0.3, 14.76, 2300);
    await dwait(400);
    await tapEl(()=>q('[data-act=next]'));          // step 5: shadow myth
    await tapEl(()=>shadowSw);
    await dragDays(7.38, 14.76, 1500);
    await dwait(800);
    await tapEl(()=>q('[data-act=next]'));          // step 6: hemisphere
    await tapEl(()=>hemiSw);
    await dwait(900);
    await tapEl(()=>q('[data-act=next]'));          // free play
    await tapEl(()=>q('[data-act=quiz]'));
    await tapEl(()=>q('[data-act=ans][data-i="1"]'));
    await dwait(1300);
  }
}
function startDemo(){ demo.active=true; ptr.hidden=false; banner.hidden=false; placePtr(); demoScript().catch(()=>{}); }
function endDemo(){ if(!demo.active) return; demo.active=false; ptr.hidden=true; banner.hidden=true; ptr.classList.remove('down'); }
['pointerdown','keydown','wheel','touchstart'].forEach(type=>window.addEventListener(type,e=>{ if(e.isTrusted) endDemo(); },{capture:true,passive:true}));
['pointerdown','keydown','click','touchend'].forEach(type=>window.addEventListener(type,e=>{ if(e.isTrusted) Sound.unlock(); },{capture:true,passive:true}));

// ---------- main loop ----------
let last=performance.now(), lastIdx=-1, readySent=false, fAcc=0, fN=-40;
function loop(now){
  const dt=Math.min(0.1,Math.max(0,(now-last)/1000)); last=now;
  if(state.playing) setDay(state.day+dt*SPEED);
  const target=state.hemi==='S'?Math.PI:0;
  if(state.hemiRot!==target){ state.hemiRot+=(target-state.hemiRot)*Math.min(1,dt*7); if(Math.abs(target-state.hemiRot)<0.002) state.hemiRot=target; }
  const t=now/1000;
  drawOrbit(t); drawMoonView(t);
  const idx=phaseIndex();
  if(idx!==lastIdx){ if(lastIdx!==-1) Sound.chime(idx); lastIdx=idx; dirty=true; }
  if(dirty){ updateReadout(); dirty=false; }
  if(shownPlaying!==state.playing) updatePlayBtn();
  // automatic quality: lower the canvas resolution if frames are slow
  fN++; if(fN>0){ fAcc+=dt; if(fN>=90){ if(fAcc/fN>0.026 && quality>0 && !document.hidden){ quality--; resizeAll(); } fAcc=0; fN=0; } }
  if(!readySent){ readySent=true; try{ parent.postMessage({vcb:'ready'},'*'); }catch(e){} if(isDemo) startDemo(); }
  requestAnimationFrame(loop);
}

// ---------- init ----------
updateMuteBtn(); updatePlayBtn();
resizeAll();
resetAll();
renderTicks(); updateReadout();
if(window.ResizeObserver){ const ro=new ResizeObserver(()=>resizeAll()); ro.observe($('#orbitPanel')); ro.observe($('#moonView')); }
window.addEventListener('resize',resizeAll);
requestAnimationFrame(loop);
})();
</script>
</body>
</html>

Try 2 · index.html

works57.4 KB · 1,023 lines · no libraries
Download
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>Why the Moon Has Phases</title>
<style>
:root{
  --bg:#060914;--panel:#0e1324;--panel2:#161c33;--line:#26304f;--text:#eef1f8;--muted:#9aa3c0;
  --sun:#ffd166;--view:#5ad1ff;--good:#4ade80;--bad:#f87171;--shadow:#ff9c80;
}
*{box-sizing:border-box}
html,body{margin:0;background:var(--bg);color:var(--text);font-family:system-ui,-apple-system,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;-webkit-text-size-adjust:100%}
body{min-height:100vh;min-height:100dvh;display:flex;flex-direction:column}
header{display:flex;align-items:center;gap:8px;padding:8px 10px;flex-wrap:wrap}
header h1{margin:0;flex:1;min-width:180px;font-size:clamp(17px,2.2vw,24px);letter-spacing:.01em}
header h1 .hl{color:var(--sun)}
.btn{min-height:44px;min-width:44px;padding:0 14px;border-radius:12px;border:1px solid var(--line);background:var(--panel2);color:var(--text);font:inherit;font-size:15px;font-weight:650;cursor:pointer;touch-action:manipulation;-webkit-tap-highlight-color:transparent;transition:transform .1s,background .2s,opacity .2s}
.btn:active:not(:disabled){transform:scale(.96)}
.btn:disabled{opacity:.38;cursor:not-allowed}
.btn.primary{background:linear-gradient(#ffd98a,#f2b640);color:#1d1503;border-color:transparent}
.btn.ghost{background:transparent}
.btn.small{font-size:14px;padding:0 12px}
.btn.icon{padding:0;width:48px;font-size:16px}
.btn:focus-visible,.switch:focus-visible,.opt:focus-visible,input:focus-visible{outline:3px solid var(--view);outline-offset:2px}
main{flex:1;min-height:0;display:grid;gap:10px;padding:0 10px 10px;
  grid-template-columns:minmax(0,1.25fr) minmax(0,1fr);
  grid-template-rows:minmax(0,1fr) auto auto;
  grid-template-areas:"orbit sky" "orbit guide" "time time"}
@media (min-width:761px){
  body{height:100vh;height:100dvh}
  main{min-height:560px}
}
.panel{background:var(--panel);border:1px solid var(--line);border-radius:16px;display:flex;flex-direction:column;min-height:0;overflow:hidden}
.panel h2{font-size:12px;letter-spacing:.07em;text-transform:uppercase;color:var(--muted);margin:0;padding:9px 12px 6px;font-weight:700}
.panel h2 .hint{color:var(--sun);text-transform:none;letter-spacing:0;font-weight:600}
.canvasbox{position:relative;flex:1;min-height:0}
.canvasbox canvas{position:absolute;inset:0;width:100%;height:100%;display:block}
#orbitPanel{grid-area:orbit}
#orbitPanel .canvasbox{min-height:300px}
#orbit{touch-action:none;cursor:grab}
#skyPanel{grid-area:sky}
#skyPanel .canvasbox{min-height:170px}
#guide{grid-area:guide}
#timeline{grid-area:time;padding:8px 10px;gap:6px}
.skyinfo{padding:4px 12px 12px}
.phase{font-size:clamp(20px,2.4vw,28px);font-weight:800;color:#fff3cf;transform-origin:left center;line-height:1.15}
.phase.pop{animation:pop .55s ease-out}
@keyframes pop{0%{transform:scale(1.14);color:var(--sun)}100%{transform:scale(1)}}
.meta{color:var(--view);font-size:13px;font-weight:650;margin-top:3px}
.desc{margin:6px 0 0;font-size:14.5px;line-height:1.45;color:#d0d6e8;min-height:3em}
.desc.shadowmsg{color:var(--shadow)}
.guide{padding:12px 14px;overflow:auto}
.guide h3{margin:6px 0 6px;font-size:clamp(18px,1.9vw,22px)}
.guide p{margin:0 0 12px;line-height:1.5;color:#d6dbea;font-size:15.5px}
.gtop{display:flex;justify-content:space-between;align-items:center;gap:8px;font-size:12px;color:var(--muted);text-transform:uppercase;letter-spacing:.06em;font-weight:700}
.dots i{display:inline-block;width:9px;height:9px;border-radius:50%;background:#2a3352;margin-left:5px}
.dots i.on{background:var(--sun)}
.gbtns{display:flex;gap:8px;flex-wrap:wrap}
.badge{display:inline-block;background:rgba(255,209,102,.14);color:var(--sun);border:1px solid rgba(255,209,102,.4);border-radius:999px;padding:3px 10px;font-size:12px;font-weight:800;letter-spacing:.05em;text-transform:uppercase}
.opts{display:flex;flex-direction:column;gap:8px;margin:8px 0 10px}
.opt{text-align:left;min-height:44px;padding:10px 12px;border-radius:12px;border:1px solid var(--line);background:var(--panel2);color:var(--text);font:inherit;font-size:15px;cursor:pointer;touch-action:manipulation}
.opt:disabled{cursor:default}
.opt.right{border-color:var(--good);background:rgba(74,222,128,.16)}
.opt.wrong{border-color:var(--bad);background:rgba(248,113,113,.16)}
.fb{font-weight:650}
.fb.good{color:var(--good)}
.fb.bad{color:#fca5a5}
.trow{display:flex;align-items:center;gap:8px}
.trow.wrap{flex-wrap:wrap}
.rangewrap{flex:1;min-width:0;display:flex;flex-direction:column}
#scrub{width:100%;height:44px;margin:0;background:transparent;-webkit-appearance:none;appearance:none;touch-action:none;cursor:pointer}
#scrub:disabled{cursor:not-allowed;opacity:.55}
#scrub::-webkit-slider-runnable-track{height:10px;border-radius:5px;background:linear-gradient(90deg,var(--sun) var(--p,0%),#2a3352 var(--p,0%))}
#scrub::-webkit-slider-thumb{-webkit-appearance:none;appearance:none;width:28px;height:28px;border-radius:50%;background:#fff;border:4px solid var(--sun);margin-top:-9px;box-shadow:0 0 0 5px rgba(255,209,102,.22)}
#scrub::-moz-range-track{height:10px;border-radius:5px;background:#2a3352}
#scrub::-moz-range-progress{height:10px;border-radius:5px;background:var(--sun)}
#scrub::-moz-range-thumb{width:20px;height:20px;border-radius:50%;background:#fff;border:4px solid var(--sun)}
#strip{display:block;width:100%;height:30px;touch-action:none}
.daylabel{font-weight:700;font-size:14px;color:#fff3cf;min-width:170px;flex:1}
.switch{display:inline-flex;align-items:center;gap:8px;min-height:44px;padding:0 12px;border-radius:999px;border:1px solid var(--line);background:var(--panel2);color:var(--text);font:inherit;font-size:14px;font-weight:650;cursor:pointer;touch-action:manipulation;-webkit-tap-highlight-color:transparent}
.switch:disabled{opacity:.38;cursor:not-allowed}
.switch .knob{width:40px;height:24px;border-radius:12px;background:#2a3352;position:relative;flex:none;transition:background .2s}
.switch .knob::after{content:"";position:absolute;top:3px;left:3px;width:18px;height:18px;border-radius:50%;background:#fff;transition:transform .2s}
.switch[aria-checked="true"] .knob{background:#d9603f}
.switch[aria-checked="true"] .knob::after{transform:translateX(16px)}
.seg{display:inline-flex;border-radius:999px;background:#2a3352;padding:2px}
.seg b{padding:4px 10px;border-radius:999px;font-weight:700;color:var(--muted);transition:background .2s,color .2s}
#hemiSw[aria-checked="false"] .seg .n,#hemiSw[aria-checked="true"] .seg .s{background:var(--view);color:#04131c}
#eclipseBtn[aria-pressed="true"]{border-color:var(--shadow);color:var(--shadow)}
.locknote{font-size:13px;color:var(--sun);font-weight:600}
.locknote.shake{animation:shake .4s}
@keyframes shake{0%,100%{transform:none}25%{transform:translateX(-5px)}75%{transform:translateX(5px)}}
.keys{font-size:12px;color:var(--muted)}
@media (pointer:coarse){.keys{display:none}}
#fakePointer{position:fixed;left:0;top:0;width:30px;height:30px;pointer-events:none;z-index:50;transform:translate(-100px,-100px);filter:drop-shadow(0 2px 4px rgba(0,0,0,.7))}
#fakePointer[hidden]{display:none}
#fakePointer .ring{position:absolute;left:-16px;top:-16px;width:32px;height:32px;border-radius:50%;border:3px solid var(--sun);opacity:0;transform:scale(.4)}
#fakePointer.press .ring{animation:ring .5s ease-out}
@keyframes ring{0%{opacity:1;transform:scale(.4)}100%{opacity:0;transform:scale(1.7)}}
#demoTag{position:fixed;right:10px;bottom:10px;z-index:49;background:rgba(255,209,102,.95);color:#1d1503;font-weight:800;font-size:12px;padding:6px 10px;border-radius:999px;letter-spacing:.05em}
#demoTag[hidden]{display:none}
@media (max-width:760px){
  main{grid-template-columns:minmax(0,1fr);grid-template-rows:auto auto auto auto;grid-template-areas:"orbit" "sky" "time" "guide"}
  #orbitPanel .canvasbox{flex:none;aspect-ratio:1/1;min-height:0;max-height:72vh}
  #skyPanel{flex-direction:row;flex-wrap:wrap}
  #skyPanel h2{width:100%}
  #skyPanel .canvasbox{flex:none;width:42%;aspect-ratio:1/1;min-height:0}
  #skyPanel .skyinfo{flex:1;min-width:0;padding:0 10px 10px}
  .desc{font-size:14px}
  .daylabel{min-width:100%}
}
@media (prefers-reduced-motion:reduce){.phase.pop{animation:none}}
</style>
</head>
<body>
<header>
  <h1>Why does the Moon have <span class="hl">phases</span>?</h1>
  <button class="btn" id="muteBtn" aria-pressed="false">&#9834; Sound on</button>
  <button class="btn" id="restartBtn">&#8634; Restart</button>
</header>
<main>
  <section class="panel" id="orbitPanel">
    <h2>Top view: Sun, Earth &amp; Moon <span id="dragHint" class="hint" hidden>&middot; drag the Moon!</span></h2>
    <div class="canvasbox"><canvas id="orbit" role="img" aria-label="Top-down diagram: sunlight from the right, Earth in the middle, the Moon on its orbit and a small stargazer on Earth"></canvas></div>
  </section>
  <section class="panel" id="skyPanel">
    <h2>What you see from Earth <span id="hemiTag" class="hint">(Northern Hemisphere)</span></h2>
    <div class="canvasbox"><canvas id="sky" role="img" aria-label="The Moon as it looks from Earth right now"></canvas></div>
    <div class="skyinfo">
      <div id="phaseName" class="phase" aria-live="polite">Waxing Crescent</div>
      <div id="phaseMeta" class="meta"></div>
      <p id="phaseDesc" class="desc"></p>
    </div>
  </section>
  <section class="panel guide" id="guide"><div id="guideInner"></div></section>
  <section class="panel" id="timeline">
    <div class="trow">
      <button class="btn icon" id="playBtn" aria-label="Play">&#9654;</button>
      <button class="btn icon" id="minusBtn" aria-label="Back one day">&minus;1</button>
      <div class="rangewrap">
        <input type="range" id="scrub" min="0" max="29.53" step="0.01" value="4.2" aria-label="Day in the lunar month">
        <canvas id="strip" aria-hidden="true"></canvas>
      </div>
      <button class="btn icon" id="plusBtn" aria-label="Forward one day">+1</button>
    </div>
    <div class="trow wrap">
      <div id="dayLabel" class="daylabel"></div>
      <button class="switch" id="hemiSw" role="switch" aria-checked="false" aria-label="Hemisphere: North or South"><span>Hemisphere:</span><span class="seg"><b class="n">North</b><b class="s">South</b></span></button>
      <button class="switch" id="shadowSw" role="switch" aria-checked="false"><span class="knob"></span><span>Show Earth's shadow</span></button>
      <button class="btn small" id="eclipseBtn" aria-pressed="false">Line up an eclipse</button>
    </div>
    <div id="lockNote" class="locknote">Free play unlocks after the tour (or tap &ldquo;Skip tour&rdquo;).</div>
    <div class="keys">Keys: &larr; &rarr; move one day &middot; Space play/pause &middot; N / B next / back &middot; H hemisphere &middot; S shadow &middot; M sound</div>
  </section>
</main>
<div id="fakePointer" hidden><span class="ring"></span><svg width="26" height="30" viewBox="0 0 26 30" aria-hidden="true"><path d="M1 1 L1 23 L7 17.5 L11 27 L15 25.2 L11 16 L19 16 Z" fill="#fff" stroke="#111" stroke-width="1.6" stroke-linejoin="round"/></svg></div>
<div id="demoTag" hidden>DEMO &middot; tap anywhere to play</div>
<script>
(function(){
'use strict';
var P = 29.53, TAU = Math.PI * 2;
function $(id){ return document.getElementById(id); }
function mod(d){ return ((d % P) + P) % P; }
function clamp(v,a,b){ return v < a ? a : v > b ? b : v; }
function ease(f){ return f < .5 ? 2*f*f : 1 - Math.pow(-2*f + 2, 2) / 2; }
function mulberry32(a){ return function(){ a |= 0; a = a + 0x6D2B79F5 | 0; var t = Math.imul(a ^ a >>> 15, 1 | a); t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t; return ((t ^ t >>> 14) >>> 0) / 4294967296; }; }

var NAMES = ['New Moon','Waxing Crescent','First Quarter','Waxing Gibbous','Full Moon','Waning Gibbous','Last Quarter','Waning Crescent'];
var SHORT = ['New','Wax. cres.','1st qtr','Wax. gib.','Full','Wan. gib.','Last qtr','Wan. cres.'];
var DESC = [
  "The Moon is between Earth and the Sun. Its sunlit half faces away from us, so we see (almost) nothing.",
  "A thin sliver of the sunlit half is turning toward us. “Waxing” means growing.",
  "A quarter of the way around its orbit. We see half of the sunlit half, so it looks like a half-circle.",
  "More than half lit and still growing. “Gibbous” means bulging.",
  "The Moon is on the far side of Earth from the Sun. Its whole sunlit half faces us.",
  "Past full, the lit part we can see starts shrinking. “Waning” means shrinking.",
  "Three-quarters of the way around. Half-lit again, but now the other side is bright.",
  "Just a thin sliver left before the next New Moon."
];
function phaseIndex(d){
  var w = 1.0;
  if (d < w || d > P - w) return 0;
  if (d < P/4 - w) return 1;
  if (d <= P/4 + w) return 2;
  if (d < P/2 - w) return 3;
  if (d <= P/2 + w) return 4;
  if (d < 3*P/4 - w) return 5;
  if (d <= 3*P/4 + w) return 6;
  return 7;
}

var state = { day: 4.2, playing: false, hemi: 'N', rot: 0, shadow: false, eclipse: false, mode: 'tour', step: 0 };
var quiz = { i: 0, score: 0, answered: false, picked: -1 };
function angle(){ return mod(state.day) / P * TAU; }
function unlocked(){ return state.mode !== 'tour'; }

/* ---------- tweening ---------- */
var queue = [], cur = null;
function stopAnim(){ queue = []; cur = null; }
function animating(){ return !!cur || queue.length > 0; }
function plan(){
  var c = state.day, q = [];
  var api = {
    short: function(d, ms){ var dd = mod(d - c); if (dd > P/2) dd -= P; c += dd; q.push({to:c, ms:ms}); return api; },
    fwd: function(d, ms){ var dd = mod(d - c); if (dd > P - 0.02) dd = 0; c += dd; q.push({to:c, ms:ms}); return api; },
    around: function(ms){ c += P; q.push({to:c, ms:ms}); return api; },
    wait: function(ms){ q.push({to:null, ms:ms}); return api; },
    go: function(){ queue = q; cur = null; }
  };
  return api;
}
function stepTween(ms){
  if (!cur){ if (!queue.length) return; var n = queue.shift(); cur = {to:n.to, ms:Math.max(1, n.ms), t:0, from:state.day}; }
  cur.t += ms;
  var f = Math.min(1, cur.t / cur.ms);
  if (cur.to !== null) state.day = cur.from + (cur.to - cur.from) * ease(f);
  if (f >= 1){ cur = null; if (!queue.length) state.day = mod(state.day); }
}

/* ---------- sound ---------- */
var AC = null, master = null, muted = false;
function ensureAudio(){
  if (AC){ if (AC.state === 'suspended') AC.resume(); return; }
  try {
    var Ctx = window.AudioContext || window.webkitAudioContext;
    if (!Ctx) return;
    AC = new Ctx(); master = AC.createGain(); master.gain.value = muted ? 0 : 0.5; master.connect(AC.destination);
  } catch(e){ AC = null; }
}
function tone(freq, dur, type, vol, delay){
  if (!AC || muted) return;
  try {
    var t = AC.currentTime + (delay || 0);
    var o = AC.createOscillator(), g = AC.createGain();
    o.type = type || 'sine'; o.frequency.setValueAtTime(freq, t);
    g.gain.setValueAtTime(0.0001, t);
    g.gain.exponentialRampToValueAtTime(vol || 0.15, t + 0.012);
    g.gain.exponentialRampToValueAtTime(0.0001, t + dur);
    o.connect(g); g.connect(master); o.start(t); o.stop(t + dur + 0.05);
  } catch(e){}
}
var SCALE = [0, 2, 4, 7, 9, 12, 14, 16];
var sfx = {
  tick: function(i){ tone(392 * Math.pow(2, SCALE[i] / 12), 0.22, 'sine', 0.09); tone(784 * Math.pow(2, SCALE[i] / 12), 0.12, 'triangle', 0.025); },
  click: function(){ tone(700, 0.05, 'triangle', 0.05); },
  good: function(){ tone(660, 0.16, 'sine', 0.18); tone(880, 0.22, 'sine', 0.16, 0.11); tone(1320, 0.3, 'sine', 0.1, 0.22); },
  bad: function(){ tone(220, 0.22, 'sawtooth', 0.04); tone(185, 0.3, 'sawtooth', 0.035, 0.1); },
  swoosh: function(){ tone(300, 0.25, 'sine', 0.06); tone(450, 0.25, 'sine', 0.05, 0.08); }
};
window.addEventListener('pointerdown', ensureAudio, true);
window.addEventListener('keydown', ensureAudio, true);

/* ---------- canvases ---------- */
var O = { c: $('orbit') }, S = { c: $('sky') }, ST = { c: $('strip') };
var qualityCap = Math.min(2, window.devicePixelRatio || 1);
var ver = 0;
function sizeCanvas(o){
  var r = o.c.getBoundingClientRect();
  var w = Math.max(1, r.width), h = Math.max(1, r.height);
  var dpr = Math.min(qualityCap, window.devicePixelRatio || 1);
  o.w = w; o.h = h; o.dpr = dpr;
  o.c.width = Math.max(1, Math.round(w * dpr)); o.c.height = Math.max(1, Math.round(h * dpr));
  o.ctx = o.c.getContext('2d');
}
function makeLayer(o){
  var b = document.createElement('canvas'); b.width = o.c.width; b.height = o.c.height;
  var g = b.getContext('2d'); g.scale(o.dpr, o.dpr); return {b:b, g:g};
}

var LAND = (function(){
  var rnd = mulberry32(77), out = [];
  for (var i = 0; i < 6; i++){
    var a = rnd() * TAU, d = 0.3 + rnd() * 0.5, r = 0.14 + rnd() * 0.16;
    var x = Math.cos(a) * d, y = Math.sin(a) * d;
    out.push({x:x, y:y, r:r});
    for (var j = 0; j < 2; j++) out.push({x:x + (rnd() - .5) * r * 1.6, y:y + (rnd() - .5) * r * 1.6, r:r * (0.5 + rnd() * 0.4)});
  }
  return out;
})();

function buildOrbitBg(){
  var L = makeLayer(O), g = L.g, w = O.w, h = O.h, s = O.s;
  g.fillStyle = '#050816'; g.fillRect(0, 0, w, h);
  var rnd = mulberry32(12345), n = Math.round(w * h / 1700);
  g.fillStyle = '#fff';
  for (var i = 0; i < n; i++){
    var x = rnd() * w, y = rnd() * h, r = rnd() * 1.1 + 0.25;
    g.globalAlpha = 0.25 + rnd() * 0.6; g.beginPath(); g.arc(x, y, r, 0, TAU); g.fill();
  }
  g.globalAlpha = 1;
  var lg = g.createLinearGradient(w, 0, w * 0.3, 0);
  lg.addColorStop(0, 'rgba(255,200,90,0.20)'); lg.addColorStop(1, 'rgba(255,200,90,0)');
  g.fillStyle = lg; g.fillRect(0, 0, w, h);
  var sx = w + s * 0.06;
  var rg = g.createRadialGradient(sx, h/2, 0, sx, h/2, s * 0.34);
  rg.addColorStop(0, 'rgba(255,236,160,0.85)'); rg.addColorStop(0.28, 'rgba(255,190,80,0.28)'); rg.addColorStop(1, 'rgba(255,180,60,0)');
  g.fillStyle = rg; g.fillRect(0, 0, w, h);
  // faint parallel sunbeams
  g.strokeStyle = 'rgba(255,209,102,0.07)'; g.lineWidth = 1;
  var rows = 11;
  for (var k = 0; k < rows; k++){ var y2 = h * (k + 0.5) / rows; g.beginPath(); g.moveTo(w, y2); g.lineTo(0, y2); g.stroke(); }
  // arrows near the right edge
  g.strokeStyle = 'rgba(255,209,102,0.8)'; g.fillStyle = 'rgba(255,209,102,0.8)'; g.lineWidth = 2;
  var len = Math.max(26, s * 0.09);
  for (var k2 = 0; k2 < rows; k2++){
    var y3 = h * (k2 + 0.5) / rows;
    if (Math.abs(y3 - O.cy) < s * 0.09 || y3 < 40) continue;
    var x1 = w - 6, x0 = w - 6 - len;
    g.beginPath(); g.moveTo(x1, y3); g.lineTo(x0 + 6, y3); g.stroke();
    g.beginPath(); g.moveTo(x0, y3); g.lineTo(x0 + 8, y3 - 4.5); g.lineTo(x0 + 8, y3 + 4.5); g.closePath(); g.fill();
  }
  g.textAlign = 'right'; g.textBaseline = 'middle';
  g.font = '800 ' + (O.fs + 1) + 'px system-ui,sans-serif'; g.fillStyle = '#ffd166';
  g.fillText('SUNLIGHT ←', w - 10, 16);
  g.font = '600 ' + O.fs + 'px system-ui,sans-serif'; g.fillStyle = 'rgba(255,220,150,0.85)';
  g.fillText('from the far-away Sun', w - 10, 31);
  return L.b;
}

function buildSkyBg(){
  var L = makeLayer(S), g = L.g, w = S.w, h = S.h;
  var gr = g.createLinearGradient(0, 0, 0, h);
  gr.addColorStop(0, '#060c26'); gr.addColorStop(1, '#1c2756');
  g.fillStyle = gr; g.fillRect(0, 0, w, h);
  var rnd = mulberry32(4242), n = Math.round(w * h / 1300);
  g.fillStyle = '#fff';
  for (var i = 0; i < n; i++){ g.globalAlpha = 0.2 + rnd() * 0.6; g.beginPath(); g.arc(rnd() * w, rnd() * h * 0.85, rnd() * 1 + 0.25, 0, TAU); g.fill(); }
  g.globalAlpha = 1;
  function hy(x){ return h * 0.86 - (Math.sin(x * 0.013 + 1) * 0.035 + Math.sin(x * 0.037 + 2) * 0.015) * h; }
  g.fillStyle = '#04060e'; g.beginPath(); g.moveTo(0, h);
  for (var x = 0; x <= w + 4; x += 4) g.lineTo(x, hy(x));
  g.lineTo(w, h); g.closePath(); g.fill();
  // stargazer silhouette
  var px = w * 0.8, py = hy(px), f = Math.max(5, Math.min(w, h) * 0.03);
  g.strokeStyle = '#04060e'; g.fillStyle = '#04060e'; g.lineWidth = Math.max(2, f * 0.35); g.lineCap = 'round';
  g.beginPath(); g.moveTo(px - f * 0.4, py + 1); g.lineTo(px, py - f); g.lineTo(px + f * 0.4, py + 1);
  g.moveTo(px, py - f); g.lineTo(px, py - f * 1.9);
  g.moveTo(px, py - f * 1.6); g.lineTo(px - f * 0.8, py - f * 2.3); g.stroke();
  g.beginPath(); g.arc(px + f * 0.05, py - f * 2.3, f * 0.42, 0, TAU); g.fill();
  return L.b;
}

function buildMoonTex(px){
  var c = document.createElement('canvas'); c.width = c.height = px;
  var g = c.getContext('2d'), r = px / 2;
  g.beginPath(); g.arc(r, r, r, 0, TAU); g.clip();
  var base = g.createRadialGradient(r * 0.85, r * 0.8, r * 0.1, r, r, r);
  base.addColorStop(0, '#f6f2e6'); base.addColorStop(0.72, '#dcd7c8'); base.addColorStop(1, '#a9a495');
  g.fillStyle = base; g.fillRect(0, 0, px, px);
  var rnd = mulberry32(2024);
  var maria = [[-.28,-.35,.26],[.12,-.32,.2],[.32,-.06,.18],[-.38,.06,.22],[-.12,.14,.17],[.02,.42,.13],[.4,.26,.11],[-.05,-.08,.12]];
  g.fillStyle = 'rgba(92,96,110,0.26)';
  for (var i = 0; i < maria.length; i++){
    var m = maria[i];
    for (var j = 0; j < 5; j++){
      g.beginPath();
      g.arc(r + (m[0] + (rnd() - .5) * m[2]) * r, r + (m[1] + (rnd() - .5) * m[2]) * r, m[2] * r * (0.5 + rnd() * 0.5), 0, TAU);
      g.fill();
    }
  }
  for (var k = 0; k < 80; k++){
    var a = rnd() * TAU, d = Math.sqrt(rnd()) * 0.95;
    var x = r + Math.cos(a) * d * r, y = r + Math.sin(a) * d * r;
    var cr = (rnd() * rnd() * 0.06 + 0.01) * px;
    g.fillStyle = 'rgba(60,60,72,0.2)'; g.beginPath(); g.arc(x, y, cr, 0, TAU); g.fill();
    g.strokeStyle = 'rgba(255,255,255,0.2)'; g.lineWidth = Math.max(1, cr * 0.18);
    g.beginPath(); g.arc(x, y, cr, Math.PI * 0.1, Math.PI * 0.9); g.stroke();
  }
  // a bright rayed crater
  var tx = r * 0.82, ty = r * 1.62;
  g.strokeStyle = 'rgba(255,255,255,0.12)'; g.lineWidth = Math.max(1, px * 0.004);
  for (var q = 0; q < 14; q++){ var aa = rnd() * TAU, ll = (0.2 + rnd() * 0.45) * r; g.beginPath(); g.moveTo(tx, ty); g.lineTo(tx + Math.cos(aa) * ll, ty + Math.sin(aa) * ll); g.stroke(); }
  g.fillStyle = 'rgba(255,255,255,0.5)'; g.beginPath(); g.arc(tx, ty, px * 0.012, 0, TAU); g.fill();
  return c;
}

/* ---------- moon phase shape ---------- */
function moonPath(c, r, e){
  var k = Math.cos(e), waxing = Math.sin(e) >= 0, sgn = waxing ? 1 : -1;
  c.beginPath();
  c.arc(0, 0, r, -Math.PI / 2, Math.PI / 2, !waxing);
  var a = Math.max(Math.abs(k * r), 0.0001), mid = sgn * k;
  if (mid >= 0) c.ellipse(0, 0, a, r, 0, Math.PI / 2, -Math.PI / 2, true);
  else c.ellipse(0, 0, a, r, 0, Math.PI / 2, Math.PI * 1.5, false);
  c.closePath();
}
function drawMoon(c, x, y, r, e, tex, rot){
  c.save(); c.translate(x, y); if (rot) c.rotate(rot);
  c.beginPath(); c.arc(0, 0, r, 0, TAU); c.fillStyle = '#181b25'; c.fill();
  if (tex){ c.save(); c.clip(); c.globalAlpha = 0.15; c.drawImage(tex, -r, -r, 2 * r, 2 * r); c.restore(); }
  moonPath(c, r, e);
  if (tex){ c.save(); c.clip(); c.drawImage(tex, -r, -r, 2 * r, 2 * r); c.restore(); }
  else { c.fillStyle = '#efe8d2'; c.fill(); }
  c.restore();
}

/* ---------- Earth's shadow geometry (in Moon radii, sky view) ---------- */
function shadowGeom(e){
  var a = e - Math.PI; a = Math.atan2(Math.sin(a), Math.cos(a));
  var node = state.eclipse ? Math.PI : Math.PI / 2;
  var dx = a * 180 / Math.PI * 0.11;
  var dy = 3.9 * Math.sin(e - node);
  var dist = Math.hypot(dx, dy), UR = 2.4;
  return { a:a, dx:dx, dy:dy, dist:dist, UR:UR, cover:clamp((UR + 1 - dist) / 2, 0, 1), total: dist < UR - 1, node:node };
}

/* ---------- draw: orbit ---------- */
function drawOrbit(){
  var c = O.ctx; if (!c) return;
  var w = O.w, h = O.h, s = O.s, cx = O.cx, cy = O.cy, R = O.R, rE = O.rE, rM = O.rM, e = angle();
  c.setTransform(O.dpr, 0, 0, O.dpr, 0, 0);
  c.drawImage(O.bg, 0, 0, w, h);
  var tour = state.mode === 'tour';
  var showLit = !tour || state.step >= 1, showView = !tour || state.step >= 2;
  var G = shadowGeom(e);

  // Earth's shadow
  if (state.shadow){
    c.save();
    var sg = c.createLinearGradient(cx, 0, 0, 0);
    sg.addColorStop(0, 'rgba(0,0,0,0.72)'); sg.addColorStop(1, 'rgba(0,0,0,0.35)');
    c.fillStyle = sg;
    c.beginPath(); c.moveTo(cx, cy - rE); c.lineTo(0, cy - rE * 0.75); c.lineTo(0, cy + rE * 0.75); c.lineTo(cx, cy + rE); c.closePath(); c.fill();
    c.setLineDash([5, 4]); c.strokeStyle = 'rgba(255,140,110,0.75)'; c.lineWidth = 1.5;
    c.beginPath(); c.moveTo(cx, cy - rE); c.lineTo(0, cy - rE * 0.75); c.moveTo(cx, cy + rE); c.lineTo(0, cy + rE * 0.75); c.stroke();
    c.setLineDash([]);
    c.font = '700 ' + O.fs + 'px system-ui,sans-serif'; c.textAlign = 'left'; c.textBaseline = 'bottom';
    c.fillStyle = '#ff9c80'; c.fillText("Earth's shadow", 8, cy - rE - 5);
    c.restore();
  }

  // orbit ring
  c.save(); c.setLineDash([4, 6]); c.strokeStyle = 'rgba(200,210,255,0.35)'; c.lineWidth = 1.5;
  c.beginPath(); c.arc(cx, cy, R, 0, TAU); c.stroke(); c.restore();
  // direction arrow (counter-clockwise)
  var a0 = 1.95, ax = cx + R * Math.cos(a0), ay = cy - R * Math.sin(a0);
  var tx = -Math.sin(a0), ty = -Math.cos(a0), nx = -ty, ny = tx, as = Math.max(5, s * 0.018);
  c.fillStyle = 'rgba(200,210,255,0.75)'; c.beginPath();
  c.moveTo(ax + tx * as, ay + ty * as); c.lineTo(ax - tx * as + nx * as * 0.7, ay - ty * as + ny * as * 0.7); c.lineTo(ax - tx * as - nx * as * 0.7, ay - ty * as - ny * as * 0.7);
  c.closePath(); c.fill();

  // phase markers
  var idx = phaseIndex(mod(state.day));
  for (var k = 0; k < 8; k++){
    var a = k * TAU / 8, mx = cx + R * Math.cos(a), my = cy - R * Math.sin(a);
    c.beginPath(); c.arc(mx, my, k === idx ? 4.5 : 3, 0, TAU);
    c.fillStyle = k === idx ? '#ffd166' : 'rgba(200,210,255,0.55)'; c.fill();
    if (O.labels){
      var lr = R + rM + 9, lx = cx + lr * Math.cos(a), ly = cy - lr * Math.sin(a), ca = Math.cos(a), sa = Math.sin(a);
      c.textAlign = ca > 0.3 ? 'left' : ca < -0.3 ? 'right' : 'center';
      c.textBaseline = sa > 0.3 ? 'bottom' : sa < -0.3 ? 'top' : 'middle';
      c.font = (k === idx ? '800 ' : '600 ') + O.fs + 'px system-ui,sans-serif';
      c.fillStyle = k === idx ? '#ffd166' : 'rgba(200,210,255,0.7)';
      c.fillText(O.labels === 'full' ? NAMES[k] : SHORT[k], lx, ly);
    }
  }

  var ce = Math.cos(e), se = Math.sin(e);
  var mx2 = cx + R * ce, my2 = cy - R * se;
  // line of sight
  if (showView){
    c.save(); c.setLineDash([3, 4]); c.strokeStyle = 'rgba(90,209,255,0.65)'; c.lineWidth = 1.5;
    var r0 = rE + O.f * 2.6, r1 = R - rM - 9;
    c.beginPath(); c.moveTo(cx + r0 * ce, cy - r0 * se); c.lineTo(cx + r1 * ce, cy - r1 * se); c.stroke(); c.restore();
  }

  // Earth
  c.save(); c.beginPath(); c.arc(cx, cy, rE, 0, TAU); c.clip();
  c.fillStyle = '#2d6fd8'; c.fillRect(cx - rE, cy - rE, rE * 2, rE * 2);
  c.fillStyle = '#3faa5c';
  for (var i = 0; i < LAND.length; i++){ var b = LAND[i]; c.beginPath(); c.arc(cx + b.x * rE, cy + b.y * rE, b.r * rE, 0, TAU); c.fill(); }
  c.fillStyle = 'rgba(255,255,255,0.9)'; c.beginPath(); c.arc(cx, cy, rE * 0.17, 0, TAU); c.fill();
  c.fillStyle = 'rgba(3,6,20,0.64)'; c.fillRect(cx - rE, cy - rE, rE, rE * 2);
  c.restore();
  c.strokeStyle = 'rgba(130,195,255,0.65)'; c.lineWidth = 2; c.beginPath(); c.arc(cx, cy, rE + 1, 0, TAU); c.stroke();

  // stargazer on Earth, facing the Moon
  drawObserver(c, cx, cy, rE, e, O.f);

  // Moon (top view: sun-facing half lit)
  c.beginPath(); c.arc(mx2, my2, rM, 0, TAU); c.fillStyle = '#2a2e3b'; c.fill();
  c.beginPath(); c.moveTo(mx2, my2); c.arc(mx2, my2, rM, -Math.PI / 2, Math.PI / 2); c.closePath(); c.fillStyle = '#f6f0da'; c.fill();
  if (state.shadow && G.cover > 0){ c.beginPath(); c.arc(mx2, my2, rM, 0, TAU); c.fillStyle = 'rgba(170,55,25,' + (0.8 * G.cover).toFixed(3) + ')'; c.fill(); }
  c.lineWidth = 1; c.strokeStyle = 'rgba(255,255,255,0.3)'; c.beginPath(); c.arc(mx2, my2, rM, 0, TAU); c.stroke();
  if (showLit){ c.lineWidth = 3; c.strokeStyle = '#ffd166'; c.beginPath(); c.arc(mx2, my2, rM + 3, -Math.PI / 2, Math.PI / 2); c.stroke(); }
  if (showView){ var cA = -e - Math.PI; c.lineWidth = 3; c.strokeStyle = '#5ad1ff'; c.beginPath(); c.arc(mx2, my2, rM + 7.5, cA - Math.PI / 2, cA + Math.PI / 2); c.stroke(); }

  // labels
  c.lineJoin = 'round';
  c.font = '800 ' + (O.fs + 1) + 'px system-ui,sans-serif'; c.textAlign = 'center'; c.textBaseline = 'middle';
  var mlx = mx2 - ce * (rM + 20), mly = my2 + se * (rM + 20);
  c.lineWidth = 4; c.strokeStyle = 'rgba(5,8,22,0.85)'; c.strokeText('Moon', mlx, mly); c.fillStyle = '#fff'; c.fillText('Moon', mlx, mly);
  var elx = cx, ely = cy + rE + 12 + (se < -0.6 ? O.f * 2.4 : 0);
  c.strokeText('Earth', elx, ely); c.fillStyle = '#9fd0ff'; c.fillText('Earth', elx, ely);

  // legend
  var lyy = 14; c.font = '600 ' + O.fs + 'px system-ui,sans-serif'; c.textAlign = 'left'; c.textBaseline = 'middle'; c.lineWidth = 3;
  if (showLit){ c.strokeStyle = '#ffd166'; c.beginPath(); c.moveTo(10, lyy); c.lineTo(26, lyy); c.stroke(); c.fillStyle = '#ffe7ad'; c.fillText('sunlit half', 32, lyy); lyy += 17; }
  if (showView){ c.strokeStyle = '#5ad1ff'; c.beginPath(); c.moveTo(10, lyy); c.lineTo(26, lyy); c.stroke(); c.fillStyle = '#bdeeff'; c.fillText('half facing Earth', 32, lyy); lyy += 17; }

  if (state.shadow){
    drawSideInset(c, e, G);
    if (!state.eclipse && Math.abs(G.a) < 0.45){
      c.font = '700 ' + O.fs + 'px system-ui,sans-serif'; c.textAlign = 'left'; c.textBaseline = 'top';
      c.fillStyle = '#ffb4a0'; c.fillText('Looks like a hit from above, but', 8, cy + rE + 6);
      c.fillText('the Moon passes over it (side view)', 8, cy + rE + 8 + O.fs);
    }
  }
}
function drawObserver(c, cx, cy, rE, e, f){
  var ux = Math.cos(e), uy = -Math.sin(e), px = -uy, py = ux;
  var bx = cx + ux * rE, by = cy + uy * rE;
  c.save(); c.lineCap = 'round';
  function body(col, lw){
    c.strokeStyle = col; c.lineWidth = lw;
    var hx = bx + ux * f * 0.9, hy = by + uy * f * 0.9, nx = bx + ux * f * 1.7, ny = by + uy * f * 1.7;
    c.beginPath();
    c.moveTo(bx + px * f * 0.45, by + py * f * 0.45); c.lineTo(hx, hy); c.lineTo(bx - px * f * 0.45, by - py * f * 0.45);
    c.moveTo(hx, hy); c.lineTo(nx, ny);
    c.moveTo(bx + ux * f * 1.25 + px * f * 0.6, by + uy * f * 1.25 + py * f * 0.6); c.lineTo(bx + ux * f * 1.55, by + uy * f * 1.55); c.lineTo(bx + ux * f * 1.25 - px * f * 0.6, by + uy * f * 1.25 - py * f * 0.6);
    c.stroke();
  }
  body('rgba(5,8,22,0.9)', Math.max(3, f * 0.6));
  body('#ffffff', Math.max(1.5, f * 0.3));
  c.beginPath(); c.arc(bx + ux * f * 2.15, by + uy * f * 2.15, f * 0.45, 0, TAU);
  c.fillStyle = '#ffe08a'; c.fill(); c.lineWidth = 1; c.strokeStyle = 'rgba(5,8,22,0.9)'; c.stroke();
  c.restore();
}
function roundRect(c, x, y, w, h, r){
  c.beginPath(); c.moveTo(x + r, y); c.lineTo(x + w - r, y); c.quadraticCurveTo(x + w, y, x + w, y + r); c.lineTo(x + w, y + h - r);
  c.quadraticCurveTo(x + w, y + h, x + w - r, y + h); c.lineTo(x + r, y + h); c.quadraticCurveTo(x, y + h, x, y + h - r); c.lineTo(x, y + r); c.quadraticCurveTo(x, y, x + r, y); c.closePath();
}
function drawSideInset(c, e, G){
  var s = O.s, iw = Math.max(120, s * 0.36), ih = Math.max(58, s * 0.17), x = 8, y = O.h - ih - 8;
  c.save();
  roundRect(c, x, y, iw, ih, 10); c.fillStyle = 'rgba(8,11,26,0.9)'; c.fill(); c.strokeStyle = '#2b3557'; c.lineWidth = 1; c.stroke();
  c.font = '700 ' + Math.max(9, O.fs - 1) + 'px system-ui,sans-serif'; c.textAlign = 'left'; c.textBaseline = 'top'; c.fillStyle = '#9aa3c0';
  c.fillText('SIDE VIEW (tilt exaggerated)', x + 7, y + 5);
  c.textAlign = 'right'; c.fillStyle = '#ffd166'; c.fillText('Sun →', x + iw - 6, y + 5);
  var ex = x + iw * 0.6, ey = y + ih * 0.6, er = Math.max(3, ih * 0.09), Rw = iw * 0.32, Rh = ih * 0.25;
  c.save(); roundRect(c, x, y, iw, ih, 10); c.clip();
  c.fillStyle = 'rgba(0,0,0,0.75)'; c.fillRect(x, ey - er, ex - x, er * 2);
  c.setLineDash([3, 3]); c.strokeStyle = 'rgba(255,140,110,0.7)';
  c.beginPath(); c.moveTo(x, ey - er); c.lineTo(ex, ey - er); c.moveTo(x, ey + er); c.lineTo(ex, ey + er); c.stroke();
  c.strokeStyle = 'rgba(200,210,255,0.5)'; c.beginPath();
  for (var i = 0; i <= 48; i++){ var t = i / 48 * TAU, px = ex + Rw * Math.cos(t), py = ey - Rh * Math.sin(t - G.node); if (i) c.lineTo(px, py); else c.moveTo(px, py); }
  c.stroke(); c.setLineDash([]);
  c.restore();
  c.beginPath(); c.arc(ex, ey, er, 0, TAU); c.fillStyle = '#2d6fd8'; c.fill();
  c.beginPath(); c.arc(ex, ey, er, -Math.PI / 2, Math.PI / 2); c.fillStyle = '#6fb0ff'; c.fill();
  var mx = ex + Rw * Math.cos(e), my = ey - Rh * Math.sin(e - G.node), mr = Math.max(2.5, er * 0.55);
  c.beginPath(); c.arc(mx, my, mr, 0, TAU); c.fillStyle = G.cover > 0 ? '#d0603c' : '#f6f0da'; c.fill();
  c.restore();
}

/* ---------- draw: sky ---------- */
function drawSky(){
  var c = S.ctx; if (!c) return;
  var w = S.w, h = S.h, r = S.r, cx = w / 2, cy = S.cy, e = angle();
  c.setTransform(S.dpr, 0, 0, S.dpr, 0, 0);
  c.drawImage(S.bg, 0, 0, w, h);
  var lit = (1 - Math.cos(e)) / 2;
  if (lit > 0.02){
    var gr = c.createRadialGradient(cx, cy, r * 0.9, cx, cy, r * 2.3);
    gr.addColorStop(0, 'rgba(255,248,225,' + (0.2 * lit).toFixed(3) + ')'); gr.addColorStop(1, 'rgba(255,248,225,0)');
    c.fillStyle = gr; c.fillRect(0, 0, w, h);
  }
  c.save(); c.translate(cx, cy); c.rotate(state.rot);
  drawMoon(c, 0, 0, r, e, S.tex, 0);
  var G = null;
  if (state.shadow){
    G = shadowGeom(e);
    if (Math.abs(G.dx) < 14){
      var X = G.dx * r, Y = G.dy * r;
      c.save();
      c.beginPath(); c.arc(X, Y, 4.3 * r, 0, TAU); c.fillStyle = 'rgba(0,0,0,0.10)'; c.fill();
      c.beginPath(); c.arc(X, Y, G.UR * r, 0, TAU); c.fillStyle = 'rgba(25,0,0,0.28)'; c.fill();
      c.setLineDash([6, 5]); c.lineWidth = 2; c.strokeStyle = 'rgba(255,140,110,0.85)'; c.stroke(); c.setLineDash([]);
      c.beginPath(); c.arc(0, 0, r, 0, TAU); c.clip();
      c.beginPath(); c.arc(X, Y, 4.3 * r, 0, TAU); c.fillStyle = 'rgba(0,0,0,0.16)'; c.fill();
      c.globalCompositeOperation = 'multiply';
      c.beginPath(); c.arc(X, Y, G.UR * r, 0, TAU); c.fillStyle = 'rgb(165,62,32)'; c.fill();
      c.globalCompositeOperation = 'source-over';
      c.fillStyle = 'rgba(130,35,12,0.22)'; c.fill();
      c.restore();
    } else G = null;
  }
  c.restore();
  if (G){
    var cs = Math.cos(state.rot), sn = Math.sin(state.rot), X2 = G.dx * r, Y2 = G.dy * r;
    var lx = cx + X2 * cs - Y2 * sn, ly = cy + X2 * sn + Y2 * cs;
    if (G.dist < G.UR + 1.2){ lx = cx; ly = cy + r + 14; }
    lx = clamp(lx, 55, w - 55); ly = clamp(ly, 14, h - 14);
    c.font = '800 12px system-ui,sans-serif'; c.textAlign = 'center'; c.textBaseline = 'middle'; c.lineJoin = 'round';
    c.lineWidth = 4; c.strokeStyle = 'rgba(0,0,0,0.75)'; c.strokeText("Earth's shadow", lx, ly);
    c.fillStyle = '#ffb4a0'; c.fillText("Earth's shadow", lx, ly);
  }
}

/* ---------- draw: phase strip ---------- */
function drawStrip(){
  var c = ST.ctx; if (!c) return;
  c.setTransform(ST.dpr, 0, 0, ST.dpr, 0, 0); c.clearRect(0, 0, ST.w, ST.h);
  var idx = phaseIndex(mod(state.day)), r = Math.min(9, ST.h * 0.3), y = ST.h / 2;
  for (var k = 0; k <= 8; k++){
    var x = 14 + (k / 8) * (ST.w - 28);
    var hl = (k % 8) === idx;
    if (hl){ c.beginPath(); c.arc(x, y, r + 5, 0, TAU); c.fillStyle = 'rgba(255,209,102,0.28)'; c.fill(); }
    drawMoon(c, x, y, r, k * TAU / 8, null, state.rot);
    c.beginPath(); c.arc(x, y, r, 0, TAU); c.lineWidth = 1; c.strokeStyle = hl ? '#ffd166' : 'rgba(255,255,255,0.3)'; c.stroke();
  }
}

/* ---------- DOM refs ---------- */
var phaseName = $('phaseName'), phaseMeta = $('phaseMeta'), phaseDesc = $('phaseDesc'), dayLabel = $('dayLabel');
var scrub = $('scrub'), playBtn = $('playBtn'), minusBtn = $('minusBtn'), plusBtn = $('plusBtn');
var hemiSw = $('hemiSw'), shadowSw = $('shadowSw'), eclipseBtn = $('eclipseBtn'), lockNote = $('lockNote'), dragHint = $('dragHint');
var muteBtn = $('muteBtn'), restartBtn = $('restartBtn'), guideInner = $('guideInner'), hemiTag = $('hemiTag');

function shadowCaption(e){
  var G = shadowGeom(e), dir = state.hemi === 'N' ? 'below' : 'above';
  if (G.total) return "Total lunar eclipse! The Moon is completely inside Earth's shadow, so it glows a dim coppery red.";
  if (G.cover > 0) return "Lunar eclipse! Earth's shadow is sliding across the Full Moon. This is the ONLY time the shadow touches the Moon.";
  if (Math.abs(G.a) < 0.7) return state.eclipse ? "Earth's shadow is close. Keep moving toward Full Moon to see the eclipse!" : "Full Moon, but this month Earth's shadow passes just " + dir + " it, because the Moon's orbit is a bit tilted. No eclipse.";
  return "Earth's shadow points away from the Sun, far from the Moon. It is NOT what makes this phase!";
}
var lastPhaseIdx = -1, lastTxt = {};
function setText(el, key, txt){ if (lastTxt[key] !== txt){ lastTxt[key] = txt; el.textContent = txt; } }
function updateDOM(){
  var d = mod(state.day), e = d / P * TAU, idx = phaseIndex(d);
  if (idx !== lastPhaseIdx){
    phaseName.textContent = NAMES[idx];
    phaseName.classList.remove('pop'); void phaseName.offsetWidth; phaseName.classList.add('pop');
    if (lastPhaseIdx !== -1) sfx.tick(idx);
    lastPhaseIdx = idx;
  }
  var lit = (1 - Math.cos(e)) / 2, side;
  if (lit > 0.97) side = 'the whole face is lit';
  else if (lit < 0.03) side = 'almost nothing lit faces us';
  else side = 'bright side on the ' + (((Math.sin(e) > 0) === (state.hemi === 'N')) ? 'right' : 'left');
  setText(phaseMeta, 'meta', 'Day ' + d.toFixed(1) + ' · ' + Math.round(lit * 100) + '% lit · ' + side);
  var cap = state.shadow ? shadowCaption(e) : DESC[idx];
  setText(phaseDesc, 'desc', cap);
  phaseDesc.classList.toggle('shadowmsg', state.shadow);
  setText(dayLabel, 'day', 'Day ' + d.toFixed(1) + ' of 29.5 · ' + NAMES[idx]);
  if (Math.abs(parseFloat(scrub.value) - d) > 0.005) scrub.value = d.toFixed(2);
  scrub.style.setProperty('--p', (d / P * 100).toFixed(2) + '%');
}

/* ---------- controls ---------- */
function setShadow(v){ state.shadow = v; if (!v) state.eclipse = false; updateSwitches(); }
function setHemi(h){ state.hemi = h; updateSwitches(); }
function setPlaying(v){
  state.playing = v; if (v) stopAnim();
  playBtn.innerHTML = v ? '&#10074;&#10074;' : '&#9654;';
  playBtn.setAttribute('aria-label', v ? 'Pause' : 'Play');
}
function updateSwitches(){
  hemiSw.setAttribute('aria-checked', state.hemi === 'S' ? 'true' : 'false');
  hemiTag.textContent = state.hemi === 'S' ? '(Southern Hemisphere)' : '(Northern Hemisphere)';
  shadowSw.setAttribute('aria-checked', state.shadow ? 'true' : 'false');
  eclipseBtn.setAttribute('aria-pressed', state.eclipse ? 'true' : 'false');
  eclipseBtn.textContent = state.eclipse ? 'Eclipse lined up ✓' : 'Line up an eclipse';
  applyLocks();
}
function applyLocks(){
  var un = unlocked(), sh = un || state.step === 5;
  scrub.disabled = !un; playBtn.disabled = !un; minusBtn.disabled = !un; plusBtn.disabled = !un;
  hemiSw.disabled = !un; shadowSw.disabled = !sh; eclipseBtn.disabled = !(sh && state.shadow);
  lockNote.hidden = un; dragHint.hidden = !un;
  if (!un && state.playing) setPlaying(false);
}
function nudgeLock(){ lockNote.classList.remove('shake'); void lockNote.offsetWidth; lockNote.classList.add('shake'); }
function userSetDay(d){ stopAnim(); setPlaying(false); state.day = mod(d); }

scrub.addEventListener('input', function(){ if (!unlocked()) return; userSetDay(parseFloat(scrub.value)); });
playBtn.addEventListener('click', function(){ if (!unlocked()) return; sfx.click(); setPlaying(!state.playing); });
minusBtn.addEventListener('click', function(){ if (!unlocked()) return; setPlaying(false); plan().short(mod(state.day) - 1, 260).go(); });
plusBtn.addEventListener('click', function(){ if (!unlocked()) return; setPlaying(false); plan().short(mod(state.day) + 1, 260).go(); });
hemiSw.addEventListener('click', function(){ if (hemiSw.disabled) return; sfx.swoosh(); setHemi(state.hemi === 'N' ? 'S' : 'N'); });
shadowSw.addEventListener('click', function(){ if (shadowSw.disabled) return; sfx.click(); setShadow(!state.shadow); });
eclipseBtn.addEventListener('click', function(){
  if (eclipseBtn.disabled) return; sfx.click();
  state.eclipse = !state.eclipse; updateSwitches();
  if (state.eclipse && Math.abs(mod(state.day) - P / 2) > 2.5){ setPlaying(false); plan().short(P / 2 - 2.2, 700).wait(200).fwd(P / 2, 2600).go(); }
});
muteBtn.addEventListener('click', function(){
  muted = !muted; if (master) master.gain.value = muted ? 0 : 0.5;
  muteBtn.innerHTML = muted ? '&#9834; Muted' : '&#9834; Sound on';
  muteBtn.setAttribute('aria-pressed', muted ? 'true' : 'false');
  if (!muted) sfx.click();
});
restartBtn.addEventListener('click', function(){ resetAll(); });

// orbit dragging
var drag = null;
function localPt(ev, el){ var r = el.getBoundingClientRect(); return { x: ev.clientX - r.left, y: ev.clientY - r.top }; }
function setAngleFrom(dx, dy){ var a = Math.atan2(-dy, dx); if (a < 0) a += TAU; state.day = a / TAU * P; }
O.c.addEventListener('pointerdown', function(ev){
  if (!unlocked()){ nudgeLock(); return; }
  var p = localPt(ev, O.c), dx = p.x - O.cx, dy = p.y - O.cy;
  if (Math.hypot(dx, dy) < O.rE * 0.9) return;
  ev.preventDefault();
  try { O.c.setPointerCapture(ev.pointerId); } catch(_){}
  drag = { id: ev.pointerId, x0: p.x, y0: p.y, moved: 0 };
  stopAnim(); setPlaying(false); setAngleFrom(dx, dy);
});
O.c.addEventListener('pointermove', function(ev){
  if (!drag || ev.pointerId !== drag.id) return;
  var p = localPt(ev, O.c);
  drag.moved = Math.max(drag.moved, Math.hypot(p.x - drag.x0, p.y - drag.y0));
  setAngleFrom(p.x - O.cx, p.y - O.cy);
});
function endDrag(ev){
  if (!drag || (ev && ev.pointerId !== drag.id)) return;
  if (drag.moved < 6){
    var d = mod(state.day), k = Math.round(d / (P / 8));
    if (Math.abs(d - k * P / 8) < P / 8 * 0.35) plan().short((k % 8) * P / 8, 250).go();
  }
  drag = null;
}
O.c.addEventListener('pointerup', endDrag);
O.c.addEventListener('pointercancel', endDrag);
ST.c.addEventListener('pointerdown', function(ev){
  if (!unlocked()){ nudgeLock(); return; }
  var p = localPt(ev, ST.c), k = clamp(Math.round((p.x - 14) / Math.max(1, ST.w - 28) * 8), 0, 8);
  setPlaying(false); plan().short((k % 8) * P / 8, 450).go();
});

/* ---------- tour ---------- */
var STEPS = [
  { title: 'Sunlight comes from one side',
    text: "This top view looks down on Earth from high above the North Pole. The Sun is far off to the right, so its light streams in from that side. The Moon makes no light of its own: moonlight is just sunlight bouncing off it.",
    enter: function(){ plan().short(4.2, 900).go(); } },
  { title: 'Half the Moon is always lit',
    text: "Watch the Moon go around Earth. The half facing the Sun (yellow outline) is always bright, and the far half is always dark. Earth works the same way: it's daytime on the side facing the Sun.",
    enter: function(){ plan().short(4.2, 500).around(6000).go(); } },
  { title: 'You only see the half that faces you',
    text: "The little stargazer on Earth can only see the Moon's Earth-facing half (blue outline). The phase is the overlap: how much of the sunlit half is also turned toward you. At New Moon the Moon sits between us and the Sun, so its lit half faces away and we see almost nothing.",
    enter: function(){ plan().short(0, 1200).go(); } },
  { title: 'Waxing: the bright part grows',
    text: "Each day the Moon moves about 1/30 of the way around its orbit, and more of its sunlit half swings into view: first a waxing crescent, then, after about a week, First Quarter. It looks like half a circle, but it's called a “quarter” because the Moon is a quarter of the way around.",
    enter: function(){ plan().short(0, 700).wait(300).fwd(P / 4, 3600).go(); } },
  { title: 'Full Moon, then waning',
    text: "About two weeks in, the Moon is on the far side of Earth from the Sun, and its whole sunlit half faces us: Full Moon! After that, the part we see shrinks (waning gibbous, Last Quarter, waning crescent) until New Moon comes back, about 29.5 days after the last one.",
    enter: function(){ plan().short(P / 4, 600).fwd(P / 2, 2600).wait(800).fwd(3 * P / 4, 2600).go(); } },
  { title: "Myth buster: it's NOT Earth's shadow",
    text: "Lots of people think Earth's shadow makes the phases. Look: Earth's shadow (now switched on) always points straight away from the Sun. At this First Quarter Moon, it's nowhere near the Moon! The shadow only touches the Moon during a lunar eclipse, which can only happen at Full Moon. Tap “Line up an eclipse” to see one.",
    enter: function(){ setShadow(true); plan().short(P / 4, 1200).go(); } }
];
function enterStep(i){
  state.mode = 'tour'; state.step = clamp(i, 0, STEPS.length - 1);
  setPlaying(false); setHemi('N');
  if (state.step < 5) setShadow(false);
  STEPS[state.step].enter();
  renderGuide();
}
function startTour(){ enterStep(0); }
function goFree(){ state.mode = 'free'; renderGuide(); }

/* ---------- quiz ---------- */
var QUIZ = [
  { q: 'Why does the Moon have phases?',
    opts: ["Earth's shadow covers part of the Moon", 'As the Moon orbits Earth, we see different amounts of its sunlit half', 'The Moon really changes shape during the month', 'Clouds on the Moon block some of its light'],
    ans: 1,
    yes: 'Yes! Half the Moon is always sunlit. Where it is in its orbit decides how much of that lit half faces us.',
    no: 'Not quite. Half the Moon is always sunlit; the phase depends on how much of that lit half is turned toward Earth.',
    show: function(){ plan().short(P / 4, 900).go(); } },
  { q: 'At Full Moon, where is the Moon?',
    opts: ['Between Earth and the Sun', 'Off to the side, a quarter of the way around', 'On the far side of Earth, opposite the Sun'],
    ans: 2,
    yes: 'Right! With the Sun behind us, the Moon’s whole sunlit half faces Earth.',
    no: 'Not quite. Between Earth and Sun is New Moon. At Full Moon, the Moon is opposite the Sun, so its whole lit half faces us.',
    show: function(){ plan().short(P / 2, 1100).go(); } },
  { q: "When does Earth's shadow actually fall on the Moon?",
    opts: ['Only during a lunar eclipse, which can happen only at Full Moon', 'Every night: it makes the dark part of the Moon', 'At every New Moon'],
    ans: 0,
    yes: "Exactly! Earth's shadow points away from the Sun, so it can only reach the Moon at Full Moon, and only when everything lines up.",
    no: "Nope! The shadow points away from the Sun. It only reaches the Moon during a lunar eclipse, at Full Moon.",
    show: function(){ setShadow(true); state.eclipse = true; updateSwitches(); plan().short(P / 2, 1100).go(); } }
];
function startQuiz(){ quiz = { i: 0, score: 0, answered: false, picked: -1 }; state.mode = 'quiz'; renderGuide(); }
function answer(j){
  if (quiz.answered) return;
  var Q = QUIZ[quiz.i]; quiz.answered = true; quiz.picked = j;
  if (j === Q.ans){ quiz.score++; sfx.good(); } else sfx.bad();
  setPlaying(false); Q.show(); renderGuide();
}

function esc(t){ return String(t).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;'); }
function renderGuide(){
  var html = '';
  if (state.mode === 'tour'){
    var st = STEPS[state.step], dots = '';
    for (var i = 0; i < STEPS.length; i++) dots += '<i class="' + (i <= state.step ? 'on' : '') + '"></i>';
    html = '<div class="gtop"><span>Step ' + (state.step + 1) + ' of ' + STEPS.length + '</span><span class="dots" aria-hidden="true">' + dots + '</span></div>' +
      '<h3>' + esc(st.title) + '</h3><p>' + esc(st.text) + '</p>' +
      '<div class="gbtns"><button class="btn" data-act="back"' + (state.step === 0 ? ' disabled' : '') + '>&larr; Back</button>' +
      '<button class="btn primary" data-act="next">' + (state.step === STEPS.length - 1 ? 'Start free play &rarr;' : 'Next &rarr;') + '</button>' +
      '<button class="btn ghost" data-act="skip">Skip tour</button></div>';
  } else if (state.mode === 'free'){
    html = '<span class="badge">Free play unlocked</span><h3>Your turn to explore!</h3>' +
      '<p>Drag the Moon around its orbit, scrub the timeline or press Play. Flip the Hemisphere switch to South to see why the Moon looks upside-down from places like Australia or Chile. Turn on Earth’s shadow and line up an eclipse. Then test yourself!</p>' +
      '<div class="gbtns"><button class="btn primary" data-act="quiz">Take the quiz (3 questions)</button><button class="btn" data-act="tour">Replay tour</button></div>';
  } else if (state.mode === 'quiz'){
    var Q = QUIZ[quiz.i], opts = '';
    for (var j = 0; j < Q.opts.length; j++){
      var cls = 'opt';
      if (quiz.answered){ if (j === Q.ans) cls += ' right'; else if (j === quiz.picked) cls += ' wrong'; }
      opts += '<button class="' + cls + '" data-act="ans" data-i="' + j + '"' + (quiz.answered ? ' disabled' : '') + '>' + esc(Q.opts[j]) + '</button>';
    }
    var fb = '';
    if (quiz.answered){ var ok = quiz.picked === Q.ans; fb = '<p class="fb ' + (ok ? 'good' : 'bad') + '">' + (ok ? '✓ ' : '✗ ') + esc(ok ? Q.yes : Q.no) + '</p>'; }
    html = '<div class="gtop"><span>Quiz &middot; Question ' + (quiz.i + 1) + ' of ' + QUIZ.length + '</span><span>Score ' + quiz.score + '</span></div>' +
      '<h3>' + esc(Q.q) + '</h3><div class="opts">' + opts + '</div>' + fb +
      '<div class="gbtns">' + (quiz.answered ? '<button class="btn primary" data-act="qnext">' + (quiz.i === QUIZ.length - 1 ? 'See my score' : 'Next question &rarr;') + '</button>' : '') +
      '<button class="btn ghost" data-act="free">Back to free play</button></div>';
  } else {
    var msg = quiz.score === 3 ? 'Perfect! You really get why the Moon has phases.' : quiz.score === 2 ? 'Great job! Try the one you missed again.' : 'Good try! Replay the tour and have another go.';
    html = '<span class="badge">Quiz done</span><h3>You got ' + quiz.score + ' of 3!</h3><p>' + msg + '</p>' +
      '<div class="gbtns"><button class="btn primary" data-act="quiz">Try again</button><button class="btn" data-act="free">Free play</button><button class="btn ghost" data-act="tour">Replay tour</button></div>';
  }
  guideInner.innerHTML = html;
  applyLocks();
  ver++;
}
$('guide').addEventListener('click', function(ev){
  var b = ev.target.closest ? ev.target.closest('[data-act]') : null;
  if (!b || b.disabled) return;
  var act = b.getAttribute('data-act');
  if (act !== 'ans') sfx.click();
  if (act === 'back') enterStep(state.step - 1);
  else if (act === 'next'){ if (state.step < STEPS.length - 1) enterStep(state.step + 1); else goFree(); }
  else if (act === 'skip') goFree();
  else if (act === 'quiz') startQuiz();
  else if (act === 'tour') startTour();
  else if (act === 'free') goFree();
  else if (act === 'ans') answer(parseInt(b.getAttribute('data-i'), 10));
  else if (act === 'qnext'){ quiz.i++; quiz.answered = false; quiz.picked = -1; if (quiz.i >= QUIZ.length) state.mode = 'done'; renderGuide(); }
});

/* ---------- keyboard ---------- */
window.addEventListener('keydown', function(ev){
  var t = ev.target, tag = t && t.tagName, k = ev.key;
  if (ev.ctrlKey || ev.metaKey || ev.altKey) return;
  if (k === 'ArrowRight' || k === 'ArrowLeft'){
    if (t === scrub) return;
    if (unlocked()){ ev.preventDefault(); (k === 'ArrowRight' ? plusBtn : minusBtn).click(); }
    else nudgeLock();
  } else if (k === ' ' || k === 'Spacebar'){
    if (tag === 'BUTTON' || tag === 'INPUT') return;
    ev.preventDefault(); if (unlocked()) playBtn.click(); else nudgeLock();
  } else if (k === 'n' || k === 'N'){
    var nb = document.querySelector('[data-act="next"]'); if (nb) nb.click();
  } else if (k === 'b' || k === 'B'){
    var bb = document.querySelector('[data-act="back"]'); if (bb && !bb.disabled) bb.click();
  } else if (k === 'h' || k === 'H'){ hemiSw.click(); }
  else if (k === 's' || k === 'S'){ shadowSw.click(); }
  else if (k === 'm' || k === 'M'){ muteBtn.click(); }
});

/* ---------- reset ---------- */
function resetAll(){
  stopAnim(); setPlaying(false);
  state.hemi = 'N'; state.rot = 0; state.shadow = false; state.eclipse = false; state.day = 4.2;
  quiz = { i: 0, score: 0, answered: false, picked: -1 };
  updateSwitches(); startTour();
  try { window.scrollTo(0, 0); } catch(e){}
}

/* ---------- sizing ---------- */
function resizeAll(){
  sizeCanvas(O);
  var s = Math.min(O.w, O.h); O.s = s;
  O.cx = O.w / 2 - s * 0.02; O.cy = O.h / 2; O.R = s * 0.31; O.rE = s * 0.07; O.rM = s * 0.038;
  O.f = Math.max(3.5, s * 0.016); O.fs = s < 420 ? 10 : 12;
  O.labels = s >= 330 ? (s >= 420 ? 'full' : 'short') : null;
  O.bg = buildOrbitBg();
  sizeCanvas(S);
  S.r = Math.min(S.w, S.h) * 0.29; S.cy = S.h * 0.43;
  S.bg = buildSkyBg();
  var px = clamp(Math.ceil(S.r * 2 * S.dpr), 32, 1024);
  if (!S.tex || S.tex.width !== px) S.tex = buildMoonTex(px);
  sizeCanvas(ST);
  ver++;
}
var pendingResize = false;
function queueResize(){ if (pendingResize) return; pendingResize = true; requestAnimationFrame(function(){ pendingResize = false; resizeAll(); }); }
if (window.ResizeObserver){
  var ro = new ResizeObserver(queueResize);
  ro.observe(O.c.parentElement); ro.observe(S.c.parentElement); ro.observe(ST.c);
} else window.addEventListener('resize', queueResize);

/* ---------- main loop ---------- */
var last = performance.now(), lastSig = '', readySent = false, pf = 0, pa = 0;
function update(dt){
  stepTween(dt * 1000);
  if (state.playing){ state.day += dt * 2.2; if (!animating()) state.day = mod(state.day); }
  var tr = state.hemi === 'S' ? Math.PI : 0, df = tr - state.rot;
  state.rot = Math.abs(df) < 0.002 ? tr : state.rot + df * Math.min(1, dt * 7);
}
function perf(dt, drew){
  if (!drew){ pf = 0; pa = 0; return; }
  pf++; pa += dt;
  if (pf >= 60){
    var avg = pa / pf;
    if (avg > 1 / 40 && qualityCap > 1){ qualityCap = qualityCap > 1.5 ? 1.5 : 1; resizeAll(); }
    pf = 0; pa = 0;
  }
}
function frame(t){
  var dt = Math.min(0.05, Math.max(0, (t - last) / 1000)); last = t;
  update(dt);
  var sig = state.day.toFixed(4) + '|' + state.rot.toFixed(4) + '|' + state.shadow + state.eclipse + state.mode + state.step + state.hemi + '|' + ver;
  var drew = false;
  if (sig !== lastSig){ lastSig = sig; drawOrbit(); drawSky(); drawStrip(); updateDOM(); drew = true; }
  perf(dt, drew);
  if (!readySent){ readySent = true; try { parent.postMessage({ vcb: 'ready' }, '*'); } catch(e){} }
  requestAnimationFrame(frame);
}

/* ---------- demo mode ---------- */
var demo = false, demoToken = 0, fp = $('fakePointer'), demoTag = $('demoTag'), fpX = 0, fpY = 0;
function setFP(x, y){ fpX = x; fpY = y; fp.style.transform = 'translate(' + x.toFixed(1) + 'px,' + y.toFixed(1) + 'px)'; }
function pressFP(){ fp.classList.remove('press'); void fp.offsetWidth; fp.classList.add('press'); }
function nextFrame(){ return new Promise(function(res){ requestAnimationFrame(res); }); }
function sleep(ms, tok){ return new Promise(function(res, rej){ setTimeout(function(){ if (tok === demoToken) res(); else rej('stop'); }, ms); }); }
function check(tok){ if (tok !== demoToken) throw 'stop'; }
async function moveTo(x, y, ms, tok){
  var x0 = fpX, y0 = fpY, t0 = performance.now();
  for (;;){
    await nextFrame(); check(tok);
    var f = Math.min(1, (performance.now() - t0) / ms), k = ease(f);
    setFP(x0 + (x - x0) * k, y0 + (y - y0) * k);
    if (f >= 1) break;
  }
}
function centerOf(el){ var r = el.getBoundingClientRect(); return [r.left + r.width / 2, r.top + r.height / 2]; }
async function clickEl(sel, tok){
  var el = document.querySelector(sel); if (!el) return;
  try { el.scrollIntoView({ block: 'nearest' }); } catch(e){}
  await nextFrame(); check(tok);
  var p = centerOf(el);
  await moveTo(p[0], p[1], 650, tok);
  pressFP(); await sleep(140, tok);
  el.click();
}
async function dragScrub(toDay, ms, tok){
  try { scrub.scrollIntoView({ block: 'nearest' }); } catch(e){}
  await nextFrame(); check(tok);
  var r = scrub.getBoundingClientRect();
  function xFor(d){ return r.left + 14 + (d / P) * (r.width - 28); }
  var y = r.top + r.height / 2, d0 = mod(state.day);
  await moveTo(xFor(d0), y, 600, tok); pressFP();
  stopAnim(); setPlaying(false);
  var t0 = performance.now();
  for (;;){
    await nextFrame(); check(tok);
    var f = Math.min(1, (performance.now() - t0) / ms), d = d0 + (toDay - d0) * ease(f);
    state.day = mod(d); setFP(xFor(d), y);
    if (f >= 1) break;
  }
}
async function dragOrbit(toDay, ms, tok){
  try { O.c.scrollIntoView({ block: 'nearest' }); } catch(e){}
  await nextFrame(); check(tok);
  function pos(d){ var r = O.c.getBoundingClientRect(), e = d / P * TAU; return [r.left + O.cx + O.R * Math.cos(e), r.top + O.cy - O.R * Math.sin(e)]; }
  var d0 = mod(state.day), d1 = toDay; if (d1 < d0) d1 += P;
  var p = pos(d0); await moveTo(p[0], p[1], 650, tok); pressFP();
  stopAnim(); setPlaying(false);
  var t0 = performance.now();
  for (;;){
    await nextFrame(); check(tok);
    var f = Math.min(1, (performance.now() - t0) / ms), d = d0 + (d1 - d0) * ease(f);
    state.day = mod(d); var q = pos(d); setFP(q[0], q[1]);
    if (f >= 1) break;
  }
}
async function demoOnce(tok){
  resetAll();
  setFP(window.innerWidth * 0.6, window.innerHeight * 0.55);
  await sleep(700, tok);
  await clickEl('[data-act="next"]', tok); await sleep(1500, tok);
  await clickEl('[data-act="next"]', tok); await sleep(1400, tok);
  await clickEl('[data-act="skip"]', tok); await sleep(400, tok);
  await dragScrub(P / 2, 2200, tok); await sleep(500, tok);
  await clickEl('#shadowSw', tok); await sleep(900, tok);
  await clickEl('#eclipseBtn', tok); await sleep(1300, tok);
  await dragOrbit(3 * P / 4, 1800, tok); await sleep(400, tok);
  await clickEl('#hemiSw', tok); await sleep(1300, tok);
  await clickEl('[data-act="quiz"]', tok); await sleep(600, tok);
  await clickEl('[data-act="ans"][data-i="1"]', tok); await sleep(1800, tok);
}
async function runDemo(tok){
  try { while (tok === demoToken && demo){ await demoOnce(tok); } } catch(e){}
}
function startDemo(){
  if (demo) return;
  demo = true; fp.hidden = false; demoTag.hidden = false;
  var tok = ++demoToken;
  requestAnimationFrame(function(){ runDemo(tok); });
}
function endDemo(){
  if (!demo) return;
  demo = false; demoToken++; fp.hidden = true; demoTag.hidden = true;
}
['pointerdown', 'keydown', 'wheel', 'touchstart', 'mousedown'].forEach(function(type){
  window.addEventListener(type, function(ev){ if (demo && ev.isTrusted) endDemo(); }, { capture: true, passive: true });
});
function isDemoHash(){ return location.hash === '#demo' || /#demo$/.test(location.href); }
window.addEventListener('hashchange', function(){ if (isDemoHash()) startDemo(); });

/* ---------- boot ---------- */
resizeAll();
updateSwitches();
startTour();
requestAnimationFrame(function(t){ last = t; frame(t); });
if (isDemoHash()) startDemo();
})();
</script>
</body>
</html>