/* global React, HpBar, ResourceBar, CastBar, Portrait, formatNum */
const { useState: useStateC, useEffect: useEffectC } = React;

// ============================================================
// UNIT CARDS (enemies + party)
// ============================================================

function EnemyCard({ unit, isCasting, castProgress, isTargeted }) {
  const t = unit.tpl;
  const isDead = unit.hp <= 0;
  const hpPct = (unit.hp / t.hpMax) * 100;
  return (
    <div className={`unit-card enemy ${isDead ? 'dead' : ''} ${isTargeted ? 'targeted' : ''}`}>
      <div className="unit-head">
        <div className="unit-head-text">
          <span className="name">{t.name}</span>
          <span className="sub">Nivel {t.lvl}</span>
        </div>
        <span className={`unit-rank ${t.rank === 'Élite' ? 'elite' : ''}`}>{t.rank}</span>
      </div>

      <Portrait
        glyph={t.glyph}
        tint={t.tint}
        slotLabel="enemy portrait"
        imageUrl={t.imageUrl || null}
        badges={unit.debuffs?.map(d => ({ kind: 'dot', glyph: d.glyph }))}
      />

      <div className="unit-stats">
        <HpBar hp={unit.hp} hpMax={t.hpMax} />
        <CastBar
          ability={isCasting && !isDead ? { name: t.ability, glyph: '⚡', kind: 'physical' } : null}
          progress={castProgress || 0}
        />
        {isDead && (
          <div style={{
            position: 'absolute',
            inset: 0,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            background: 'rgba(0,0,0,0.55)',
            fontFamily: 'Cinzel, serif',
            fontSize: 22,
            letterSpacing: '0.2em',
            color: 'var(--hp-low)',
            fontWeight: 700,
            textTransform: 'uppercase',
            pointerEvents: 'none',
          }}>Muerto</div>
        )}
      </div>
    </div>
  );
}

function PartyCard({ unit, ability, isActive, isCasting, castProgress, slotLabel }) {
  const isDead = unit.hp <= 0;
  return (
    <div className={`unit-card party ${isActive ? 'active' : ''} ${isDead ? 'dead' : ''}`}>
      <div className="unit-head">
        <div className="unit-head-text">
          <span className="name">{unit.name}</span>
          <span className="sub">{unit.cls} · Nivel {unit.lvl}</span>
        </div>
        {unit.subtitle && <span className="unit-rank elite">{unit.subtitle.toUpperCase()}</span>}
      </div>

      <Portrait
        glyph={unit.portraitGlyph}
        tint={unit.portraitTint}
        slotLabel={slotLabel || 'character portrait'}
        imageUrl={unit.portraitImg || null}
        badges={unit.buffs?.map(b => ({ kind: 'buff', glyph: b.glyph }))}
      />

      <div className="unit-stats">
        <HpBar hp={unit.hp} hpMax={unit.hpMax} />
        {unit.resource === 'mp' && <ResourceBar value={unit.mp} max={unit.mpMax} kind="mp" label="MP" />}
        {unit.resource === 'fur' && <ResourceBar value={unit.fur} max={unit.furMax} kind="fur" label="FUR" />}
        {unit.resource === 'ene' && <ResourceBar value={unit.ene} max={unit.eneMax} kind="ene" label="ENE" />}
        <CastBar
          ability={isCasting ? ability : null}
          progress={castProgress || 0}
          kind={ability?.kind === 'heal' ? 'cast' : 'cast'}
        />
      </div>
    </div>
  );
}

// ============================================================
// ABILITY SLOT (in bottom dock)
// ============================================================

function AbilitySlot({ ability, cd, cdMax, ready, casting, hotkey, onClick, disabled }) {
  if (!ability) return <div className="ability-slot disabled"></div>;
  const cdPct = cd > 0 ? cd / cdMax : 0;
  return (
    <div
      className={`ability-slot ${ready ? 'ready' : ''} ${cd > 0 ? 'cooldown' : ''} ${casting ? 'casting' : ''} ${disabled ? 'disabled' : ''}`}
      onClick={onClick}
      title={ability.name}
    >
      <span className="glyph">{ability.glyph}</span>
      <span className="hotkey">{hotkey}</span>
      {cd > 0 && (
        <div className="cd-overlay" style={{ height: `${cdPct * 100}%` }}>
          <span className="cd-num">{cd >= 10 ? Math.ceil(cd) : cd.toFixed(1)}</span>
        </div>
      )}
    </div>
  );
}

function AbilityBlock({ unit, ability, cd, cdMax, ready, casting, hotkey, onCast, onToggleAuto, autoCast, isYou }) {
  const disabled = unit.hp <= 0;
  return (
    <div className="ability-block">
      <span className={`owner ${isYou ? 'you' : ''}`}>{unit.name}{isYou ? ' (TÚ)' : ''}</span>
      <AbilitySlot
        ability={ability}
        cd={cd}
        cdMax={cdMax}
        ready={ready}
        casting={casting}
        hotkey={hotkey}
        onClick={() => !disabled && onCast()}
        disabled={disabled}
      />
      <div className="auto-toggle" onClick={onToggleAuto}>
        <span>Auto</span>
        <div className={`toggle ${autoCast ? 'on' : ''}`}></div>
      </div>
    </div>
  );
}

Object.assign(window, { EnemyCard, PartyCard, AbilitySlot, AbilityBlock });
