import { useEffect, useState } from 'react'
import type { CSSProperties, Dispatch, SetStateAction } from 'react'
import {
  IWT2_BOSS_METADATA,
  type Iwt2BalanceOverrides,
  type Iwt2BossId,
  type Iwt2BossMetadata,
} from '../modes/iwt2/content/bosses'

type AdminItem = {
  id: number
  slug: string
  name: string
  slot: string
  rarity: string
  itemLevel: number
  healingPower: number
  maxResourceBonus: number
  glyph: string
  imageUrl: string
  description: string
}

type AdminEncounter = {
  id: number
  dungeonId: number
  sequence: number
  slug: string
  enemyName: string
  encounterType: string
  maxHealth: number
  baseDamage: number
  tankDamage: number
  partyDamage: number
  imageUrl: string
  description: string
}

type AdminDifficulty = {
  id: number
  slug: string
  name: string
  droppedItemLevel: number
}

type AdminLootEntry = {
  encounterId: number
  itemId: number
  difficultyId: number
  dropWeight: number
  dropChance: number
}

type AdminRecipeComponent = {
  itemId: number
  quantity: number
}

type AdminRecipe = {
  id: number
  itemId: number
  difficultyId: number | null
  sourceDungeonId: number | null
  sourceEncounterId: number | null
  components: AdminRecipeComponent[]
}

type AdminDungeon = {
  id: number
  slug: string
  name: string
  recommendedLevel: number
  contentType: string
  partySize: number
  experienceReward: number
  imageUrl: string
  description: string
}

type AdminUpgradePath = {
  fromItemId: number
  toItemId: number
}

type AdminAbility = {
  id: number
  classId: number
  slug: string
  name: string
  spellType: string
  cost: number
  cooldown: number
  power: number
  unlockLevel: number
  glyph: string
  description: string
}

type AdminTalent = {
  id: number
  classId: number
  slug: string
  name: string
  maxRank: number
  tier: number
  branch: number
  prerequisiteTalentId: number | null
  prerequisiteRank: number
  prerequisiteName: string | null
  effectType: string
  effectValuePerRank: number
  glyph: string
  description: string
}

type AdminClass = {
  id: number
  slug: string
  name: string
  resourceName: string
  maxResource: number
  themeColor: string
  description: string
  abilities: AdminAbility[]
  talents: AdminTalent[]
}

type AdminData = {
  items: AdminItem[]
  encounters: AdminEncounter[]
  difficulties: AdminDifficulty[]
  encounterLoot: AdminLootEntry[]
  craftingRecipes: AdminRecipe[]
  dungeons: AdminDungeon[]
  gearUpgradePaths: AdminUpgradePath[]
  classes: AdminClass[]
}

type Iwt2AdminAsset = {
  filename: string
  size: number
  url: string
}

type Iwt2AdminData = {
  balanceOverrides: Iwt2BalanceOverrides
  bossAssets: Iwt2AdminAsset[]
}

type Iwt2AdminAttack = {
  name: string
  frequency: string
  damage: string
  details: string
}

type Iwt2AdminEntityRow = {
  id: string
  bossId: Iwt2BossId
  kind: 'boss' | 'mob'
  name: string
  slug: string
  icon: string
  color: string
  maxHealth: number
  attacks: Iwt2AdminAttack[]
  assets: Iwt2AdminAsset[]
}

type AdminTab = 'items' | 'dungeons' | 'encounters' | 'loot' | 'crafting' | 'upgrades' | 'classes' | 'iwt2'
type SavingState = Record<string, boolean>
type SetData = Dispatch<SetStateAction<AdminData | null>>
type SetSaving = Dispatch<SetStateAction<SavingState>>

const API = '/api/admin'
const tabs: { id: AdminTab; label: string }[] = [
  { id: 'items', label: 'Items' },
  { id: 'dungeons', label: 'Dungeons' },
  { id: 'encounters', label: 'Mobs/Bosses' },
  { id: 'loot', label: 'Loot' },
  { id: 'crafting', label: 'Crafting' },
  { id: 'upgrades', label: 'Upgrades' },
  { id: 'classes', label: 'Classes' },
  { id: 'iwt2', label: 'IWT2' },
]

async function fetchJson<T>(url: string, init?: RequestInit): Promise<T> {
  const res = await fetch(url, init)
  const body = await res.json()
  if (!res.ok) throw new Error(body.error ?? 'Request failed')
  return body
}

export function AdminScreen({ onBack }: { onBack: () => void }) {
  const [data, setData] = useState<AdminData | null>(null)
  const [tab, setTab] = useState<AdminTab>('items')
  const [error, setError] = useState('')
  const [saving, setSaving] = useState<SavingState>({})

  useEffect(() => {
    fetchJson<AdminData>(`${API}/data`)
      .then(setData)
      .catch((e: unknown) => setError(e instanceof Error ? e.message : 'Failed to load'))
  }, [])

  if (error) return <section className="content-screen"><p className="error-message">{error}</p></section>
  if (!data) return <section className="content-screen"><p>Loading admin data...</p></section>

  return (
    <section className="content-screen admin-screen">
      <div className="screen-heading">
        <div><p className="eyebrow">Developer Tools</p><h1>Admin Panel</h1></div>
        <button className="back-button" onClick={onBack} type="button">Back</button>
      </div>
      <nav className="admin-tabs">
        {tabs.map((candidate) => (
          <button key={candidate.id} className={`admin-tab ${tab === candidate.id ? 'active' : ''}`}
            onClick={() => setTab(candidate.id)} type="button">
            {candidate.label}
          </button>
        ))}
      </nav>
      {tab === 'items' && <ItemsTab data={data} setData={setData} setSaving={setSaving} saving={saving} />}
      {tab === 'dungeons' && <DungeonsTab data={data} setData={setData} setSaving={setSaving} saving={saving} />}
      {tab === 'encounters' && <EncountersTab data={data} setData={setData} setSaving={setSaving} saving={saving} />}
      {tab === 'loot' && <LootTab data={data} setData={setData} setSaving={setSaving} saving={saving} />}
      {tab === 'crafting' && <CraftingTab data={data} setData={setData} setSaving={setSaving} saving={saving} />}
      {tab === 'upgrades' && <UpgradesTab data={data} setData={setData} setSaving={setSaving} saving={saving} />}
      {tab === 'classes' && <ClassesTab data={data} />}
      {tab === 'iwt2' && <Iwt2AdminTab />}
    </section>
  )
}

