import { useEffect, useState } from "react";
import { Copy, Check, Globe } from "lucide-react";

/** Shows the user's public IP so they can whitelist it in Delta. */
export function IpBadge() {
  const [ip, setIp] = useState<string | null>(null);
  const [err, setErr] = useState<string | null>(null);
  const [copied, setCopied] = useState(false);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      // ipify has permissive CORS; fall back to ipapi.co if it fails
      const sources = ["https://api.ipify.org?format=json", "https://ipapi.co/json/"];
      for (const url of sources) {
        try {
          const r = await fetch(url);
          const j = await r.json();
          const found = j.ip ?? j.query;
          if (found && !cancelled) { setIp(String(found)); return; }
        } catch { /* try next */ }
      }
      if (!cancelled) setErr("Could not detect IP");
    })();
    return () => { cancelled = true; };
  }, []);

  const copy = async () => {
    if (!ip) return;
    await navigator.clipboard.writeText(ip);
    setCopied(true);
    setTimeout(() => setCopied(false), 1500);
  };

  return (
    <div className="rounded-lg border border-border/60 bg-background/40 p-3">
      <div className="flex items-center gap-2 text-xs text-muted-foreground">
        <Globe className="h-3.5 w-3.5" aria-hidden />
        Your public IP
      </div>
      <div className="mt-1.5 flex items-center gap-2">
        <code className="num rounded bg-muted/40 px-2 py-1 text-sm font-semibold">
          {ip ?? (err ? "—" : "Detecting…")}
        </code>
        {ip && (
          <button
            type="button"
            onClick={copy}
            aria-label="Copy IP to clipboard"
            className="inline-flex h-7 items-center gap-1 rounded border border-border/60 px-2 text-xs hover:bg-muted/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
          >
            {copied ? <Check className="h-3 w-3 text-bull" /> : <Copy className="h-3 w-3" />}
            {copied ? "Copied" : "Copy"}
          </button>
        )}
      </div>
      <p className="mt-2 text-[11px] leading-relaxed text-muted-foreground">
        Whitelist this IP on your Delta API key <strong>only if you run the self-hosted backend from this
        machine</strong>. The in-browser Lovable proxy runs on Cloudflare — its IP changes and can't be
        whitelisted. Easiest fix: remove IP restrictions on the key.
      </p>
      {err && <p className="mt-1 text-[11px] text-bear">{err}</p>}
    </div>
  );
}
