import { useState } from "react";
import LabFixtureLoad from "../LabFixtureLoad";
import { LAB_PURPOSE_NOTE } from "../validationFixtures";
import { apiUrl } from "../api";
import { useToast } from "../toast";

export default function Emulate() {
  const toast = useToast();
  const [hex, setHex] = useState("8C");
  const [out, setOut] = useState("");
  const [busy, setBusy] = useState(false);

  const send = async () => {
    setBusy(true);
    setOut("");
    try {
      const r = await fetch(apiUrl("/api/nfc/emulate-raw"), {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ hex: hex.replace(/\s/g, "") }),
      });
      const t = await r.text();
      if (!r.ok) {
        throw new Error(t);
      }
      try {
        setOut(JSON.stringify(JSON.parse(t), null, 2));
      } catch {
        setOut(t);
      }
      toast("PN532 emulation command sent");
    } catch (e) {
      toast(String(e), "err");
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="glass space-y-6 p-6">
      <h1 className="font-display text-2xl font-bold">Card emulation (PN532 target mode)</h1>
      <p className="text-sm text-slate-400">
        Sends <code className="text-bubble-mint">TgInitAsTarget</code> (0x8C) and following bytes as one PN532
        payload. Real card emulation depends on UID length, timing, and reader behavior — this is an{" "}
        <strong>expert / experimental</strong> path. Build the byte sequence from NXP UM0701 or community
        examples. Wrong frames can leave the RF stack busy; power-cycle if the field acts stuck.
      </p>
      <p className="text-[11px] leading-relaxed text-slate-500">{LAB_PURPOSE_NOTE}</p>
      <LabFixtureLoad mode="emulate" onApplyHex={(h) => setHex(h)} />
      <label className="block text-sm">
        Command + parameters (hex, no spaces required)
        <textarea
          value={hex}
          onChange={(e) => setHex(e.target.value)}
          rows={4}
          className="mt-1 w-full rounded-2xl border border-white/10 bg-black/25 p-3 font-mono text-xs"
        />
      </label>
      <button
        type="button"
        disabled={busy}
        onClick={send}
        className="rounded-2xl bg-bubble-accent px-6 py-2 font-semibold text-white disabled:opacity-50"
      >
        {busy ? "Sending…" : "Send emulate frame"}
      </button>
      {out && (
        <pre className="max-h-80 overflow-auto rounded-2xl border border-white/10 bg-black/40 p-4 text-xs text-slate-200">
          {out}
        </pre>
      )}
    </div>
  );
}
