import type { Location, PlayerState, CombatState, Profile, WorkbenchTab } from './types'
import { useState, useEffect, useRef, useCallback } from 'react'
import { useTranslation } from 'react-i18next'
import { useAudio } from '../../contexts/AudioContext'
import Workbench from './Workbench'
import { GameTooltip } from '../common/GameTooltip'
import { GameButton } from '../common/GameButton'
import { GameDropdown } from '../common/GameDropdown'
import { getAssetPath } from '../../utils/assetPath'
import { getTranslatedText } from '../../utils/i18nUtils'
import { DialogModal } from './DialogModal'
import { TradeModal } from './TradeModal'
import { GameItemCard } from '../common/GameItemCard'
import { GameModal } from './GameModal'
import './LocationView.css'

const CARD_SIZE = 90; // px - must match CSS
const CARD_GAP = 6.4; // px - 0.4rem at default 16px font

/**
 * Calculate how many cards fit in a container of given width.
 * Returns the max number that fit in one row.
 */
function calcFitCount(containerWidth: number): number {
  if (containerWidth <= 0) return 3; // fallback
  // First card doesn't need a gap before it
  return Math.max(1, Math.floor((containerWidth + CARD_GAP) / (CARD_SIZE + CARD_GAP)));
}


interface LocationViewProps {
  location: Location
  playerState: PlayerState | null
  combatState: CombatState | null
  message: string
  locationMessages: Array<{ time: string; message: string; location_name?: string | { [key: string]: string } }>
  expandedCorpse: string | null
  corpseDetails: any
  mobileMenuOpen: string
  showCraftingMenu: boolean
  showRepairMenu: boolean
  workbenchTab: WorkbenchTab
  craftableItems: any[]
  repairableItems: any[]
  uncraftableItems: any[]
  craftFilter: string
  repairFilter: string
  uncraftFilter: string
  craftCategoryFilter: string
  profile: Profile | null
  onSetMessage: (msg: string) => void
  onInitiateCombat: (npcId: number) => void
  onInitiatePvP: (playerId: number) => void
  onPickup: (itemId: number, quantity: number) => void
  onLootCorpse: (corpseId: string) => void
  onLootCorpseItem: (corpseId: string, itemIndex: number | null) => void
  onSetExpandedCorpse: (corpseId: string | null) => void
  onOpenCrafting?: () => void
  onOpenRepair?: () => void
  onCloseCrafting: () => void
  onSwitchWorkbenchTab: (tab: WorkbenchTab) => void
  onSetCraftFilter: (filter: string) => void
  onSetRepairFilter: (filter: string) => void
  onSetUncraftFilter: (filter: string) => void
  onSetCraftCategoryFilter: (category: string) => void
  onCraft: (itemId: number) => void
  onRepair: (uniqueItemId: string, inventoryId: number) => void
  onUncraft: (uniqueItemId: string, inventoryId: number, quantity?: number) => void
  failedActionItemId: string | number | null
  quests: { active: any[], available: any[] }
}