function ItemsTab({ data, setData, setSaving, saving }: {
  data: AdminData
  setData: SetData
  setSaving: SetSaving
  saving: SavingState
}) {
  const [filter, setFilter] = useState('')
  const [editId, setEditId] = useState<number | null>(null)
  const [form, setForm] = useState<Partial<AdminItem>>({})
  const groups = groupBy(data.items.filter((item) =>
    item.name.toLowerCase().includes(filter.toLowerCase())
    || item.slug.toLowerCase().includes(filter.toLowerCase())
    || item.slot.toLowerCase().includes(filter.toLowerCase())),
  (item) => item.slot)

  async function saveItem(id: number) {
    setSaving((prev) => ({ ...prev, [`item-${id}`]: true }))
    try {
      const body: Record<string, string | number> = {}
      if (form.name !== undefined) body.name = form.name
      if (form.slug !== undefined) body.slug = form.slug
      if (form.glyph !== undefined) body.glyph = form.glyph
      if (form.description !== undefined) body.description = form.description
      if (form.rarity !== undefined) body.rarity = form.rarity
      if (form.slot !== undefined) body.slot = form.slot
      if (form.itemLevel !== undefined) body.item_level = form.itemLevel
      if (form.healingPower !== undefined) body.healing_power = form.healingPower
      if (form.maxResourceBonus !== undefined) body.max_resource_bonus = form.maxResourceBonus
      await fetchJson(`${API}/items/${id}`, jsonRequest('PUT', body))
      setData((prev) => prev ? { ...prev, items: prev.items.map((item) => item.id === id ? { ...item, ...form } : item) } : prev)
      setEditId(null)
      setForm({})
    } catch (e: unknown) {
      alert(e instanceof Error ? e.message : 'Save failed')
    } finally {
      setSaving((prev) => ({ ...prev, [`item-${id}`]: false }))
    }
  }

  async function uploadItemImage(itemId: number, file: File | undefined) {
    if (!file) return
    setSaving((prev) => ({ ...prev, [`item-image-${itemId}`]: true }))
    try {
      const imageData = await fileToDataUrl(file)
      const result = await fetchJson<{ imageUrl: string }>(`${API}/items/${itemId}/image`, jsonRequest('PUT', { imageData }))
      setData((prev) => prev ? {
        ...prev,
        items: prev.items.map((item) => item.id === itemId ? { ...item, imageUrl: result.imageUrl } : item),
      } : prev)
    } catch (e: unknown) {
      alert(e instanceof Error ? e.message : 'Upload failed')
    } finally {
      setSaving((prev) => ({ ...prev, [`item-image-${itemId}`]: false }))
    }
  }

  return (
    <div className="admin-panel">
      <input className="admin-search" placeholder="Search items..." value={filter}
        onChange={(e) => setFilter(e.target.value)} />
      {Object.entries(groups).map(([slot, items]) => (
        <details key={slot} open={slot !== 'component'}>
          <summary className="admin-group-header">{slot} ({items.length})</summary>
          <div className="admin-grid">
            {items.map((item) => (
              <div key={item.id} className="admin-card">
                {editId === item.id ? (
                  <div className="admin-edit-form">
                    <label>Glyph <input value={form.glyph ?? item.glyph} onChange={(e) => setForm({ ...form, glyph: e.target.value })} /></label>
                    <label>Name <input value={form.name ?? item.name} onChange={(e) => setForm({ ...form, name: e.target.value })} /></label>
                    <label>Slug <input value={form.slug ?? item.slug} onChange={(e) => setForm({ ...form, slug: e.target.value })} /></label>
                    <label>Slot <select value={form.slot ?? item.slot} onChange={(e) => setForm({ ...form, slot: e.target.value })}>
                      {['weapon', 'helmet', 'chest', 'gloves', 'boots', 'pants', 'ring', 'necklace', 'trinket', 'component'].map((slotName) => (
                        <option key={slotName} value={slotName}>{slotName}</option>
                      ))}
                    </select></label>
                    <label>Rarity <select value={form.rarity ?? item.rarity} onChange={(e) => setForm({ ...form, rarity: e.target.value })}>
                      {['common', 'uncommon', 'rare', 'epic', 'legendary'].map((rarity) => (
                        <option key={rarity} value={rarity}>{rarity}</option>
                      ))}
                    </select></label>
                    <label>iLvl <input type="number" value={form.itemLevel ?? item.itemLevel} onChange={(e) => setForm({ ...form, itemLevel: Number(e.target.value) })} /></label>
                    <label>Healing <input type="number" value={form.healingPower ?? item.healingPower} onChange={(e) => setForm({ ...form, healingPower: Number(e.target.value) })} /></label>
                    <label>Resource <input type="number" value={form.maxResourceBonus ?? item.maxResourceBonus} onChange={(e) => setForm({ ...form, maxResourceBonus: Number(e.target.value) })} /></label>
                    <label>Description <textarea value={form.description ?? item.description} onChange={(e) => setForm({ ...form, description: e.target.value })} /></label>
                    <div className="admin-edit-actions">
                      <button className="primary-button" onClick={() => saveItem(item.id)} disabled={saving[`item-${item.id}`]} type="button">
                        {saving[`item-${item.id}`] ? 'Saving...' : 'Save'}
                      </button>
                      <button className="text-button" onClick={() => { setEditId(null); setForm({}) }} type="button">Cancel</button>
                    </div>
                  </div>
                ) : (
                  <>
                    <div className="admin-item-header">
                      <img className="admin-thumb" src={item.imageUrl || '/equipment-placeholder.svg'} alt={`${item.name} icon`} />
                      <span className={`admin-glyph rarity-${item.rarity}`}>{item.glyph}</span>
                      <div>
                        <strong>{item.name}</strong>
                        <small className="admin-item-meta">{item.slot} · iLvl {item.itemLevel} · {item.rarity}</small>
                      </div>
                    </div>
                    <p className="admin-item-desc">{item.description}</p>
                    <div className="admin-item-stats">
                      <span>+{item.healingPower} healing</span>
                      <span>+{item.maxResourceBonus} resource</span>
                    </div>
                    <div className="admin-edit-actions">
                      <button className="text-button" onClick={() => { setEditId(item.id); setForm({}) }} type="button">Edit</button>
                      {item.slot !== 'component' && (
                        <label className="boss-upload-button">
                          {saving[`item-image-${item.id}`] ? 'Uploading...' : 'Upload Art'}
                          <input accept="image/png,image/jpeg,image/webp,image/gif" disabled={saving[`item-image-${item.id}`]}
                            onChange={(event) => uploadItemImage(item.id, event.target.files?.[0])} type="file" />
                        </label>
                      )}
                    </div>
                  </>
                )}
              </div>
            ))}
          </div>
        </details>
      ))}
    </div>
  )
}

function DungeonsTab({ data, setData, setSaving, saving }: {
  data: AdminData
  setData: SetData
  setSaving: SetSaving
  saving: SavingState
}) {
  const [editId, setEditId] = useState<number | null>(null)
  const [form, setForm] = useState<Partial<AdminDungeon>>({})

  async function saveDungeon(id: number) {
    setSaving((prev) => ({ ...prev, [`dungeon-${id}`]: true }))
    try {
      const body: Record<string, string | number> = {}
      if (form.name !== undefined) body.name = form.name
      if (form.slug !== undefined) body.slug = form.slug
      if (form.contentType !== undefined) body.content_type = form.contentType
      if (form.recommendedLevel !== undefined) body.recommended_level = form.recommendedLevel
      if (form.partySize !== undefined) body.party_size = form.partySize
      if (form.experienceReward !== undefined) body.experience_reward = form.experienceReward
      if (form.description !== undefined) body.description = form.description
      await fetchJson(`${API}/dungeons/${id}`, jsonRequest('PUT', body))
      setData((prev) => prev ? { ...prev, dungeons: prev.dungeons.map((dungeon) => dungeon.id === id ? { ...dungeon, ...form } : dungeon) } : prev)
      setEditId(null)
      setForm({})
    } catch (e: unknown) {
      alert(e instanceof Error ? e.message : 'Save failed')
    } finally {
      setSaving((prev) => ({ ...prev, [`dungeon-${id}`]: false }))
    }
  }

  async function uploadDungeonImage(dungeonId: number, file: File | undefined) {
    if (!file) return
    setSaving((prev) => ({ ...prev, [`dungeon-image-${dungeonId}`]: true }))
    try {
      const imageData = await fileToDataUrl(file)
      const result = await fetchJson<{ imageUrl: string }>(`${API}/dungeons/${dungeonId}/image`, jsonRequest('PUT', { imageData }))
      setData((prev) => prev ? {
        ...prev,
        dungeons: prev.dungeons.map((dungeon) => dungeon.id === dungeonId ? { ...dungeon, imageUrl: result.imageUrl } : dungeon),
      } : prev)
    } catch (e: unknown) {
      alert(e instanceof Error ? e.message : 'Upload failed')
    } finally {
      setSaving((prev) => ({ ...prev, [`dungeon-image-${dungeonId}`]: false }))
    }
  }

  return (
    <div className="admin-panel">
      <div className="admin-grid">
        {data.dungeons.map((dungeon) => (
          <div key={dungeon.id} className="admin-card">
            {editId === dungeon.id ? (
              <div className="admin-edit-form">
                <label>Name <input value={form.name ?? dungeon.name} onChange={(e) => setForm({ ...form, name: e.target.value })} /></label>
                <label>Slug <input value={form.slug ?? dungeon.slug} onChange={(e) => setForm({ ...form, slug: e.target.value })} /></label>
                <label>Type <select value={form.contentType ?? dungeon.contentType} onChange={(e) => setForm({ ...form, contentType: e.target.value })}>
                  <option value="dungeon">dungeon</option>
                  <option value="raid">raid</option>
                </select></label>
                <label>Level <input type="number" value={form.recommendedLevel ?? dungeon.recommendedLevel} onChange={(e) => setForm({ ...form, recommendedLevel: Number(e.target.value) })} /></label>
                <label>Party <input type="number" value={form.partySize ?? dungeon.partySize} onChange={(e) => setForm({ ...form, partySize: Number(e.target.value) })} /></label>
                <label>XP <input type="number" value={form.experienceReward ?? dungeon.experienceReward} onChange={(e) => setForm({ ...form, experienceReward: Number(e.target.value) })} /></label>
                <label>Description <textarea value={form.description ?? dungeon.description} onChange={(e) => setForm({ ...form, description: e.target.value })} /></label>
                <div className="admin-edit-actions">
                  <button className="primary-button" onClick={() => saveDungeon(dungeon.id)} disabled={saving[`dungeon-${dungeon.id}`]} type="button">
                    {saving[`dungeon-${dungeon.id}`] ? 'Saving...' : 'Save'}
                  </button>
                  <button className="text-button" onClick={() => { setEditId(null); setForm({}) }} type="button">Cancel</button>
                </div>
              </div>
            ) : (
              <>
                <div className="admin-item-header">
                  <img className="admin-thumb" src={dungeon.imageUrl || '/boss-placeholder.svg'} alt={`${dungeon.name} art`} />
                  <div>
                    <strong>{dungeon.name}</strong>
                    <small className="admin-item-meta">#{dungeon.id} · {dungeon.contentType} · party {dungeon.partySize}</small>
                  </div>
                </div>
                <p className="admin-item-desc">{dungeon.description}</p>
                <div className="admin-edit-actions">
                  <button className="text-button" onClick={() => { setEditId(dungeon.id); setForm({}) }} type="button">Edit</button>
                  <label className="boss-upload-button">
                    {saving[`dungeon-image-${dungeon.id}`] ? 'Uploading...' : 'Upload Art'}
                    <input accept="image/png,image/jpeg,image/webp,image/gif" disabled={saving[`dungeon-image-${dungeon.id}`]}
                      onChange={(event) => uploadDungeonImage(dungeon.id, event.target.files?.[0])} type="file" />
                  </label>
                </div>
              </>
            )}
          </div>
        ))}
      </div>
    </div>
  )
}

