// Math Lab: multiplication strategies from Sarah's class flip book (content
// built by scripts/build-math-lab.js, wording from Dragon Caretaker's
// strategies.json). Each strategy has easy / medium / hard quizzes on the
// numeric keypad, plus Mixed Practice. Finishing one writes a Dragon Caretaker
// reward to the outbox (server.js); the gift is only mentioned once
// features.dcRewardsLive says the game can claim it.

const DC_ITEM_NAMES = { shell: 'River Shell', pearl: 'River Pearl', crystal: 'Hollow Crystal' };

function MathLab({ onBack, features = {} }) {
  const [content, setContent] = useState(null);
  const [progress, setProgress] = useState({});
  const [loadError, setLoadError] = useState(false);
  const [strategy, setStrategy] = useState(null); // a strategy item, or 'mixed'

  const load = useCallback(async () => {
    setLoadError(false);
    const [c, act] = await Promise.all([api('/api/explorers/math-lab'), api('/api/activities/math-lab')]);
    if (!c || c.error) { setLoadError(true); return; }
    setContent(c);
    if (act && act.quizzes) setProgress(Object.fromEntries(act.quizzes.map(q => [q.slug, q.userProgress])));
  }, []);
  useEffect(() => { load(); }, [load]);

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

  const accent = content.explorer.color || '#E0A526';
  const giftLine = result => {
    if (!features.dcRewardsLive || !result.dcReward) return null;
    const r = result.dcReward;
    return <div className="dc-gift">🎁 Your dragon gets {r.qty} {DC_ITEM_NAMES[r.item] || r.item}{r.qty > 1 ? 's' : ''}! Find {r.qty > 1 ? 'them' : 'it'} in Dragon Caretaker.</div>;
  };

  if (strategy) {
    const mixed = strategy === 'mixed';
    return (
      <div className="craft-page" style={{ '--accent': accent }}>
        <QuizFlow activitySlug="math-lab" theme="craft" backLabel="Back to Math Lab"
          onBack={() => { setStrategy(null); load(); }}
          heading={mixed ? 'Mixed Practice' : `${strategy.name} ${strategy.emoji}`}
          quizFilter={mixed ? (q => q.slug === 'mixed-practice') : (q => q.slug.startsWith(strategy.id + '-'))}
          endExtra={giftLine}
          intro={mixed ? (
            <div className="strategy-card big">
              <p>Every question is a different times table. Pick the right trick for each one!</p>
            </div>
          ) : (
            <div className="strategy-card big">
              <div className="strategy-name">The trick: <strong>{strategy.trick || strategy.strategy}</strong></div>
              <ol className="strategy-how">{strategy.how.map((h, i) => <li key={i}>{h}</li>)}</ol>
              <div className="strategy-example">Example: {strategy.example}</div>
            </div>
          )} />
      </div>
    );
  }

  const stars = slug => { const p = progress[slug]; return p ? starsFor(p.score, p.total) : 0; };
  return (
    <div className="craft-page" style={{ '--accent': accent }}>
      <div className="explorer-header" style={{ background: `linear-gradient(135deg, ${accent}, #F6C66B)` }}>
        <ExplorerImage className="explorer-header-img" src="/images/headers/math-lab.webp" emoji="🧮" size="4rem" />
        <button className="back-btn header-back" onClick={onBack}>← Workshop</button>
        <h1>🧮 Math Lab</h1>
      </div>
      <div className="craft-content">
        <HootSays pool="math_intro" pose="math" size={96} />
        <h2 className="section-title">Pick a times table</h2>
        <div className="strategy-grid">
          {content.items.map(s => (
            <button key={s.id} className="strategy-tile" onClick={() => { setStrategy(s); window.scrollTo(0, 0); }}>
              <div className="strategy-tile-top">
                <span className="strategy-emoji">{s.emoji}</span>
                <span className="strategy-tile-name">{s.name}</span>
              </div>
              <div className="strategy-tile-trick">“{s.trick || s.strategy}”</div>
              <div className="strategy-levels">
                {s.quizzes.map((slug, i) => (
                  <span key={slug} className={`level-pip ${stars(slug) === 3 ? 'gold' : stars(slug) > 0 ? 'done' : ''}`}
                    title={['Warm-up', 'Faster', 'Expert'][i]}>
                    {['Easy', 'Medium', 'Hard'][i]}{stars(slug) === 3 ? ' ★' : stars(slug) > 0 ? ' ✓' : ''}
                  </span>
                ))}
              </div>
            </button>
          ))}
          <button className="strategy-tile mixed" onClick={() => { setStrategy('mixed'); window.scrollTo(0, 0); }}>
            <div className="strategy-tile-top"><span className="strategy-emoji">🎲</span><span className="strategy-tile-name">Mixed Practice</span></div>
            <div className="strategy-tile-trick">Every table, all mixed up. Which trick fits?</div>
            <div className="strategy-levels">
              <span className={`level-pip ${stars('mixed-practice') === 3 ? 'gold' : stars('mixed-practice') > 0 ? 'done' : ''}`}>
                {stars('mixed-practice') === 3 ? 'Perfect ★' : stars('mixed-practice') > 0 ? 'Done ✓' : 'Try it!'}
              </span>
            </div>
          </button>
        </div>
      </div>
    </div>
  );
}
