"use client";

import Link from "next/link";
import { useState, useEffect, useCallback } from "react";

export default function VaultNetworkPage() {
  const [btcUsd, setBtcUsd] = useState<number | null>(null);
  const [btcErr, setBtcErr] = useState<string | null>(null);
  const [broadcast, setBroadcast] = useState("");
  const [terminalLines, setTerminalLines] = useState<string[]>([]);
  const [sessionToken, setSessionToken] = useState("");

  const fetchBtc = useCallback(async () => {
    try {
      const res = await fetch("https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd", {
        cache: "no-store",
      });
      if (!res.ok) throw new Error("rate http");
      const j = (await res.json()) as { bitcoin?: { usd?: number } };
      const p = j.bitcoin?.usd;
      if (p && Number.isFinite(p)) {
        setBtcUsd(p);
        setBtcErr(null);
      } else throw new Error("bad payload");
    } catch {
      setBtcErr("Could not load BTC/USD");
    }
  }, []);

  useEffect(() => {
    setSessionToken(
      typeof crypto !== "undefined" && "randomUUID" in crypto ? crypto.randomUUID().slice(0, 13) : String(Date.now()),
    );
  }, []);

  useEffect(() => {
    void fetchBtc();
    const id = setInterval(() => void fetchBtc(), 60_000);
    return () => clearInterval(id);
  }, [fetchBtc]);

  useEffect(() => {
    const interval = setInterval(() => {
      const logs = [
        `[TOR] circuit refresh (synthetic tick — not your live Tor log)`,
        `[NGINX] 200 GET /market from 127.0.0.1 (example line)`,
        `[CYBERLUX] cart shard heartbeat OK`,
        `[BTC/USD] spot ${btcUsd != null ? `$${btcUsd.toLocaleString(undefined, { maximumFractionDigits: 0 })}` : "…"}`,
      ];
      setTerminalLines((prev) => [...prev.slice(-15), logs[Math.floor(Math.random() * logs.length)]!]);
    }, 4500);
    return () => clearInterval(interval);
  }, [btcUsd]);

  const handleBroadcast = () => {
    localStorage.setItem("shadow_broadcast", broadcast);
    setTerminalLines((prev) => [...prev, `[ADMIN] GLOBAL BROADCAST: ${broadcast || "(empty)"}`]);
  };

  const btcDisplay =
    btcUsd != null
      ? btcUsd.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })
      : btcErr ?? "…";

  return (
    <div className="flex min-h-screen flex-col overflow-hidden bg-[#050000] p-6 font-mono text-[#00ff41]">
      <header className="mb-6 flex flex-wrap items-center justify-between gap-4 border-b border-[#00ff41]/30 pb-4">
        <div className="flex items-center gap-4">
          <div className="h-3 w-3 animate-ping rounded-full bg-red-600" />
          <h1 className="text-xl font-black tracking-tighter text-white uppercase">Network digest</h1>
        </div>
        <div className="flex flex-wrap gap-6 text-[10px] uppercase tracking-widest opacity-80">
          <div>UI session: {sessionToken || "—"}</div>
          <div className="text-green-500">Not live Tor admin — decorative console</div>
        </div>
      </header>

      <div className="grid flex-1 grid-cols-12 gap-6">
        <div className="col-span-12 space-y-6 lg:col-span-4">
          <div className="border border-[#00ff41]/20 bg-black p-6 shadow-[0_0_20px_rgba(0,255,65,0.05)]">
            <h2 className="mb-4 text-xs uppercase opacity-50">Public spot (CoinGecko)</h2>
            <div className="flex items-end justify-between">
              <span className="text-[10px] uppercase">BTC/USD</span>
              <span className="text-2xl font-bold text-white">${btcDisplay}</span>
            </div>
            <p className="mt-3 text-[10px] uppercase leading-relaxed text-[#00ff41]/50">
              Refreshes about every minute. For deposits use{" "}
              <Link href="/account/add-funds" className="text-[#7dd3fc] underline">
                Add funds
              </Link>
              .
            </p>
          </div>

          <div className="border border-red-600/40 bg-black p-6 shadow-[0_0_20px_rgba(255,0,0,0.1)]">
            <h2 className="mb-4 text-xs font-bold uppercase text-red-600">Broadcast stub</h2>
            <textarea
              value={broadcast}
              onChange={(e) => setBroadcast(e.target.value)}
              className="mb-4 h-24 w-full resize-none border border-red-900 bg-[#111] p-3 text-xs text-red-500 focus:outline-none"
              placeholder="Message stored in localStorage key shadow_broadcast…"
            />
            <button
              type="button"
              onClick={handleBroadcast}
              className="w-full bg-red-900/90 py-2 text-xs font-bold uppercase text-red-100 transition-all hover:bg-red-800"
            >
              Store broadcast (local)
            </button>
          </div>

          <div className="relative h-48 overflow-hidden border border-[#00ff41]/20 bg-black p-6">
            <h2 className="mb-4 text-xs uppercase opacity-50">Node map</h2>
            <p className="relative z-10 text-[8px] leading-relaxed opacity-80">
              Decorative. Real topology is Tor + nginx on your host — see README / DEPLOY.md.
            </p>
          </div>
        </div>

        <div className="col-span-12 flex flex-col gap-6 lg:col-span-8">
          <div className="flex min-h-[200px] flex-1 flex-col overflow-hidden border border-[#00ff41]/20 bg-black p-4 text-[10px]">
            <div className="mb-2 flex items-center justify-between border-b border-[#00ff41]/10 pb-2">
              <span className="uppercase opacity-50">Chatter console</span>
              <span className="animate-pulse text-green-500">● FEED</span>
            </div>
            <div className="scrollbar-hide flex-1 space-y-1 overflow-y-auto">
              {terminalLines.map((line, i) => (
                <div key={`${i}-${line.slice(0, 24)}`} className={line.includes("[ADMIN]") ? "font-bold text-red-500" : ""}>
                  {line}
                </div>
              ))}
              <div className="animate-pulse">_</div>
            </div>
          </div>

          <div className="border border-[#00ff41]/20 bg-black/80 p-4 text-[10px] uppercase tracking-widest opacity-50">
            <Link href="/dashboard" className="text-[#7dd3fc] hover:underline">
              Dashboard
            </Link>
            {" · "}
            <Link href="/checkout" className="text-[#7dd3fc] hover:underline">
              Checkout
            </Link>
            {" · "}
            <Link href="/" className="text-[#7dd3fc] hover:underline">
              Hub
            </Link>
          </div>
        </div>
      </div>
    </div>
  );
}
