import { useEffect, useReducer, useRef } from "react";
import { CombatScene } from "../../r3f/combat/CombatScene";
import { combatReducer, initialCombatState } from "../../r3f/combat/combatState";
import type { SliceEvent } from "../types";
import { metricLabel, sliceButton, slicePanel } from "./sliceStyles";

function MiniBar({ label, value, color }: { label: string; value: number; color: string }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "68px 1fr 38px", gap: 8, alignItems: "center", fontSize: 10 }}>
      <span style={{ color, fontFamily: "var(--font-mono)" }}>{label}</span>
      <div style={{ height: 6, background: "rgba(255,255,255,0.06)", borderRadius: 999, overflow: "hidden" }}>
        <div style={{ width: `${Math.max(0, Math.min(100, value))}%`, height: "100%", background: color }} />
      </div>
      <span style={{ textAlign: "right", color: "#94a3b8", fontVariantNumeric: "tabular-nums" }}>{value.toFixed(0)}%</span>
    </div>
  );
}

export function SliceCombatStage({ emit }: { emit: (event: SliceEvent) => void }) {
  const [state, dispatch] = useReducer(combatReducer, initialCombatState);
  const victoryEmitted = useRef(false);

  const emitVictory = () => {
    if (victoryEmitted.current) return;
    victoryEmitted.current = true;
    emit({ type: "combat.victory", targetName: "Guristas Pirata", bounty: 7500, loot: [{ item: "Damaged Railgun", category: "loot", quantity: 1, unitPrice: 1800 }] });
    emit({ type: "xp.awarded", skill: "Gunnery", amount: 45 });
  };

  useEffect(() => {
    if (state.enemy.hull > 0) return;
    emitVictory();
    // emitVictory intentionally closes over the stable ref and emit callback.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [emit, state.enemy.hull]);

  return (
    <section className="slice-loop-panel" style={{ ...slicePanel, position: "relative", height: "100%", minHeight: 0, overflow: "hidden" }}>
      <CombatScene state={state} dispatch={dispatch} />
      <div style={{ position: "absolute", inset: 12, zIndex: 1, pointerEvents: "none", display: "grid", gridTemplateColumns: "minmax(180px, 230px) 1fr minmax(180px, 230px)", gridTemplateRows: "auto 1fr auto", gap: 8 }}>
        <div style={{ ...slicePanel, padding: 12, pointerEvents: "auto" }}>
          <div style={metricLabel}>USS ENTERPRISE</div>
          <MiniBar label="SHIELD" value={state.player.shields} color="#22d3ee" />
          <MiniBar label="ARMOR" value={state.player.armor} color="#f0a030" />
          <MiniBar label="HULL" value={state.player.hull} color="#22c55e" />
        </div>
        <div style={{ ...slicePanel, padding: 12, pointerEvents: "auto", gridColumn: 3 }}>
          <div style={metricLabel}>Guristas Pirata</div>
          <MiniBar label="SHIELD" value={state.enemy.shields} color="#22d3ee" />
          <MiniBar label="ARMOR" value={state.enemy.armor} color="#f0a030" />
          <MiniBar label="HULL" value={state.enemy.hull} color="#ef4444" />
          <button style={{ ...sliceButton, width: "100%", marginTop: 10 }} onClick={() => dispatch({ type: "startLock" })}>Lock Target</button>
          <button style={{ ...sliceButton, width: "100%", marginTop: 8, border: "1px dashed rgba(148,163,184,0.52)", color: "#94a3b8", fontSize: 10 }} onClick={emitVictory}>Debug Resolve</button>
        </div>
        <div style={{ ...slicePanel, padding: 10, display: "flex", gap: 8, justifyContent: "center", flexWrap: "wrap", pointerEvents: "auto", gridColumn: "1 / -1", alignSelf: "end" }}>
          {state.modules.map((module) => (
            <button key={module.id} style={{ ...sliceButton, border: `1px solid ${module.color}`, color: module.cooldown > 0 ? "#64748b" : module.color }} onClick={() => dispatch({ type: "castModule", id: module.id, playerPosition: [-16, 0, 2], enemyPosition: [18, 0, -2], elapsed: performance.now() / 1000 })}>
              {module.key}. {module.name} {module.cooldown > 0 ? `${module.cooldown.toFixed(1)}s` : ""}
            </button>
          ))}
        </div>
      </div>
    </section>
  );
}