function EncountersTab({ data, setData, setSaving, saving }: {
  data: AdminData
  setData: SetData
  setSaving: SetSaving
  saving: SavingState
}) {
  const [filter, setFilter] = useState('')
  const [editId, setEditId] = useState<number | null>(null)
  const [form, setForm] = useState<Partial<AdminEncounter>>({})
  const encounters = data.encounters.filter((encounter) =>
    encounter.enemyName.toLowerCase().includes(filter.toLowerCase())
    || encounter.slug.toLowerCase().includes(filter.toLowerCase())
    || dungeonName(data, encounter.dungeonId).toLowerCase().includes(filter.toLowerCase()))

  async function saveEncounter(id: number) {
    setSaving((prev) => ({ ...prev, [`encounter-${id}`]: true }))
    try {
      const body: Record<string, string | number> = {}
      if (form.enemyName !== undefined) body.name = form.enemyName
      if (form.slug !== undefined) body.slug = form.slug
      if (form.encounterType !== undefined) body.encounter_type = form.encounterType
      if (form.maxHealth !== undefined) body.max_health = form.maxHealth
      if (form.baseDamage !== undefined) body.base_damage = form.baseDamage
      if (form.tankDamage !== undefined) body.tank_damage = form.tankDamage
      if (form.partyDamage !== undefined) body.party_damage = form.partyDamage
      if (form.description !== undefined) body.description = form.description
      await fetchJson(`${API}/encounters/${id}`, jsonRequest('PUT', body))
      setData((prev) => prev ? {
        ...prev,
        encounters: prev.encounters.map((encounter) => encounter.id === id ? { ...encounter, ...form } : encounter),
      } : prev)
      setEditId(null)
      setForm({})
    } catch (e: unknown) {
      alert(e instanceof Error ? e.message : 'Save failed')
    } finally {
      setSaving((prev) => ({ ...prev, [`encounter-${id}`]: false }))
    }
  }

  async function uploadEncounterImage(encounterId: number, file: File | undefined) {
    if (!file) return
    setSaving((prev) => ({ ...prev, [`encounter-image-${encounterId}`]: true }))
    try {
      const imageData = await fileToDataUrl(file)
      const result = await fetchJson<{ imageUrl: string }>(`${API}/encounters/${encounterId}/image`, jsonRequest('PUT', { imageData }))
      setData((prev) => prev ? {
        ...prev,
        encounters: prev.encounters.map((encounter) => encounter.id === encounterId ? { ...encounter, imageUrl: result.imageUrl } : encounter),
      } : prev)
    } catch (e: unknown) {
      alert(e instanceof Error ? e.message : 'Upload failed')
    } finally {
      setSaving((prev) => ({ ...prev, [`encounter-image-${encounterId}`]: false }))
    }
  }

  return (
    <div className="admin-panel">
      <input className="admin-search" placeholder="Search mobs, bosses, dungeons..." value={filter}
        onChange={(e) => setFilter(e.target.value)} />
      <div className="admin-grid boss-image-grid">
        {encounters.map((encounter) => (
          <div key={encounter.id} className="admin-card">
            {editId === encounter.id ? (
              <div className="admin-edit-form">
                <label>Name <input value={form.enemyName ?? encounter.enemyName} onChange={(e) => setForm({ ...form, enemyName: e.target.value })} /></label>
                <label>Slug <input value={form.slug ?? encounter.slug} onChange={(e) => setForm({ ...form, slug: e.target.value })} /></label>
                <label>Type <select value={form.encounterType ?? encounter.encounterType} onChange={(e) => setForm({ ...form, encounterType: e.target.value })}>
                  <option value="trash">trash</option>
                  <option value="boss">boss</option>
                </select></label>
                <label>Health <input type="number" value={form.maxHealth ?? encounter.maxHealth} onChange={(e) => setForm({ ...form, maxHealth: Number(e.target.value) })} /></label>
                <label>Base Dmg <input type="number" value={form.baseDamage ?? encounter.baseDamage} onChange={(e) => setForm({ ...form, baseDamage: Number(e.target.value) })} /></label>
                <label>Tank Dmg <input type="number" value={form.tankDamage ?? encounter.tankDamage} onChange={(e) => setForm({ ...form, tankDamage: Number(e.target.value) })} /></label>
                <label>Party Dmg <input type="number" value={form.partyDamage ?? encounter.partyDamage} onChange={(e) => setForm({ ...form, partyDamage: Number(e.target.value) })} /></label>
                <label>Description <textarea value={form.description ?? encounter.description} onChange={(e) => setForm({ ...form, description: e.target.value })} /></label>
                <div className="admin-edit-actions">
                  <button className="primary-button" onClick={() => saveEncounter(encounter.id)} disabled={saving[`encounter-${encounter.id}`]} type="button">
                    {saving[`encounter-${encounter.id}`] ? 'Saving...' : 'Save'}
                  </button>
                  <button className="text-button" onClick={() => { setEditId(null); setForm({}) }} type="button">Cancel</button>
                </div>
              </div>
            ) : (
              <>
                <img className="admin-recipe-image" src={encounter.imageUrl || '/boss-placeholder.svg'} alt={`${encounter.enemyName} art`} />
                <div>
                  <strong>{encounter.enemyName}</strong>
                  <small className="admin-item-meta">{dungeonName(data, encounter.dungeonId)} · {encounter.encounterType} · #{encounter.sequence}</small>
                </div>
                <p className="admin-item-desc">{encounter.description}</p>
                <div className="admin-item-stats">
                  <span>{encounter.maxHealth} hp</span>
                  <span>{encounter.baseDamage} dmg</span>
                </div>
                <div className="admin-edit-actions">
                  <button className="text-button" onClick={() => { setEditId(encounter.id); setForm({}) }} type="button">Edit</button>
                  <label className="boss-upload-button">
                    {saving[`encounter-image-${encounter.id}`] ? 'Uploading...' : 'Upload Art'}
                    <input accept="image/png,image/jpeg,image/webp,image/gif" disabled={saving[`encounter-image-${encounter.id}`]}
                      onChange={(event) => uploadEncounterImage(encounter.id, event.target.files?.[0])} type="file" />
                  </label>
                </div>
              </>
            )}
          </div>
        ))}
      </div>
    </div>
  )
}

