import { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
  ArrowLeft,
  Shield,
  Swords,
  BookOpen,
  Package,
  Edit2,
  Trash2,
  Plus,
  Minus,
  Sparkles,
  FlaskConical,
  User,
  Star,
  Coins,
  Moon,
  Download,
  Eye,
  Footprints,
} from 'lucide-react';
import {
  Button,
  Card,
  CardHeader,
  CardTitle,
  CardContent,
  Spinner,
} from '@/shared/components/ui';
import { api } from '@/shared/lib/api';
import { useAuthStore } from '@/features/auth';
import { HpControl } from './hp-control';
import { AddConditionModal } from './add-condition-modal';
import { AddItemModal } from './add-item-modal';
import { ItemDetailModal } from './item-detail-modal';
import { EditCharacterModal } from './edit-character-modal';
import { AddFeatModal } from './add-feat-modal';
import { FeatDetailModal } from './feat-detail-modal';
import { ActionsTab } from './actions-tab';
import { RestModal } from './rest-modal';
import { AlchemyTab } from './alchemy-tab';
import { useCharacterSocket } from '@/shared/hooks/use-character-socket';
import { downloadCharacterHTML } from '../utils/export-character-html';
import type { Character, CharacterItem, CharacterFeat, Campaign } from '@/shared/types';

type TabType = 'status' | 'skills' | 'inventory' | 'feats' | 'spells' | 'alchemy' | 'actions';

const TABS: { id: TabType; label: string; icon: React.ReactNode }[] = [
  { id: 'status', label: 'Status', icon: <User className="h-4 w-4" /> },
  { id: 'skills', label: 'Fertigkeiten', icon: <BookOpen className="h-4 w-4" /> },
  { id: 'inventory', label: 'Inventar', icon: <Package className="h-4 w-4" /> },
  { id: 'feats', label: 'Talente', icon: <Star className="h-4 w-4" /> },
  { id: 'spells', label: 'Zauber', icon: <Sparkles className="h-4 w-4" /> },
  { id: 'alchemy', label: 'Alchemie', icon: <FlaskConical className="h-4 w-4" /> },
  { id: 'actions', label: 'Aktionen', icon: <Swords className="h-4 w-4" /> },
];

const PROFICIENCY_NAMES: Record<string, string> = {
  UNTRAINED: 'Ungeübt',
  TRAINED: 'Geübt',
  EXPERT: 'Experte',
  MASTER: 'Meister',
  LEGENDARY: 'Legendär',
};

const PROFICIENCY_COLORS: Record<string, string> = {
  UNTRAINED: 'text-text-secondary',
  TRAINED: 'text-blue-500',
  EXPERT: 'text-purple-500',
  MASTER: 'text-orange-500',
  LEGENDARY: 'text-red-500',
};

// Proficiency bonus values (added to level for trained+)
const PROFICIENCY_BONUS: Record<string, number> = {
  UNTRAINED: 0,
  TRAINED: 2,
  EXPERT: 4,
  MASTER: 6,
  LEGENDARY: 8,
};

// Skill translations and linked abilities
const SKILL_DATA: Record<string, { german: string; ability: 'STR' | 'DEX' | 'CON' | 'INT' | 'WIS' | 'CHA' }> = {
  'Acrobatics': { german: 'Akrobatik', ability: 'DEX' },
  'Arcana': { german: 'Arkane Künste', ability: 'INT' },
  'Athletics': { german: 'Athletik', ability: 'STR' },
  'Crafting': { german: 'Handwerkskunst', ability: 'INT' },
  'Deception': { german: 'Täuschung', ability: 'CHA' },
  'Diplomacy': { german: 'Diplomatie', ability: 'CHA' },
  'Intimidation': { german: 'Einschüchtern', ability: 'CHA' },
  'Medicine': { german: 'Medizin', ability: 'WIS' },
  'Nature': { german: 'Naturkunde', ability: 'WIS' },
  'Occultism': { german: 'Okkultismus', ability: 'INT' },
  'Performance': { german: 'Darbietung', ability: 'CHA' },
  'Religion': { german: 'Religionskunde', ability: 'WIS' },
  'Society': { german: 'Gesellschaftskunde', ability: 'INT' },
  'Stealth': { german: 'Heimlichkeit', ability: 'DEX' },
  'Survival': { german: 'Überleben', ability: 'WIS' },
  'Thievery': { german: 'Diebeskunst', ability: 'DEX' },
};

// Short proficiency indicators
const PROFICIENCY_SHORT: Record<string, string> = {
  UNTRAINED: 'U',
  TRAINED: 'G',
  EXPERT: 'E',
  MASTER: 'M',
  LEGENDARY: 'L',
};

