// The explorer series (Weather, Ocean, Dinosaurs, Bugs, ...): one component,
// content from content/explorers/<topic>.json via /api/explorers/:slug.
// Space has its own dark solar-system view (space.jsx); these are Craft Table.
//
// Art (falls back to the emoji when a file is missing):
//   /images/headers/<art>.webp            the explorer's header
//   /images/explorers/<art>/<item id>.webp each fact card's picture
// where <art> is the content's "art" field (e.g. "dinosaurs").

function ExplorerImage({ src, emoji, className, size }) {
  const [broken, setBroken] = useState(false);
  useEffect(() => { setBroken(false); }, [src]);
  if (broken || !src) return <div className={`${className} emoji-fallback`} style={size ? { fontSize: size } : null}>{emoji}</div>;
  return <img className={className} src={src} alt="" loading="lazy" onError={() => setBroken(true)} />;
}

function Explorer({ slug, onBack }) {
  const [data, setData] = useState(null);
  const [loadError, setLoadError] = useState(false);
  const [view, setView] = useState('items'); // items | item | quiz
  const [item, setItem] = useState(null);
  const [seen, setSeen] = useState(() => new Set());

  const load = useCallback(async () => {
    setLoadError(false);
    const d = await api(`/api/explorers/${slug}`);
    if (!d || d.error) { setLoadError(true); return; }
    setData(d);
  }, [slug]);
  useEffect(() => { load(); }, [load]);

  if (loadError) return <div className="craft-page"><OopsCard message="This explorer could not load." onRetry={load} /></div>;
  if (!data) return <div className="loading-screen"><div className="spinner" /></div>;

  const ex = data.explorer;
  const art = ex.art || slug.replace(/-explorer$/, '');
  const items = data.items;
  const accent = ex.color || 'var(--coral)';
  const open = it => { setItem(it); setView('item'); setSeen(s => new Set(s).add(it.id)); window.scrollTo(0, 0); };
  const step = dir => {
    const i = items.findIndex(x => x.id === item.id) + dir;
    if (i >= 0 && i < items.length) open(items[i]);
  };

  if (view === 'quiz') {
    return (
      <div className="craft-page" style={{ '--accent': accent }}>
        <QuizFlow activitySlug={slug} theme="craft" heading={`${ex.name} Quizzes`}
          backLabel={`Back to ${ex.name}`} onBack={() => setView('items')} />
      </div>
    );
  }

  if (view === 'item' && item) {
    const i = items.findIndex(x => x.id === item.id);
    const sourceTitle = id => ((ex.sources || []).find(s => s.id === id) || {}).title;
    return (
      <div className="craft-page" style={{ '--accent': accent }}>
        <div className="craft-nav">
          <button className="back-btn inline" onClick={() => setView('items')}>← All {ex.name.replace(' Explorer', '')} cards</button>
        </div>
        <div className="fact-detail">
          <ExplorerImage className="fact-detail-img" src={`/images/explorers/${art}/${item.id}.webp`} emoji={item.emoji} size="5rem" />
          <h2 style={{ color: accent }}>{item.emoji} {item.name}</h2>
          {item.blurb && <p className="fact-blurb">{item.blurb}</p>}
          <div className="fact-cards">
            {(item.cards || []).map((c, k) => (
              <div key={k} className="fact-card" title={c.source ? `Source: ${sourceTitle(c.source) || c.source}` : undefined}>
                <div className="fact-label">{c.icon} {c.label}</div>
                <div className="fact-value">{c.value}</div>
              </div>
            ))}
          </div>
          {item.funFact && (
            <div className="fun-fact">
              <div className="fun-fact-head">🤩 Wow fact!</div>
              <div>{item.funFact}</div>
            </div>
          )}
          <div className="fact-steps">
            {i > 0 ? <button className="btn-secondary" onClick={() => step(-1)}>← {items[i - 1].name}</button> : <span />}
            {i < items.length - 1
              ? <button className="btn-primary" onClick={() => step(1)}>{items[i + 1].name} →</button>
              : <button className="btn-primary" onClick={() => setView('quiz')}>Quiz time! 🎯</button>}
          </div>
        </div>
      </div>
    );
  }

  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/${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="explorer-actions">
          <button className="btn-primary big" onClick={() => setView('quiz')}>🎯 Quiz time!</button>
          <span className="explorer-progress">You've read {seen.size} of {items.length} cards</span>
        </div>
        <div className="fact-grid">
          {items.map(it => (
            <button key={it.id} className={`fact-tile ${seen.has(it.id) ? 'seen' : ''}`} onClick={() => open(it)}>
              <ExplorerImage className="fact-tile-img" src={`/images/explorers/${art}/${it.id}.webp`} emoji={it.emoji} size="3rem" />
              <div className="fact-tile-name">{it.name}</div>
              {seen.has(it.id) && <div className="fact-tile-seen">✓</div>}
            </button>
          ))}
        </div>
        {ex.sources && ex.sources.length > 0 && (
          <details className="sources">
            <summary>For grown-ups: where these facts come from (checked {ex.verified})</summary>
            <ul>
              {ex.sources.map(s => (
                <li key={s.id}><a href={s.url} target="_blank" rel="noopener noreferrer">{s.title}</a></li>
              ))}
            </ul>
          </details>
        )}
      </div>
    </div>
  );
}