function LootTab({ data, setData, setSaving, saving }: {
  data: AdminData
  setData: SetData
  setSaving: SetSaving
  saving: SavingState
}) {
  const [encounterId, setEncounterId] = useState(data.encounters.filter(e => e.encounterType === 'boss')[0]?.id ?? 0)
  const [difficultyId, setDifficultyId] = useState(data.difficulties[0]?.id ?? 0)
  const [addItemId, setAddItemId] = useState(0)
  const [addDropWeight, setAddDropWeight] = useState(100)
  const [addDropChance, setAddDropChance] = useState(1)
  const [renameItemId, setRenameItemId] = useState<number | null>(null)
  const [renameValue, setRenameValue] = useState('')
  const [bossSort, setBossSort] = useState<'dungeon' | 'boss'>('dungeon')
  const enc = data.encounters.find(e => e.id === encounterId)
  const bossOptions = data.encounters
    .filter((e) => e.encounterType === 'boss')
    .sort((a, b) => bossSort === 'boss'
      ? a.enemyName.localeCompare(b.enemyName) || a.dungeonId - b.dungeonId || a.sequence - b.sequence
      : a.dungeonId - b.dungeonId || a.sequence - b.sequence || a.enemyName.localeCompare(b.enemyName))
  const bossLoot = data.encounterLoot.filter(
    (loot) => loot.encounterId === encounterId && loot.difficultyId === difficultyId,
  )

  async function renameItem(itemId: number) {
    if (renameValue.trim() === '' || renameValue === itemName(data, itemId)) return
    setSaving((prev) => ({ ...prev, [`loot-rename-${itemId}`]: true }))
    try {
      await fetchJson(`${API}/items/${itemId}`, jsonRequest('PUT', { name: renameValue.trim() }))
      setData((prev) => prev ? {
        ...prev,
        items: prev.items.map((item) => item.id === itemId ? { ...item, name: renameValue.trim() } : item),
      } : prev)
      setRenameItemId(null)
      setRenameValue('')
    } catch (e: unknown) {
      alert(e instanceof Error ? e.message : 'Rename failed')
    } finally {
      setSaving((prev) => ({ ...prev, [`loot-rename-${itemId}`]: false }))
    }
  }

  async function deleteLoot(eId: number, dId: number, iId: number) {
    try {
      await fetchJson(`${API}/encounter-loot/${eId}/${dId}/${iId}`, { method: 'DELETE' })
      setData((prev) => prev ? {
        ...prev,
        encounterLoot: prev.encounterLoot.filter((loot) => !(loot.encounterId === eId && loot.difficultyId === dId && loot.itemId === iId)),
      } : prev)
    } catch (e: unknown) {
      alert(e instanceof Error ? e.message : 'Delete failed')
    }
  }

  async function addLoot() {
    if (!addItemId) return
    try {
      await fetchJson(`${API}/encounter-loot`, jsonRequest('POST', { encounterId, itemId: addItemId, difficultyId, dropWeight: addDropWeight, dropChance: addDropChance }))
      setData((prev) => prev ? {
        ...prev,
        encounterLoot: [
          ...prev.encounterLoot.filter((loot) => !(loot.encounterId === encounterId && loot.difficultyId === difficultyId && loot.itemId === addItemId)),
          { encounterId, itemId: addItemId, difficultyId, dropWeight: addDropWeight, dropChance: addDropChance },
        ],
      } : prev)
      setAddItemId(0)
      setAddDropWeight(100)
      setAddDropChance(1)
    } catch (e: unknown) {
      alert(e instanceof Error ? e.message : 'Add failed')
    }
  }

  return (
    <div className="admin-panel">
      <div className="admin-loot-selectors">
        <label>Boss <select value={encounterId} onChange={(e) => setEncounterId(Number(e.target.value))}>
          {bossOptions.map((encounter) => (
            <option key={encounter.id} value={encounter.id}>{encounter.enemyName} ({dungeonName(data, encounter.dungeonId)})</option>
          ))}
        </select></label>
        <label>Sort <select value={bossSort} onChange={(e) => setBossSort(e.target.value as 'dungeon' | 'boss')}>
          <option value="dungeon">Dungeon order</option>
          <option value="boss">Boss name</option>
        </select></label>
        <label>Difficulty <select value={difficultyId} onChange={(e) => setDifficultyId(Number(e.target.value))}>
          {data.difficulties.map((difficulty) => (
            <option key={difficulty.id} value={difficulty.id}>{difficulty.name} (iLvl {difficulty.droppedItemLevel})</option>
          ))}
        </select></label>
      </div>

      <h3 className="admin-loot-title">{enc?.enemyName ?? 'Unknown'} - {difficultyName(data, difficultyId)}</h3>
      {bossLoot.length === 0 && <p className="admin-empty">No loot entries.</p>}
      <div className="admin-loot-list">
        {bossLoot.map((entry) => (
          <div key={`${entry.itemId}`} className="admin-loot-row">
            <span className={`admin-glyph rarity-${data.items.find(i => i.id === entry.itemId)?.rarity ?? 'common'}`}>{itemGlyph(data, entry.itemId)}</span>
            {renameItemId === entry.itemId ? (
              <span className="admin-loot-name"><input className="admin-rename-input" value={renameValue}
                onChange={(e) => setRenameValue(e.target.value)}
                onKeyDown={(e) => { if (e.key === 'Enter') renameItem(entry.itemId); if (e.key === 'Escape') { setRenameItemId(null); setRenameValue('') } }} /></span>
            ) : (
              <span className="admin-loot-name">{itemName(data, entry.itemId)}</span>
            )}
            <span className="admin-loot-weight">Weight: {entry.dropWeight}</span>
            <span className="admin-loot-chance">Chance: {(entry.dropChance * 100).toFixed(0)}%</span>
            {renameItemId === entry.itemId ? (
              <>
                <button className="primary-button" disabled={saving[`loot-rename-${entry.itemId}`]} onClick={() => renameItem(entry.itemId)} type="button">
                  {saving[`loot-rename-${entry.itemId}`] ? 'Saving...' : 'Save'}
                </button>
                <button className="text-button" onClick={() => { setRenameItemId(null); setRenameValue('') }} type="button">Cancel</button>
              </>
            ) : (
              <>
                <button className="text-button" onClick={() => { setRenameItemId(entry.itemId); setRenameValue(itemName(data, entry.itemId)) }} type="button">Rename</button>
                <button className="danger-button" onClick={() => deleteLoot(entry.encounterId, entry.difficultyId, entry.itemId)} type="button">X</button>
              </>
            )}
          </div>
        ))}
      </div>

      <details className="admin-add-section">
        <summary>Add Item to Loot Table</summary>
        <div className="admin-add-form">
          <label>Item <select value={addItemId} onChange={(e) => setAddItemId(Number(e.target.value))}>
            <option value={0}>Select item...</option>
            {data.items.filter((item) => !bossLoot.some((loot) => loot.itemId === item.id)).map((item) => (
              <option key={item.id} value={item.id}>[{item.glyph}] {item.name} ({item.slot})</option>
            ))}
          </select></label>
          <label>Drop Weight <input type="number" value={addDropWeight} onChange={(e) => setAddDropWeight(Number(e.target.value))} /></label>
          <label>Drop Chance <input type="number" min="0" max="1" step="0.05" value={addDropChance} onChange={(e) => setAddDropChance(Number(e.target.value))} /></label>
          <button className="primary-button" onClick={addLoot} disabled={!addItemId} type="button">Add</button>
        </div>
      </details>
    </div>
  )
}

