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 { 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';
import { t, useT } from '../i18n';
// 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;
  onOpenHeroSheet: () => void;
  /** Quests done but reward not claimed yet — shown on Hero button */
  completedQuestCount?: number;
}

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%',
  minWidth: 0,
};

const heroHpBuffColumnStyle: CSSProperties = {
  display: 'flex',
  flexDirection: 'column',
  gap: 6,
  width: '100%',
};

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 = {
  display: 'flex',
  justifyContent: 'center',
  width: '100%',
  pointerEvents: 'auto',
};

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',
};

const sheetBtnStyle: CSSProperties = {
  flexShrink: 0,
  minWidth: 44,
  height: 40,
  padding: '3px 6px',
  borderRadius: 6,
  border: '1px solid rgba(140, 170, 220, 0.35)',
  backgroundColor: 'rgba(25, 35, 55, 0.75)',
  color: '#b8c8e8',
  cursor: 'pointer',
  pointerEvents: 'auto',
  display: 'flex',
  flexDirection: 'column',
  alignItems: 'center',
  justifyContent: 'center',
  gap: 1,
  userSelect: 'none',
  WebkitTapHighlightColor: 'transparent',
};

const sheetBtnIconStyle: CSSProperties = {
  lineHeight: 1,
  fontSize: 14,
};

const sheetBtnLabelStyle: CSSProperties = {
  fontSize: 9,
  fontWeight: 700,
  letterSpacing: 0.4,
  textTransform: 'uppercase',
  color: 'rgba(200, 215, 240, 0.95)',
  lineHeight: 1,
};

/** Gold next to Hero sheet button — matches inventory tab styling */
const hudGoldChipStyle: CSSProperties = {
  flexShrink: 0,
  display: 'inline-flex',
  alignItems: 'center',
  gap: 4,
  padding: '4px 8px',
  borderRadius: 6,
  background: 'rgba(255, 215, 0, 0.08)',
  border: '1px solid rgba(255, 215, 0, 0.22)',
  color: '#ffd700',
  fontWeight: 700,
  fontSize: 12,
  pointerEvents: 'none',
  userSelect: 'none',
  whiteSpace: 'nowrap',
};

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

  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 style={heroHpBuffColumnStyle}>
              <div style={hpBuffRowStyle}>
                <div
                  style={{
                    position: 'relative',
                    flexShrink: 0,
                  }}
                >
                  <button
                    type="button"
                    style={sheetBtnStyle}
                    onClick={onOpenHeroSheet}
                    aria-label={
                      completedQuestCount > 0
                        ? `Hero sheet. ${t(tr.heroSheetQuestBadgeAria, { count: completedQuestCount })}`
                        : 'Hero sheet — stats, character, inventory'
                    }
                    title="Hero — stats, character, inventory, journal, quests"
                  >
                    <span style={sheetBtnIconStyle} aria-hidden>&#x2694;&#xFE0F;</span>
                    <span style={sheetBtnLabelStyle}>{tr.hero}</span>
                  </button>
                  {completedQuestCount > 0 && (
                    <div
                      style={{
                        position: 'absolute',
                        top: -5,
                        right: -6,
                        display: 'flex',
                        alignItems: 'center',
                        gap: 2,
                        padding: '2px 5px',
                        minHeight: 18,
                        borderRadius: 8,
                        background: 'linear-gradient(180deg, rgba(200, 160, 80, 0.98), rgba(150, 110, 40, 0.98))',
                        border: '1px solid rgba(255, 235, 180, 0.45)',
                        fontSize: 10,
                        fontWeight: 800,
                        color: '#fff',
                        lineHeight: 1,
                        pointerEvents: 'none',
                        boxShadow: '0 2px 8px rgba(0,0,0,0.45)',
                        textShadow: '0 1px 2px rgba(0,0,0,0.5)',
                      }}
                      aria-hidden
                      title={t(tr.heroSheetQuestBadgeAria, { count: completedQuestCount })}
                    >
                      <span style={{ fontSize: 11, lineHeight: 1 }}>&#x1F4DC;</span>
                      <span>{completedQuestCount > 99 ? '99+' : completedQuestCount}</span>
                    </div>
                  )}
                </div>
                <div style={hudGoldChipStyle} aria-label={`Gold: ${hero.gold}`}>
                  <span style={{ fontSize: 14 }} aria-hidden>{'\uD83E\uDE99'}</span>
                  <span>{hero.gold.toLocaleString()}</span>
                </div>
                <div style={hpBarFlex}>
                  <HPBar
                    current={hero.hp}
                    max={hero.maxHp}
                    color="#44cc44"
                    height={28}
                    showText
                    label={tr.hp}
                  />
                </div>
              </div>
              <div style={{ pointerEvents: 'auto' as const, width: '100%' }}>
                <BuffStatusStrip buffs={hero.activeBuffs} nowMs={nowMs} />
              </div>
            </div>
            <InventoryStrip hero={hero} lastLoot={lastVictoryLoot} />

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

          </>
        )}

        {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>

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

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