import type { Combatant, Encounter } from '@/lib/schemas';

export interface EnemyStatus {
  label: 'Healthy' | 'Bloodied' | 'Down';
  cls: string;
}

/** Hide exact enemy HP from players — a status band instead. */
export function enemyStatus(c: Pick<Combatant, 'hp'>): EnemyStatus {
  if (c.hp.current <= 0) return { label: 'Down', cls: 'text-danger' };
  const frac = c.hp.max > 0 ? c.hp.current / c.hp.max : 1;
  if (frac <= 0.5) return { label: 'Bloodied', cls: 'text-warning' };
  return { label: 'Healthy', cls: 'text-success' };
}

export interface PlayerCombatant {
  id: string;
  name: string;
  kind: Combatant['kind'];
  initiative: number;
  isCurrent: boolean;
  /** exact HP for PCs; undefined for hidden enemies */
  hp?: { current: number; max: number; temp: number };
  status?: EnemyStatus;
  /** visible conditions (shown to players for everyone in the fight) */
  conditions: { name: string; value?: number }[];
}

export interface PlayerEncounter {
  id: string;
  name: string;
  round: number;
  combatants: PlayerCombatant[];
}

/** Build the player-safe view of an encounter (enemy HP masked). */
export function toPlayerEncounter(e: Encounter): PlayerEncounter {
  return {
    id: e.id,
    name: e.name,
    round: e.round,
    combatants: e.combatants.map((c, idx) => {
      const isPC = c.kind === 'pc';
      return {
        id: c.id,
        name: c.name,
        kind: c.kind,
        initiative: c.initiative,
        isCurrent: idx === e.turnIndex,
        conditions: c.conditions.map((x) => ({ name: x.name, ...(x.value !== undefined ? { value: x.value } : {}) })),
        ...(isPC ? { hp: c.hp } : { status: enemyStatus(c) }),
      };
    }),
  };
}