function CraftingTab({ data, setData, setSaving, saving }: {
  data: AdminData
  setData: SetData
  setSaving: SetSaving
  saving: SavingState
}) {
  const [recipeId, setRecipeId] = useState(data.craftingRecipes[0]?.id ?? 0)
  const [itemLevelFilter, setItemLevelFilter] = useState('all')
  const [bossFilterId, setBossFilterId] = useState(0)
  const [addItemId, setAddItemId] = useState(0)
  const [addQty, setAddQty] = useState(1)
  const [outputNameByItem, setOutputNameByItem] = useState<Record<number, string>>({})
  const [recipeDraft, setRecipeDraft] = useState<Record<number, Partial<AdminRecipe>>>({})
  const bossEncounters = data.encounters.filter((encounter) => encounter.encounterType === 'boss')
  const bossLootItemIds = new Set(data.encounterLoot.filter((entry) => bossEncounters.some((boss) => boss.id === entry.encounterId)).map((entry) => entry.itemId))
  const itemLevels = Array.from(new Set(
    data.craftingRecipes.map((candidate) => data.items.find((item) => item.id === candidate.itemId)?.itemLevel)
      .filter((itemLevel): itemLevel is number => itemLevel !== undefined),
  )).sort((a, b) => a - b)
  const filteredRecipes = data.craftingRecipes.filter((candidate) => {
    const item = data.items.find((i) => i.id === candidate.itemId)
    if (!item) return false
    if (itemLevelFilter !== 'all' && item.itemLevel !== Number(itemLevelFilter)) return false
    if (bossFilterId === 0) return true
    return candidate.sourceEncounterId === bossFilterId
      || candidate.components.some((component) => data.encounterLoot.some((entry) => entry.encounterId === bossFilterId && entry.itemId === component.itemId))
  })
  const recipe = filteredRecipes.find((candidate) => candidate.id === recipeId) ?? filteredRecipes[0] ?? null
  const draft = recipe ? recipeDraft[recipe.id] ?? {} : {}
  const outputItem = recipe ? data.items.find((item) => item.id === recipe.itemId) : null
  const outputName = outputItem ? outputNameByItem[outputItem.id] ?? outputItem.name : ''
  const bossComponentOptions = data.items.filter((item) => (
    item.slot === 'component'
    && bossLootItemIds.has(item.id)
    && !recipe?.components.some((component) => component.itemId === item.id)
  ))
  const addComponentIsValid = bossComponentOptions.some((item) => item.id === addItemId)

  async function saveOutputName() {
    if (!outputItem || outputName.trim() === '' || outputName === outputItem.name) return
    setSaving((prev) => ({ ...prev, [`item-name-${outputItem.id}`]: true }))
    try {
      await fetchJson(`${API}/items/${outputItem.id}`, jsonRequest('PUT', { name: outputName.trim() }))
      setData((prev) => prev ? {
        ...prev,
        items: prev.items.map((item) => item.id === outputItem.id ? { ...item, name: outputName.trim() } : item),
      } : prev)
      setOutputNameByItem((prev) => ({ ...prev, [outputItem.id]: outputName.trim() }))
    } catch (e: unknown) {
      alert(e instanceof Error ? e.message : 'Rename failed')
    } finally {
      setSaving((prev) => ({ ...prev, [`item-name-${outputItem.id}`]: false }))
    }
  }

  async function uploadItemImage(itemId: number, file: File | undefined) {
    if (!file) return
    setSaving((prev) => ({ ...prev, [`item-image-${itemId}`]: true }))
    try {
      const imageData = await fileToDataUrl(file)
      const result = await fetchJson<{ imageUrl: string }>(`${API}/items/${itemId}/image`, jsonRequest('PUT', { imageData }))
      setData((prev) => prev ? {
        ...prev,
        items: prev.items.map((item) => item.id === itemId ? { ...item, imageUrl: result.imageUrl } : item),
      } : prev)
    } catch (e: unknown) {
      alert(e instanceof Error ? e.message : 'Upload failed')
    } finally {
      setSaving((prev) => ({ ...prev, [`item-image-${itemId}`]: false }))
    }
  }

  async function saveRecipeMeta() {
    if (!recipe) return
    const next = { ...recipe, ...draft }
    setSaving((prev) => ({ ...prev, [`recipe-${recipe.id}`]: true }))
    try {
      await fetchJson(`${API}/crafting-recipes/${recipe.id}`, jsonRequest('PUT', {
        difficultyId: next.difficultyId,
        sourceDungeonId: next.sourceDungeonId,
        sourceEncounterId: next.sourceEncounterId,
      }))
      setData((prev) => prev ? {
        ...prev,
        craftingRecipes: prev.craftingRecipes.map((candidate) => candidate.id === recipe.id ? next : candidate),
      } : prev)
    } catch (e: unknown) {
      alert(e instanceof Error ? e.message : 'Save failed')
    } finally {
      setSaving((prev) => ({ ...prev, [`recipe-${recipe.id}`]: false }))
    }
  }

  async function deleteComponent(rId: number, iId: number) {
    try {
      await fetchJson(`${API}/crafting-recipes/${rId}/components/${iId}`, { method: 'DELETE' })
      setData((prev) => prev ? {
        ...prev,
        craftingRecipes: prev.craftingRecipes.map((candidate) =>
          candidate.id === rId ? { ...candidate, components: candidate.components.filter((component) => component.itemId !== iId) } : candidate),
      } : prev)
    } catch (e: unknown) {
      alert(e instanceof Error ? e.message : 'Delete failed')
    }
  }

  async function addComponent() {
    if (!addComponentIsValid || !recipe) return
    try {
      await fetchJson(`${API}/crafting-recipes/${recipe.id}/components`, jsonRequest('POST', { itemId: addItemId, quantity: addQty }))
      setData((prev) => prev ? {
        ...prev,
        craftingRecipes: prev.craftingRecipes.map((candidate) =>
          candidate.id === recipe.id
            ? { ...candidate, components: [...candidate.components.filter((component) => component.itemId !== addItemId), { itemId: addItemId, quantity: addQty }] }
            : candidate),
      } : prev)
      setAddItemId(0)
      setAddQty(1)
    } catch (e: unknown) {
      alert(e instanceof Error ? e.message : 'Add failed')
    }
  }

  async function updateQty(rId: number, iId: number, quantity: number) {
    try {
      await fetchJson(`${API}/crafting-recipes/${rId}/components`, jsonRequest('POST', { itemId: iId, quantity }))
      setData((prev) => prev ? {
        ...prev,
        craftingRecipes: prev.craftingRecipes.map((candidate) =>
          candidate.id === rId
            ? { ...candidate, components: candidate.components.map((component) => component.itemId === iId ? { ...component, quantity } : component) }
            : candidate),
      } : prev)
    } catch (e: unknown) {
      alert(e instanceof Error ? e.message : 'Update failed')
    }
  }

  return (
    <div className="admin-panel">
      <div className="admin-crafting-filters">
        <label>Item Level <select value={itemLevelFilter} onChange={(e) => setItemLevelFilter(e.target.value)}>
          <option value="all">All levels</option>
          {itemLevels.map((itemLevel) => <option key={itemLevel} value={itemLevel}>iLvl {itemLevel}</option>)}
        </select></label>
        <label>Boss <select value={bossFilterId} onChange={(e) => setBossFilterId(Number(e.target.value))}>
          <option value={0}>All bosses</option>
          {bossEncounters.map((boss) => <option key={boss.id} value={boss.id}>{boss.enemyName}</option>)}
        </select></label>
        <label>Recipe <select value={recipe?.id ?? 0} onChange={(e) => setRecipeId(Number(e.target.value))}>
          {filteredRecipes.length === 0 && <option value={0}>No matching recipes</option>}
          {filteredRecipes.map((candidate) => (
            <option key={candidate.id} value={candidate.id}>[{itemGlyph(data, candidate.itemId)}] {itemName(data, candidate.itemId)} - {encounterName(data, candidate.sourceEncounterId)}</option>
          ))}
        </select></label>
      </div>

      {outputItem && recipe && (
        <div className="admin-recipe-header">
          <img className="admin-recipe-image" src={outputItem.imageUrl || '/equipment-placeholder.svg'} alt={`${outputItem.name} icon`} />
          <div>
            <label className="admin-inline-field">Name <input value={outputName}
              onChange={(e) => setOutputNameByItem((prev) => ({ ...prev, [outputItem.id]: e.target.value }))} /></label>
            <small className="admin-item-meta">{outputItem.slot} · iLvl {outputItem.itemLevel} · {outputItem.rarity}</small>
          </div>
          <div className="admin-recipe-actions">
            <button className="primary-button" disabled={saving[`item-name-${outputItem.id}`] || outputName.trim() === '' || outputName === outputItem.name}
              onClick={saveOutputName} type="button">{saving[`item-name-${outputItem.id}`] ? 'Saving...' : 'Rename'}</button>
            <label className="boss-upload-button">{saving[`item-image-${outputItem.id}`] ? 'Uploading...' : 'Upload Art'}
              <input accept="image/png,image/jpeg,image/webp,image/gif" disabled={saving[`item-image-${outputItem.id}`]}
                onChange={(event) => uploadItemImage(outputItem.id, event.target.files?.[0])} type="file" />
            </label>
          </div>
        </div>
      )}

      {recipe && (
        <div className="admin-add-form">
          <label>Difficulty <select value={draft.difficultyId ?? recipe.difficultyId ?? 0}
            onChange={(e) => setRecipeDraft((prev) => ({ ...prev, [recipe.id]: { ...prev[recipe.id], difficultyId: Number(e.target.value) || null } }))}>
            <option value={0}>None</option>
            {data.difficulties.map((difficulty) => <option key={difficulty.id} value={difficulty.id}>{difficulty.name}</option>)}
          </select></label>
          <label>Source Dungeon <select value={draft.sourceDungeonId ?? recipe.sourceDungeonId ?? 0}
            onChange={(e) => setRecipeDraft((prev) => ({ ...prev, [recipe.id]: { ...prev[recipe.id], sourceDungeonId: Number(e.target.value) || null } }))}>
            <option value={0}>None</option>
            {data.dungeons.map((dungeon) => <option key={dungeon.id} value={dungeon.id}>{dungeon.name}</option>)}
          </select></label>
          <label>Source Boss <select value={draft.sourceEncounterId ?? recipe.sourceEncounterId ?? 0}
            onChange={(e) => setRecipeDraft((prev) => ({ ...prev, [recipe.id]: { ...prev[recipe.id], sourceEncounterId: Number(e.target.value) || null } }))}>
            <option value={0}>None</option>
            {bossEncounters.map((boss) => <option key={boss.id} value={boss.id}>{boss.enemyName}</option>)}
          </select></label>
          <button className="primary-button" onClick={saveRecipeMeta} disabled={saving[`recipe-${recipe.id}`]} type="button">
            {saving[`recipe-${recipe.id}`] ? 'Saving...' : 'Save Source'}
          </button>
        </div>
      )}

      <h3 className="admin-loot-title">Required Components</h3>
      {(!recipe || recipe.components.length === 0) && (
        <p className="admin-empty">No component requirements. Crafting and upgrades are blocked until materials are added.</p>
      )}
      <div className="admin-loot-list">
        {recipe?.components.map((comp) => (
          <div key={comp.itemId} className="admin-loot-row">
            <span className={`admin-glyph rarity-${data.items.find(i => i.id === comp.itemId)?.rarity ?? 'common'}`}>{itemGlyph(data, comp.itemId)}</span>
            <span className="admin-loot-name">{itemName(data, comp.itemId)}</span>
            <span className="admin-loot-weight">Qty: <input className="admin-qty-input" type="number" min="1" value={comp.quantity}
              onChange={(e) => updateQty(recipe.id, comp.itemId, Number(e.target.value))} /></span>
            <button className="danger-button" onClick={() => deleteComponent(recipe.id, comp.itemId)} type="button">X</button>
          </div>
        ))}
      </div>

      <details className="admin-add-section">
        <summary>Add Component</summary>
        <div className="admin-add-form">
          <label>Component <select value={addItemId} onChange={(e) => setAddItemId(Number(e.target.value))}>
            <option value={0}>Select component...</option>
            {bossComponentOptions.map((item) => (
              <option key={item.id} value={item.id}>[{item.glyph}] {item.name} ({componentBossNames(data, item.id)})</option>
            ))}
          </select></label>
          <label>Quantity <input type="number" min="1" value={addQty} onChange={(e) => setAddQty(Number(e.target.value))} /></label>
          <button className="primary-button" onClick={addComponent} disabled={!recipe || !addComponentIsValid} type="button">Add</button>
        </div>
      </details>
    </div>
  )
}

