/* ===== 学习模式 · 除法(反推面积 / 分篮子 可切换) ===== */
(function () {
  const { useState, useEffect, useRef } = React;

  const BASKET_COLORS = ['var(--pink)', 'var(--blue)', 'var(--mint)', 'var(--purple)', 'var(--orange)', 'var(--coral)', 'var(--yellow)', 'var(--green)', 'var(--blue)'];

  function DivLearn() {
    const [scheme, setScheme] = useState('area'); // 'area' | 'basket'
    const [total, setTotal] = useState(12);
    const [groups, setGroups] = useState(3);

    const per = Math.floor(total / groups);
    const rem = total % groups;

    return (
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 16, padding: '4px 16px 30px' }}>
        {/* 切换 */}
        <div style={{ display: 'flex', gap: 10, background: '#fff', padding: 6, borderRadius: 999, boxShadow: 'var(--shadow-sm)' }}>
          {[['area', '🔲 摆成方阵'], ['basket', '🧺 分进篮子']].map(([k, label]) => (
            <button key={k} className="num" onClick={() => { Sound.click(); setScheme(k); }}
              style={{ border: 'none', cursor: 'pointer', borderRadius: 999, padding: '10px 22px', fontSize: 20, whiteSpace: 'nowrap',
                background: scheme === k ? 'var(--mint)' : 'transparent', color: scheme === k ? '#fff' : 'var(--ink-soft)',
                boxShadow: scheme === k ? '0 4px 0 rgba(0,0,0,.12)' : 'none', transition: 'all .15s' }}>
              {label}
            </button>
          ))}
        </div>

        <div className="card" style={{ padding: '12px 22px', display: 'flex', gap: 26, flexWrap: 'wrap', justifyContent: 'center' }}>
          <Stepper label="一共几个" value={total} min={2} max={24} onChange={setTotal} color="var(--orange)" />
          <Stepper label="分成几份" value={groups} min={2} max={6} onChange={setGroups} color="var(--mint)" />
        </div>

        {scheme === 'area' ? <AreaView total={total} groups={groups} per={per} rem={rem} />
                           : <BasketView total={total} groups={groups} per={per} rem={rem} />}

        <div className="num" style={{ fontSize: 'clamp(32px,6vw,52px)', background: 'var(--paper)',
          padding: '14px 24px', borderRadius: 22, boxShadow: 'var(--shadow-sm)', whiteSpace: 'nowrap' }}>
          <span style={{ color: 'var(--orange)' }}>{total}</span>
          <span style={{ color: 'var(--ink-soft)' }}> ÷ </span>
          <span style={{ color: 'var(--mint)' }}>{groups}</span>
          <span style={{ color: 'var(--ink-soft)' }}> = </span>
          <span style={{ color: 'var(--green)' }}>{per}</span>
          {rem > 0 && <span style={{ color: 'var(--coral)', fontSize: '0.7em' }}> … 余 {rem}</span>}
        </div>
      </div>
    );
  }

  /* ---- 方阵:groups 行 × per 列,余数单独放 ---- */
  function AreaView({ total, groups, per, rem }) {
    const C = 40, G = 6;
    return (
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 12 }}>
        <div style={{ fontSize: 19, color: 'var(--ink-soft)' }}>每一行就是一份,看看每份有几个 👇</div>
        <div style={{ display: 'flex', gap: 16, alignItems: 'center' }}>
          <div style={{ padding: 12, background: '#fff', borderRadius: 18, boxShadow: 'inset 0 0 0 3px rgba(74,59,107,.08)' }}>
            <div style={{ display: 'grid', gridTemplateColumns: `repeat(${Math.max(per, 1)}, ${C}px)`, gap: G }}>
              {Array.from({ length: groups * per }).map((_, k) => {
                const row = Math.floor(k / Math.max(per, 1));
                return <Dot key={k} size={C} color={BASKET_COLORS[row % BASKET_COLORS.length]} />;
              })}
            </div>
          </div>
          {rem > 0 && (
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: 16, color: 'var(--coral)', marginBottom: 6 }}>剩下</div>
              <div style={{ display: 'flex', gap: G, padding: 10, background: '#fff', borderRadius: 16,
                boxShadow: 'inset 0 0 0 3px rgba(255,123,107,.3)' }}>
                {Array.from({ length: rem }).map((_, k) => <Dot key={k} size={C} color="var(--coral)" />)}
              </div>
            </div>
          )}
        </div>
      </div>
    );
  }

  /* ---- 篮子:点“发糖”一颗颗轮流分 ---- */
  function BasketView({ total, groups, per, rem }) {
    const [placed, setPlaced] = useState(0);
    const timer = useRef(null);

    useEffect(() => { setPlaced(0); if (timer.current) clearInterval(timer.current); }, [total, groups]);
    useEffect(() => () => timer.current && clearInterval(timer.current), []);

    const dist = total - rem; // 能平均分出去的数量
    const deal = () => {
      if (timer.current) clearInterval(timer.current);
      setPlaced(0);
      let i = 0;
      timer.current = setInterval(() => {
        i += 1; setPlaced(i); Sound.pop();
        if (i >= dist) { clearInterval(timer.current); timer.current = null; Sound.correct(); Celebrate.stars(10); Sound.speak(`每份 ${per} 个`); }
      }, 220);
    };

    const inBasket = (g) => {
      // 轮流分:第 g 个篮子已放入的数量
      let cnt = 0;
      for (let k = 0; k < placed; k++) if (k % groups === g) cnt++;
      return cnt;
    };
    const remaining = total - placed;

    return (
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 14 }}>
        {/* 待分糖果堆 */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, flexWrap: 'wrap', justifyContent: 'center' }}>
          <div style={{ fontSize: 19, color: 'var(--ink-soft)' }}>糖果堆:</div>
          <div style={{ display: 'flex', gap: 5, flexWrap: 'wrap', maxWidth: 280, minHeight: 30 }}>
            {Array.from({ length: remaining }).map((_, k) => <Dot key={k} size={26} color="var(--pink)" />)}
          </div>
          <button className="btn num" onClick={() => { Sound.click(); deal(); }}
            style={{ background: 'var(--mint)', fontSize: 22, padding: '12px 22px', borderRadius: 18, whiteSpace: 'nowrap' }}>🍬 发糖</button>
        </div>

        {/* 篮子 */}
        <div style={{ display: 'flex', gap: 14, flexWrap: 'wrap', justifyContent: 'center' }}>
          {Array.from({ length: groups }).map((_, g) => (
            <div key={g} style={{ padding: '12px 14px 8px', background: '#fff', borderRadius: '16px 16px 22px 22px',
              boxShadow: 'inset 0 0 0 3px rgba(74,59,107,.08)', textAlign: 'center', minWidth: 78 }}>
              <div style={{ display: 'grid', gridTemplateColumns: `repeat(${Math.max(Math.min(per, 3), 1)}, 26px)`, gap: 5,
                justifyContent: 'center', minHeight: 26 }}>
                {Array.from({ length: inBasket(g) }).map((_, i) => <Dot key={i} size={24} color={BASKET_COLORS[g % BASKET_COLORS.length]} />)}
              </div>
              <div style={{ fontSize: 30, marginTop: 6 }}>🧺</div>
              <div className="num" style={{ fontSize: 20, color: 'var(--mint)' }}>{inBasket(g)}</div>
            </div>
          ))}
        </div>
      </div>
    );
  }

  function Dot({ size, color }) {
    return <div style={{ width: size, height: size, borderRadius: '50%', background: color,
      boxShadow: 'inset -3px -4px 0 rgba(0,0,0,.13), inset 3px 3px 0 rgba(255,255,255,.4)' }} />;
  }

  Object.assign(window, { DivLearn });
})();
