import { useEffect, useMemo, useState } from "react";
import { HudSpaceScene } from "../r3f/hud/HudSpaceScene";
import { useGameSliceSession } from "../game-slice/useGameSliceSession";
import { withGameSliceSession } from "../game-slice/gameSliceState";

export function GameHudDemo() {
  const { session: sliceSession } = useGameSliceSession();
  const [modules, setModules] = useState([
    { id: "h1", name: "150mm Railgun", active: false, type: "weapon" },
    { id: "h2", name: "Missile Launcher", active: false, type: "weapon" },
    { id: "m1", name: "Shield Booster", active: false, type: "shield" },
    { id: "m2", name: "Afterburner", active: false, type: "propulsion" },
    { id: "l1", name: "Damage Control", active: true, type: "armor" },
  ]);
  const [filter, setFilter] = useState("all");
  const entities = [
    { id: "e1", name: "Asteroid Belt", type: "asteroid", dist: "12 km" },
    { id: "e2", name: "Guristas Pirate", type: "hostile", dist: "24 km" },
    { id: "e3", name: "CMDR Riker", type: "friendly", dist: "38 km" },
    { id: "e4", name: "Jita IV Station", type: "station", dist: "45 km" },
    { id: "e5", name: "Jump Gate", type: "gate", dist: "120 km" },
  ];
  const visible = useMemo(() => filter === "all" ? entities : entities.filter((entity) => entity.type === filter), [filter]);
  const afterburner = modules.some((module) => module.id === "m2" && module.active);

  useEffect(() => {
    if (!sliceSession) return;
    setModules(sliceSession.fittedModules.map((module) => ({ id: module.id, name: module.name, active: Boolean(module.active), type: module.type })));
  }, [sliceSession]);

  return (
    <div className="mx-auto max-w-content">
      <h1 style={{ marginBottom: 8 }}>Game HUD — Live Concept (R3F)</h1>
      <div style={{ position: "relative", width: "100%", height: 680, background: "#040810", borderRadius: "var(--radius-lg)", border: "1px solid var(--border)", overflow: "hidden", marginTop: "var(--sp-5)" }}>
        <HudSpaceScene targetLocked afterburner={afterburner} />
        <div style={{ position: "absolute", inset: 0, zIndex: 1, display: "grid", gridTemplateColumns: "220px 1fr 280px", gridTemplateRows: "40px 1fr 120px", pointerEvents: "none", color: "#d4dce8" }}>
          <div style={{ gridColumn: "1 / -1", display: "flex", alignItems: "center", gap: 14, padding: "0 14px", background: "rgba(8,12,20,0.82)", pointerEvents: "auto" }}>
            <a href="/docs/overview" style={{ color: "var(--fg-dim)" }}>DOCS</a>
            <strong>JITA</strong>
            <span style={{ color: "#22c55e" }}>1.0 SEC</span>
            <span>{sliceSession ? `${sliceSession.currentSystemId.toUpperCase()} · ${sliceSession.dockedStationName ?? "IN SPACE"}` : "USS ENTERPRISE"}</span>
            {sliceSession && <span style={{ color: "#f0a030" }}>ISK {sliceSession.wallet.toLocaleString()}</span>}
            <span style={{ marginLeft: "auto", color: afterburner ? "#22d3ee" : "#94a3b8" }}>SPD {afterburner ? "280" : "0"} m/s</span>
            {sliceSession && <button onClick={() => { window.location.href = withGameSliceSession("/docs/demos/game-loop", sliceSession.id); }}>Return to Loop</button>}
          </div>
          <div style={{ padding: 10, pointerEvents: "auto" }}>
            {["SHIELD", "ARMOR", "HULL", "CAP"].map((label, index) => (
              <div key={label} style={{ background: "rgba(15,22,35,0.85)", border: "1px solid var(--border)", borderRadius: 8, padding: 10, marginBottom: 8 }}>
                <div style={{ fontSize: 10, color: "#94a3b8" }}>{label}</div>
                <div style={{ height: 6, background: "#111827", borderRadius: 999, overflow: "hidden" }}>
                  <div style={{ width: `${[100, 92, 100, 78][index]}%`, height: "100%", background: ["#22d3ee", "#f0a030", "#22c55e", "#a78bfa"][index] }} />
                </div>
              </div>
            ))}
          </div>
          <div style={{ padding: 10, pointerEvents: "auto", gridColumn: 3 }}>
            <div style={{ background: "rgba(15,22,35,0.85)", border: "1px solid var(--border)", borderRadius: 8, overflow: "hidden" }}>
              <div style={{ padding: 10, borderBottom: "1px solid var(--border)" }}>Overview</div>
              <div style={{ padding: 8 }}>
                {["all", "hostile", "asteroid", "station"].map((item) => <button key={item} onClick={() => setFilter(item)} style={{ marginRight: 6 }}>{item}</button>)}
              </div>
              {sliceSession && (
                <div style={{ padding: "7px 10px", borderTop: "1px solid rgba(255,255,255,0.05)", color: "#f0a030", fontSize: 12 }}>
                  Objective: {sliceSession.activeObjectiveId.replace(/_/g, " ")}
                </div>
              )}
              {visible.map((entity) => (
                <div key={entity.id} style={{ display: "flex", justifyContent: "space-between", padding: "7px 10px", borderTop: "1px solid rgba(255,255,255,0.05)" }}>
                  <span>{entity.name}</span><span>{entity.dist}</span>
                </div>
              ))}
            </div>
          </div>
          <div style={{ gridColumn: "1 / -1", pointerEvents: "auto", display: "flex", justifyContent: "center", alignItems: "center", gap: 8, background: "rgba(8,12,20,0.72)" }}>
            {sliceSession && (
              <>
                <button onClick={() => { window.location.href = withGameSliceSession("/docs/demos/starmap", sliceSession.id); }}>Star Map</button>
                <button onClick={() => { window.location.href = withGameSliceSession("/docs/demos/movement", sliceSession.id); }}>Movement</button>
                <button onClick={() => { window.location.href = withGameSliceSession("/docs/demos/combat", sliceSession.id); }}>Combat</button>
              </>
            )}
            {modules.map((module) => (
              <button key={module.id} onClick={() => setModules((prev) => prev.map((item) => item.id === module.id ? { ...item, active: !item.active } : item))} style={{ minWidth: 120, color: module.active ? "#22d3ee" : undefined }}>
                {module.name}<br /><small>{module.active ? "ACTIVE" : "OFFLINE"}</small>
              </button>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}