function UpgradesTab({ data, setData, setSaving, saving }: {
  data: AdminData
  setData: SetData
  setSaving: SetSaving
  saving: SavingState
}) {
  const equipment = data.items.filter((item) => item.slot !== 'component')
  const bossEncounters = data.encounters.filter((encounter) => encounter.encounterType === 'boss')
  const [bossFilterId, setBossFilterId] = useState(0)
  const [slotFilter, setSlotFilter] = useState('all')
  const [sortBy, setSortBy] = useState<'boss' | 'slot' | 'level' | 'name'>('boss')
  const [startItemId, setStartItemId] = useState(equipment[0]?.id ?? 0)
  const [draftTargets, setDraftTargets] = useState<Record<number, number>>({})

  const pathByFromItem = new Map(data.gearUpgradePaths.map((path) => [path.fromItemId, path.toItemId]))
  const recipeByItem = new Map(data.craftingRecipes.map((recipe) => [recipe.itemId, recipe]))
  const bossNameForItem = (itemId: number) => encounterName(data, recipeByItem.get(itemId)?.sourceEncounterId ?? null)
  const chainBossIds = (itemId: number) => buildUpgradeChain(itemId, pathByFromItem, equipment)
    .map((item) => recipeByItem.get(item.id)?.sourceEncounterId ?? 0)
  const filteredStarts = equipment
    .filter((item) => slotFilter === 'all' || item.slot === slotFilter)
    .filter((item) => bossFilterId === 0 || chainBossIds(item.id).includes(bossFilterId))
    .sort((left, right) => {
      if (sortBy === 'boss') return bossNameForItem(left.id).localeCompare(bossNameForItem(right.id)) || left.slot.localeCompare(right.slot) || left.itemLevel - right.itemLevel
      if (sortBy === 'slot') return left.slot.localeCompare(right.slot) || left.itemLevel - right.itemLevel || left.name.localeCompare(right.name)
      if (sortBy === 'level') return left.itemLevel - right.itemLevel || left.slot.localeCompare(right.slot) || left.name.localeCompare(right.name)
      return left.name.localeCompare(right.name)
    })
  const selectedStart = filteredStarts.find((item) => item.id === startItemId) ?? filteredStarts[0] ?? null
  const chain = selectedStart ? buildUpgradeChain(selectedStart.id, pathByFromItem, equipment) : []

  function targetOptions(item: AdminItem) {
    return equipment
      .filter((candidate) => candidate.slot === item.slot && candidate.itemLevel > item.itemLevel)
      .sort((left, right) => left.itemLevel - right.itemLevel || bossNameForItem(left.id).localeCompare(bossNameForItem(right.id)) || left.name.localeCompare(right.name))
  }

  function selectedTargetId(item: AdminItem) {
    return draftTargets[item.id] ?? pathByFromItem.get(item.id) ?? targetOptions(item)[0]?.id ?? 0
  }

  async function savePath(fromItem: AdminItem, toItemId: number) {
    if (!toItemId) return
    setSaving((prev) => ({ ...prev, [`upgrade-${fromItem.id}`]: true }))
    try {
      await fetchJson(`${API}/gear-upgrade-paths`, jsonRequest('POST', { fromItemId: fromItem.id, toItemId }))
      setData((prev) => prev ? {
        ...prev,
        gearUpgradePaths: [
          ...prev.gearUpgradePaths.filter((path) => path.fromItemId !== fromItem.id),
          { fromItemId: fromItem.id, toItemId },
        ],
      } : prev)
    } catch (e: unknown) {
      alert(e instanceof Error ? e.message : 'Save failed')
    } finally {
      setSaving((prev) => ({ ...prev, [`upgrade-${fromItem.id}`]: false }))
    }
  }

  async function deletePath(itemId: number) {
    try {
      await fetchJson(`${API}/gear-upgrade-paths/${itemId}`, { method: 'DELETE' })
      setData((prev) => prev ? {
        ...prev,
        gearUpgradePaths: prev.gearUpgradePaths.filter((path) => path.fromItemId !== itemId),
      } : prev)
    } catch (e: unknown) {
      alert(e instanceof Error ? e.message : 'Delete failed')
    }
  }

  return (
    <div className="admin-panel">
      <div className="admin-upgrade-toolbar">
        <label>Boss <select value={bossFilterId} onChange={(e) => setBossFilterId(Number(e.target.value))}>
          <option value={0}>All bosses</option>
          {bossEncounters.map((boss) => <option key={boss.id} value={boss.id}>{boss.enemyName}</option>)}
        </select></label>
        <label>Slot <select value={slotFilter} onChange={(e) => setSlotFilter(e.target.value)}>
          <option value="all">All slots</option>
          {Array.from(new Set(equipment.map((item) => item.slot))).sort().map((slot) => <option key={slot} value={slot}>{slot}</option>)}
        </select></label>
        <label>Sort <select value={sortBy} onChange={(e) => setSortBy(e.target.value as 'boss' | 'slot' | 'level' | 'name')}>
          <option value="boss">Boss</option>
          <option value="slot">Slot</option>
          <option value="level">Item level</option>
          <option value="name">Name</option>
        </select></label>
        <label>Gear Path <select value={selectedStart?.id ?? 0} onChange={(e) => setStartItemId(Number(e.target.value))}>
          {filteredStarts.length === 0 && <option value={0}>No matching gear</option>}
          {filteredStarts.map((item) => <option key={item.id} value={item.id}>{bossNameForItem(item.id)} - {itemOptionName(item)}</option>)}
        </select></label>
      </div>

      {chain.length === 0 && <p className="admin-empty">No gear matches these filters.</p>}
      <div className="admin-upgrade-chain">
        {chain.map((item, index) => {
          const options = targetOptions(item)
          const targetId = selectedTargetId(item)
          const target = equipment.find((candidate) => candidate.id === targetId) ?? null
          const targetRecipe = target ? recipeByItem.get(target.id) : null
          return (
            <div key={item.id} className="admin-upgrade-step">
              <div className="admin-upgrade-current">
                <span className={`admin-glyph rarity-${item.rarity}`}>{item.glyph}</span>
                <div>
                  <strong>{index + 1}. {item.name}</strong>
                  <small className="admin-item-meta">{item.slot} · iLvl {item.itemLevel} · {bossNameForItem(item.id)}</small>
                </div>
              </div>
              <label>Upgrades To
                <select value={targetId} onChange={(e) => setDraftTargets((prev) => ({ ...prev, [item.id]: Number(e.target.value) }))}>
                  {options.length === 0 && <option value={0}>End of path</option>}
                  {options.map((candidate) => <option key={candidate.id} value={candidate.id}>{bossNameForItem(candidate.id)} - {itemOptionName(candidate)}</option>)}
                </select>
              </label>
              <p className="admin-item-desc">
                {target
                  ? `Target requirements: ${targetRecipe && targetRecipe.components.length > 0
                    ? targetRecipe.components.map((component) => `${component.quantity}x ${itemName(data, component.itemId)}`).join(', ')
                    : 'none configured - upgrade blocked until materials are added'}`
                  : 'No next upgrade selected.'}
              </p>
              <div className="admin-edit-actions">
                <button className="primary-button" onClick={() => savePath(item, targetId)} disabled={!targetId || saving[`upgrade-${item.id}`]} type="button">
                  {saving[`upgrade-${item.id}`] ? 'Saving...' : 'Save Step'}
                </button>
                {pathByFromItem.has(item.id) && <button className="danger-button" onClick={() => deletePath(item.id)} type="button">Remove Link</button>}
              </div>
            </div>
          )
        })}
      </div>

      <details className="admin-add-section">
        <summary>All Upgrade Links ({data.gearUpgradePaths.length})</summary>
        <div className="admin-loot-list">
          {data.gearUpgradePaths
            .slice()
            .sort((left, right) => itemName(data, left.fromItemId).localeCompare(itemName(data, right.fromItemId)))
            .map((path) => (
              <div key={path.fromItemId} className="admin-loot-row">
                <span className="admin-loot-name">{itemName(data, path.fromItemId)}</span>
                <span className="admin-loot-chance">to</span>
                <span className="admin-loot-name">{itemName(data, path.toItemId)}</span>
                <button className="danger-button" onClick={() => deletePath(path.fromItemId)} type="button">X</button>
              </div>
            ))}
        </div>
      </details>
    </div>
  )
}

