// Art Explorer: real paintings from real museums (content/explorers/art.json,
// "kind": "art"). Built on the explorer template: the styles are the items,
// and Explorer (explorer.jsx) hands an art explorer to ArtExplorer.
//
//   home     the big idea (see / feel / imagine), the seven styles, try-it pieces
//   style    the style's question, one-idea cards, its tell, its paintings
//   work     one painting: Hoot's "look closely" questions (open answers, no
//            scoring), look-for, cards, Then and Now cards
//   check    the style's 5-question check (its badge needs 4 of 5)
//   quiz     the other quizzes (which style, odd one out, find the tell, riddles)
//   zoom     Seurat zoom: pinch into La Grande Jatte until the dots appear
//   collage  Cubism collage: cut a picture up and put it back your own way
//
// Pictures: /images/art/{full,mid,thumb}/<work id>.webp (tools/art/build_art_images.py);
// in-copyright works are under /images/art-private/ (signed-in only).
// Voice keys (content/hoot/voice-manifest.json): art.big-idea, art.vts.<n>,
// art.style.<id>.question|tell|card.<n>, art.work.<id>.look|card.<n>, art.then-now.<id>.

const ART_LENSES = {
  see: { emoji: '👀', label: 'what you see' },
  feel: { emoji: '💛', label: 'what you feel' },
  imagine: { emoji: '💭', label: 'what you imagine' }
};
// In-copyright works ("private": true in art.json, used privately) come from
// /images/art-private, which the server only serves to signed-in users.
const ART_PRIVATE = new Set();
const artSrc = (size, id) => `/images/${ART_PRIVATE.has(id) ? 'art-private' : 'art'}/${size}/${id}.webp`;

// Small per-device memory (which paintings she has looked at, her notes).
// Storage can be missing or blocked: everything still works without it.
function artLoad(key, fallback) {
  try { const v = localStorage.getItem('wk_art_' + key); return v === null ? fallback : JSON.parse(v); } catch (e) { return fallback; }
}
function artSave(key, value) {
  try { localStorage.setItem('wk_art_' + key, JSON.stringify(value)); } catch (e) {}
}

function ArtPicture({ id, size = 'thumb', alt = '', className = '' }) {
  const [broken, setBroken] = useState(false);
  useEffect(() => { setBroken(false); }, [id, size]);
  if (broken) return <div className={`${className} emoji-fallback art-missing`}>🖼️</div>;
  // the big picture at the top of a page loads straight away; tiles can wait
  return <img className={className} src={artSrc(size, id)} alt={alt} loading={size === 'full' ? 'eager' : 'lazy'}
    draggable="false" onError={() => setBroken(true)} />;
}

function LensChip({ lens }) {
  const l = ART_LENSES[lens];
  if (!l) return null;
  return <span className={`lens-chip lens-${lens}`}>{l.emoji} {l.label}</span>;
}

// Hoot asks the three Visual Thinking Strategies questions, one at a time.
// Open answers: she says it out loud (or writes it); nothing is scored.
function LookClosely({ workId, questions }) {
  const voice = useHootVoice();
  const [step, setStep] = useState(0);
  const [cheer, setCheer] = useState(null);
  const [note, setNote] = useState(() => artLoad('note_' + workId, ''));
  useEffect(() => { setStep(0); setCheer(null); setNote(artLoad('note_' + workId, '')); }, [workId]);
  const next = () => {
    setCheer(voice.line('art_look'));
    setStep(s => (s + 1) % questions.length);
  };
  const write = v => { setNote(v); artSave('note_' + workId, v); };
  return (
    <div className="look-closely">
      <div className="look-head">🔍 Look closely</div>
      <HootSays text={questions[step]} voiceKey={`art.vts.${step + 1}`} pose={step === 1 ? 'think' : 'explore'} size={84} />
      {cheer && step > 0 && <div className="look-cheer">{cheer.text}</div>}
      <p className="look-tip">Say your answer out loud, or tell a grown-up. There are no wrong answers!</p>
      <textarea className="look-note" value={note} onChange={e => write(e.target.value)} rows={2}
        placeholder="Or write what you notice here…" aria-label="What I notice" />
      <button className="btn-primary look-next" onClick={next}>
        {step < questions.length - 1 ? 'I said it! Next question →' : 'Start again 🔁'}
      </button>
    </div>
  );
}

