import { useCallback, type CSSProperties } from 'react';
import { HPBar } from './HPBar';
import { BuffBar } from './BuffBar';
import { BuffStatusStrip } from './BuffStatusStrip';
import { DebuffBar } from './DebuffBar';
import { LootPopup } from './LootPopup';
import { HeroPanel } from './HeroPanel';
import { EquipmentPanel } from './EquipmentPanel';
import { InventoryStrip } from './InventoryStrip';
import type { GameState } from '../game/types';
import { GamePhase, BuffType } from '../game/types';
import { useUiClock } from '../hooks/useUiClock';
import type { HeroResponse } from '../network/api';
// FREE_BUFF_ACTIVATIONS_PER_PERIOD removed — per-buff charges are now shown on each button

interface HUDProps {
  gameState: GameState;
  onBuffActivate: (type: BuffType) => void;
  buffCooldownEndsAt: Partial<Record<BuffType, number>>;
  onUsePotion?: () => void;
  onHeroUpdated?: (hero: HeroResponse) => void;
}

const containerStyle: CSSProperties = {
  position: 'absolute',
  top: 0,
  left: 0,
  width: '100%',
  height: '100%',
  pointerEvents: 'none',
  display: 'flex',
  flexDirection: 'column',
  justifyContent: 'space-between',
  padding: '12px 16px',
  zIndex: 10,
};

const topSection: CSSProperties = {
  display: 'flex',
  flexDirection: 'column',
  gap: 8,
  pointerEvents: 'auto',
};

const levelBadge: CSSProperties = {
  backgroundColor: 'rgba(68, 170, 255, 0.8)',
  color: '#fff',
  fontSize: 12,
  fontWeight: 700,
  padding: '2px 8px',
  borderRadius: 4,
  minWidth: 32,
  textAlign: 'center',
};

const heroTopRowStyle: CSSProperties = {
  display: 'flex',
  justifyContent: 'flex-start',
  alignItems: 'center',
  gap: 8,
  width: '100%',
};

const hpBuffRowStyle: CSSProperties = {
  display: 'flex',
  alignItems: 'center',
  gap: 8,
  width: '100%',
  marginTop: 8,
  minWidth: 0,
};

const hpBarFlex: CSSProperties = {
  flex: 1,
  minWidth: 0,
};

const enemySection: CSSProperties = {
  marginTop: 8,
};

const enemyNameStyle: CSSProperties = {
  color: '#ff6666',
  fontSize: 13,
  fontWeight: 600,
  marginBottom: 4,
  textShadow: '0 1px 2px rgba(0,0,0,0.8)',
};

const bottomSection: CSSProperties = {
  pointerEvents: 'auto',
};

const phaseIndicator: CSSProperties = {
  position: 'absolute',
  bottom: 8,
  left: 8,
  color: '#fff',
  fontSize: 10,
  fontWeight: 500,
  opacity: 0.3,
  pointerEvents: 'none',
  textTransform: 'uppercase',
  letterSpacing: 1,
};

const potionButtonStyle: CSSProperties = {
  display: 'inline-flex',
  alignItems: 'center',
  gap: 3,
  padding: '3px 8px',
  borderRadius: 6,
  border: '1px solid rgba(100, 200, 100, 0.3)',
  backgroundColor: 'rgba(30, 60, 30, 0.65)',
  color: '#88dd88',
  fontSize: 12,
  fontWeight: 600,
  cursor: 'pointer',
  pointerEvents: 'auto',
  userSelect: 'none',
};

const potionButtonDisabledStyle: CSSProperties = {
  ...potionButtonStyle,
  opacity: 0.4,
  cursor: 'default',
};

export function HUD({ gameState, onBuffActivate, buffCooldownEndsAt, onUsePotion, onHeroUpdated }: HUDProps) {
  const { hero, enemy, phase, lastVictoryLoot } = gameState;
  const nowMs = useUiClock(100);

  const handleBuffActivate = useCallback(
    (type: BuffType) => {
      onBuffActivate(type);
    },
    [onBuffActivate],
  );

  const debuffsLive =
    hero?.debuffs
      .map((d) => ({
        ...d,
        remainingMs:
          d.expiresAtMs != null ? Math.max(0, d.expiresAtMs - nowMs) : d.remainingMs,
      }))
      .filter((d) => d.remainingMs > 0) ?? [];

  return (
    <div style={containerStyle}>
      {/* Top: Hero HP + Enemy info */}
      <div style={topSection}>
        {!hero && (
          <div style={{ color: '#aaa', fontSize: 14, textAlign: 'center', padding: 16 }}>
            Loading hero...
          </div>
        )}
        {hero && (
          <>
            <div style={heroTopRowStyle}>
              <span style={levelBadge}>Lv.{hero.level}</span>
              <button
                style={hero.potions > 0 ? potionButtonStyle : potionButtonDisabledStyle}
                onClick={() => {
                  if (hero.potions > 0 && onUsePotion) onUsePotion();
                }}
              >
                <span style={{ fontSize: 14 }}>&#x1F9EA;</span> {hero.potions}
              </button>
            </div>
            <div>
              <div style={hpBuffRowStyle}>
                <div style={hpBarFlex}>
                  <HPBar
                    current={hero.hp}
                    max={hero.maxHp}
                    color="#44cc44"
                    height={28}
                    showText
                    label="HP"
                  />
                </div>
                <BuffStatusStrip buffs={hero.activeBuffs} nowMs={nowMs} />
              </div>
              {/* Per-buff charge quotas are now shown on each BuffBar button */}
            </div>
            <InventoryStrip hero={hero} lastLoot={lastVictoryLoot} />

            {/* Debuff indicators */}
            {debuffsLive.length > 0 && <DebuffBar debuffs={debuffsLive} />}

            <div style={{ display: 'flex', gap: 6, alignItems: 'flex-start' }}>
              <HeroPanel hero={hero} nowMs={nowMs} />
              <EquipmentPanel equipment={hero.equipment ?? {}} />
            </div>
          </>
        )}

        {enemy &&
          (phase === GamePhase.Fighting ||
            (phase === GamePhase.Dead && enemy)) && (
          <div style={enemySection}>
            <div style={enemyNameStyle}>{enemy.name}</div>
            <HPBar
              current={enemy.hp}
              max={enemy.maxHp}
              color="#cc3333"
              height={16}
              showText
            />
          </div>
        )}
      </div>

      {/* Center: Phase indicator (debug/subtle) */}
      <div style={phaseIndicator}>{phase}</div>

      {/* Loot popup */}
      <LootPopup loot={gameState.loot} />

      <div style={bottomSection}>
        {hero && (
          <BuffBar
            buffs={hero.activeBuffs}
            cooldownEndsAt={buffCooldownEndsAt}
            buffCharges={hero.buffCharges}
            nowMs={nowMs}
            onActivate={handleBuffActivate}
            onHeroUpdated={onHeroUpdated}
          />
        )}
      </div>
    </div>
  );
}