export function CharacterSheetPage() {
  const { id: campaignId, characterId } = useParams<{ id: string; characterId: string }>();
  const navigate = useNavigate();
  const { user } = useAuthStore();

  const [character, setCharacter] = useState<Character | null>(null);
  const [campaign, setCampaign] = useState<Campaign | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [activeTab, setActiveTab] = useState<TabType>('status');
  const [showAddCondition, setShowAddCondition] = useState(false);
  const [showAddItem, setShowAddItem] = useState(false);
  const [showAddFeat, setShowAddFeat] = useState(false);
  const [showEditCharacter, setShowEditCharacter] = useState(false);
  const [selectedItem, setSelectedItem] = useState<CharacterItem | null>(null);
  const [selectedFeat, setSelectedFeat] = useState<CharacterFeat | null>(null);
  const [editingCredits, setEditingCredits] = useState(false);
  const [creditsInput, setCreditsInput] = useState('');
  const [showRestModal, setShowRestModal] = useState(false);

  const isOwner = character?.ownerId === user?.id;
  const isGM = campaign?.gmId === user?.id;

  const fetchCharacter = async () => {
    if (!campaignId || !characterId) return;
    try {
      const [characterData, campaignData] = await Promise.all([
        api.getCharacter(campaignId, characterId),
        api.getCampaign(campaignId),
      ]);
      setCharacter(characterData);
      setCampaign(campaignData);
    } catch (error) {
      console.error('Failed to fetch character:', error);
      navigate(`/campaigns/${campaignId}`);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchCharacter();
  }, [campaignId, characterId]);

  // WebSocket connection for real-time sync
  useCharacterSocket({
    characterId: characterId || '',
    onHpUpdate: (data) => {
      setCharacter((prev) => prev ? { ...prev, hpCurrent: data.hpCurrent, hpTemp: data.hpTemp, hpMax: data.hpMax } : null);
    },
    onConditionsUpdate: (data) => {
      setCharacter((prev) => {
        if (!prev) return null;
        if (data.action === 'add' && data.condition) {
          return { ...prev, conditions: [...prev.conditions, data.condition] };
        }
        if (data.action === 'update' && data.condition) {
          return {
            ...prev,
            conditions: prev.conditions.map((c) => c.id === data.condition!.id ? data.condition! : c),
          };
        }
        if (data.action === 'remove' && data.conditionId) {
          return { ...prev, conditions: prev.conditions.filter((c) => c.id !== data.conditionId) };
        }
        return prev;
      });
    },
    onInventoryUpdate: (data) => {
      setCharacter((prev) => {
        if (!prev) return null;
        if (data.action === 'add' && data.item) {
          return { ...prev, items: [...prev.items, data.item] };
        }
        if (data.action === 'update' && data.item) {
          return {
            ...prev,
            items: prev.items.map((i) => i.id === data.item!.id ? data.item! : i),
          };
        }
        if (data.action === 'remove' && data.itemId) {
          return { ...prev, items: prev.items.filter((i) => i.id !== data.itemId) };
        }
        return prev;
      });
    },
    onEquipmentStatusUpdate: (data) => {
      setCharacter((prev) => {
        if (!prev || !data.item) return prev;
        return {
          ...prev,
          items: prev.items.map((i) => i.id === data.item.id ? data.item : i),
        };
      });
    },
    onMoneyUpdate: (data) => {
      setCharacter((prev) => prev ? { ...prev, credits: data.credits } : null);
    },
    onLevelUpdate: (data) => {
      setCharacter((prev) => prev ? { ...prev, level: data.level } : null);
    },
    onRestUpdate: (data) => {
      setCharacter((prev) => {
        if (!prev) return null;
        // Update HP
        let updated = { ...prev, hpCurrent: data.hpCurrent };
        // Remove conditions
        if (data.conditionsRemoved.length > 0) {
          updated.conditions = updated.conditions.filter(
            (c) => !data.conditionsRemoved.includes(c.name) && !data.conditionsRemoved.includes(c.nameGerman || '')
          );
        }
        // Update reduced conditions
        if (data.conditionsReduced.length > 0) {
          updated.conditions = updated.conditions.map((c) => {
            const reduced = data.conditionsReduced.find(
              (r) => r.name === c.name || r.name === c.nameGerman
            );
            if (reduced) {
              return { ...c, value: reduced.newValue };
            }
            return c;
          });
        }
        // Reset resources
        if (data.resourcesReset.length > 0) {
          updated.resources = updated.resources.map((r) => {
            if (data.resourcesReset.includes(r.name)) {
              return { ...r, current: r.max };
            }
            return r;
          });
        }
        // Reset alchemy
        if (data.alchemyReset) {
          // Always clear prepared items when alchemy is reset
          updated.preparedItems = [];
          // Update alchemy state if it exists
          if (updated.alchemyState) {
            updated.alchemyState = {
              ...updated.alchemyState,
              versatileVialsCurrent: updated.alchemyState.versatileVialsMax,
              advancedAlchemyBatch: 0,
            };
          }
        }
        return updated;
      });
    },
    onAlchemyVialsUpdate: (data) => {
      setCharacter((prev) => {
        if (!prev || !prev.alchemyState) return prev;
        return {
          ...prev,
          alchemyState: { ...prev.alchemyState, versatileVialsCurrent: data.versatileVialsCurrent },
        };
      });
    },
    onAlchemyFormulasUpdate: (data) => {
      setCharacter((prev) => {
        if (!prev) return prev;
        if (data.action === 'add' && data.formula) {
          return { ...prev, formulas: [...(prev.formulas || []), data.formula] };
        }
        if (data.action === 'remove' && data.formulaId) {
          return { ...prev, formulas: (prev.formulas || []).filter((f) => f.id !== data.formulaId) };
        }
        return prev;
      });
    },
    onAlchemyPreparedUpdate: (data) => {
      setCharacter((prev) => {
        if (!prev) return prev;
        if (data.action === 'prepare' && data.items) {
          return { ...prev, preparedItems: [...(prev.preparedItems || []), ...data.items] };
        }
        if (data.action === 'quick_alchemy' && data.item) {
          return { ...prev, preparedItems: [data.item, ...(prev.preparedItems || [])] };
        }
        if (data.action === 'update' && data.item) {
          return {
            ...prev,
            preparedItems: (prev.preparedItems || []).map((i) => i.id === data.item!.id ? data.item! : i),
          };
        }
        if (data.action === 'remove' && data.itemId) {
          return { ...prev, preparedItems: (prev.preparedItems || []).filter((i) => i.id !== data.itemId) };
        }
        return prev;
      });
    },
    onAlchemyStateUpdate: (data) => {
      setCharacter((prev) => prev ? { ...prev, alchemyState: data } : prev);
    },
    onFullUpdate: (updatedCharacter) => {
      setCharacter(updatedCharacter);
    },
  });

  const handleHpChange = async (newHp: number) => {
    if (!character || !campaignId) return;
    const clampedHp = Math.max(0, Math.min(character.hpMax, newHp));
    await api.updateCharacterHp(campaignId, character.id, clampedHp);
    setCharacter({ ...character, hpCurrent: clampedHp });
  };

  const handleDelete = async () => {
    if (!character || !campaignId || !confirm('Charakter wirklich löschen?')) return;
    try {
      await api.deleteCharacter(campaignId, character.id);
      navigate(`/campaigns/${campaignId}`);
    } catch (error) {
      console.error('Failed to delete character:', error);
    }
  };

  const handleRemoveCondition = async (conditionId: string) => {
    if (!character || !campaignId) return;
    try {
      await api.removeCharacterCondition(campaignId, character.id, conditionId);
      setCharacter({
        ...character,
        conditions: character.conditions.filter((c) => c.id !== conditionId),
      });
    } catch (error) {
      console.error('Failed to remove condition:', error);
    }
  };

  const handleAddCondition = async (condition: { name: string; nameGerman: string; value?: number }) => {
    if (!character || !campaignId) return;
    const newCondition = await api.addCharacterCondition(campaignId, character.id, condition);
    setCharacter({
      ...character,
      conditions: [...character.conditions, newCondition],
    });
  };

  const handleAddItem = async (item: {
    equipmentId: string;
    name: string;
    nameGerman?: string;
    quantity: number;
    bulk: number;
    equipped: boolean;
  }) => {
    if (!character || !campaignId) return;
    const newItem = await api.addCharacterItem(campaignId, character.id, item);
    setCharacter({
      ...character,
      items: [...character.items, newItem],
    });
  };

  const handleAddFeat = async (feat: {
    featId?: string;
    name: string;
    nameGerman?: string;
    level: number;
    source: 'CLASS' | 'ANCESTRY' | 'GENERAL' | 'SKILL' | 'BONUS' | 'ARCHETYPE';
  }) => {
    if (!character || !campaignId) return;
    const newFeat = await api.addCharacterFeat(campaignId, character.id, feat);
    setCharacter({
      ...character,
      feats: [...character.feats, newFeat],
    });
  };

  const handleRemoveFeat = async (featId: string) => {
    if (!character || !campaignId) return;
    try {
      await api.removeCharacterFeat(campaignId, character.id, featId);
      setCharacter({
        ...character,
        feats: character.feats.filter((f) => f.id !== featId),
      });
    } catch (error) {
      console.error('Failed to remove feat:', error);
    }
  };

  const handleRemoveItem = async (itemId: string) => {
    if (!character || !campaignId) return;
    try {
      await api.removeCharacterItem(campaignId, character.id, itemId);
      setCharacter({
        ...character,
        items: character.items.filter((i) => i.id !== itemId),
      });
    } catch (error) {
      console.error('Failed to remove item:', error);
    }
  };

  const handleToggleEquipped = async (itemId: string, equipped: boolean) => {
    if (!character || !campaignId) return;
    try {
      const updatedItem = await api.updateCharacterItem(campaignId, character.id, itemId, { equipped });
      const updatedItems = character.items.map((i) =>
        i.id === itemId ? updatedItem : i
      );
      setCharacter({
        ...character,
        items: updatedItems,
      });
      // Update selected item if it's the one being modified
      if (selectedItem?.id === itemId) {
        setSelectedItem(updatedItem);
      }
    } catch (error) {
      console.error('Failed to toggle equipped:', error);
    }
  };

  const handleUpdateItemQuantity = async (itemId: string, quantity: number) => {
    if (!character || !campaignId) return;
    try {
      const updatedItem = await api.updateCharacterItem(campaignId, character.id, itemId, { quantity });
      const updatedItems = character.items.map((i) =>
        i.id === itemId ? updatedItem : i
      );
      setCharacter({
        ...character,
        items: updatedItems,
      });
      // Update selected item if it's the one being modified
      if (selectedItem?.id === itemId) {
        setSelectedItem(updatedItem);
      }
    } catch (error) {
      console.error('Failed to update item quantity:', error);
    }
  };

  const handleUpdateCredits = async (newCredits: number) => {
    if (!character || !campaignId) return;
    try {
      await api.updateCharacterCredits(campaignId, character.id, newCredits);
      setCharacter({ ...character, credits: newCredits });
      setEditingCredits(false);
    } catch (error) {
      console.error('Failed to update credits:', error);
    }
  };

  const handleUpdateItem = async (itemId: string, data: {
    alias?: string;
    customName?: string;
    customDamage?: string;
    customDamageType?: string;
    customTraits?: string[];
    customRange?: string;
    customHands?: string;
  }) => {
    if (!character || !campaignId) return;
    try {
      const updatedItem = await api.updateCharacterItem(campaignId, character.id, itemId, data);
      const updatedItems = character.items.map((i) =>
        i.id === itemId ? updatedItem : i
      );
      setCharacter({
        ...character,
        items: updatedItems,
      });
      // Update selected item if it's the one being modified
      if (selectedItem?.id === itemId) {
        setSelectedItem(updatedItem);
      }
    } catch (error) {
      console.error('Failed to update item:', error);
    }
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-12">
        <Spinner size="lg" />
      </div>
    );
  }

  if (!character) {
    return (
      <div className="text-center py-12">
        <p className="text-text-secondary">Charakter nicht gefunden</p>
      </div>
    );
  }

  // Tab Content Renderers
  const renderStatusTab = () => {
    // AC Berechnung
    const calculateAC = () => {
      const pb = character.pathbuilderData as {
        build?: {
          abilities?: { dex: number };
          proficiencies?: Record<string, number>;
        };
      } | null;

      // Finde angelegte Rüstung und Schild
      const equippedArmor = character.items.find(
        i => i.equipped && i.equipment?.itemCategory === 'Armor'
      );
      const equippedShield = character.items.find(
        i => i.equipped && i.equipment?.itemCategory === 'Shields'
      );

      // Base
      let ac = 10;

      // DEX Modifier (ggf. durch Rüstung begrenzt)
      const dexScore = pb?.build?.abilities?.dex ?? character.abilities.find(a => a.ability === 'DEX')?.score ?? 10;
      const dexMod = Math.floor((dexScore - 10) / 2);
      const dexCap = equippedArmor?.equipment?.dexCap;
      const effectiveDex = dexCap !== null && dexCap !== undefined ? Math.min(dexMod, dexCap) : dexMod;
      ac += effectiveDex;

      // Proficiency (basierend auf Rüstungstyp)
      const proficiencies = pb?.build?.proficiencies;
      let profBonus = 0;
      let profName = 'Ohne Rüstung';

      if (proficiencies) {
        const armorCategory = equippedArmor?.equipment?.armorCategory?.toLowerCase();
        if (!equippedArmor) {
          profBonus = proficiencies.unarmored || 0;
          profName = 'Ohne Rüstung';
        } else if (armorCategory?.includes('light')) {
          profBonus = proficiencies.light || 0;
          profName = 'Leichte Rüstung';
        } else if (armorCategory?.includes('medium')) {
          profBonus = proficiencies.medium || 0;
          profName = 'Mittlere Rüstung';
        } else if (armorCategory?.includes('heavy')) {
          profBonus = proficiencies.heavy || 0;
          profName = 'Schwere Rüstung';
        } else {
          profBonus = proficiencies.unarmored || 0;
          profName = 'Ohne Rüstung';
        }
      }

      // Proficiency rank name
      let profRank: string;
      let hasProficiency = true;
      if (profBonus === 0) {
        profRank = 'Ungeübt';
        hasProficiency = false;
      } else if (profBonus === 2) {
        profRank = 'Geübt';
      } else if (profBonus === 4) {
        profRank = 'Experte';
      } else if (profBonus === 6) {
        profRank = 'Meister';
      } else if (profBonus === 8) {
        profRank = 'Legendär';
      } else {
        profRank = `+${profBonus}`;
      }

      const levelBonus = profBonus > 0 ? character.level : 0;
      ac += profBonus + levelBonus;

      // Rüstungsbonus
      const armorBonus = equippedArmor?.equipment?.ac || 0;
      ac += armorBonus;

      // Schildbonus (wenn angelegt)
      const shieldBonus = equippedShield?.equipment?.ac || 0;

      return {
        total: ac,
        withShield: ac + shieldBonus,
        shieldBonus,
        armorName: equippedArmor?.nameGerman || equippedArmor?.name,
        shieldName: equippedShield?.nameGerman || equippedShield?.name,
        profName,
        profRank,
        hasProficiency,
      };
    };

    const acData = calculateAC();

    // Get speed from pathbuilder data
    const pbSpeed = character.pathbuilderData as {
      build?: { attributes?: { speed?: number } };
    } | undefined;
    const speed = pbSpeed?.build?.attributes?.speed || 25;

    return (
    <div className="space-y-4">
      {/* HP Row - Full width on mobile */}
      <HpControl
        hpCurrent={character.hpCurrent}
        hpMax={character.hpMax}
        hpTemp={character.hpTemp}
        onHpChange={handleHpChange}
      />

      {/* AC & Speed Row */}
      <div className="grid grid-cols-2 gap-3">
        {/* AC Card */}
        <Card>
          <CardContent className="p-4 flex flex-col items-center justify-center">
            <div className="flex items-center gap-2 mb-2">
              <Shield className={`h-4 w-4 ${acData.hasProficiency ? 'text-blue-400' : 'text-red-400'}`} />
              <span className={`text-xs font-medium ${acData.hasProficiency ? 'text-blue-400' : 'text-red-400'}`}>Rüstungsklasse</span>
            </div>
            <div className="flex items-baseline gap-1">
              <p className={`text-3xl font-bold ${acData.hasProficiency ? 'text-blue-400' : 'text-red-400'}`}>{acData.total}</p>
              {acData.shieldBonus > 0 && (
                <span className="text-sm font-semibold text-cyan-400">+{acData.shieldBonus}</span>
              )}
            </div>
            <p className={`text-xs mt-1 ${acData.hasProficiency ? 'text-text-secondary' : 'text-red-400'}`}>
              {acData.profRank}
            </p>
          </CardContent>
        </Card>

        {/* Speed Card */}
        <Card>
          <CardContent className="p-4 flex flex-col items-center justify-center">
            <div className="flex items-center gap-2 mb-2">
              <Footprints className="h-4 w-4 text-emerald-400" />
              <span className="text-xs font-medium text-emerald-400">Geschwindigkeit</span>
            </div>
            <p className="text-3xl font-bold text-emerald-400">{speed}</p>
            <p className="text-xs text-text-secondary mt-1">ft / Aktion</p>
          </CardContent>
        </Card>
      </div>

      {/* Abilities */}
      <div className="grid grid-cols-3 sm:grid-cols-6 gap-2">
        {character.abilities.map((ability) => {
          const mod = Math.floor((ability.score - 10) / 2);
          const isPositive = mod >= 0;
          return (
            <div
              key={ability.ability}
              className="relative text-center p-3 rounded-xl bg-bg-secondary border border-border hover:border-primary-500/50 transition-colors"
            >
              {/* Ability Name Badge */}
              <div className="absolute -top-2 left-1/2 -translate-x-1/2 px-2 py-0.5 rounded bg-bg-tertiary border border-border text-[10px] font-semibold text-text-secondary uppercase tracking-wider">
                {ability.ability}
              </div>
              {/* Modifier */}
              <p className={`text-2xl font-bold mt-2 ${isPositive ? 'text-text-primary' : 'text-red-400'}`}>
                {isPositive ? `+${mod}` : mod}
              </p>
              {/* Score */}
              <p className="text-xs text-text-muted mt-1">{ability.score}</p>
            </div>
          );
        })}
      </div>

      {/* Saving Throws & Perception */}
      {(() => {
        const getAbilityMod = (abilityType: 'STR' | 'DEX' | 'CON' | 'INT' | 'WIS' | 'CHA') => {
          const ability = character.abilities.find(a => a.ability === abilityType);
          return ability ? Math.floor((ability.score - 10) / 2) : 0;
        };

        const level = character.level;

        // Get proficiency values from Pathbuilder data
        const pb = character.pathbuilderData as {
          build?: {
            proficiencies?: Record<string, number>;
          };
        } | undefined;
        const proficiencies = pb?.build?.proficiencies || {};

        // Calculate save totals using actual proficiency data
        // Proficiency values: 0 = untrained, 2 = trained, 4 = expert, 6 = master, 8 = legendary
        const getSaveTotal = (saveName: string, abilityMod: number) => {
          const prof = proficiencies[saveName] || 2; // Default to trained if not found
          const levelBonus = prof > 0 ? level : 0;
          return abilityMod + levelBonus + prof;
        };

        const getSaveProfName = (saveName: string) => {
          const prof = proficiencies[saveName] || 2;
          if (prof === 0) return 'Ungeübt';
          if (prof === 2) return 'Geübt';
          if (prof === 4) return 'Experte';
          if (prof === 6) return 'Meister';
          if (prof === 8) return 'Legendär';
          return 'Geübt';
        };

        const saves = [
          {
            name: 'Zähigkeit',
            key: 'fortitude',
            ability: 'CON' as const,
            color: 'text-red-400',
            bgColor: 'bg-red-500/20',
          },
          {
            name: 'Reflex',
            key: 'reflex',
            ability: 'DEX' as const,
            color: 'text-green-400',
            bgColor: 'bg-green-500/20',
          },
          {
            name: 'Willen',
            key: 'will',
            ability: 'WIS' as const,
            color: 'text-blue-400',
            bgColor: 'bg-blue-500/20',
          },
        ];

        // Calculate Perception
        // Perception = WIS mod + proficiency bonus + level (if trained+)
        const perceptionSkill = character.skills.find(s => s.skillName === 'Perception');
        const perceptionProf = perceptionSkill
          ? PROFICIENCY_BONUS[perceptionSkill.proficiency] || 0
          : (proficiencies['perception'] || 2);
        const perceptionProfName = perceptionSkill
          ? PROFICIENCY_NAMES[perceptionSkill.proficiency] || 'Geübt'
          : getSaveProfName('perception');
        const wisdomMod = getAbilityMod('WIS');
        const perceptionLevelBonus = perceptionProf > 0 ? level : 0;
        const perceptionTotal = wisdomMod + perceptionLevelBonus + perceptionProf;
        const perceptionString = perceptionTotal >= 0 ? `+${perceptionTotal}` : `${perceptionTotal}`;

        return (
          <div className="grid grid-cols-1 sm:grid-cols-4 gap-3">
            {/* Perception */}
            <div className="sm:col-span-1">
              <Card className="h-full">
                <CardContent className="p-4 flex flex-col items-center justify-center h-full">
                  <div className="flex items-center gap-2 mb-2">
                    <Eye className="h-4 w-4 text-amber-400" />
                    <span className="text-xs font-medium text-amber-400">Wahrnehmung</span>
                  </div>
                  <p className="text-3xl font-bold text-amber-400">{perceptionString}</p>
                  <p className="text-xs text-text-secondary mt-1">{perceptionProfName}</p>
                </CardContent>
              </Card>
            </div>

            {/* Saving Throws */}
            <div className="sm:col-span-3">
              <Card className="h-full">
                <CardHeader className="pb-2">
                  <CardTitle className="flex items-center gap-2">
                    <Shield className="h-5 w-5" />
                    Rettungswürfe
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="grid grid-cols-3 gap-3">
                    {saves.map((save) => {
                      const abilityMod = getAbilityMod(save.ability);
                      const total = getSaveTotal(save.key, abilityMod);
                      const bonusString = total >= 0 ? `+${total}` : `${total}`;
                      const profName = getSaveProfName(save.key);

                      return (
                        <div
                          key={save.name}
                          className={`text-center p-3 rounded-lg ${save.bgColor}`}
                        >
                          <p className={`text-xs font-medium mb-1 ${save.color}`}>
                            {save.name}
                          </p>
                          <p className={`text-2xl font-bold ${save.color}`}>
                            {bonusString}
                          </p>
                          <p className="text-xs text-text-secondary">
                            {profName}
                          </p>
                        </div>
                      );
                    })}
                  </div>
                </CardContent>
              </Card>
            </div>
          </div>
        );
      })()}

      {/* Conditions - Compact inline display */}
      <div className="flex items-center gap-2 flex-wrap">
        <span className="text-xs text-text-secondary">Zustände:</span>
        {character.conditions.length === 0 ? (
          <span className="text-xs text-text-muted">Keine</span>
        ) : (
          character.conditions.map((condition) => (
            <div
              key={condition.id}
              className="flex items-center gap-1.5 px-2 py-1 rounded-full bg-red-500/20 text-red-400 text-xs"
            >
              <span className="font-medium">
                {condition.nameGerman || condition.name}
                {condition.value && ` ${condition.value}`}
              </span>
              <button
                onClick={() => handleRemoveCondition(condition.id)}
                className="hover:text-red-300"
              >
                <Trash2 className="h-3 w-3" />
              </button>
            </div>
          ))
        )}
        <Button
          size="sm"
          variant="ghost"
          className="h-6 w-6 p-0 text-text-secondary hover:text-text-primary"
          onClick={() => setShowAddCondition(true)}
        >
          <Plus className="h-3.5 w-3.5" />
        </Button>
      </div>

      {/* Rest Button */}
      <Card className="hover:border-indigo-500/50 transition-colors cursor-pointer" onClick={() => setShowRestModal(true)}>
        <CardContent className="p-4 flex items-center justify-center gap-3">
          <div className="w-10 h-10 rounded-full bg-indigo-500/20 flex items-center justify-center">
            <Moon className="h-5 w-5 text-indigo-400" />
          </div>
          <div className="text-left">
            <p className="font-semibold text-indigo-400">Rasten</p>
            <p className="text-xs text-text-secondary">8 Stunden Ruhe + Tägliche Vorbereitung</p>
          </div>
        </CardContent>
      </Card>
    </div>
  );
  };

  const renderSkillsTab = () => {
    // Filter out saves and perception (these are displayed separately)
    const EXCLUDED_SKILLS = ['Fortitude', 'Reflex', 'Will', 'Perception'];
    const filteredSkills = character.skills.filter(
      (skill) => !EXCLUDED_SKILLS.includes(skill.skillName)
    );

    return (
    <div className="space-y-4">
      {/* Skills Grid */}
      <div className="grid gap-1 sm:grid-cols-2">
        {filteredSkills.map((skill) => {
          // Get skill data (German name + linked ability)
          const skillData = SKILL_DATA[skill.skillName];
          const germanName = skillData?.german || skill.skillName;
          const linkedAbility = skillData?.ability || 'INT';

          // Get ability modifier
          const abilityScore = character.abilities.find(a => a.ability === linkedAbility)?.score || 10;
          const abilityMod = Math.floor((abilityScore - 10) / 2);

          // Calculate total bonus
          const profBonus = PROFICIENCY_BONUS[skill.proficiency] || 0;
          const levelBonus = skill.proficiency !== 'UNTRAINED' ? character.level : 0;
          const totalBonus = abilityMod + levelBonus + profBonus;
          const bonusString = totalBonus >= 0 ? `+${totalBonus}` : `${totalBonus}`;

          // Check if it's a Lore skill
          const isLore = skill.skillName.toLowerCase().includes('lore');
          const displayName = isLore ? skill.skillName.replace(' Lore', '') + ' (Wissen)' : germanName;

          return (
            <div
              key={skill.skillName}
              className="flex items-center justify-between py-2.5 px-3 rounded-lg bg-bg-secondary hover:bg-bg-tertiary"
            >
              <div className="flex items-center gap-2 min-w-0 flex-1">
                <span
                  className={`text-xs font-bold w-5 h-5 rounded flex items-center justify-center flex-shrink-0 ${PROFICIENCY_COLORS[skill.proficiency]} bg-current/10`}
                  title={PROFICIENCY_NAMES[skill.proficiency]}
                >
                  {PROFICIENCY_SHORT[skill.proficiency]}
                </span>
                <span className="text-text-primary text-sm truncate">{displayName}</span>
              </div>
              <span className={`font-bold text-lg tabular-nums ${totalBonus >= 0 ? 'text-text-primary' : 'text-red-400'}`}>
                {bonusString}
              </span>
            </div>
          );
        })}
      </div>

      {/* Legend */}
      <div className="flex flex-wrap gap-3 text-xs text-text-secondary pt-2 border-t border-border">
        <span className="flex items-center gap-1">
          <span className="text-text-secondary font-bold">U</span> Ungeübt
        </span>
        <span className="flex items-center gap-1">
          <span className="text-blue-500 font-bold">G</span> Geübt
        </span>
        <span className="flex items-center gap-1">
          <span className="text-purple-500 font-bold">E</span> Experte
        </span>
        <span className="flex items-center gap-1">
          <span className="text-orange-500 font-bold">M</span> Meister
        </span>
        <span className="flex items-center gap-1">
          <span className="text-red-500 font-bold">L</span> Legendär
        </span>
      </div>
    </div>
  );
  };

  const renderInventoryTab = () => {
    // Filter out coin/money items (tracked separately as credits)
    const isCoinItem = (name: string) => {
      const lowerName = name.toLowerCase();
      return lowerName.includes('coin') || lowerName.includes('money') || lowerName.includes('purse') || lowerName.includes('gold') || lowerName.includes('silver') || lowerName.includes('copper');
    };

    const filteredItems = character.items.filter((i) => !isCoinItem(i.name));

    // Calculate total bulk (parse Decimal from Prisma)
    const totalBulk = filteredItems.reduce((sum, item) => {
      const itemBulk = parseFloat(String(item.bulk)) || 0;
      return sum + itemBulk * item.quantity;
    }, 0);

    // STR modifier for bulk limit
    const strScore = character.abilities.find((a) => a.ability === 'STR')?.score || 10;
    const strMod = Math.floor((strScore - 10) / 2);
    const bulkLimit = 5 + strMod;
    const encumberedLimit = bulkLimit + 5;

    const isEncumbered = totalBulk > bulkLimit;
    const isOverburdened = totalBulk > encumberedLimit;

    // Kategorisiere Items basierend auf Equipment-Daten (ohne Münzen)
    // Echte Waffen haben einen Schadenswert - Items ohne Schaden sind Munition/Zubehör
    const isRealWeapon = (item: CharacterItem) => {
      return item.equipment?.itemCategory === 'Weapons' && !!item.equipment?.damage;
    };

    const weaponItems = filteredItems.filter(isRealWeapon);
    const armorItems = filteredItems.filter(
      (i) => i.equipment?.itemCategory === 'Armor'
    );
    const shieldItems = filteredItems.filter(
      (i) => i.equipment?.itemCategory === 'Shields'
    );
    const otherItems = filteredItems.filter(
      (i) => !isRealWeapon(i) && i.equipment?.itemCategory !== 'Armor' && i.equipment?.itemCategory !== 'Shields'
    );

    // Berechne Waffenboni basierend auf Pathbuilder-Daten
    const calculateWeaponBonuses = (eq: CharacterItem['equipment']) => {
      if (!eq) return null;

      const pb = character.pathbuilderData as {
        build?: {
          abilities?: { str: number; dex: number };
          proficiencies?: Record<string, number>;
        };
      } | null;

      if (!pb?.build) return null;

      const abilities = pb.build.abilities;
      const proficiencies = pb.build.proficiencies;
      if (!abilities || !proficiencies) return null;

      // Ability Modifiers
      const strMod = Math.floor((abilities.str - 10) / 2);
      const dexMod = Math.floor((abilities.dex - 10) / 2);

      // Bestimme Proficiency basierend auf Waffenkategorie
      const weaponCat = eq.weaponCategory?.toLowerCase() || 'simple';
      let profBonus = 0;
      if (weaponCat.includes('simple')) profBonus = proficiencies.simple || 0;
      else if (weaponCat.includes('martial')) profBonus = proficiencies.martial || 0;
      else if (weaponCat.includes('advanced')) profBonus = proficiencies.advanced || 0;
      else if (weaponCat.includes('unarmed')) profBonus = proficiencies.unarmed || 0;

      // Level-Bonus nur wenn geübt (profBonus > 0)
      const levelBonus = profBonus > 0 ? character.level : 0;

      // Bestimme Ability für Angriff (Finesse = DEX oder STR, Ranged = DEX)
      const isFinesse = eq.traits?.some(t => t.toLowerCase() === 'finesse');
      const isRanged = !!eq.range;
      const attackAbilityMod = (isRanged || isFinesse) ? Math.max(strMod, dexMod) : strMod;

      // Schadensbonus (meist STR, Propulsive = halber STR, Ranged ohne Thrown = 0)
      const isPropulsive = eq.traits?.some(t => t.toLowerCase() === 'propulsive');
      const isThrown = eq.traits?.some(t => t.toLowerCase() === 'thrown');
      let damageAbilityMod = strMod;
      if (isRanged && !isThrown) {
        damageAbilityMod = isPropulsive ? Math.floor(strMod / 2) : 0;
      }

      const attackBonus = attackAbilityMod + profBonus + levelBonus;
      const damageBonus = damageAbilityMod;

      return { attackBonus, damageBonus };
    };

    // Render Waffen-Karte mit Stats
    const renderWeaponCard = (item: typeof character.items[0]) => {
      const eq = item.equipment;
      const bonuses = calculateWeaponBonuses(eq);
      return (
        <div
          key={item.id}
          className={`p-3 rounded-lg bg-bg-secondary cursor-pointer hover:bg-bg-tertiary transition-colors ${
            item.equipped ? 'border border-red-500/30' : ''
          }`}
          onClick={() => setSelectedItem(item)}
        >
          <div className="flex items-start justify-between gap-2 mb-2">
            <div className="min-w-0 flex-1">
              <p className="font-medium text-text-primary truncate">
                {item.nameGerman || item.name}
                {item.quantity > 1 && <span className="text-text-secondary"> x{item.quantity}</span>}
              </p>
            </div>
            {item.equipped && (
              <span className="text-xs px-1.5 py-0.5 rounded bg-red-500/20 text-red-400">Angelegt</span>
            )}
          </div>
          {/* Waffen-Stats */}
          <div className="flex flex-wrap gap-1.5 mb-2">
            {bonuses && (
              <span className="text-xs px-2 py-0.5 rounded bg-green-500/20 text-green-400 font-medium">
                +{bonuses.attackBonus} Angriff
              </span>
            )}
            {eq?.damage && (
              <span className="text-xs px-2 py-0.5 rounded bg-red-500/20 text-red-400 font-medium">
                {eq.damage}{bonuses && bonuses.damageBonus !== 0 ? (bonuses.damageBonus > 0 ? `+${bonuses.damageBonus}` : bonuses.damageBonus) : ''} {eq.damageType}
              </span>
            )}
            {eq?.range && (
              <span className="text-xs px-2 py-0.5 rounded bg-blue-500/20 text-blue-400">
                {eq.range}
              </span>
            )}
            {eq?.hands && (
              <span className="text-xs px-2 py-0.5 rounded bg-bg-tertiary text-text-secondary">
                {eq.hands}H
              </span>
            )}
          </div>
          {/* Traits */}
          {eq?.traits && eq.traits.length > 0 && (
            <div className="flex flex-wrap gap-1">
              {eq.traits.slice(0, 3).map((trait) => (
                <span key={trait} className="text-xs px-1.5 py-0.5 rounded bg-bg-tertiary text-text-muted">
                  {trait}
                </span>
              ))}
              {eq.traits.length > 3 && (
                <span className="text-xs text-text-muted">+{eq.traits.length - 3}</span>
              )}
            </div>
          )}
          {/* Bulk only - no quantity controls for weapons */}
          <div className="mt-2 pt-2 border-t border-border">
            <span className="text-xs text-text-secondary">
              {parseFloat(String(item.bulk)) > 0 ? (parseFloat(String(item.bulk)) < 1 ? 'L' : `${item.bulk} Bulk`) : '—'}
            </span>
          </div>
        </div>
      );
    };

    // Render Rüstungs-Karte mit Stats
    const renderArmorCard = (item: typeof character.items[0]) => {
      const eq = item.equipment;
      return (
        <div
          key={item.id}
          className={`p-3 rounded-lg bg-bg-secondary cursor-pointer hover:bg-bg-tertiary transition-colors ${
            item.equipped ? 'border border-blue-500/30' : ''
          }`}
          onClick={() => setSelectedItem(item)}
        >
          <div className="flex items-start justify-between gap-2 mb-2">
            <div className="min-w-0 flex-1">
              <p className="font-medium text-text-primary truncate">
                {item.nameGerman || item.name}
              </p>
            </div>
            {item.equipped && (
              <span className="text-xs px-1.5 py-0.5 rounded bg-blue-500/20 text-blue-400">Angelegt</span>
            )}
          </div>
          {/* Rüstungs-Stats */}
          <div className="flex flex-wrap gap-1.5 mb-2">
            {eq?.ac !== undefined && eq?.ac !== null && (
              <span className="text-xs px-2 py-0.5 rounded bg-blue-500/20 text-blue-400 font-medium">
                RK +{eq.ac}
              </span>
            )}
            {eq?.dexCap !== undefined && eq?.dexCap !== null && (
              <span className="text-xs px-2 py-0.5 rounded bg-yellow-500/20 text-yellow-400">
                GES +{eq.dexCap}
              </span>
            )}
            {eq?.checkPenalty !== undefined && eq?.checkPenalty !== null && eq.checkPenalty !== 0 && (
              <span className="text-xs px-2 py-0.5 rounded bg-red-500/20 text-red-400">
                Malus {eq.checkPenalty}
              </span>
            )}
            {eq?.speedPenalty !== undefined && eq?.speedPenalty !== null && eq.speedPenalty !== 0 && (
              <span className="text-xs px-2 py-0.5 rounded bg-orange-500/20 text-orange-400">
                -{eq.speedPenalty} ft
              </span>
            )}
          </div>
          {/* Bulk only - no quantity controls for armor */}
          <div className="mt-2 pt-2 border-t border-border">
            <span className="text-xs text-text-secondary">
              {parseFloat(String(item.bulk)) > 0 ? (parseFloat(String(item.bulk)) < 1 ? 'L' : `${item.bulk} Bulk`) : '—'}
            </span>
          </div>
        </div>
      );
    };

    // Render Schild-Karte mit Stats
    const renderShieldCard = (item: typeof character.items[0]) => {
      const eq = item.equipment;
      return (
        <div
          key={item.id}
          className={`p-3 rounded-lg bg-bg-secondary cursor-pointer hover:bg-bg-tertiary transition-colors ${
            item.equipped ? 'border border-cyan-500/30' : ''
          }`}
          onClick={() => setSelectedItem(item)}
        >
          <div className="flex items-start justify-between gap-2 mb-2">
            <div className="min-w-0 flex-1">
              <p className="font-medium text-text-primary truncate">
                {item.nameGerman || item.name}
              </p>
            </div>
            {item.equipped && (
              <span className="text-xs px-1.5 py-0.5 rounded bg-cyan-500/20 text-cyan-400">Angelegt</span>
            )}
          </div>
          {/* Schild-Stats */}
          <div className="flex flex-wrap gap-1.5 mb-2">
            {eq?.ac !== undefined && eq?.ac !== null && (
              <span className="text-xs px-2 py-0.5 rounded bg-blue-500/20 text-blue-400 font-medium">
                RK +{eq.ac}
              </span>
            )}
            {eq?.shieldHardness !== undefined && eq?.shieldHardness !== null && (
              <span className="text-xs px-2 py-0.5 rounded bg-gray-500/20 text-gray-400">
                Härte {eq.shieldHardness}
              </span>
            )}
            {eq?.shieldHp !== undefined && eq?.shieldHp !== null && (
              <span className="text-xs px-2 py-0.5 rounded bg-green-500/20 text-green-400">
                HP {eq.shieldHp}
              </span>
            )}
          </div>
          {/* Bulk only - no quantity controls for shields */}
          <div className="mt-2 pt-2 border-t border-border">
            <span className="text-xs text-text-secondary">
              {parseFloat(String(item.bulk)) > 0 ? (parseFloat(String(item.bulk)) < 1 ? 'L' : `${item.bulk} Bulk`) : '—'}
            </span>
          </div>
        </div>
      );
    };

    // Render Standard-Item-Karte
    const renderItemCard = (item: typeof character.items[0]) => {
      const isWornItem = item.equipment?.itemCategory === 'Worn Items';
      return (
        <div
          key={item.id}
          className={`p-3 rounded-lg bg-bg-secondary cursor-pointer hover:bg-bg-tertiary transition-colors ${
            item.equipped ? 'border border-primary-500/30' : ''
          }`}
          onClick={() => setSelectedItem(item)}
        >
          <div className="flex items-start justify-between gap-2">
            <div className="min-w-0 flex-1">
              <div className="flex items-center gap-2">
                <p className="font-medium text-text-primary truncate">
                  {item.nameGerman || item.name}
                  {item.quantity > 1 && <span className="text-text-secondary"> x{item.quantity}</span>}
                </p>
                {item.equipped && isWornItem && (
                  <span className="text-xs px-1.5 py-0.5 rounded bg-primary-500/20 text-primary-400 flex-shrink-0">Angelegt</span>
                )}
              </div>
              <p className="text-xs text-text-secondary">
                {item.bulk > 0 ? (item.bulk < 1 ? 'L' : `${item.bulk} Bulk`) : '—'}
              </p>
            </div>
            {!isWornItem && (
              <div className="flex items-center gap-1 flex-shrink-0" onClick={(e) => e.stopPropagation()}>
                <Button size="icon" variant="ghost" className="h-6 w-6" onClick={() => handleUpdateItemQuantity(item.id, Math.max(1, item.quantity - 1))} disabled={item.quantity <= 1}>
                  <Minus className="h-3 w-3" />
                </Button>
                <span className="text-sm font-medium min-w-[20px] text-center">{item.quantity}</span>
                <Button size="icon" variant="ghost" className="h-6 w-6" onClick={() => handleUpdateItemQuantity(item.id, item.quantity + 1)}>
                  <Plus className="h-3 w-3" />
                </Button>
              </div>
            )}
          </div>
        </div>
      );
    };

    return (
      <div className="space-y-4">
        {/* Credits & Bulk Row */}
        <div className="grid grid-cols-2 gap-2">
          {/* Credits */}
          <div className="p-3 rounded-lg bg-bg-secondary">
            <div className="flex items-center gap-2 mb-1">
              <Coins className="h-4 w-4 text-yellow-400" />
              <span className="text-xs text-text-secondary">Credits</span>
            </div>
            {editingCredits ? (
              <input
                type="number"
                value={creditsInput}
                onChange={(e) => setCreditsInput(e.target.value)}
                className="w-full bg-bg-tertiary border border-primary-500 rounded px-2 py-1 text-xl font-bold text-yellow-400"
                autoFocus
                onBlur={() => handleUpdateCredits(parseInt(creditsInput) || 0)}
                onKeyDown={(e) => {
                  if (e.key === 'Enter') {
                    handleUpdateCredits(parseInt(creditsInput) || 0);
                  } else if (e.key === 'Escape') {
                    setEditingCredits(false);
                  }
                }}
              />
            ) : (
              <p
                className="text-xl font-bold text-yellow-400 cursor-pointer hover:text-yellow-300"
                onClick={() => {
                  setCreditsInput(String(character.credits || 0));
                  setEditingCredits(true);
                }}
              >
                {(character.credits || 0).toLocaleString()} CR
              </p>
            )}
          </div>

          {/* Bulk Tracker */}
          <div className="p-3 rounded-lg bg-bg-secondary">
            <div className="flex items-center justify-between mb-1">
              <span className="text-xs text-text-secondary">Traglast</span>
              <span className={`text-sm font-bold ${isOverburdened ? 'text-red-400' : isEncumbered ? 'text-yellow-400' : 'text-text-primary'}`}>
                {totalBulk.toFixed(1)} / {bulkLimit}
              </span>
            </div>
            <div className="h-2 bg-bg-tertiary rounded-full overflow-hidden">
              <div
                className={`h-full transition-all ${
                  isOverburdened ? 'bg-red-500' : isEncumbered ? 'bg-yellow-500' : 'bg-primary-500'
                }`}
                style={{ width: `${Math.min(100, (totalBulk / encumberedLimit) * 100)}%` }}
              />
            </div>
            {(isEncumbered || isOverburdened) && (
              <p className={`text-xs mt-1 ${isOverburdened ? 'text-red-400' : 'text-yellow-400'}`}>
                {isOverburdened ? 'Überlastet' : 'Belastet'}
              </p>
            )}
          </div>
        </div>

        {/* Add Item Button */}
        <Button className="w-full" variant="outline" onClick={() => setShowAddItem(true)}>
          <Plus className="h-4 w-4 mr-2" />
          Gegenstand hinzufügen
        </Button>

        {/* Waffen-Sektion */}
        {weaponItems.length > 0 && (
          <div className="space-y-2">
            <h3 className="text-sm font-medium text-red-400 flex items-center gap-2">
              <Swords className="h-4 w-4" />
              Waffen ({weaponItems.length})
            </h3>
            <div className="grid gap-2 sm:grid-cols-2">
              {weaponItems.map(renderWeaponCard)}
            </div>
          </div>
        )}

        {/* Rüstung-Sektion */}
        {armorItems.length > 0 && (
          <div className="space-y-2">
            <h3 className="text-sm font-medium text-blue-400 flex items-center gap-2">
              <Shield className="h-4 w-4" />
              Rüstung ({armorItems.length})
            </h3>
            <div className="grid gap-2 sm:grid-cols-2">
              {armorItems.map(renderArmorCard)}
            </div>
          </div>
        )}

        {/* Schilde-Sektion */}
        {shieldItems.length > 0 && (
          <div className="space-y-2">
            <h3 className="text-sm font-medium text-cyan-400 flex items-center gap-2">
              <Shield className="h-4 w-4" />
              Schilde ({shieldItems.length})
            </h3>
            <div className="grid gap-2 sm:grid-cols-2">
              {shieldItems.map(renderShieldCard)}
            </div>
          </div>
        )}

        {/* Ausrüstung-Sektion */}
        <div className="space-y-2">
          <h3 className="text-sm font-medium text-text-secondary flex items-center gap-2">
            <Package className="h-4 w-4" />
            Ausrüstung ({otherItems.length})
          </h3>
          {otherItems.length === 0 ? (
            <p className="text-center text-text-muted py-6">Keine Gegenstände</p>
          ) : (
            <div className="grid gap-2 sm:grid-cols-2">
              {otherItems.map(renderItemCard)}
            </div>
          )}
        </div>
      </div>
    );
  };

  const renderFeatsTab = () => {
    const SOURCE_LABELS: Record<string, string> = {
      CLASS: 'Klasse',
      ANCESTRY: 'Abstammung',
      GENERAL: 'Allgemein',
      SKILL: 'Fertigkeit',
      ARCHETYPE: 'Archetyp',
      BONUS: 'Bonus',
    };

    const SOURCE_COLORS: Record<string, string> = {
      CLASS: 'bg-red-500/20 text-red-400',
      ANCESTRY: 'bg-blue-500/20 text-blue-400',
      GENERAL: 'bg-yellow-500/20 text-yellow-400',
      SKILL: 'bg-green-500/20 text-green-400',
      ARCHETYPE: 'bg-purple-500/20 text-purple-400',
      BONUS: 'bg-cyan-500/20 text-cyan-400',
    };

    // Group feats by source
    const featsBySource = character.feats.reduce((acc, feat) => {
      const source = feat.source || 'BONUS';
      if (!acc[source]) acc[source] = [];
      acc[source].push(feat);
      return acc;
    }, {} as Record<string, typeof character.feats>);

    const sourceOrder = ['CLASS', 'ANCESTRY', 'SKILL', 'GENERAL', 'ARCHETYPE', 'BONUS'];

    return (
      <div className="space-y-4">
        {/* Add Feat Button */}
        <Button className="w-full" variant="outline" onClick={() => setShowAddFeat(true)}>
          <Plus className="h-4 w-4 mr-2" />
          Talent hinzufügen
        </Button>

        {character.feats.length === 0 ? (
          <p className="text-center text-text-muted py-8">Keine Talente vorhanden</p>
        ) : (
          sourceOrder.map((source) => {
            const feats = featsBySource[source];
            if (!feats || feats.length === 0) return null;

            return (
              <div key={source} className="space-y-2">
                <h3 className={`text-sm font-medium flex items-center gap-2 ${SOURCE_COLORS[source]?.split(' ')[1] || 'text-text-secondary'}`}>
                  <Star className="h-4 w-4" />
                  {SOURCE_LABELS[source] || source} ({feats.length})
                </h3>
                <div className="grid gap-2 sm:grid-cols-2">
                  {feats.map((feat) => (
                    <div
                      key={feat.id}
                      onClick={() => setSelectedFeat(feat)}
                      className="p-3 rounded-lg bg-bg-secondary hover:bg-bg-tertiary transition-colors cursor-pointer"
                    >
                      <div className="flex items-center justify-between gap-2">
                        <div className="min-w-0 flex-1">
                          <p className="font-medium text-text-primary truncate">
                            {feat.nameGerman || feat.name}
                          </p>
                          <p className="text-xs text-text-secondary">
                            Level {feat.level} erhalten
                          </p>
                        </div>
                        <span className={`text-xs px-2 py-0.5 rounded flex-shrink-0 ${SOURCE_COLORS[feat.source] || 'bg-bg-tertiary text-text-secondary'}`}>
                          {SOURCE_LABELS[feat.source] || feat.source}
                        </span>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            );
          })
        )}
      </div>
    );
  };

  const renderSpellsTab = () => (
    <div className="space-y-6">
      <Card>
        <CardHeader className="flex flex-row items-center justify-between">
          <CardTitle className="flex items-center gap-2">
            <Sparkles className="h-5 w-5" />
            Zauber ({character.spells.length})
          </CardTitle>
          <Button size="sm" variant="outline">
            <Plus className="h-4 w-4" />
            Hinzufügen
          </Button>
        </CardHeader>
        <CardContent>
          {character.spells.length === 0 ? (
            <p className="text-center text-text-secondary py-4">Keine Zauber</p>
          ) : (
            <div className="space-y-4">
              {/* Group by spell level */}
              {[...new Set(character.spells.map(s => s.spellLevel))].sort().map(level => (
                <div key={level}>
                  <h4 className="text-sm font-medium text-text-secondary mb-2">
                    {level === 0 ? 'Zaubertricks' : `Grad ${level}`}
                  </h4>
                  <div className="space-y-1">
                    {character.spells.filter(s => s.spellLevel === level).map((spell) => (
                      <div
                        key={spell.id}
                        className="flex items-center justify-between p-2 rounded-lg bg-bg-secondary hover:bg-bg-tertiary"
                      >
                        <div className="flex items-center gap-2">
                          <span className={`w-2 h-2 rounded-full ${spell.prepared ? 'bg-green-500' : 'bg-text-secondary'}`} />
                          <span className="text-text-primary">
                            {spell.nameGerman || spell.name}
                          </span>
                        </div>
                        <span className="text-xs text-text-secondary">
                          {spell.tradition}
                        </span>
                      </div>
                    ))}
                  </div>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );

  const renderAlchemyTab = () => {
    if (!campaignId) return null;
    return (
      <AlchemyTab
        character={character}
        campaignId={campaignId}
        onStateUpdate={(state) => {
          setCharacter((prev) => prev ? { ...prev, alchemyState: state } : prev);
        }}
        onFormulasUpdate={(formulas) => {
          setCharacter((prev) => prev ? { ...prev, formulas } : prev);
        }}
        onPreparedItemsUpdate={(items) => {
          setCharacter((prev) => prev ? { ...prev, preparedItems: items } : prev);
        }}
      />
    );
  };

  const renderActionsTab = () => {
    return <ActionsTab characterFeats={character.feats} />;
  };

  const renderTabContent = () => {
    switch (activeTab) {
      case 'status':
        return renderStatusTab();
      case 'skills':
        return renderSkillsTab();
      case 'inventory':
        return renderInventoryTab();
      case 'feats':
        return renderFeatsTab();
      case 'spells':
        return renderSpellsTab();
      case 'alchemy':
        return renderAlchemyTab();
      case 'actions':
        return renderActionsTab();
      default:
        return null;
    }
  };

  return (
    <div className="space-y-4">
      {/* Header */}
      <div className="flex items-start justify-between gap-4">
        <div className="flex items-start gap-4">
          <Button variant="ghost" size="icon" onClick={() => navigate(`/campaigns/${campaignId}`)}>
            <ArrowLeft className="h-5 w-5" />
          </Button>
          <div className="flex items-center gap-4">
            <div className="h-14 w-14 rounded-full bg-primary-500/20 flex items-center justify-center">
              {character.avatarUrl ? (
                <img
                  src={character.avatarUrl}
                  alt={character.name}
                  className="h-14 w-14 rounded-full object-cover"
                />
              ) : (
                <Shield className="h-7 w-7 text-primary-500" />
              )}
            </div>
            <div>
              <h1 className="text-xl font-bold text-text-primary">{character.name}</h1>
              <p className="text-sm text-text-secondary">
                Level {character.level} {character.ancestryId || ''} {character.classId || character.type}
              </p>
            </div>
          </div>
        </div>
        <div className="flex items-center gap-2">
          <Button
            variant="outline"
            size="sm"
            onClick={() => downloadCharacterHTML(character)}
            title="Als HTML exportieren"
          >
            <Download className="h-4 w-4" />
          </Button>
          {isOwner && (
            <>
              <Button variant="outline" size="sm" onClick={() => setShowEditCharacter(true)}>
                <Edit2 className="h-4 w-4" />
              </Button>
              <Button variant="destructive" size="sm" onClick={handleDelete}>
                <Trash2 className="h-4 w-4" />
              </Button>
            </>
          )}
        </div>
      </div>

      {/* Tab Navigation */}
      <div className="flex gap-1 overflow-x-auto pb-2 -mx-4 px-4 sm:mx-0 sm:px-0">
        {TABS.map((tab) => (
          <button
            key={tab.id}
            onClick={() => setActiveTab(tab.id)}
            className={`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium whitespace-nowrap transition-colors ${
              activeTab === tab.id
                ? 'bg-primary-500 text-white'
                : 'bg-bg-secondary text-text-secondary hover:bg-bg-tertiary hover:text-text-primary'
            }`}
          >
            {tab.icon}
            {tab.label}
          </button>
        ))}
      </div>

      {/* Tab Content */}
      <div className="min-h-[400px]">
        {renderTabContent()}
      </div>

      {/* Modals */}
      {showAddCondition && (
        <AddConditionModal
          onClose={() => setShowAddCondition(false)}
          onAdd={handleAddCondition}
          existingConditions={character.conditions.map((c) => c.name)}
        />
      )}
      {showAddItem && (
        <AddItemModal
          onClose={() => setShowAddItem(false)}
          onAdd={handleAddItem}
          existingItemNames={character.items.map((i) => i.name)}
        />
      )}
      {selectedItem && (
        <ItemDetailModal
          item={selectedItem}
          isGM={isGM || false}
          onClose={() => setSelectedItem(null)}
          onUpdateQuantity={(quantity) => handleUpdateItemQuantity(selectedItem.id, quantity)}
          onRemove={() => handleRemoveItem(selectedItem.id)}
          onToggleEquipped={(equipped) => handleToggleEquipped(selectedItem.id, equipped)}
          onUpdateItem={(data) => handleUpdateItem(selectedItem.id, data)}
        />
      )}
      {showEditCharacter && campaignId && (
        <EditCharacterModal
          campaignId={campaignId}
          character={character}
          onClose={() => setShowEditCharacter(false)}
          onUpdated={(updated) => setCharacter(updated)}
        />
      )}
      {showAddFeat && (
        <AddFeatModal
          onClose={() => setShowAddFeat(false)}
          onAdd={handleAddFeat}
          existingFeatNames={character.feats.map((f) => f.name)}
          characterLevel={character.level}
          characterClass={character.classId}
          characterAncestry={character.ancestryId}
          characterSkills={character.skills}
        />
      )}
      {selectedFeat && (
        <FeatDetailModal
          feat={selectedFeat}
          onClose={() => setSelectedFeat(null)}
          onRemove={() => handleRemoveFeat(selectedFeat.id)}
        />
      )}
      {showRestModal && campaignId && (
        <RestModal
          campaignId={campaignId}
          characterId={character.id}
          onClose={() => setShowRestModal(false)}
          onRestComplete={(result) => {
            // The WebSocket will handle the state update
            console.log('Rest complete:', result);
          }}
        />
      )}
    </div>
  );
}