function ThenAndNowCard({ id, card }) {
  if (!card) return null;
  return (
    <div className="then-now">
      <div className="then-now-head">⏳ Then and Now</div>
      <div className="then-now-title">{card.emoji} {card.title}</div>
      <p>{card.text}</p>
      <SpeakButton voiceKey={`art.then-now.${id}`} />
    </div>
  );
}

function OneIdeaCards({ cards, keyPrefix }) {
  if (!cards || !cards.length) return null;
  return (
    <div className="fact-cards">
      {cards.map((c, i) => (
        <div key={i} className="fact-card">
          <div className="fact-label">{c.icon} {c.label}</div>
          <div className="fact-value">{c.value}</div>
          <SpeakButton voiceKey={`${keyPrefix}.card.${i + 1}`} />
        </div>
      ))}
    </div>
  );
}

// A painting filling the screen; tap anywhere to close.
function BigPicture({ id, alt, onClose }) {
  return (
    <div className="big-picture" onClick={onClose} role="dialog" aria-label="The painting, big">
      <img src={artSrc('full', id)} alt={alt} />
      <button className="big-picture-close" aria-label="Close">✕</button>
    </div>
  );
}

// ─── SEURAT ZOOM ─────────────────────────────────────────────
// OpenSeadragon (loaded only here) over the deep-zoom tiles in
// /images/art/zoom/grande-jatte/. Pinch, or use the big buttons.
const OSD_SRC = 'https://cdnjs.cloudflare.com/ajax/libs/openseadragon/4.1.1/openseadragon.min.js';
let osdLoading = null;
function loadOpenSeadragon() {
  if (window.OpenSeadragon) return Promise.resolve(window.OpenSeadragon);
  if (!osdLoading) {
    osdLoading = new Promise((resolve, reject) => {
      const s = document.createElement('script');
      s.src = OSD_SRC;
      s.crossOrigin = 'anonymous';
      s.onload = () => resolve(window.OpenSeadragon);
      s.onerror = () => { osdLoading = null; reject(new Error('OpenSeadragon did not load')); };
      document.head.appendChild(s);
    });
  }
  return osdLoading;
}
// Places to fly to, as fractions of the picture's width and height.
const ZOOM_SPOTS = [
  { label: '👧 The girl in white', x: 0.43, y: 0.38, w: 0.05, h: 0.21 },
  { label: '🐒 The monkey', x: 0.69, y: 0.77, w: 0.10, h: 0.14 },
  { label: '🎺 The trumpet player', x: 0.32, y: 0.22, w: 0.06, h: 0.22 },
  { label: '🐕 The black dog', x: 0.37, y: 0.64, w: 0.16, h: 0.22 }
];
function SeuratZoom({ workId, onBack }) {
  const box = useRef(null);
  const viewer = useRef(null);
  const [state, setState] = useState('loading'); // loading | ready | failed
  const [dots, setDots] = useState(false);
  useEffect(() => {
    let alive = true;
    Promise.all([loadOpenSeadragon(), fetch(`/images/art/zoom/${workId}/zoom.json`).then(r => r.json())])
      .then(([OSD, z]) => {
        if (!alive || !box.current) return;
        viewer.current = OSD({
          element: box.current,
          tileSources: {
            width: z.width, height: z.height, tileSize: z.tileSize, tileOverlap: z.overlap,
            getTileUrl: (level, x, y) => `/images/art/zoom/${workId}/${level}/${x}_${y}.webp`
          },
          showNavigationControl: false,
          visibilityRatio: 1,
          constrainDuringPan: true,
          maxZoomPixelRatio: 3,
          animationTime: 0.9,
          gestureSettingsTouch: { pinchRotate: false, flickEnabled: true },
          gestureSettingsMouse: { clickToZoom: false }
        });
        viewer.current.addHandler('zoom', e => {
          const v = viewer.current.viewport;
          if (v.viewportToImageZoom(e.zoom) > 0.6) setDots(true);
        });
        setState('ready');
      })
      .catch(() => alive && setState('failed'));
    return () => { alive = false; if (viewer.current) { viewer.current.destroy(); viewer.current = null; } };
  }, [workId]);
  const zoomBy = f => { const v = viewer.current && viewer.current.viewport; if (v) { v.zoomBy(f); v.applyConstraints(); } };
  const home = () => viewer.current && viewer.current.viewport.goHome();
  // OpenSeadragon's viewport runs 0..1 across and 0..height/width down.
  const flyTo = s => {
    const v = viewer.current && viewer.current.viewport;
    const item = viewer.current && viewer.current.world.getItemAt(0);
    if (!v || !item) return;
    const size = item.getContentSize();
    const r = size.y / size.x;
    v.fitBoundsWithConstraints(new window.OpenSeadragon.Rect(s.x, s.y * r, s.w, s.h * r));
  };
  return (
    <div className="craft-page">
      <div className="craft-nav"><button className="back-btn inline" onClick={onBack}>← Back</button></div>
      <div className="zoom-page">
        <h2>🔍 Seurat Zoom</h2>
        <HootSays pose="explore" size={80}
          text={dots ? 'You found the dots! Seurat put every one of them there, one little dab at a time.'
                     : 'Pinch the painting to zoom in. Keep going until the picture turns into dots!'} />
        {state === 'failed' ? (
          <div className="zoom-fallback">
            <img src={artSrc('full', workId)} alt="A Sunday on La Grande Jatte" />
            <p>The zoom needs the internet to start. Try again in a little while!</p>
          </div>
        ) : (
          <div className="zoom-box" ref={box}>{state === 'loading' && <div className="spinner" />}</div>
        )}
        {state === 'ready' && (
          <>
            <div className="zoom-buttons">
              <button className="zoom-btn" onClick={() => zoomBy(2)} aria-label="Zoom in">➕</button>
              <button className="zoom-btn" onClick={() => zoomBy(0.5)} aria-label="Zoom out">➖</button>
              <button className="zoom-btn wide" onClick={home}>🖼️ Whole picture</button>
            </div>
            <div className="zoom-spots">
              <span className="zoom-spots-label">Fly to:</span>
              {ZOOM_SPOTS.map(s => <button key={s.label} className="zoom-spot" onClick={() => flyTo(s)}>{s.label}</button>)}
            </div>
          </>
        )}
      </div>
    </div>
  );
}

