"use client";

import { useEffect, useState, useSyncExternalStore } from "react";

// Temporaneo: diagnostica della barra di stato sull'iPhone. Ogni apertura, cambio di variante e
// segnalazione viene salvata in diag_log (vedi /api/diag), così si legge cosa cambia davvero.
const VARIANTS = [
  { id: "scudo", label: "Finale" },
  { id: "off", label: "Off" },
] as const;

const OBSERVATIONS = ["Sfocata", "Nitida", "Barra bianca", "Barra nera", "Barra blu", "Barra quadretti"] as const;

const read = () => document.documentElement.dataset.barra ?? "scudo";
const subscribe = (cb: () => void) => {
  const obs = new MutationObserver(cb);
  obs.observe(document.documentElement, { attributes: true, attributeFilter: ["data-barra"] });
  return () => obs.disconnect();
};

function probe(css: string) {
  const el = document.createElement("div");
  el.style.cssText = `position:fixed;top:0;left:0;visibility:hidden;${css}`;
  document.body.appendChild(el);
  const h = el.getBoundingClientRect().height;
  el.remove();
  return h;
}

function local(key: string, make: () => string) {
  try {
    let v = localStorage.getItem(key);
    if (!v) {
      v = make();
      localStorage.setItem(key, v);
    }
    return v;
  } catch {
    return "senza-storage";
  }
}

function snapshot() {
  const html = document.documentElement;
  const header = document.querySelector("header");
  const shield = document.querySelector(".scudo-barra-ios");
  const bg = (el: Element | null) => (el ? getComputedStyle(el).backgroundColor : null);
  return {
    commit: process.env.NEXT_PUBLIC_COMMIT,
    variante: read(),
    path: location.pathname,
    standalone: matchMedia("(display-mode: standalone)").matches,
    navigatorStandalone: (navigator as Navigator & { standalone?: boolean }).standalone ?? null,
    metaPagina: document.querySelector('meta[name="apple-mobile-web-app-status-bar-style"]')?.getAttribute("content"),
    insetTop: probe("height:env(safe-area-inset-top,0px)"),
    insetBottom: probe("height:env(safe-area-inset-bottom,0px)"),
    screen: `${screen.width}x${screen.height}`,
    inner: `${innerWidth}x${innerHeight}`,
    visual: visualViewport ? `${Math.round(visualViewport.width)}x${Math.round(visualViewport.height)}` : null,
    dpr: devicePixelRatio,
    scuro: matchMedia("(prefers-color-scheme: dark)").matches,
    scrollY: Math.round(scrollY),
    bgHtml: bg(html),
    bgBody: bg(document.body),
    bgHeader: bg(header),
    headerPosition: header ? getComputedStyle(header).position : null,
    scudo: shield ? getComputedStyle(shield).display : "assente",
    primiFigliBody: [...document.body.children].slice(0, 3).map((e) => `${e.tagName.toLowerCase()}.${e.className}`.slice(0, 40)),
    ua: navigator.userAgent,
  };
}

function send(event: string, extra: Record<string, unknown> = {}) {
  const install = local("diag-install", () => Math.random().toString(36).slice(2, 8));
  const primaVolta = local("diag-installata-il", () => new Date().toISOString());
  const body = JSON.stringify({ install, event, data: { ...snapshot(), primaVolta, ...extra } });
  return fetch("/api/diag", { method: "POST", headers: { "Content-Type": "application/json" }, body, keepalive: true }).then((r) => r.ok);
}

function pick(id: string) {
  document.documentElement.dataset.barra = id;
  try {
    localStorage.setItem("barra", id);
  } catch {}
  // dopo un attimo, così il campionamento di iOS ha già visto la variante nuova
  setTimeout(() => send("variante"), 600);
}

export function ScudoSwitch() {
  const current = useSyncExternalStore(subscribe, read, () => "scudo");
  const install = useSyncExternalStore(
    () => () => {},
    () => local("diag-install", () => Math.random().toString(36).slice(2, 8)),
    () => "",
  );
  const [sent, setSent] = useState<string | null>(null);

  useEffect(() => {
    send("apertura");
    const onVisible = () => document.visibilityState === "visible" && send("ritorno");
    document.addEventListener("visibilitychange", onVisible);
    return () => document.removeEventListener("visibilitychange", onVisible);
  }, []);

  async function observe(what: string) {
    const ok = await send("segnalazione", { osservazione: what });
    setSent(ok ? `Inviato: ${what}` : "Invio non riuscito");
    setTimeout(() => setSent(null), 2000);
  }

  return (
    <div className="flex w-full max-w-md flex-col items-center gap-2 rounded-card border-2 border-dashed border-line p-3 text-xs text-muted">
      <span className="font-bold">Diagnostica barra iOS · installazione {install} · {process.env.NEXT_PUBLIC_COMMIT}</span>
      <div className="flex flex-wrap items-center justify-center gap-1.5">
        {VARIANTS.map((v) => (
          <button
            key={v.id}
            type="button"
            onClick={() => pick(v.id)}
            aria-pressed={current === v.id}
            className={`min-w-9 rounded-chip px-2.5 py-1.5 font-bold ${current === v.id ? "bg-accent text-accent-ink" : "ring-1 ring-line"}`}
          >
            {v.label}
          </button>
        ))}
      </div>
      <span>Cosa vedi in alto adesso?</span>
      <div className="flex flex-wrap items-center justify-center gap-1.5">
        {OBSERVATIONS.map((o) => (
          <button key={o} type="button" onClick={() => observe(o)} className="rounded-chip px-2.5 py-1.5 font-bold ring-1 ring-line">
            {o}
          </button>
        ))}
      </div>
      {sent && <span className="font-bold text-ink">{sent}</span>}
    </div>
  );
}
