/* ============================================================
       SCREEN: BATTLE MODE
       ============================================================ */
    const CONDITIONS = [
      { key: 'stunned', label: 'Stunned', color: 'gold' },
      { key: 'poisoned', label: 'Poisoned', color: 'blood' },
      { key: 'burning', label: 'Burning', color: 'blood' },
      { key: 'shielded', label: 'Shielded', color: 'gold' },
      { key: 'blessed', label: 'Blessed', color: 'gold' }
    ];

    const BattleSetup = ({ warbands, miniatures, onStart, onCancel, presetWarbandId }) => {
      const [yourId, setYourId] = useState(presetWarbandId || warbands[0]?.id || '');
      const [oppName, setOppName] = useState('Opposing Force');

      const yours = warbands.find(w => w.id === yourId);
      const yourMinis = yours ? miniatures.filter(m => yours.unitIds.includes(m.id)) : [];

      // Build a generic opponent from any other warband or fall back to the same warband
      const oppCandidates = warbands.filter(w => w.id !== yourId);

      return (
        <div className="pb-24">
          <Header title="Begin Battle" subtitle="Prepare for war" onBack={onCancel} />
          <div className="px-4 pt-4 space-y-5">
            <Section title="Your Warband">
              {warbands.length === 0 ? (
                <p className="text-sm text-muted">Create a warband first.</p>
              ) : (
                <select value={yourId} onChange={e => setYourId(e.target.value)}>
                  {warbands.map(w => <option key={w.id} value={w.id}>{w.name}</option>)}
                </select>
              )}
              {yours && (
                <div className="mt-2 text-xs text-muted">
                  {yourMinis.length} units · {totalPoints(yourMinis)} pts
                </div>
              )}
            </Section>

            <Section title="Opponent">
              <Field label="Opponent Name">
                <input value={oppName} onChange={e => setOppName(e.target.value)} />
              </Field>
              {oppCandidates.length > 0 && (
                <p className="text-xs text-muted">Or pick an existing warband as opponent (mock):</p>
              )}
              <div className="space-y-1">
                {oppCandidates.map(w => (
                  <button
                    key={w.id}
                    onClick={() => onStart({ yourWarbandId: yourId, opponentWarbandId: w.id, opponentName: w.name })}
                    className="w-full bg-bg border border-line rounded p-2 text-left text-sm active:bg-panel2"
                  >
                    {w.name}
                  </button>
                ))}
              </div>
            </Section>

            <button
              onClick={() => onStart({ yourWarbandId: yourId, opponentWarbandId: null, opponentName: oppName })}
              disabled={!yours}
              className="btn-blood w-full disabled:opacity-50"
            >
              <Icon name="sword" className="w-4 h-4 inline mr-1" /> Sound the Horns
            </button>
          </div>
        </div>
      );
    };

    const BattleMode = ({ battle, miniatures, warbands, onUpdate, onEnd }) => {
      const [side, setSide] = useState('yours'); // yours | opponent
      const [logOpen, setLogOpen] = useState(false);

      const yourWarband = warbands.find(w => w.id === battle.yourWarbandId);
      const oppWarband = battle.opponentWarbandId ? warbands.find(w => w.id === battle.opponentWarbandId) : null;

      const yourUnits = battle.yourUnits;
      const oppUnits = battle.oppUnits;
      const units = side === 'yours' ? yourUnits : oppUnits;

      const updateUnit = (uid, patch) => {
        const key = side === 'yours' ? 'yourUnits' : 'oppUnits';
        const nextUnits = battle[key].map(u => u.uid === uid ? { ...u, ...patch } : u);
        const log = [...battle.log];
        if (patch._logEntry) log.push({ id: Date.now() + Math.random(), text: patch._logEntry, round: battle.round, side });
        const cleanPatch = { ...patch }; delete cleanPatch._logEntry;
        const nextUnits2 = battle[key].map(u => u.uid === uid ? { ...u, ...cleanPatch } : u);
        onUpdate({ ...battle, [key]: nextUnits2, log });
      };

      const adjustHp = (u, delta) => {
        const max = u.maxHp;
        const next = Math.max(0, Math.min(max, (u.hp || 0) + delta));
        updateUnit(u.uid, {
          hp: next,
          _logEntry: `${u.name} ${delta > 0 ? 'healed' : 'took'} ${Math.abs(delta)} ${delta > 0 ? 'HP' : 'damage'} (${next}/${max})`
        });
      };

      const toggleCondition = (u, key) => {
        const conds = u.conditions || [];
        const has = conds.includes(key);
        const next = has ? conds.filter(c => c !== key) : [...conds, key];
        updateUnit(u.uid, {
          conditions: next,
          _logEntry: `${u.name} ${has ? 'cleared' : 'gained'} ${key}`
        });
      };

      const nextRound = () => {
        onUpdate({
          ...battle,
          round: battle.round + 1,
          log: [...battle.log, { id: Date.now() + Math.random(), text: `— Round ${battle.round + 1} begins —`, round: battle.round + 1, side: 'system' }]
        });
      };

      return (
        <div className="pb-24 min-h-screen">
          {/* Battle header */}
          <div className="bg-gradient-to-b from-bloodDim/40 to-bg border-b border-blood/30 px-4 py-3 sticky top-0 z-30 backdrop-blur-sm">
            <div className="flex items-center justify-between gap-2">
              <button onClick={() => { if (confirm('End the battle?')) onEnd(); }} className="text-muted hover:text-parchment p-1 -ml-1">
                <Icon name="x" className="w-5 h-5" />
              </button>
              <div className="text-center">
                <div className="text-[10px] uppercase tracking-widest text-bloodBright">Round</div>
                <div className="serif text-2xl text-parchment leading-none">{battle.round}</div>
              </div>
              <button onClick={nextRound} className="btn-blood text-xs px-3 py-2">
                Next Round
              </button>
            </div>

            <div className="flex mt-3 bg-bg/60 border border-line rounded overflow-hidden">
              <SideTab active={side === 'yours'} onClick={() => setSide('yours')} label={yourWarband?.name || 'Yours'} count={yourUnits.length} variant="gold" />
              <SideTab active={side === 'opponent'} onClick={() => setSide('opponent')} label={battle.opponentName} count={oppUnits.length} variant="blood" />
            </div>
          </div>

          {/* Units */}
          <div className="px-4 pt-4 space-y-3">
            {units.length === 0 ? (
              <EmptyState icon="users" title="No units on this side" hint="Opposing force is unstatted." />
            ) : (
              units.map(u => (
                <BattleUnitCard
                  key={u.uid}
                  unit={u}
                  onHp={(d) => adjustHp(u, d)}
                  onToggleCondition={(c) => toggleCondition(u, c)}
                />
              ))
            )}
          </div>

          {/* Log toggle */}
          <button
            onClick={() => setLogOpen(true)}
            className="fixed bottom-20 right-4 z-40 bg-panel border-2 border-gold/60 rounded-full p-3 gold-glow"
          >
            <Icon name="scroll" className="w-5 h-5 text-gold" />
            {battle.log.length > 0 && (
              <span className="absolute -top-1 -right-1 bg-blood text-parchment text-[10px] rounded-full w-5 h-5 flex items-center justify-center font-bold">
                {battle.log.length}
              </span>
            )}
          </button>

          <Modal open={logOpen} onClose={() => setLogOpen(false)} title="Battle Chronicle">
            {battle.log.length === 0 ? (
              <p className="text-sm text-muted text-center py-6">No deeds yet recorded.</p>
            ) : (
              <div className="space-y-1 text-sm">
                {[...battle.log].reverse().map(entry => (
                  <div key={entry.id} className={`p-2 border-l-2 ${
                    entry.side === 'yours' ? 'border-gold/60 bg-gold/5' :
                    entry.side === 'opponent' ? 'border-blood/60 bg-blood/5' :
                    'border-muted bg-panel2'
                  }`}>
                    <div className="text-[10px] text-muted uppercase tracking-wider">Round {entry.round}</div>
                    <div className="text-parchment">{entry.text}</div>
                  </div>
                ))}
              </div>
            )}
          </Modal>
        </div>
      );
    };

    const SideTab = ({ active, onClick, label, count, variant }) => (
      <button
        onClick={onClick}
        className={`flex-1 px-3 py-2 text-xs uppercase tracking-widest font-bold transition-colors ${
          active
            ? variant === 'gold'
              ? 'bg-gold/20 text-goldBright'
              : 'bg-blood/30 text-bloodBright'
            : 'text-muted hover:text-parchment'
        }`}
      >
        <span className="truncate block">{label}</span>
        <span className="text-[10px] opacity-70 block normal-case tracking-normal">{count} units</span>
      </button>
    );

    const BattleUnitCard = ({ unit, onHp, onToggleCondition }) => {
      const [expanded, setExpanded] = useState(false);
      const dead = unit.hp <= 0;
      const pct = unit.maxHp > 0 ? (unit.hp / unit.maxHp) * 100 : 0;

      return (
        <div className={`bg-panel border rounded panel-edge overflow-hidden ${dead ? 'border-line opacity-60' : 'border-line'}`}>
          <div className="p-3">
            <div className="flex items-start gap-3">
              <div className={`w-12 h-12 shrink-0 rounded border flex items-center justify-center serif text-lg ${
                dead ? 'border-line bg-bg text-muted' : 'border-line bg-bg text-gold'
              }`}>
                {dead ? <Icon name="skull" className="w-6 h-6 text-blood" /> : unit.name.charAt(0)}
              </div>
              <div className="flex-1 min-w-0">
                <div className="serif text-parchment truncate">{unit.name}</div>
                <div className="text-xs text-muted truncate">{unit.faction || ''}</div>
                <div className="flex flex-wrap gap-1 mt-1.5">
                  {(unit.conditions || []).map(c => {
                    const cond = CONDITIONS.find(x => x.key === c);
                    return (
                      <span key={c} className={`chip ${cond?.color === 'blood' ? 'chip-blood' : 'chip-gold'}`}>
                        {cond?.label || c}
                      </span>
                    );
                  })}
                </div>
              </div>
              <button onClick={() => setExpanded(!expanded)} className="p-2 -mr-1 text-muted hover:text-parchment">
                <Icon name={expanded ? 'chevronDown' : 'chevron'} className="w-4 h-4" />
              </button>
            </div>

            {/* HP bar */}
            <div className="mt-3">
              <div className="flex items-center justify-between text-xs mb-1">
                <span className="text-bloodBright uppercase tracking-wider font-bold text-[10px]">HP</span>
                <span className="serif text-parchment">{unit.hp} / {unit.maxHp}</span>
              </div>
              <div className="h-2.5 bg-bg border border-line rounded overflow-hidden">
                <div
                  className="h-full hp-bar transition-all duration-200"
                  style={{ width: `${pct}%` }}
                />
              </div>
            </div>

            {/* HP controls */}
            <div className="mt-3 grid grid-cols-4 gap-2">
              <button onClick={() => onHp(-5)} className="btn-blood py-3 text-base">-5</button>
              <button onClick={() => onHp(-1)} className="btn-blood py-3 text-base">-1</button>
              <button onClick={() => onHp(1)} className="btn-primary py-3 text-base">+1</button>
              <button onClick={() => onHp(5)} className="btn-primary py-3 text-base">+5</button>
            </div>
          </div>

          {expanded && (
            <div className="border-t border-line bg-bg/40 px-3 py-3 space-y-3">
              <div>
                <div className="text-[10px] uppercase tracking-widest text-gold mb-1.5">Conditions</div>
                <div className="flex flex-wrap gap-1.5">
                  {CONDITIONS.map(c => {
                    const active = (unit.conditions || []).includes(c.key);
                    return (
                      <button
                        key={c.key}
                        onClick={() => onToggleCondition(c.key)}
                        className={`chip ${active ? (c.color === 'blood' ? 'chip-blood' : 'chip-gold') : 'opacity-50 hover:opacity-100'}`}
                      >
                        {active && <Icon name="check" className="w-3 h-3" />} {c.label}
                      </button>
                    );
                  })}
                </div>
              </div>
              {unit.abilities && unit.abilities.length > 0 && (
                <div>
                  <div className="text-[10px] uppercase tracking-widest text-gold mb-1.5">Abilities</div>
                  <div className="space-y-1.5">
                    {unit.abilities.map((a, i) => (
                      <div key={i} className="text-xs">
                        <span className="serif text-parchment">{a.name}</span>
                        <span className="text-muted ml-1">— {a.description}</span>
                      </div>
                    ))}
                  </div>
                </div>
              )}
              {unit.weapons && unit.weapons.length > 0 && (
                <div>
                  <div className="text-[10px] uppercase tracking-widest text-gold mb-1.5">Weapons</div>
                  <div className="space-y-1">
                    {unit.weapons.map((w, i) => (
                      <div key={i} className="text-xs space-y-0.5">
                        <div className="serif text-parchment">{w.name}</div>
                        <div className="flex flex-wrap gap-1">
                          {Object.entries(w.fields || {}).filter(([,v]) => v).map(([k, v]) => (
                            <span key={k} className="chip"><span className="text-muted">{k}:</span> {v}</span>
                          ))}
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>
          )}
        </div>
      );
    };