// ─── CUBISM COLLAGE ──────────────────────────────────────────
// Cut a picture into pieces and put it back your own way. Each piece is the
// whole picture clipped to a polygon (clip-path also limits where it can be
// touched), moved with a transform. Drag to move, tap to turn.
const COLLAGE_PICTURES = [
  { id: 'watering-can', label: 'Girl with a watering can', src: artSrc('full', 'watering-can'), ratio: 1.387 },
  { id: 'water-lily-bridge', label: 'The water lily bridge', src: artSrc('full', 'water-lily-bridge'), ratio: 1.255 },
  { id: 'snap-the-whip', label: 'Snap the Whip', src: artSrc('full', 'snap-the-whip'), ratio: 0.6 }
];
function cutPieces(cols = 4, rows = 3) {
  const rnd = (a, b) => a + Math.random() * (b - a);
  const P = [];
  for (let i = 0; i <= rows; i++) {
    P.push([]);
    for (let j = 0; j <= cols; j++) {
      const x = (j / cols) * 100 + (j > 0 && j < cols ? rnd(-30, 30) / cols : 0);
      const y = (i / rows) * 100 + (i > 0 && i < rows ? rnd(-30, 30) / rows : 0);
      P[i].push([x, y]);
    }
  }
  const pieces = [];
  for (let i = 0; i < rows; i++) {
    for (let j = 0; j < cols; j++) {
      const quad = [P[i][j], P[i][j + 1], P[i + 1][j + 1], P[i + 1][j]];
      // about half the cells split into two triangles: sharper, more Cubist shapes
      const shapes = Math.random() < 0.5 ? [quad]
        : Math.random() < 0.5 ? [[quad[0], quad[1], quad[2]], [quad[0], quad[2], quad[3]]]
                              : [[quad[0], quad[1], quad[3]], [quad[1], quad[2], quad[3]]];
      for (const poly of shapes) {
        const cx = poly.reduce((s, p) => s + p[0], 0) / poly.length;
        const cy = poly.reduce((s, p) => s + p[1], 0) / poly.length;
        pieces.push({ id: pieces.length, poly, cx, cy, dx: 0, dy: 0, rot: 0, z: pieces.length });
      }
    }
  }
  return pieces;
}
function shuffledPieces(pieces) {
  const turns = [0, 45, 90, 135, 180, 225, 270, 315];
  return pieces.map(p => ({
    ...p,
    dx: (Math.random() - 0.5) * 30, dy: (Math.random() - 0.5) * 30,
    rot: turns[Math.floor(Math.random() * turns.length)], z: Math.floor(Math.random() * 1000)
  }));
}
function CubismCollage({ onBack }) {
  const board = useRef(null);
  const drag = useRef(null);
  const [pic, setPic] = useState(null);
  const [pieces, setPieces] = useState([]);
  const [done, setDone] = useState(null);
  const [badges, setBadges] = useState(null);
  const [saved, setSaved] = useState(null);
  const start = p => { setPic(p); setPieces(shuffledPieces(cutPieces())); setDone(null); setSaved(null); window.scrollTo(0, 0); };
  const topZ = () => pieces.reduce((m, p) => Math.max(m, p.z), 0) + 1;
  const down = (e, id) => {
    e.preventDefault();
    e.currentTarget.setPointerCapture && e.currentTarget.setPointerCapture(e.pointerId);
    const r = board.current.getBoundingClientRect();
    const p = pieces.find(x => x.id === id);
    drag.current = { id, x: e.clientX, y: e.clientY, dx: p.dx, dy: p.dy, w: r.width, h: r.height, moved: false };
    const z = topZ();
    setPieces(ps => ps.map(x => (x.id === id ? { ...x, z } : x)));
  };
  const move = e => {
    const d = drag.current;
    if (!d) return;
    const mx = e.clientX - d.x, my = e.clientY - d.y;
    if (Math.abs(mx) + Math.abs(my) > 6) d.moved = true;
    if (!d.moved) return;
    // keep each piece's middle on the board
    const clamp = (v, c) => Math.max(2 - c, Math.min(98 - c, v));
    setPieces(ps => ps.map(x => (x.id === d.id
      ? { ...x, dx: clamp(d.dx + mx / d.w * 100, x.cx), dy: clamp(d.dy + my / d.h * 100, x.cy) } : x)));
  };
  const up = () => {
    const d = drag.current;
    drag.current = null;
    if (d && !d.moved) setPieces(ps => ps.map(x => (x.id === d.id ? { ...x, rot: (x.rot + 45) % 360 } : x)));
  };
  const finish = async () => {
    setDone(HootVoice.line('art_collage') || { text: 'Now that is a Cubist picture!' });
    const r = await api('/api/activity-events', { method: 'POST', body: { activity: 'art-explorer', event: 'made', detail: 'a Cubism collage' } });
    if (r && r.badgesEarned && r.badgesEarned.length) setBadges(r.badgesEarned);
  };
  // Draw the collage onto a canvas so she can keep it (press and hold to save on the iPad).
  const keep = () => {
    const img = new Image();
    img.onload = () => {
      const W = 1200, H = Math.round(W * pic.ratio);
      const c = document.createElement('canvas');
      c.width = W; c.height = H;
      const ctx = c.getContext('2d');
      ctx.fillStyle = '#FFF8F0';
      ctx.fillRect(0, 0, W, H);
      [...pieces].sort((a, b) => a.z - b.z).forEach(p => {
        ctx.save();
        const cx = (p.cx + p.dx) / 100 * W, cy = (p.cy + p.dy) / 100 * H;
        ctx.translate(cx, cy);
        ctx.rotate(p.rot * Math.PI / 180);
        ctx.translate(-p.cx / 100 * W, -p.cy / 100 * H);
        ctx.beginPath();
        p.poly.forEach(([x, y], i) => (i ? ctx.lineTo(x / 100 * W, y / 100 * H) : ctx.moveTo(x / 100 * W, y / 100 * H)));
        ctx.closePath();
        ctx.clip();
        ctx.drawImage(img, 0, 0, W, H);
        ctx.restore();
      });
      try { setSaved(c.toDataURL('image/jpeg', 0.9)); } catch (e) { setSaved(null); }
    };
    img.src = pic.src;
  };

  if (!pic) {
    return (
      <div className="craft-page">
        <div className="craft-nav"><button className="back-btn inline" onClick={onBack}>← Back</button></div>
        <div className="collage-page">
          <h2>✂️ Cubism Collage</h2>
          <HootSays pose="think" size={80}
            text="Cubist artists cut the world into pieces and put it back together a new way. Pick a painting, and I'll cut it up for you!" />
          <div className="collage-picks">
            {COLLAGE_PICTURES.map(p => (
              <button key={p.id} className="collage-pick" onClick={() => start(p)}>
                <ArtPicture id={p.id} size="thumb" className="collage-pick-img" />
                <span>{p.label}</span>
              </button>
            ))}
          </div>
        </div>
      </div>
    );
  }
  return (
    <div className="craft-page">
      <div className="craft-nav"><button className="back-btn inline" onClick={() => setPic(null)}>← Pick another painting</button></div>
      <div className="collage-page">
        <h2>✂️ Cubism Collage</h2>
        <p className="collage-tip">Drag the pieces to move them. Tap a piece to turn it. Make it your own!</p>
        {/* the wrapper caps the width (so a tall painting still fits the screen);
            the board inside keeps the painting's shape with a % padding of that width */}
        <div className="collage-board-wrap" style={{ maxWidth: `min(620px, ${(60 / pic.ratio).toFixed(1)}vh)` }}>
        <div className="collage-board" ref={board} style={{ paddingTop: (pic.ratio * 100) + '%' }}
          onPointerMove={move} onPointerUp={up} onPointerCancel={up}>
          {pieces.map(p => (
            <div key={p.id} className="collage-piece"
              onPointerDown={e => down(e, p.id)}
              style={{
                backgroundImage: `url(${pic.src})`,
                clipPath: `polygon(${p.poly.map(([x, y]) => `${x}% ${y}%`).join(', ')})`,
                WebkitClipPath: `polygon(${p.poly.map(([x, y]) => `${x}% ${y}%`).join(', ')})`,
                transformOrigin: `${p.cx}% ${p.cy}%`,
                transform: `translate(${p.dx}%, ${p.dy}%) rotate(${p.rot}deg)`,
                zIndex: p.z
              }} />
          ))}
        </div>
        </div>
        <div className="collage-buttons">
          <button className="btn-secondary" onClick={() => setPieces(ps => shuffledPieces(ps))}>🔀 Mix them up</button>
          <button className="btn-secondary" onClick={() => setPieces(ps => ps.map(p => ({ ...p, dx: 0, dy: 0, rot: 0 })))}>🧩 Put it back</button>
          <button className="btn-secondary" onClick={() => setPieces(cutPieces())}>✂️ Cut it again</button>
          <button className="btn-primary" onClick={finish}>✅ I'm done!</button>
        </div>
        {done && (
          <div className="collage-done">
            <HootSays text={done.text} voiceKey={done.key} pose="cheer" size={80} />
            <button className="btn-secondary" onClick={keep}>📸 Keep my collage</button>
          </div>
        )}
        {saved && (
          <div className="collage-saved">
            <img src={saved} alt="My Cubism collage" />
            <p>Press and hold the picture to save it.</p>
          </div>
        )}
      </div>
      <BadgeQueue badges={badges} onDone={() => setBadges(null)} />
    </div>
  );
}