function ClassesTab({ data }: { data: AdminData }) {
  const [classId, setClassId] = useState(data.classes[0]?.id ?? 0)
  const selectedClass = data.classes.find((candidate) => candidate.id === classId)
    ?? data.classes[0]
    ?? null

  return (
    <div className="admin-panel">
      <div className="admin-class-layout">
        <aside className="admin-class-list">
          <p className="eyebrow">Classes</p>
          {data.classes.map((gameClass) => (
            <button
              className={selectedClass?.id === gameClass.id ? 'active' : ''}
              key={gameClass.id}
              onClick={() => setClassId(gameClass.id)}
              style={{ '--class-color': gameClass.themeColor } as CSSProperties}
              type="button"
            >
              <span>{gameClass.name[0]}</span>
              <div>
                <strong>{gameClass.name}</strong>
                <small>{gameClass.resourceName} {gameClass.maxResource}</small>
              </div>
            </button>
          ))}
        </aside>

        {selectedClass ? (
          <section className="admin-class-detail">
            <div className="admin-class-hero" style={{ '--class-color': selectedClass.themeColor } as CSSProperties}>
              <span>{selectedClass.name[0]}</span>
              <div>
                <p className="eyebrow">{selectedClass.slug}</p>
                <h2>{selectedClass.name}</h2>
                <small>{selectedClass.resourceName} pool: {selectedClass.maxResource}</small>
              </div>
              <p>{selectedClass.description}</p>
            </div>

            <section>
              <h3 className="admin-loot-title">Abilities ({selectedClass.abilities.length})</h3>
              <div className="admin-class-table">
                <div className="admin-class-table-head">
                  <span>Ability</span>
                  <span>Type</span>
                  <span>Default Strength</span>
                  <span>Cost</span>
                  <span>Cooldown</span>
                  <span>Unlock</span>
                </div>
                {selectedClass.abilities.map((ability) => (
                  <div key={ability.id} className="admin-class-row">
                    <span><i>{ability.glyph}</i><strong>{ability.name}</strong><small>{ability.description}</small></span>
                    <span>{ability.spellType}</span>
                    <span>{ability.power}</span>
                    <span>{ability.cost}</span>
                    <span>{ability.cooldown}s</span>
                    <span>Lvl {ability.unlockLevel}</span>
                  </div>
                ))}
              </div>
            </section>

            <section>
              <h3 className="admin-loot-title">Talents ({selectedClass.talents.length})</h3>
              <div className="admin-class-talent-grid">
                {selectedClass.talents.map((talent) => (
                  <article key={talent.id} className="admin-class-talent">
                    <div>
                      <span>{talent.glyph}</span>
                      <strong>{talent.name}</strong>
                    </div>
                    <small>Tier {talent.tier} · Branch {talent.branch} · Max {talent.maxRank}</small>
                    <p>{talent.description}</p>
                    <em>{talent.effectType}: {talent.effectValuePerRank}/rank</em>
                    {talent.prerequisiteName && (
                      <small>Requires {talent.prerequisiteName} rank {talent.prerequisiteRank}</small>
                    )}
                  </article>
                ))}
              </div>
            </section>
          </section>
        ) : (
          <p className="admin-empty">No classes found.</p>
        )}
      </div>
    </div>
  )
}

function Iwt2AdminTab() {
  const [metadata, setMetadata] = useState<Record<Iwt2BossId, Iwt2BossMetadata>>(IWT2_BOSS_METADATA)
  const [adminData, setAdminData] = useState<Iwt2AdminData | null>(null)
  const [error, setError] = useState('')
  const [selectedEntityId, setSelectedEntityId] = useState<string>('bulldrome')
  const [draftHp, setDraftHp] = useState<Record<string, string>>({})
  const [saving, setSaving] = useState<Record<string, boolean>>({})

  useEffect(() => {
    fetchJson<Iwt2AdminData>(`${API}/iwt2/data`)
      .then((result) => {
        setAdminData(result)
        setMetadata(applyIwt2AdminOverrides(IWT2_BOSS_METADATA, result.balanceOverrides))
      })
      .catch((e: unknown) => {
        setError(e instanceof Error ? e.message : 'Failed to load IWT2 admin data')
        setAdminData({ balanceOverrides: { bosses: {} }, bossAssets: [] })
      })
  }, [])

  const rows = createIwt2AdminRows(metadata, adminData?.bossAssets ?? [])
  const selectedRow = rows.find((row) => row.id === selectedEntityId) ?? rows[0]

  async function saveHp(row: Iwt2AdminEntityRow) {
    const value = Number(draftHp[row.id] ?? row.maxHealth)
    if (!Number.isFinite(value) || value <= 0) {
      alert('HP must be greater than zero.')
      return
    }
    const nextHealth = Math.round(value)
    setSaving((prev) => ({ ...prev, [row.id]: true }))
    try {
      await fetchJson(`${API}/iwt2/entities/${encodeURIComponent(row.id)}/hp`, jsonRequest('PUT', { maxHealth: nextHealth }))
      setMetadata((current) => {
        const boss = current[row.bossId]
        return {
          ...current,
          [row.bossId]: row.kind === 'boss'
            ? { ...boss, maxHealth: nextHealth }
            : { ...boss, birdHealth: nextHealth },
        }
      })
      setDraftHp((prev) => {
        const next = { ...prev }
        delete next[row.id]
        return next
      })
    } catch (e: unknown) {
      alert(e instanceof Error ? e.message : 'Save failed')
    } finally {
      setSaving((prev) => ({ ...prev, [row.id]: false }))
    }
  }

  return (
    <div className="admin-panel iwt2-admin-panel">
      {error && <p className="error-message">{error}</p>}
      <div className="iwt2-admin-summary">
        <span>{rows.length} mobs / bosses</span>
        <span>{adminData?.bossAssets.length ?? 0} uploaded boss assets</span>
        <span>HP edits write to IWT2 balance overrides</span>
      </div>
      <div className="iwt2-admin-layout">
        <aside className="iwt2-admin-entity-list" aria-label="IWT2 mobs and bosses">
          {rows.map((row) => (
            <button
              className={selectedRow?.id === row.id ? 'active' : ''}
              key={row.id}
              onClick={() => setSelectedEntityId(row.id)}
              type="button"
            >
              <span className="iwt2-admin-token" style={{ '--iwt2-entity-color': row.color } as CSSProperties}>{row.icon}</span>
              <span>
                <strong>{row.name}</strong>
                <small>{row.kind} · {row.maxHealth} hp · {row.attacks.length} attacks</small>
              </span>
            </button>
          ))}
        </aside>
        {selectedRow && (
          <Iwt2AdminDetail
            draftHp={draftHp}
            row={selectedRow}
            saveHp={saveHp}
            saving={saving}
            setDraftHp={setDraftHp}
          />
        )}
      </div>
    </div>
  )
}

function Iwt2AdminDetail({
  draftHp,
  row,
  saveHp,
  saving,
  setDraftHp,
}: {
  draftHp: Record<string, string>
  row: Iwt2AdminEntityRow
  saveHp: (row: Iwt2AdminEntityRow) => void
  saving: Record<string, boolean>
  setDraftHp: Dispatch<SetStateAction<Record<string, string>>>
}) {
  const value = draftHp[row.id] ?? String(row.maxHealth)
  const changed = Number(value) !== row.maxHealth

  return (
    <section className="iwt2-admin-detail">
      <header className="iwt2-admin-detail-hero">
        <span className="iwt2-admin-token" style={{ '--iwt2-entity-color': row.color } as CSSProperties}>{row.icon}</span>
        <div>
          <p className="eyebrow">{row.kind}</p>
          <h2>{row.name}</h2>
          <small>{row.slug} · source boss: {row.bossId}</small>
        </div>
      </header>

      <label className="iwt2-admin-hp">
        HP
        <input
          min="1"
          step="1"
          type="number"
          value={value}
          onChange={(event) => setDraftHp((prev) => ({ ...prev, [row.id]: event.target.value }))}
        />
        <button
          className="primary-button"
          disabled={!changed || saving[row.id]}
          onClick={() => saveHp(row)}
          type="button"
        >
          {saving[row.id] ? 'Saving...' : 'Save HP'}
        </button>
      </label>

      <section className="iwt2-admin-section">
        <div className="iwt2-admin-section-heading">
          <h3>Assets</h3>
          <span>{row.assets.length} uploaded</span>
        </div>
        <div className="iwt2-admin-assets">
          <div className="iwt2-admin-swatch" style={{ '--iwt2-entity-color': row.color } as CSSProperties}>
            <span>{row.icon}</span>
            <strong>Runtime Token</strong>
            <small>Icon and color used by current arena renderer.</small>
          </div>
          {row.assets.length > 0 ? row.assets.map((asset) => {
            const label = iwt2AssetLabel(asset.filename)
            return (
              <a href={asset.url} key={asset.filename} target="_blank" rel="noreferrer">
                <img src={asset.url} alt={`${row.name} ${label}`} />
                <strong>{label}</strong>
                <small>{asset.filename}</small>
              </a>
            )
          }) : (
            <p className="admin-item-desc">No uploaded raster asset matched. Runtime uses shape, icon, and color.</p>
          )}
        </div>
      </section>

      <section className="iwt2-admin-section">
        <div className="iwt2-admin-section-heading">
          <h3>Attacks</h3>
          <span>{row.attacks.length} mechanics</span>
        </div>
        <div className="iwt2-admin-attacks">
          <div className="iwt2-admin-attack-head">
            <span>Attack</span>
            <span>Frequency</span>
            <span>Damage</span>
          </div>
          {row.attacks.map((attack) => (
            <div className="iwt2-admin-attack-row" key={`${row.id}-${attack.name}`}>
              <strong>{attack.name}</strong>
              <span>{attack.frequency}</span>
              <span>{attack.damage}</span>
              <small>{attack.details}</small>
            </div>
          ))}
        </div>
      </section>
    </section>
  )
}