function LocationView({
  location,

  locationMessages,
  expandedCorpse,
  corpseDetails,
  mobileMenuOpen,
  showCraftingMenu,
  showRepairMenu,
  workbenchTab,
  craftableItems,
  repairableItems,
  failedActionItemId,
  uncraftableItems,
  craftFilter,
  repairFilter,
  uncraftFilter,
  craftCategoryFilter,
  profile,
  quests,

  onInitiateCombat,
  onInitiatePvP,
  onPickup,
  onLootCorpse,
  onLootCorpseItem,
  onSetExpandedCorpse,
  onOpenCrafting,
  onOpenRepair,
  onCloseCrafting,
  onSwitchWorkbenchTab,
  onSetCraftFilter,
  onSetRepairFilter,
  onSetUncraftFilter,
  onSetCraftCategoryFilter,
  onCraft,
  onRepair,
  onUncraft
}: LocationViewProps) {
  const { t } = useTranslation()
  const { playSfx } = useAudio()
  // const { token } = useGame() // No longer needed for fetching here

  // Dropdown State
  const [activeDropdown, setActiveDropdown] = useState<string | null>(null)

  // Entity "Show All" Modal State
  const [entityModal, setEntityModal] = useState<{ type: string; title: string } | null>(null)

  // Measure entity-list container widths for dynamic fit
  const [sectionWidths, setSectionWidths] = useState<Record<string, number>>({});
  const sectionRefs = useRef<Record<string, HTMLDivElement | null>>({});

  const measureSections = useCallback(() => {
    const newWidths: Record<string, number> = {};
    Object.entries(sectionRefs.current).forEach(([key, el]) => {
      if (el) newWidths[key] = el.clientWidth;
    });
    setSectionWidths(newWidths);
  }, []);

  useEffect(() => {
    measureSections();
    const observer = new ResizeObserver(() => measureSections());
    Object.values(sectionRefs.current).forEach(el => {
      if (el) observer.observe(el);
    });
    return () => observer.disconnect();
  }, [measureSections, location]);

  const getSectionRef = useCallback((key: string) => (el: HTMLDivElement | null) => {
    sectionRefs.current[key] = el;
  }, []);

  const getFitCount = (sectionKey: string) => calcFitCount(sectionWidths[sectionKey] || 0);

  // NPC Interaction State
  const [activeDialogNpc, setActiveDialogNpc] = useState<string | null>(null)
  const [showTradeModal, setShowTradeModal] = useState<boolean>(false)
  const [activeNpcData, setActiveNpcData] = useState<any>(null)

  // Quest State
  const [questIndicators, setQuestIndicators] = useState<{ [npcId: string]: string }>({})

  // Handle dropdown toggle
  const handleDropdownClick = (e: React.MouseEvent, id: string) => {
    e.stopPropagation()
    if (activeDropdown === id) {
      setActiveDropdown(null)
    } else {
      setActiveDropdown(id)
    }
  }

  // Close dropdown when clicking outside
  useEffect(() => {
    const handleClickOutside = () => setActiveDropdown(null)
    window.addEventListener('click', handleClickOutside)
    return () => window.removeEventListener('click', handleClickOutside)
  }, [])

  // Calculate Quest Indicators from props
  useEffect(() => {
    const indicators: { [id: string]: string } = {};
    if (!quests) return;

    const { active, available } = quests;

    // Check Available (New Quests)
    available.forEach((q: any) => {
      // Filter by location if needed? available/ endpoints already filters by location usually?
      // Actually /api/quests/available returns quests available *at the current location*.
      // But GameEngine fetches it globally? 
      // Wait, /api/quests/available depends on current_user's location.
      // So useGameEngine.ts fetching valid ONLY for current location.
      // If player moves, fetchGameData is called, so available quests are refreshed. Correct.

      if (q.giver_id) {
        if (q.type === 'global') indicators[q.giver_id] = 'blue_exclamation';
        else indicators[q.giver_id] = 'yellow_exclamation';
      }
    });

    // Check Active (Ready to turn in or Cooldown)
    active.forEach((q: any) => {
      if (q.giver_id) {
        let allDone = true;

        if (q.objectives) {
          q.objectives.forEach((obj: any) => {
            const current = q.progress?.[obj.target] || 0;
            if (current < obj.count) allDone = false;
          });
        }

        if (allDone && q.status === 'active') {
          indicators[q.giver_id] = 'yellow_question';
        }

        if (q.on_cooldown) {
          indicators[q.giver_id] = 'gray_loop';
        }
      }
    });

    setQuestIndicators(indicators);
  }, [quests, location.id]);

  const handleNpcClick = (npc: any) => {
    setActiveNpcData(npc);
    setActiveDialogNpc(npc.id);
  };

  const renderItemPickupOptions = (item: any, isModal: boolean = false) => {
    const options = [];
    options.push({ label: `${t('common.pickUp')}${item.quantity > 1 ? ' (x1)' : ''}`, qty: 1 });
    if (item.quantity >= 5) options.push({ label: `${t('common.pickUp')} (x5)`, qty: 5 });
    if (item.quantity >= 10) options.push({ label: `${t('common.pickUp')} (x10)`, qty: 10 });
    if (item.quantity > 1) options.push({ label: `${t('common.pickUpAll')}`, qty: item.quantity });

    return (
      <div className="pickup-options-vertical" style={{ display: 'flex', flexDirection: 'column', gap: '4px', marginTop: '8px' }}>
        {options.map((opt) => (
          <GameButton
            key={opt.label}
            variant="success"
            size="sm"
            onClick={(e) => {
              e.stopPropagation();
              playSfx('/audio/sfx/pickup.wav');
              onPickup(Number(item.id), opt.qty);
              setActiveDropdown(null);
              if (isModal) setEntityModal(null);
            }}
            style={{ width: '100%', justifyContent: 'center' }}
          >
            {opt.label}
          </GameButton>
        ))}
      </div>
    );
  };

  const renderIndicator = (npcId: string) => {
    const type = questIndicators[npcId];
    if (!type) return null;

    let symbol = '';
    let color = '';

    switch (type) {
      case 'yellow_exclamation': symbol = '!'; color = '#ffeb3b'; break;
      case 'blue_exclamation': symbol = '!'; color = '#4fc3f7'; break;
      case 'yellow_question': symbol = '?'; color = '#ffeb3b'; break;
      case 'gray_loop': symbol = '⟳'; color = '#9e9e9e'; break;
      default: return null;
    }

    return (
      <div style={{
        position: 'absolute', top: '-10px', right: '-5px',
        color: color, fontSize: '1.5rem', fontWeight: 'bold',
        textShadow: '0 0 5px black', zIndex: 10,
        animation: 'bounce 2s infinite'
      }}>
        {symbol}
      </div>
    );
  };

  return (
    <div className="location-view">
      <div className="location-info">
        {location.tags && location.tags.length > 0 && (
          <div className="location-tags">
            {location.tags.map((tag: string, i: number) => {
              const isClickable = tag === 'workbench' || tag === 'repair_station'
              const handleClick = () => {
                if (tag === 'workbench' && onOpenCrafting) onOpenCrafting()
                else if (tag === 'repair_station' && onOpenRepair) onOpenRepair()
              }

              // Use GameButton for workbench and repair_station
              if (isClickable) {
                return (
                  <GameButton
                    key={i}
                    variant="secondary"
                    size="sm"
                    onClick={handleClick}
                  >
                    {tag === 'workbench' ? t('tags.workbench') : t('tags.repairStation')}
                  </GameButton>
                )
              }

              // Regular span for non-interactive tags
              return (
                <GameTooltip key={i} content={`This location has: ${tag}`}>
                  <span className={`location-tag tag-${tag}`}>
                    {tag === 'safe_zone' && t('tags.safeZone')}
                    {tag === 'shop' && t('tags.shop')}
                    {tag === 'shelter' && t('tags.shelter')}
                    {tag === 'medical' && t('tags.medical')}
                    {tag === 'storage' && t('tags.storage')}
                    {tag === 'water_source' && t('tags.water')}
                    {tag === 'food_source' && t('tags.food')}
                    {tag !== 'workbench' && tag !== 'repair_station' && tag !== 'safe_zone' && tag !== 'shop' && tag !== 'shelter' && tag !== 'medical' && tag !== 'storage' && tag !== 'water_source' && tag !== 'food_source' && `🏷️ ${tag}`}
                  </span>
                </GameTooltip>
              )
            })}
          </div>
        )}

        {location.image_url && (
          <div className="location-image-container">
            <img
              src={getAssetPath(location.image_url)}
              alt={getTranslatedText(location.name)}
              className="location-image"
              onError={(e: any) => (e.currentTarget.style.display = 'none')}
            />
          </div>
        )}

        <div className="location-description-box">
          <p className="location-description">{getTranslatedText(location.description)}</p>
        </div>
      </div>

      {locationMessages.length > 0 && (
        <div className="location-messages-log">
          <h4>{t('location.recentActivity')}</h4>
          <div className="messages-scroll">
            {locationMessages.slice(-10).reverse().map((msg, idx) => (
              <div key={idx} className="location-message-item">
                <span className="message-time">{msg.time}</span>
                <span className="message-text">{getTranslatedText(msg.message)}</span>
                {msg.location_name && (
                  <span className="message-location">[{getTranslatedText(msg.location_name)}]</span>
                )}
              </div>
            ))}
          </div>
        </div>
      )}
      {locationMessages.length === 0 && (
        <div className="location-messages-log location-messages-empty">
          <h4>{t('location.recentActivity')}</h4>
          <div className="messages-scroll">
            <div className="location-message-item empty-state">
              <span className="message-text" style={{ opacity: 0.5, fontStyle: 'italic' }}>
                {t('location.noRecentActivity', 'No recent activity')}
              </span>
            </div>
          </div>
        </div>
      )}

      <div className={`ground-entities mobile-menu-panel bottom ${mobileMenuOpen === 'bottom' ? 'open' : ''}`}>
        {/* Combined Entities Container for Grid Layout */}
        <div className="entities-container">
          {/* Enemies */}
          {(() => {
            const enemies = location.npcs.filter((npc: any) => npc.type === 'enemy');
            if (enemies.length === 0) return null;
            const limit = getFitCount('enemies');
            const visibleEnemies = enemies.length > limit ? enemies.slice(0, limit - 1) : enemies;
            const hasMore = enemies.length > limit;

            return (
              <div className="entity-section enemies-section">
                <h3>{t('location.enemies')}</h3>
                <div className="entity-list grid-view" ref={getSectionRef('enemies')}>
                  {visibleEnemies.map((enemy: any) => {
                    const isShaking = failedActionItemId == enemy.id;
                    const id = `enemy-${enemy.id}`;
                    if (!enemy || !enemy.id) return null;

                    return (
                      <div key={enemy.id} className={`entity-card enemy-card grid-card ${isShaking ? 'shake-animation' : ''}`}
                        onClick={(e) => handleDropdownClick(e, id)}
                      >
                        {enemy.id && (
                          <div className="entity-image padded-image">
                            <img
                              src={getAssetPath(enemy.image_path || `images/npcs/${(typeof enemy.name === 'string' ? enemy.name : enemy.name?.en || '').toLowerCase().replace(/ /g, '_')}.webp`)}
                              alt={getTranslatedText(enemy.name)}
                              onError={(e: any) => { e.currentTarget.style.display = 'none' }}
                            />
                          </div>
                        )}

                        <GameTooltip content={
                          <div>
                            <div className="tooltip-title">{getTranslatedText(enemy.name)}</div>
                            <div>{t('location.level')} {enemy.level}</div>
                            <div style={{ color: '#f56565', fontSize: '0.8rem' }}>Click for actions</div>
                          </div>
                        }>
                          <div className="grid-overlay"></div>
                        </GameTooltip>

                        {activeDropdown === id && (
                          <GameDropdown
                            isOpen={true}
                            onClose={() => setActiveDropdown(null)}
                            width="160px"
                          >
                            <div className="game-dropdown-header">{getTranslatedText(enemy.name)}</div>
                            <GameButton
                              variant="danger"
                              size="sm"
                              onClick={() => { onInitiateCombat(enemy.id); setActiveDropdown(null); }}
                              style={{ width: '100%', justifyContent: 'flex-start' }}
                            >
                              ⚔️ {t('common.fight')}
                            </GameButton>
                            <div className="game-dropdown-divider" />
                            <div style={{ padding: '0.5rem', fontSize: '0.8rem', color: '#a0aec0' }}>
                              {t('location.level')} {enemy.level}
                            </div>
                          </GameDropdown>
                        )}
                      </div>
                    );
                  })}
                  {hasMore && (
                    <div className="entity-show-more-card" onClick={() => setEntityModal({ type: 'enemies', title: t('location.enemies') })}>
                      <span className="show-more-count">+{enemies.length - (limit - 1)}</span>
                      <span className="show-more-label">{t('common.showAll', 'Show All')}</span>
                    </div>
                  )}
                </div>
              </div>
            );
          })()}

          {/* Corpses */}
          {(() => {
            const corpses = location.corpses || [];
            if (corpses.length === 0) return null;
            const limit = getFitCount('corpses');
            const visibleCorpses = corpses.length > limit ? corpses.slice(0, limit - 1) : corpses;
            const hasMore = corpses.length > limit;

            return (
              <div className="entity-section corpses-section">
                <h3>{t('location.corpses')}</h3>
                <div className="entity-list grid-view" ref={getSectionRef('corpses')}>
                  {visibleCorpses.map((corpse: any) => (
                    <div key={corpse.id} className="corpse-container">
                      <div className="entity-card corpse-card grid-card"
                        onClick={(e) => handleDropdownClick(e, `corpse-${corpse.id}`)}
                      >
                        <GameTooltip content={
                          <div>
                            <div className="tooltip-title">{corpse.emoji} {getTranslatedText(corpse.name)}</div>
                            <div>{corpse.loot_count} {t('location.items')}</div>
                          </div>
                        }>
                          <div className="grid-corpse-content">
                            {corpse.image_path ? (
                              <img
                                src={getAssetPath(corpse.image_path)}
                                alt={getTranslatedText(corpse.name)}
                                className="corpse-image"
                                onError={(e) => {
                                  (e.target as HTMLImageElement).style.display = 'none';
                                  (e.target as HTMLImageElement).nextElementSibling?.classList.remove('hidden');
                                }}
                              />
                            ) : null}
                            <div style={{ fontSize: '2rem', display: corpse.image_path ? 'none' : 'block' }} className={corpse.image_path ? 'hidden' : ''}>
                              {corpse.emoji}
                            </div>
                            <div className="corpse-loot-count">{corpse.loot_count} items</div>
                          </div>
                        </GameTooltip>

                        {activeDropdown === `corpse-${corpse.id}` && (
                          <GameDropdown
                            isOpen={true}
                            onClose={() => setActiveDropdown(null)}
                            width="160px"
                          >
                            <div className="game-dropdown-header">{getTranslatedText(corpse.name)}</div>
                            <GameButton
                              variant="secondary"
                              size="sm"
                              onClick={() => {
                                playSfx('/audio/sfx/interact.wav')
                                onLootCorpse(String(corpse.id))
                                setActiveDropdown(null)
                              }}
                              disabled={corpse.loot_count === 0}
                              style={{ width: '100%', justifyContent: 'flex-start' }}
                            >
                              🔍 {t('common.examine')}
                            </GameButton>
                          </GameDropdown>
                        )}
                      </div>
                    </div>
                  ))}
                  {hasMore && (
                    <div className="entity-show-more-card" onClick={() => setEntityModal({ type: 'corpses', title: t('location.corpses') })}>
                      <span className="show-more-count">+{corpses.length - (limit - 1)}</span>
                      <span className="show-more-label">{t('common.showAll', 'Show All')}</span>
                    </div>
                  )}
                </div>
              </div>
            );
          })()}

          {/* Friendly NPCs */}
          {(() => {
            const friendlyNpcs = location.npcs.filter((npc: any) => npc.type !== 'enemy');
            if (friendlyNpcs.length === 0) return null;
            const limit = getFitCount('npcs');
            const visibleNpcs = friendlyNpcs.length > limit ? friendlyNpcs.slice(0, limit - 1) : friendlyNpcs;
            const hasMore = friendlyNpcs.length > limit;

            return (
              <div className="entity-section npcs-section">
                <h3>{t('location.npcs')}</h3>
                <div className="entity-list grid-view" ref={getSectionRef('npcs')}>
                  {visibleNpcs.map((npc: any, i: number) => (
                    <div key={i} className="entity-card npc-card grid-card"
                      onClick={() => handleNpcClick(npc)}
                      style={{ cursor: 'pointer', position: 'relative' }}
                    >
                      {npc.image_path ? (
                        <img src={getAssetPath(npc.image_path)} alt={getTranslatedText(npc.name)} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                      ) : (
                        <span className="entity-icon" style={{ fontSize: '2.5rem' }}>🧑</span>
                      )}

                      {renderIndicator(npc.id)}

                      <GameTooltip content={
                        <div>
                          <div className="tooltip-title">{getTranslatedText(npc.name)}</div>
                          <div style={{ color: '#ff9800', fontSize: '0.8rem' }}>Click to Interact</div>
                        </div>
                      }>
                        <div className="grid-overlay"></div>
                      </GameTooltip>
                    </div>
                  ))}
                  {hasMore && (
                    <div className="entity-show-more-card" onClick={() => setEntityModal({ type: 'npcs', title: t('location.npcs') })}>
                      <span className="show-more-count">+{friendlyNpcs.length - (limit - 1)}</span>
                      <span className="show-more-label">{t('common.showAll', 'Show All')}</span>
                    </div>
                  )}
                </div>
              </div>
            );
          })()}

          {/* Items on Ground - Stable Sort */}
          {(() => {
            const sortedItems = [...location.items].sort((a: any, b: any) => (a.id || 0) - (b.id || 0));
            if (sortedItems.length === 0) return null;
            const limit = getFitCount('items');
            const visibleItems = sortedItems.length > limit ? sortedItems.slice(0, limit - 1) : sortedItems;
            const hasMore = sortedItems.length > limit;

            const renderItemCard = (item: any, i: number) => {
              const isShaking = failedActionItemId == item.id;
              const itemId = `item-${item.id}-${i}`;

              return (
                <div key={itemId} className={`entity-wrapper ${isShaking ? 'shake-animation' : ''}`} style={{ position: 'relative' }}>
                  <GameItemCard
                    item={item}
                    onClick={(e) => handleDropdownClick(e, itemId)}
                    isActive={activeDropdown === itemId}
                    showQuantity={true}
                    showDurability={true}
                    className="entity-card item-card grid-card"
                  />

                  {activeDropdown === itemId && (
                    <GameDropdown
                      isOpen={true}
                      onClose={() => setActiveDropdown(null)}
                      width="200px"
                    >
                      <div className="game-dropdown-header">{getTranslatedText(item.name)} {item.quantity > 1 ? `(x${item.quantity})` : ''}</div>
                      {renderItemPickupOptions(item)}
                    </GameDropdown>
                  )}
                </div>
              );
            };

            return (
              <div className="entity-section items-section">
                <h3>{t('location.items')}</h3>
                <div className="entity-list grid-view" ref={getSectionRef('items')}>
                  {visibleItems.map((item: any, i: number) => renderItemCard(item, i))}
                  {hasMore && (
                    <div className="entity-show-more-card" onClick={() => setEntityModal({ type: 'items', title: t('location.items') })}>
                      <span className="show-more-count">+{sortedItems.length - (limit - 1)}</span>
                      <span className="show-more-label">{t('common.showAll', 'Show All')}</span>
                    </div>
                  )}
                </div>
              </div>
            );
          })()}

          {/* Other Players */}
          {(() => {
            const players = location.other_players || [];
            if (players.length === 0) return null;
            const limit = getFitCount('players');
            const visiblePlayers = players.length > limit ? players.slice(0, limit - 1) : players;
            const hasMore = players.length > limit;

            const renderPlayerCard = (player: any, i: number) => {
              const playerId = `player-${player.id}-${i}`;
              const canPvP = player.can_pvp;

              return (
                <div key={i} className="entity-card player-card grid-card"
                  onClick={(e) => handleDropdownClick(e, playerId)}
                >
                  <GameTooltip content={
                    <div>
                      <div className="tooltip-title">{player.name || player.username}</div>
                      <div>{t('location.level', 'Level')} {player.level}</div>
                      {player.level_diff !== undefined && (
                        <div style={{ fontSize: '0.8rem', color: player.level_diff > 0 ? '#f56565' : '#48bb78' }}>
                          {player.level_diff > 0 ? `+${player.level_diff}` : player.level_diff} levels
                        </div>
                      )}
                      <div style={{ color: '#ebf8ff', fontSize: '0.8rem', marginTop: '0.5rem' }}>Click for actions</div>
                    </div>
                  }>
                    <div className="grid-corpse-content">
                      <div style={{ fontSize: '2.5rem' }}>
                        🧍
                      </div>
                      <div className="item-quantity-badge" style={{ top: '2px', right: '2px', bottom: 'auto', background: 'rgba(49, 130, 206, 0.8)', borderColor: 'rgba(99, 179, 237, 0.4)' }}>
                        Lv.{player.level}
                      </div>
                    </div>
                  </GameTooltip>

                  {activeDropdown === playerId && (
                    <GameDropdown
                      isOpen={true}
                      onClose={() => setActiveDropdown(null)}
                      width="180px"
                    >
                      <div className="game-dropdown-header">{player.name || player.username}</div>

                      {canPvP ? (
                        <GameButton
                          variant="danger"
                          size="sm"
                          onClick={() => {
                            onInitiatePvP(player.id);
                            setActiveDropdown(null);
                          }}
                          style={{ width: '100%', justifyContent: 'flex-start' }}
                        >
                          ⚔️ {t('game.attack')}
                        </GameButton>
                      ) : (
                        <div style={{ padding: '0.5rem', fontSize: '0.8rem', color: '#a0aec0', fontStyle: 'italic' }}>
                          {location.danger_level !== undefined && location.danger_level < 3
                            ? t('game.areaTooSafeForPvP')
                            : (player.level_diff !== undefined && Math.abs(player.level_diff) > 3)
                              ? t('game.levelDifferenceTooHigh')
                              : "PvP Unavailable"}
                        </div>
                      )}

                      <div className="game-dropdown-divider" />
                      <div style={{ padding: '0.5rem', fontSize: '0.8rem', color: '#a0aec0' }}>
                        Level {player.level}
                      </div>
                    </GameDropdown>
                  )}
                </div>
              );
            };

            return (
              <div className="entity-section players-section">
                <h3>👥 {t('location.otherPlayers', 'Other Players')}</h3>
                <div className="entity-list grid-view" ref={getSectionRef('players')}>
                  {visiblePlayers.map((player: any, i: number) => renderPlayerCard(player, i))}
                  {hasMore && (
                    <div className="entity-show-more-card" onClick={() => setEntityModal({ type: 'players', title: t('location.players') })}>
                      <span className="show-more-count">+{players.length - (limit - 1)}</span>
                      <span className="show-more-label">{t('common.showAll', 'Show All')}</span>
                    </div>
                  )}
                </div>
              </div>
            );
          })()}
        </div>
      </div>


      {/* Corpse Loot Overlay Modal */}
      {
        expandedCorpse && corpseDetails && corpseDetails.loot_items && (
          <GameModal
            title={t('location.lootableItems')}
            onClose={() => onSetExpandedCorpse(null)}
            className="corpse-loot-modal-wrapper"
          >
            <div className="corpse-items-list">
              {corpseDetails.loot_items.map((item: any) => (
                <div key={item.index} className={`corpse-item ${!item.can_loot ? 'locked' : ''}`}>
                  {/* Item Image */}
                  <div className="corpse-item-image">
                    {item.image_path ? (
                      <img
                        src={getAssetPath(item.image_path)}
                        alt={item.item_name}
                        className="item-img-thumb"
                        style={{ width: '40px', height: '40px', objectFit: 'contain', marginRight: '10px' }}
                        onError={(e) => {
                          (e.target as HTMLImageElement).style.display = 'none';
                        }}
                      />
                    ) : <span style={{ fontSize: '2rem', marginRight: '10px' }}>{item.emoji || '📦'}</span>}
                  </div>

                  <div className="corpse-item-info" style={{ flex: 1 }}>
                    <div className="corpse-item-name">
                      {getTranslatedText(item.item_name)}
                    </div>
                    {item.description && <div className="corpse-item-desc" style={{ fontSize: '0.75rem', color: '#a0aec0' }}>{getTranslatedText(item.description)}</div>}
                    <div className="corpse-item-qty">
                      {t('common.qty')}: {item.quantity_min}{item.quantity_min !== item.quantity_max ? `-${item.quantity_max}` : ''}
                    </div>
                    {item.required_tool && (
                      <div className={`corpse-item-tool ${item.has_tool ? 'has-tool' : 'needs-tool'}`}>
                        🔧 {getTranslatedText(item.required_tool_name)} {item.has_tool ? '✓' : '✗'}
                      </div>
                    )}
                  </div>

                  <GameTooltip content={!item.can_loot ? `Requires ${getTranslatedText(item.required_tool_name)}` : 'Loot this item'}>
                    <button
                      className="corpse-item-loot-btn"
                      onClick={() => onLootCorpseItem(expandedCorpse, item.index)}
                      disabled={!item.can_loot}
                    >
                      {item.can_loot ? `📦 ${t('common.loot')}` : '🔒'}
                    </button>
                  </GameTooltip>
                </div>
              ))}
            </div>
            <button
              className="loot-all-btn"
              onClick={() => onLootCorpseItem(expandedCorpse, null)}
            >
              📦 {t('common.lootAll')}
            </button>
          </GameModal>
        )
      }


      {
        (showCraftingMenu || showRepairMenu) && (
          <Workbench
            showCraftingMenu={showCraftingMenu}
            showRepairMenu={showRepairMenu}
            workbenchTab={workbenchTab}
            craftableItems={craftableItems}
            repairableItems={repairableItems}
            uncraftableItems={uncraftableItems}
            craftFilter={craftFilter}
            repairFilter={repairFilter}
            uncraftFilter={uncraftFilter}
            craftCategoryFilter={craftCategoryFilter}
            profile={profile}
            onCloseCrafting={onCloseCrafting}
            onSwitchTab={onSwitchWorkbenchTab}
            onSetCraftFilter={onSetCraftFilter}
            onSetRepairFilter={onSetRepairFilter}
            onSetUncraftFilter={onSetUncraftFilter}
            onSetCraftCategoryFilter={onSetCraftCategoryFilter}
            onCraft={onCraft}
            onRepair={onRepair}
            onUncraft={onUncraft}
          />
        )
      }

      {
        activeDialogNpc && activeNpcData && (
          <DialogModal
            npcId={activeDialogNpc}
            npcData={activeNpcData}
            onClose={() => setActiveDialogNpc(null)}
            onTrade={() => {
              setActiveDialogNpc(null);
              setShowTradeModal(true);
            }}
          />
        )
      }

      {
        showTradeModal && activeNpcData && (
          <TradeModal
            npcId={activeNpcData.id}
            onClose={() => setShowTradeModal(false)}
          />
        )
      }
      {/* Entity "Show All" Modal */}
      {
        entityModal && (
          <GameModal
            title={entityModal.title}
            onClose={() => setEntityModal(null)}
            className="entity-show-all-modal"
          >
            <div className="entity-modal-grid">
              {entityModal.type === 'enemies' && location.npcs
                .filter((npc: any) => npc.type === 'enemy')
                .map((enemy: any) => {
                  const id = `modal-enemy-${enemy.id}`;
                  return (
                    <div key={enemy.id} className="entity-card enemy-card grid-card"
                      onClick={(e) => handleDropdownClick(e, id)}
                    >
                      {enemy.id && (
                        <div className="entity-image padded-image">
                          <img
                            src={getAssetPath(enemy.image_path || `images/npcs/${(typeof enemy.name === 'string' ? enemy.name : enemy.name?.en || '').toLowerCase().replace(/ /g, '_')}.webp`)}
                            alt={getTranslatedText(enemy.name)}
                            onError={(e: any) => { e.currentTarget.style.display = 'none' }}
                          />
                        </div>
                      )}
                      <GameTooltip content={
                        <div>
                          <div className="tooltip-title">{getTranslatedText(enemy.name)}</div>
                          <div>{t('location.level')} {enemy.level}</div>
                        </div>
                      }>
                        <div className="grid-overlay"></div>
                      </GameTooltip>
                      {activeDropdown === id && (
                        <GameDropdown isOpen={true} onClose={() => setActiveDropdown(null)} width="160px">
                          <div className="game-dropdown-header">{getTranslatedText(enemy.name)}</div>
                          <GameButton variant="danger" size="sm"
                            onClick={() => { onInitiateCombat(enemy.id); setActiveDropdown(null); setEntityModal(null); }}
                            style={{ width: '100%', justifyContent: 'flex-start' }}
                          >
                            ⚔️ {t('common.fight')}
                          </GameButton>
                        </GameDropdown>
                      )}
                    </div>
                  );
                })}

              {entityModal.type === 'corpses' && (location.corpses || []).map((corpse: any) => (
                <div key={corpse.id} className="entity-card corpse-card grid-card"
                  onClick={(e) => handleDropdownClick(e, `modal-corpse-${corpse.id}`)}
                >
                  <div className="grid-corpse-content">
                    {corpse.image_path ? (
                      <img src={getAssetPath(corpse.image_path)} alt={getTranslatedText(corpse.name)} className="corpse-image"
                        onError={(e) => { (e.target as HTMLImageElement).style.display = 'none'; }} />
                    ) : <div style={{ fontSize: '2rem' }}>{corpse.emoji}</div>}
                    <div className="corpse-loot-count">{corpse.loot_count} items</div>
                  </div>
                  {activeDropdown === `modal-corpse-${corpse.id}` && (
                    <GameDropdown isOpen={true} onClose={() => setActiveDropdown(null)} width="160px">
                      <div className="game-dropdown-header">{getTranslatedText(corpse.name)}</div>
                      <GameButton variant="secondary" size="sm"
                        onClick={() => { playSfx('/audio/sfx/interact.wav'); onLootCorpse(String(corpse.id)); setActiveDropdown(null); setEntityModal(null); }}
                        disabled={corpse.loot_count === 0}
                        style={{ width: '100%', justifyContent: 'flex-start' }}
                      >
                        🔍 {t('common.examine')}
                      </GameButton>
                    </GameDropdown>
                  )}
                </div>
              ))}

              {entityModal.type === 'npcs' && location.npcs
                .filter((npc: any) => npc.type !== 'enemy')
                .map((npc: any, i: number) => (
                  <div key={i} className="entity-card npc-card grid-card"
                    onClick={() => { handleNpcClick(npc); setEntityModal(null); }}
                    style={{ cursor: 'pointer' }}
                  >
                    {npc.image_path ? (
                      <img src={getAssetPath(npc.image_path)} alt={getTranslatedText(npc.name)} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                    ) : <span className="entity-icon" style={{ fontSize: '2.5rem' }}>🧑</span>}
                    <div className="grid-overlay"></div>
                  </div>
                ))}

              {entityModal.type === 'items' && [...location.items]
                .sort((a: any, b: any) => (a.id || 0) - (b.id || 0))
                .map((item: any, i: number) => {
                  const itemId = `modal-item-${item.id}-${i}`;
                  return (
                    <div key={itemId} style={{ position: 'relative' }}>
                      <GameItemCard
                        item={item}
                        onClick={(e) => handleDropdownClick(e, itemId)}
                        isActive={activeDropdown === itemId}
                        showQuantity={true}
                        showDurability={true}
                        className="entity-card item-card"
                      />
                      {activeDropdown === itemId && (
                        <GameDropdown isOpen={true} onClose={() => setActiveDropdown(null)} width="200px">
                          <div className="game-dropdown-header">{getTranslatedText(item.name)} {item.quantity > 1 ? `(x${item.quantity})` : ''}</div>
                          {renderItemPickupOptions(item, true)}
                        </GameDropdown>
                      )}
                    </div>
                  );
                })}

              {entityModal.type === 'players' && (location.other_players || []).map((player: any, i: number) => {
                const playerId = `modal-player-${player.id}-${i}`;
                return (
                  <div key={i} className="entity-card player-card grid-card"
                    onClick={(e) => handleDropdownClick(e, playerId)}
                  >
                    <div className="grid-corpse-content">
                      <div style={{ fontSize: '2.5rem' }}>🧍</div>
                      <div className="grid-quantity" style={{ top: '2px', right: '2px', bottom: 'auto', background: 'rgba(49, 130, 206, 0.8)', borderColor: 'rgba(99, 179, 237, 0.4)' }}>
                        Lv.{player.level}
                      </div>
                    </div>
                    {activeDropdown === playerId && (
                      <GameDropdown isOpen={true} onClose={() => setActiveDropdown(null)} width="180px">
                        <div className="game-dropdown-header">{player.name || player.username}</div>
                        {player.can_pvp ? (
                          <GameButton variant="danger" size="sm"
                            onClick={() => { onInitiatePvP(player.id); setActiveDropdown(null); setEntityModal(null); }}
                            style={{ width: '100%', justifyContent: 'flex-start' }}
                          >
                            ⚔️ {t('game.attack')}
                          </GameButton>
                        ) : (
                          <div style={{ padding: '0.5rem', fontSize: '0.8rem', color: '#a0aec0' }}>PvP Unavailable</div>
                        )}
                      </GameDropdown>
                    )}
                  </div>
                );
              })}
            </div>
          </GameModal>
        )
      }
    </div >
  )
}

export default LocationView
