import type { Character } from "../types";
import HpBar from "./HpBar";
import StatBlock from "./StatBlock";
import styles from "./CharacterCard.module.css";
import { calculateAC } from "../utils/derived-ac";
import { getTalentHpBonus } from "../utils/talent-effects";

interface CharacterCardProps {
  character: Character;
  onHpChange: (characterId: number, hp: number) => void;
  onStatChange: (characterId: number, statName: string, value: number) => void;
  onClick: (characterId: number) => void;
}

export default function CharacterCard({
  character,
  onHpChange,
  onStatChange,
  onClick,
}: CharacterCardProps) {
  const totalSlots = character.gear.reduce((sum, g) => sum + g.slot_count, 0);

  return (
    <div
      className={styles.card}
      onClick={() => onClick(character.id)}
      style={{ borderLeftColor: character.color, borderLeftWidth: "3px" }}
    >
      <div className={styles.cardHeader}>
        <span className={styles.name}>
          {character.name}
          {character.title ? ` ${character.title}` : ""}
        </span>
        <span className={styles.level}>Lvl {character.level}</span>
      </div>
      <div className={styles.meta}>
        {character.ancestry} {character.class}
      </div>
      <div className={styles.hpAcRow} onClick={(e) => e.stopPropagation()}>
        <HpBar
          current={character.hp_current}
          max={character.hp_max + getTalentHpBonus(character)}
          onChange={(hp) => onHpChange(character.id, hp)}
        />
        <div className={styles.ac}>
          <span className={styles.acLabel}>AC</span>
          <span className={styles.acValue}>
            {calculateAC(character).effective}
          </span>
        </div>
      </div>
      <div onClick={(e) => e.stopPropagation()}>
        <StatBlock
          stats={character.stats}
          onStatChange={(statName, value) =>
            onStatChange(character.id, statName, value)
          }
        />
      </div>
      <div className={styles.gearSummary}>
        {totalSlots} gear slot{totalSlots !== 1 ? "s" : ""} used
      </div>
      <div className={styles.xp}>
        XP: {character.xp} / {character.level * 10}
      </div>
    </div>
  );
}
