import { useEffect, useReducer, useRef } from "react";
import { CombatScene } from "../r3f/combat/CombatScene";
import { combatReducer, initialCombatState } from "../r3f/combat/combatState";
import { useGameSliceSession } from "../game-slice/useGameSliceSession";
import { withGameSliceSession } from "../game-slice/gameSliceState";

const panel = {
  background: "rgba(15,22,35,0.88)",
  border: "1px solid var(--border)",
  borderRadius: "8px",
  backdropFilter: "blur(8px)",
} as const;

function Bar({ 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: "var(--fg-dim)", fontVariantNumeric: "tabular-nums" }}>{value.toFixed(0)}%</span>
    </div>
  );
}

export function CombatDemo() {
  const [state, dispatch] = useReducer(combatReducer, initialCombatState);
  const { session: sliceSession, emit } = useGameSliceSession();
  const victoryEmitted = useRef(false);
  const lockPct = state.lockState === "locked" ? 100 : state.lockProgress * 100;
  const overloaded = state.overloadedUntil > 0;

  useEffect(() => {
    if (!sliceSession || victoryEmitted.current || state.enemy.hull > 0) 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 });
  }, [sliceSession, state.enemy.hull, emit]);

  return (
    <div style={{ position: "relative", width: "100%", height: "100vh", minHeight: 680, overflow: "hidden", background: "#040810", color: "#d4dce8", fontFamily: "var(--font-mono)", cursor: "crosshair" }}>
      <CombatScene state={state} dispatch={dispatch} />
      <div style={{ position: "absolute", inset: 0, zIndex: 1, display: "grid", gridTemplateColumns: "220px 1fr 250px", gridTemplateRows: "42px 1fr auto", gap: 8, padding: 8, pointerEvents: "none" }}>
        <div style={{ gridColumn: "1 / -1", display: "flex", alignItems: "center", gap: 12, pointerEvents: "auto", ...panel, padding: "0 12px" }}>
          <button onClick={() => { window.location.href = "/docs/overview"; }}>DOCS</button>
          <strong style={{ color: "#f0a030" }}>COMBAT</strong>
          <span>Lock: {state.lockState.toUpperCase()} {lockPct.toFixed(0)}%</span>
          {overloaded && <span style={{ color: "#f0a030" }}>OVERLOAD</span>}
          <span style={{ marginLeft: "auto", color: state.lockState === "locked" ? "#22c55e" : "#94a3b8" }}>{state.lockState === "locked" ? "TARGET LOCKED" : "TARGETING STANDBY"}</span>
          {sliceSession && <button onClick={() => { window.location.href = withGameSliceSession("/docs/demos/game-loop", sliceSession.id); }}>Return to Loop</button>}
        </div>

        <div style={{ pointerEvents: "auto", display: "flex", flexDirection: "column", gap: 8 }}>
          <div style={{ ...panel, padding: 12 }}>
            <h3 style={{ margin: "0 0 10px", fontSize: 12 }}>USS ENTERPRISE</h3>
            <Bar label="SHIELD" value={state.player.shields} color="#22d3ee" />
            <Bar label="ARMOR" value={state.player.armor} color="#f0a030" />
            <Bar label="HULL" value={state.player.hull} color="#22c55e" />
            <Bar label="ENERGY" value={state.player.energy} color="#a78bfa" />
          </div>
          <div style={{ ...panel, padding: 12 }}>
            <h3 style={{ margin: "0 0 10px", fontSize: 12 }}>POWER</h3>
            {(["weapons", "shields", "engines", "aux"] as const).map((system) => (
              <div key={system} style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 8 }}>
                <button onClick={() => dispatch({ type: "adjustPower", system, delta: -1 })}>-</button>
                <span style={{ width: 72, textTransform: "uppercase" }}>{system}</span>
                <span style={{ flex: 1, color: "#f0a030" }}>{"|".repeat(state.power[system])}</span>
                <button onClick={() => dispatch({ type: "adjustPower", system, delta: 1 })}>+</button>
              </div>
            ))}
            <button style={{ width: "100%", marginTop: 8 }} onClick={() => dispatch({ type: "startLock" })}>Lock Target</button>
          </div>
        </div>

        <div style={{ alignSelf: "start", justifySelf: "center", pointerEvents: "auto", ...panel, padding: "10px 16px", textAlign: "center" }}>
          <div style={{ color: "#f0a030", fontSize: 11, marginBottom: 6 }}>{state.lockState === "locked" ? "DOGFIGHT ACTIVE" : state.lockState === "locking" ? "ACQUIRING LOCK" : "IDLE"}</div>
          <div style={{ width: 260, height: 6, background: "rgba(255,255,255,0.08)", borderRadius: 999, overflow: "hidden" }}>
            <div style={{ width: `${lockPct}%`, height: "100%", background: "#f0a030" }} />
          </div>
        </div>

        <div style={{ pointerEvents: "auto", display: "flex", flexDirection: "column", gap: 8 }}>
          <div style={{ ...panel, padding: 12 }}>
            <h3 style={{ margin: "0 0 10px", fontSize: 12 }}>Guristas Pirata</h3>
            <Bar label="SHIELD" value={state.enemy.shields} color="#22d3ee" />
            <Bar label="ARMOR" value={state.enemy.armor} color="#f0a030" />
            <Bar label="HULL" value={state.enemy.hull} color="#ef4444" />
            <Bar label="WEAPONS" value={state.enemy.weapons} color="#fb7185" />
            <Bar label="ENGINES" value={state.enemy.engines} color="#22c55e" />
            {sliceSession && state.enemy.hull <= 0 && (
              <button onClick={() => { window.location.href = withGameSliceSession("/docs/demos/game-loop", sliceSession.id); }} style={{ width: "100%", marginTop: 10 }}>
                Victory Logged - Return to Loop
              </button>
            )}
          </div>
          <div style={{ ...panel, padding: 12 }}>
            <h3 style={{ margin: "0 0 10px", fontSize: 12 }}>Subsystem Target</h3>
            {(["hull", "shields", "weapons", "engines"] as const).map((subsystem) => (
              <button key={subsystem} onClick={() => dispatch({ type: "setSubsystem", subsystem })} style={{ margin: "0 6px 6px 0", color: state.subsystem === subsystem ? "#f0a030" : undefined }}>
                {subsystem}
              </button>
            ))}
          </div>
        </div>

        <div style={{ gridColumn: "1 / -1", display: "grid", gridTemplateColumns: "1fr 360px", gap: 8, pointerEvents: "auto" }}>
          <div style={{ ...panel, padding: 10, display: "flex", gap: 8, justifyContent: "center" }}>
            {state.modules.map((module) => (
              <button key={module.id} onClick={() => dispatch({ type: "castModule", id: module.id, playerPosition: [-16, 0, 2], enemyPosition: [18, 0, -2], elapsed: performance.now() / 1000 })} style={{ minWidth: 92, borderColor: module.color, color: module.cooldown > 0 ? "#64748b" : module.color }}>
                <div>{module.key}. {module.name}</div>
                <small>{module.cooldown > 0 ? `${module.cooldown.toFixed(1)}s` : "READY"}</small>
              </button>
            ))}
          </div>
          <div style={{ ...panel, padding: 10, maxHeight: 130, overflow: "auto", fontSize: 10 }}>
            {state.log.slice().reverse().map((entry, index) => (
              <div key={`${entry.time}-${index}`} style={{ color: entry.color }}><span style={{ color: "#64748b" }}>{entry.time}</span> {entry.msg}</div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}
