'use client';

import { useShallow } from 'zustand/react/shallow';
import { useCombatStore, useManaStore, usePrestigeStore, useGameStore, fmt, computeMaxMana, computeRegen } from '@/lib/game/stores';
import { computeDisciplineEffects } from '@/lib/game/effects/discipline-effects';
import { getUnifiedEffects } from '@/lib/game/effects';
import { useCraftingStore } from '@/lib/game/stores/craftingStore';
import { SpireHeader } from './SpireHeader';
import { RoomDisplay } from './RoomDisplay';
import { SpireCombatControls } from './SpireCombatControls';
import { SpireActivityLog } from './SpireActivityLog';
import { SpireManaDisplay } from './SpireManaDisplay';
import { DebugName } from '@/components/game/debug/debug-context';

// ─── Derived Stats Hook ──────────────────────────────────────────────────────

function useSpireStats(prestigeUpgrades: Record<string, number>, equippedInstances: Record<string, string | null>, equipmentInstances: Record<string, import('@/lib/game/types').EquipmentInstance>) {
  let disciplineEffects: ReturnType<typeof computeDisciplineEffects> | null = null;
  try {
    disciplineEffects = computeDisciplineEffects();
  } catch {
    // If discipline state is corrupted, proceed without discipline effects
    disciplineEffects = { bonuses: {}, multipliers: {}, specials: new Set(), meditationCapBonus: 0, conversions: {} };
  }

  const upgradeEffects = getUnifiedEffects({
    skillUpgrades: {},
    skillTiers: {},
    equippedInstances,
    equipmentInstances,
  });

  const maxMana = computeMaxMana({
    skills: {},
    prestigeUpgrades,
    skillUpgrades: {},
    skillTiers: {},
  }, upgradeEffects, disciplineEffects);

  const baseRegen = computeRegen({
    skills: {},
    prestigeUpgrades,
    skillUpgrades: {},
    skillTiers: {},
    attunements: {},
  }, upgradeEffects, disciplineEffects);

  return { maxMana, baseRegen };
}

// ─── Main Component ───────────────────────────────────────────────────────────

export function SpireCombatPage() {
  // ─── Spec: read room-aware state from combat store ───────────────────────
  const {
    currentFloor,
    castProgress,
    isDescending,
    currentRoom,
    activityLog,
    climbDirection,
    currentRoomIndex,
    roomsPerFloor,
    isDescentComplete,
    startFloor,
    exitSpireMode,
    startClimbUp,
    startClimbDown,
    addActivityLog,
    setAction,
    skipNonCombatRoom,
    stayLongerInRoom,
  } = useCombatStore(useShallow((s) => ({
    currentFloor: s.currentFloor,
    castProgress: s.castProgress,
    isDescending: s.isDescending,
    currentRoom: s.currentRoom,
    activityLog: s.activityLog,
    climbDirection: s.climbDirection,
    currentRoomIndex: s.currentRoomIndex,
    roomsPerFloor: s.roomsPerFloor,
    isDescentComplete: s.isDescentComplete,
    startFloor: s.startFloor,
    exitSpireMode: s.exitSpireMode,
    startClimbUp: s.startClimbUp,
    startClimbDown: s.startClimbDown,
    addActivityLog: s.addActivityLog,
    setAction: s.setAction,
    skipNonCombatRoom: s.skipNonCombatRoom,
    stayLongerInRoom: s.stayLongerInRoom,
  })));

  const { rawMana, elements } = useManaStore(useShallow((s) => ({
    rawMana: s.rawMana,
    elements: s.elements,
  })));

  const { prestigeUpgrades, insight } = usePrestigeStore(useShallow((s) => ({
    prestigeUpgrades: s.prestigeUpgrades,
    insight: s.insight,
  })));

  const { equippedInstances, equipmentInstances } = useCraftingStore(useShallow((s) => ({
    equippedInstances: s.equippedInstances,
    equipmentInstances: s.equipmentInstances,
  })));

  // ─── Combat spec §10: read current in-game time ──────────────────────────
  const day = useGameStore((s) => s.day);
  const hour = useGameStore((s) => s.hour);

  const { maxMana, baseRegen } = useSpireStats(prestigeUpgrades, equippedInstances, equipmentInstances);

  const handleClimbUp = () => {
    startClimbUp();
    addActivityLog('floor_transition', `⬆️ Climbing to floor ${currentFloor + 1}...`);
  };

  const handleClimbDown = () => {
    if (currentFloor <= 1) return;
    startClimbDown();
    addActivityLog('floor_transition', `⬇️ Descending to floor ${currentFloor - 1}...`);
  };

  const handleExitSpire = () => {
    exitSpireMode();
    addActivityLog('floor_transition', '🚪 Exited the Spire.');
  };

  return (
    <DebugName name="SpireCombatPage">
    <div className="min-h-screen bg-gray-950 flex flex-col">
      <header className="sticky top-0 z-50 bg-gray-900/95 border-b border-gray-800 px-4 py-2">
        <div className="flex items-center justify-between">
          <h1 className="text-lg font-bold text-amber-400 tracking-wider">🏔️ SPIRE</h1>
          <div className="text-xs text-gray-500">
            Floor {currentFloor} · Insight: {fmt(insight)}
          </div>
        </div>
      </header>

      <main className="flex-1 p-4 space-y-4 max-w-7xl mx-auto w-full">
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
          <div className="lg:col-span-2">
            <SpireHeader
              currentFloor={currentFloor}
              roomsCleared={currentRoomIndex}
              totalRooms={roomsPerFloor}
              onClimbUp={handleClimbUp}
              onClimbDown={handleClimbDown}
              onExitSpire={handleExitSpire}
              isDescending={isDescending}
            />
          </div>
          <div>
            <SpireManaDisplay maxMana={maxMana} effectiveRegen={baseRegen} />
          </div>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
          <div className="lg:col-span-2">
            <RoomDisplay
              floorState={currentRoom}
              floor={currentFloor}
              roomIndex={currentRoomIndex}
              totalRooms={roomsPerFloor}
              day={day}
              hour={hour}
              onSkip={skipNonCombatRoom}
              onStayLonger={stayLongerInRoom}
            />
          </div>
          <div>
            <SpireCombatControls castProgress={castProgress} />
          </div>
        </div>

        <SpireActivityLog activityLog={activityLog} maxEntries={20} />
      </main>
    </div>
    </DebugName>
  );
}