// ─── THE EXPLORER ────────────────────────────────────────────
function ArtExplorer({ data, slug, onBack }) {
  const ex = data.explorer;
  const styles = data.items;
  const works = ex.works || {};
  Object.entries(works).forEach(([id, w]) => { if (w.private) ART_PRIVATE.add(id); });
  const accent = ex.color || '#8E5BB5';
  const [view, setView] = useState({ name: 'home' });
  const [progress, setProgress] = useState({});
  const [seen, setSeen] = useState(() => new Set(artLoad('seen', [])));
  const [big, setBig] = useState(false);

  const loadProgress = useCallback(async () => {
    const act = await api(`/api/activities/${slug}`);
    if (act && act.quizzes) setProgress(Object.fromEntries(act.quizzes.map(q => [q.slug, q.userProgress])));
  }, [slug]);
  useEffect(() => { loadProgress(); }, [loadProgress]);

  const go = (name, extra = {}) => { setBig(false); setView({ name, ...extra }); window.scrollTo(0, 0); };
  const openWork = id => {
    setSeen(s => {
      const n = new Set(s).add(id);
      artSave('seen', [...n]);
      return n;
    });
    go('work', { id });
  };
  const styleOf = id => styles.find(s => s.id === id);
  const mastered = s => {
    const p = progress[`style-${s.id}`];
    return p && p.total > 0 && p.score / p.total >= 0.8;
  };
  const lessonWorks = s => (s.works || []).filter(id => works[id]);

  // ── a style's check, or the other quizzes
  if (view.name === 'check' || view.name === 'quiz') {
    const s = view.name === 'check' ? styleOf(view.style) : null;
    return (
      <div className="craft-page" style={{ '--accent': accent }}>
        <QuizFlow activitySlug={slug} theme="craft"
          heading={s ? `${s.name} check ${s.emoji}` : 'Art Explorer Quizzes'}
          backLabel={s ? `Back to ${s.name}` : 'Back to Art Explorer'}
          onBack={() => { loadProgress(); s ? go('style', { id: s.id }) : go('home'); }}
          quizFilter={s ? (q => q.slug === `style-${s.id}`) : (q => !q.slug.startsWith('style-'))}
          intro={s ? (
            <div className="strategy-card big">
              <div>🔎 <strong>The tell:</strong> {s.tell}</div>
              <div className="check-note">Get 4 out of 5 to earn a badge!</div>
            </div>
          ) : (
            <div className="strategy-card big">Each style has its own check too: open a style and look for the 🏅 button.</div>
          )} />
      </div>
    );
  }

  if (view.name === 'zoom') return <SeuratZoom workId="grande-jatte" onBack={() => openWork('grande-jatte')} />;
  if (view.name === 'collage') return <CubismCollage onBack={() => go('home')} />;

  // ── one painting
  if (view.name === 'work' && works[view.id]) {
    const id = view.id;
    const w = works[id];
    const s = styleOf(w.style);
    const list = s ? lessonWorks(s) : [];
    const i = list.indexOf(id);
    return (
      <div className="craft-page" style={{ '--accent': s ? s.color : accent }}>
        <div className="craft-nav">
          <button className="back-btn inline" onClick={() => go('style', { id: w.style })}>← {s ? s.name : 'Back'}</button>
        </div>
        <div className="work-page">
          <button className="work-picture" onClick={() => setBig(true)} aria-label="See the painting big">
            <ArtPicture id={id} size="full" alt={w.alt} className="work-img" />
            <span className="work-picture-hint">Tap to see it big</span>
          </button>
          <h2 className="work-title">{w.title}</h2>
          <div className="work-meta">{w.artist}{w.date ? `, ${w.date}` : ''}</div>
          <div className="work-museum">{w.museum}</div>
          <div className="work-lens">This painting is mostly about <LensChip lens={w.leans} /></div>
          <LookClosely workId={id} questions={ex.vts} />
          {w.lookFor && (
            <div className="look-for">
              <strong>👀 Look for:</strong> {w.lookFor}
              <SpeakButton voiceKey={`art.work.${id}.look`} />
            </div>
          )}
          {w.zoom && <button className="btn-primary big zoom-cta" onClick={() => go('zoom')}>🔍 Zoom in until you see the dots!</button>}
          <OneIdeaCards cards={w.cards} keyPrefix={`art.work.${id}`} />
          {(w.thenAndNow || []).map(t => <ThenAndNowCard key={t} id={t} card={(ex.thenAndNow || {})[t]} />)}
          <div className="fact-steps">
            {i > 0 ? <button className="btn-secondary" onClick={() => openWork(list[i - 1])}>← {works[list[i - 1]].title}</button> : <span />}
            {i >= 0 && i < list.length - 1
              ? <button className="btn-primary" onClick={() => openWork(list[i + 1])}>{works[list[i + 1]].title} →</button>
              : s && <button className="btn-primary" onClick={() => go('check', { style: s.id })}>🏅 {s.name} check</button>}
          </div>
          <div className="work-credit">
            Picture: {w.museum}{w.credit ? ` (${w.credit})` : ''}. {w.rights.license}.
            {' '}<a href={w.museumUrl} target="_blank" rel="noopener noreferrer">Museum page</a>
          </div>
        </div>
        {big && <BigPicture id={id} alt={w.alt} onClose={() => setBig(false)} />}
      </div>
    );
  }

  // ── one style
  if (view.name === 'style' && styleOf(view.id)) {
    const s = styleOf(view.id);
    const si = styles.indexOf(s);
    return (
      <div className="craft-page" style={{ '--accent': s.color }}>
        <div className="craft-nav"><button className="back-btn inline" onClick={() => go('home')}>← All styles</button></div>
        <div className="style-page">
          <h2 className="style-title" style={{ color: s.color }}>{s.emoji} {s.name}</h2>
          {s.say && <div className="say-it">Say it: <strong>{s.say}</strong></div>}
          <HootSays text={s.question} voiceKey={`art.style.${s.id}.question`} pose="think" size={90}>
            <div className="style-q-label">The artists' big question:</div>
          </HootSays>
          <OneIdeaCards cards={s.cards} keyPrefix={`art.style.${s.id}`} />
          <div className="tell-card" style={{ borderColor: s.color }}>
            <div>🔎 <strong>The tell:</strong> {s.tell}</div>
            <SpeakButton voiceKey={`art.style.${s.id}.tell`} />
          </div>
          <h3 className="section-title">Look closely at these</h3>
          <div className="work-grid">
            {lessonWorks(s).map(id => (
              <button key={id} className={`work-tile ${seen.has(id) ? 'seen' : ''}`} onClick={() => openWork(id)}>
                <ArtPicture id={id} size="thumb" alt={works[id].alt} className="work-tile-img" />
                <div className="work-tile-title">{works[id].title}</div>
                <div className="work-tile-artist">{works[id].artist}</div>
                {seen.has(id) && <div className="fact-tile-seen">✓</div>}
              </button>
            ))}
          </div>
          {(s.tryIt || []).length > 0 && (
            <div className="tryit-row">
              {s.tryIt.map(t => t.href
                ? <a key={t.label} className="tryit-card" href={t.href}>{t.label}</a>
                : <button key={t.label} className="tryit-card" onClick={() => go(t.view)}>{t.label}</button>)}
            </div>
          )}
          <div className="style-check">
            <button className="btn-primary big" onClick={() => go('check', { style: s.id })}>
              🏅 Take the {s.name} check{mastered(s) ? ' again' : ''}
            </button>
            <div className="style-check-note">{mastered(s) ? 'You earned this badge! ⭐' : 'Get 4 out of 5 to earn a badge.'}</div>
          </div>
          <div className="fact-steps">
            {si > 0 ? <button className="btn-secondary" onClick={() => go('style', { id: styles[si - 1].id })}>← {styles[si - 1].name}</button> : <span />}
            {si < styles.length - 1
              ? <button className="btn-primary" onClick={() => go('style', { id: styles[si + 1].id })}>{styles[si + 1].name} →</button>
              : <button className="btn-primary" onClick={() => go('quiz')}>Quiz time! 🎯</button>}
          </div>
        </div>
      </div>
    );
  }

  // ── the way in
  const sourceList = ex.sources || [];
  const credited = Object.entries(works).sort((a, b) => a[1].title.localeCompare(b[1].title));
  return (
    <div className="craft-page" style={{ '--accent': accent }}>
      <div className="explorer-header" style={{ background: `linear-gradient(135deg, ${accent}, ${accent}aa)` }}>
        <ExplorerImage className="explorer-header-img" src={`/images/headers/${ex.art || 'art'}.webp`} emoji={ex.icon} size="4rem" />
        <button className="back-btn header-back" onClick={onBack}>← Workshop</button>
        <h1>{ex.icon} {ex.name}</h1>
      </div>
      <div className="craft-content">
        <HootSays text={ex.intro} voiceKey={`hoot.intro.${slug}`} pose="explore" size={96} />
        <div className="big-idea">
          <div className="big-idea-text">{ex.bigIdea}</div>
          <div className="lens-row">{Object.keys(ART_LENSES).map(l => <LensChip key={l} lens={l} />)}</div>
          <SpeakButton voiceKey="art.big-idea" />
        </div>
        <h2 className="section-title">Seven ways to make a picture</h2>
        <div className="style-grid">
          {styles.map(s => {
            const ids = lessonWorks(s);
            const looked = ids.filter(id => seen.has(id)).length;
            return (
              <button key={s.id} className="style-tile" style={{ borderColor: s.color }} onClick={() => go('style', { id: s.id })}>
                {ids[0] && <ArtPicture id={ids[0]} size="thumb" alt="" className="style-tile-img" />}
                <div className="style-tile-body">
                  <div className="style-tile-name" style={{ color: s.color }}>{s.emoji} {s.name}</div>
                  <div className="style-tile-q">“{s.question}”</div>
                  <div className="style-tile-meta">
                    👀 {looked} of {ids.length} looked at{mastered(s) ? ' · 🏅 badge!' : ''}
                  </div>
                </div>
              </button>
            );
          })}
        </div>
        <h2 className="section-title">Try it yourself</h2>
        <div className="tryit-row">
          <button className="tryit-card" onClick={() => go('zoom')}>🔍 Seurat Zoom<span>Zoom in until a painting turns into dots</span></button>
          <button className="tryit-card" onClick={() => go('collage')}>✂️ Cubism Collage<span>Cut a painting up and put it back your way</span></button>
          <a className="tryit-card" href="/activities/color-lab/?tab=dots">🔴 Dot Painter<span>Paint with dots in Color Lab, then step back</span></a>
        </div>
        <div className="explorer-actions">
          <button className="btn-primary big" onClick={() => go('quiz')}>🎯 Quiz time!</button>
        </div>
        <details className="sources">
          <summary>For grown-ups: the paintings, and where the facts come from (checked {ex.verified})</summary>
          <p className="sources-note">Every painting is public domain in the US. The pictures come from the museums'
            own open-access (CC0) collections where they offer one, otherwise from Wikimedia Commons.</p>
          <ul>
            {credited.map(([id, w]) => (
              <li key={id}>
                <strong>{w.title}</strong>, {w.artist}, {w.date}. {w.museum}. {w.rights.license}.{' '}
                <a href={w.rights.sourceUrl} target="_blank" rel="noopener noreferrer">Source</a>
              </li>
            ))}
          </ul>
          <ul>
            {sourceList.map(src => (
              <li key={src.id}><a href={src.url} target="_blank" rel="noopener noreferrer">{src.title}</a></li>
            ))}
          </ul>
        </details>
      </div>
    </div>
  );
}
