"use client";

import { useSyncExternalStore } from "react";

// Temporaneo: per provare sull'iPhone se lo scudo toglie la sfumatura in alto, e vedere
// se l'app installata usa già la barra di stato nuova (serve toglierla e rimetterla nella home)
const VARIANTS = [
  { id: "scudo", label: "Scudo" },
  { id: "html", label: "Blu 1" },
  { id: "header", label: "Blu 2" },
  { id: "off", label: "Off" },
] 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 insetTop() {
  const probe = document.createElement("div");
  probe.style.cssText = "position:fixed;top:0;height:env(safe-area-inset-top,0px);visibility:hidden";
  document.body.appendChild(probe);
  const h = probe.getBoundingClientRect().height;
  probe.remove();
  return h;
}
const readDiag = () => {
  const app = matchMedia("(display-mode: standalone)").matches || ("standalone" in navigator && navigator.standalone === true);
  if (!app) return "Safari";
  const meta = document.querySelector('meta[name="apple-mobile-web-app-status-bar-style"]')?.getAttribute("content");
  return `${insetTop() > 0 ? "app, barra trasparente" : "app, barra opaca"} · meta della pagina: ${meta}`;
};

function pick(id: string) {
  document.documentElement.dataset.barra = id;
  try {
    localStorage.setItem("barra", id);
  } catch {}
}

export function ScudoSwitch() {
  const current = useSyncExternalStore(subscribe, read, () => "scudo");
  const diag = useSyncExternalStore(() => () => {}, readDiag, () => "");
  return (
    <div className="flex flex-col items-center gap-1.5 text-xs text-muted">
      <div className="flex flex-wrap items-center justify-center gap-1.5">
        <span>Prova barra iOS:</span>
        {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>
      {diag && <span>{diag}</span>}
    </div>
  );
}