function jsonRequest(method: 'POST' | 'PUT', body: unknown): RequestInit {
  return {
    method,
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  }
}

function applyIwt2AdminOverrides(
  metadata: Record<Iwt2BossId, Iwt2BossMetadata>,
  overrides: Iwt2BalanceOverrides,
): Record<Iwt2BossId, Iwt2BossMetadata> {
  return (Object.keys(metadata) as Iwt2BossId[]).reduce((nextMetadata, bossId) => ({
    ...nextMetadata,
    [bossId]: {
      ...metadata[bossId],
      ...overrides.bosses?.[bossId],
    },
  }), {} as Record<Iwt2BossId, Iwt2BossMetadata>)
}

function createIwt2AdminRows(
  metadata: Record<Iwt2BossId, Iwt2BossMetadata>,
  bossAssets: Iwt2AdminAsset[],
): Iwt2AdminEntityRow[] {
  const bosses = Object.values(metadata).map((boss): Iwt2AdminEntityRow => ({
    assets: assetsForIwt2Boss(boss.id, bossAssets),
    attacks: bossAttacks(boss),
    bossId: boss.id,
    color: boss.color,
    icon: boss.icon,
    id: boss.id,
    kind: 'boss',
    maxHealth: boss.maxHealth,
    name: boss.name,
    slug: boss.id,
  }))
  const yian = metadata['yian-kut-ku']
  if (!yian.birdHealth) return bosses
  return [
    ...bosses,
    {
      assets: [],
      attacks: yianBirdAttacks(yian),
      bossId: yian.id,
      color: '#f0b84f',
      icon: 'v',
      id: `${yian.id}:yian-bird`,
      kind: 'mob',
      maxHealth: yian.birdHealth,
      name: 'Yian Kut Ku Hatchling',
      slug: 'yian-bird',
    },
  ]
}

function bossAttacks(boss: Iwt2BossMetadata): Iwt2AdminAttack[] {
  const attacks: Iwt2AdminAttack[] = [{
    damage: `${boss.meleeDamage}`,
    details: `Range ${boss.meleeRange}px`,
    frequency: `${formatSeconds(boss.meleeCooldown)} cooldown`,
    name: 'Melee',
  }]
  if (boss.chargeCooldown > 0) {
    attacks.push({
      damage: `${boss.chargeDamage}`,
      details: `${formatSeconds(boss.chargeWindup)} windup, ${formatSeconds(boss.chargeStunSeconds)} stun / knockdown`,
      frequency: `${formatSeconds(boss.chargeCooldown)} cooldown`,
      name: 'Charge',
    })
  }
  if (boss.slamDamage > 0) {
    attacks.push({
      damage: `${boss.slamDamage}`,
      details: `${boss.slamRadius}px radius, ${formatSeconds(boss.slamStunSeconds)} stun / knockdown`,
      frequency: 'Every 3rd charge',
      name: 'Ground Slam',
    })
  }
  if (boss.fireballCooldown && boss.fireballDamage) {
    attacks.push({
      damage: `${boss.fireballDamage} hit + ${boss.firePuddleDamage ?? 0}/tick puddle`,
      details: `${boss.firePuddleRadius ?? 0}px puddle for ${formatSeconds(boss.firePuddleSeconds ?? 0)}`,
      frequency: `${formatSeconds(boss.fireballCooldown)} cooldown`,
      name: 'Fireball',
    })
  }
  if (boss.birdWaveThresholds?.length) {
    attacks.push({
      damage: `${boss.birdContactDamage ?? 0} contact`,
      details: `${boss.birdWaveThresholds.map((threshold) => `${Math.round(threshold * 100)}%`).join(', ')} HP thresholds`,
      frequency: 'Health threshold',
      name: 'Bird Wave',
    })
  }
  return attacks
}

function yianBirdAttacks(boss: Iwt2BossMetadata): Iwt2AdminAttack[] {
  return [
    {
      damage: `${boss.birdContactDamage ?? 0}`,
      details: `Contact radius ${boss.birdRadius ?? 0}px`,
      frequency: '1.15s cooldown',
      name: 'Peck',
    },
    {
      damage: '10',
      details: `${formatSeconds(boss.birdFlightWindup ?? 0)} windup, ${formatSeconds(boss.birdStunSeconds ?? 0)} stun`,
      frequency: `${formatSeconds(boss.birdFlightCooldown ?? 0)} cooldown`,
      name: 'Flight Lane',
    },
  ]
}

function assetsForIwt2Boss(bossId: Iwt2BossId, bossAssets: Iwt2AdminAsset[]): Iwt2AdminAsset[] {
  const terms = bossId.split('-').filter((part) => part.length > 2)
  return bossAssets.filter((asset) => {
    const filename = asset.filename.toLowerCase()
    return filename.includes(bossId) || terms.some((term) => filename.includes(term))
  })
}

function iwt2AssetLabel(filename: string) {
  const normalized = filename.toLowerCase()
  if (normalized.includes('approach')) return 'Approach Illustration'
  if (normalized.includes('guardians')) return 'Party Encounter Art'
  if (normalized.includes('boss')) return 'Boss Portrait'
  return 'Primary Boss Art'
}

function formatSeconds(value: number) {
  return `${Number.isInteger(value) ? value.toFixed(0) : value.toFixed(2).replace(/0$/, '')}s`
}

function fileToDataUrl(file: File) {
  return new Promise<string>((resolve, reject) => {
    const reader = new FileReader()
    reader.addEventListener('load', () => {
      if (typeof reader.result === 'string') resolve(reader.result)
      else reject(new Error('Unable to read image.'))
    })
    reader.addEventListener('error', () => reject(reader.error ?? new Error('Unable to read image.')))
    reader.readAsDataURL(file)
  })
}

function itemName(data: AdminData, id: number | null) {
  return id ? data.items.find((item) => item.id === id)?.name ?? `Item #${id}` : 'None'
}

function itemGlyph(data: AdminData, id: number) {
  return data.items.find((item) => item.id === id)?.glyph ?? '?'
}

function itemOptionName(item: AdminItem) {
  return `[${item.glyph}] ${item.name} (${item.slot}, iLvl ${item.itemLevel})`
}

function dungeonName(data: AdminData, id: number | null) {
  return id ? data.dungeons.find((dungeon) => dungeon.id === id)?.name ?? `Dungeon #${id}` : 'No dungeon'
}

function encounterName(data: AdminData, id: number | null) {
  return id ? data.encounters.find((encounter) => encounter.id === id)?.enemyName ?? `Encounter #${id}` : 'Any boss'
}

function difficultyName(data: AdminData, id: number | null) {
  return id ? data.difficulties.find((difficulty) => difficulty.id === id)?.name ?? `Difficulty #${id}` : 'None'
}

function componentBossNames(data: AdminData, itemId: number) {
  return data.encounterLoot
    .filter((entry) => entry.itemId === itemId)
    .map((entry) => encounterName(data, entry.encounterId))
    .join(', ')
}

function buildUpgradeChain(startItemId: number, pathByFromItem: Map<number, number>, equipment: AdminItem[]) {
  const itemById = new Map(equipment.map((item) => [item.id, item]))
  const chain: AdminItem[] = []
  const seen = new Set<number>()
  let current = itemById.get(startItemId)
  while (current && !seen.has(current.id)) {
    chain.push(current)
    seen.add(current.id)
    current = itemById.get(pathByFromItem.get(current.id) ?? 0)
  }
  return chain
}

function groupBy<T>(items: T[], keyFn: (item: T) => string): Record<string, T[]> {
  const groups: Record<string, T[]> = {}
  for (const item of items) {
    const key = keyFn(item)
    if (!groups[key]) groups[key] = []
    groups[key].push(item)
  }
  return groups
}
