const APP_VERSION = "50c23f2";

// ── User dropdown menu ────────────────────────────────────────────────────────

function UserMenu({ username, onLogout }) {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);

  React.useEffect(() => {
    function handleClick(e) {
      if (ref.current && !ref.current.contains(e.target)) setOpen(false);
    }
    document.addEventListener("mousedown", handleClick);
    return () => document.removeEventListener("mousedown", handleClick);
  }, []);

  return (
    <div className="relative" ref={ref}>
      <button
        onClick={() => setOpen((o) => !o)}
        className="flex items-center gap-1.5 text-sm text-gray-700 bg-[#e8d4a0] hover:bg-[#dcc88a] rounded-full pl-1 pr-3 py-1 transition-colors"
      >
        <Avatar username={username} size={24} />
        <span>{username}</span>
        <svg
          className={`w-3.5 h-3.5 transition-transform ${open ? "rotate-180" : ""}`}
          fill="none"
          stroke="currentColor"
          viewBox="0 0 24 24"
        >
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            strokeWidth={2}
            d="M19 9l-7 7-7-7"
          />
        </svg>
      </button>
      {open && (
        <div className="absolute right-0 mt-1.5 bg-white rounded-lg shadow-lg border border-gray-100 py-1 min-w-[130px] z-50">
          <button
            onClick={() => {
              setOpen(false);
              onLogout();
            }}
            className="w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-50 transition-colors"
          >
            Esci
          </button>
        </div>
      )}
    </div>
  );
}

// ── Hash routing ──────────────────────────────────────────────────────────────

function useRoute() {
  const [hash, setHash] = React.useState(window.location.hash || "#/receipts");
  React.useEffect(() => {
    const h = () => setHash(window.location.hash || "#/receipts");
    window.addEventListener("hashchange", h);
    return () => window.removeEventListener("hashchange", h);
  }, []);

  if (hash.startsWith("#/receipts/") && hash.endsWith("/correct")) {
    const id = hash.slice(11, -8);
    return { page: "correct", id };
  }
  if (hash.startsWith("#/receipts/"))
    return { page: "receipt", id: hash.slice(11) };
  if (hash.startsWith("#/new-receipt")) return { page: "new-receipt" };
  if (hash.startsWith("#/items")) return { page: "items" };
  if (hash.startsWith("#/basket")) return { page: "basket" };
  if (hash.startsWith("#/stats")) return { page: "stats" };
  if (hash.startsWith("#/item/"))
    return { page: "item-details", barcode: hash.slice(7) };
  if (hash.startsWith("#/item")) return { page: "item-details", barcode: "" };
  return { page: "receipts" };
}

// ── Auth state ────────────────────────────────────────────────────────────────

function useAuth() {
  // null = not authed, undefined = loading, object = { user_id, username }
  const [auth, setAuth] = React.useState(undefined);

  React.useEffect(() => {
    fetch("/auth/me")
      .then((r) => (r.ok ? r.json() : null))
      .then(setAuth)
      .catch(() => setAuth(null));
  }, []);

  async function logout() {
    await fetch("/auth/logout", { method: "POST" });
    setAuth(null);
  }

  return { auth, setAuth, logout };
}

// ── App shell ─────────────────────────────────────────────────────────────────

function App() {
  const route = useRoute();
  const { auth, setAuth, logout } = useAuth();

  const onReceipts = route.page === "receipts" || route.page === "receipt";
  const onItems = route.page === "items";
  const onBasket = route.page === "basket";
  const onStats = route.page === "stats";

  // Loading — check session before rendering anything
  if (auth === undefined) {
    return (
      <div className="min-h-screen bg-gray-100 flex items-center justify-center">
        <div className="text-gray-400 text-sm">Caricamento…</div>
      </div>
    );
  }

  // Not authenticated — show login form
  if (auth === null) {
    return <Login onLogin={setAuth} />;
  }

  if (route.page === "correct") {
    return (
      <div className="min-h-screen bg-gray-100">
        <ReceiptCorrect id={route.id} />
      </div>
    );
  }

  if (route.page === "new-receipt") {
    return (
      <div className="min-h-screen bg-gray-100 px-4 py-4 md:py-6">
        <ManualReceiptCreate />
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-100 flex flex-col">
      {/* Top bar */}
      <header className="bg-[#fcf3df] sticky top-0 z-10 shadow-md">
        {/* Mobile: brand + logout */}
        <div className="md:hidden flex items-center justify-between px-4 py-3">
          <a href="/" className="shrink-0">
            <img
              src="/static/logo-text.png"
              className="h-8 w-auto"
              alt="Spesa"
            />
          </a>
          <UserMenu username={auth.username} onLogout={logout} />
        </div>
        {/* Desktop: brand + nav */}
        <div className="hidden md:flex items-center gap-8 px-6 py-3 max-w-3xl mx-auto">
          <a href="/" className="shrink-0">
            <img
              src="/static/logo-text.png"
              className="h-8 w-auto"
              alt="Spesa"
            />
          </a>
          <a
            href="#/receipts"
            className={`text-sm text-gray-700 transition-all px-3 py-1.5 rounded-full ${onReceipts ? "bg-[#e8d4a0] font-medium" : "opacity-75 hover:opacity-100 hover:bg-[#f0e4c0]"}`}
          >
            Scontrini
          </a>
          <a
            href="#/items"
            className={`text-sm text-gray-700 transition-all px-3 py-1.5 rounded-full ${onItems ? "bg-[#e8d4a0] font-medium" : "opacity-75 hover:opacity-100 hover:bg-[#f0e4c0]"}`}
          >
            Prodotti
          </a>
          <a
            href="#/basket"
            className={`text-sm text-gray-700 transition-all px-3 py-1.5 rounded-full ${onBasket ? "bg-[#e8d4a0] font-medium" : "opacity-75 hover:opacity-100 hover:bg-[#f0e4c0]"}`}
          >
            Spesa
          </a>
          <a
            href="#/stats"
            className={`text-sm text-gray-700 transition-all px-3 py-1.5 rounded-full ${onStats ? "bg-[#e8d4a0] font-medium" : "opacity-75 hover:opacity-100 hover:bg-[#f0e4c0]"}`}
          >
            Statistiche
          </a>
          <div className="ml-auto">
            <UserMenu username={auth.username} onLogout={logout} />
          </div>
        </div>
      </header>

      <main className="flex-1 max-w-2xl w-full mx-auto px-4 py-4 md:py-6 pb-24 md:pb-6">
        {route.page === "receipts" && <ReceiptsList />}
        {route.page === "receipt" && <ReceiptDetail id={route.id} />}
        {route.page === "items" && <ItemsPage />}
        {route.page === "basket" && <BasketPage />}
        {route.page === "stats" && <StatsPage />}
        {route.page === "item-details" && (
          <ItemDetailsPage key={route.barcode} initialBarcode={route.barcode} />
        )}
      </main>

      {/* Footer */}
      <footer className="w-full px-4 py-4 pb-24 md:pb-4 text-center text-xs text-gray-400 bg-gray-100 border-t border-gray-200 mt-auto">
        <p>
          Dati prodotto da{" "}
          <a
            href="https://openfoodfacts.org"
            target="_blank"
            rel="noopener noreferrer"
            className="text-[#2d7a3a] hover:underline"
          >
            Open Food Facts
          </a>
          , disponibile sotto{" "}
          <a
            href="https://opendatacommons.org/licenses/odbl/"
            target="_blank"
            rel="noopener noreferrer"
            className="text-[#2d7a3a] hover:underline"
          >
            ODbL
          </a>{" "}
          e{" "}
          <a
            href="https://opendatacommons.org/licenses/dbcl/"
            target="_blank"
            rel="noopener noreferrer"
            className="text-[#2d7a3a] hover:underline"
          >
            DBCL
          </a>
          .
        </p>
        <p className="mt-1">
          Immagini prodotti ©{" "}
          <a
            href="https://openfoodfacts.org"
            target="_blank"
            rel="noopener noreferrer"
            className="text-[#2d7a3a] hover:underline"
          >
            Open Food Facts
          </a>{" "}
          collaboratori, sotto{" "}
          <a
            href="https://creativecommons.org/licenses/by-sa/3.0/"
            target="_blank"
            rel="noopener noreferrer"
            className="text-[#2d7a3a] hover:underline"
          >
            CC BY-SA 3.0
          </a>
          .
        </p>
        <p className="mt-2 text-gray-300">
          © 2026 Spesa <br />
          Version: {APP_VERSION[0] === "_" ? "dev" : `${APP_VERSION}`}
        </p>
      </footer>

      {/* Mobile bottom tab bar */}
      <nav className="md:hidden fixed bottom-0 inset-x-0 bg-white border-t border-gray-200 flex z-50">
        <a
          href="#/receipts"
          className={`flex-1 flex flex-col items-center py-3 gap-0.5 text-xs font-medium transition-colors ${
            onReceipts ? "text-[#2d7a3a]" : "text-gray-400"
          }`}
        >
          <svg
            className="w-6 h-6"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"
            />
          </svg>
          Scontrini
        </a>
        <a
          href="#/items"
          className={`flex-1 flex flex-col items-center py-3 gap-0.5 text-xs font-medium transition-colors ${
            onItems ? "text-[#2d7a3a]" : "text-gray-400"
          }`}
        >
          <svg
            className="w-6 h-6"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z"
            />
          </svg>
          Prodotti
        </a>
        <a
          href="#/basket"
          className={`flex-1 flex flex-col items-center py-3 gap-0.5 text-xs font-medium transition-colors ${
            onBasket ? "text-[#2d7a3a]" : "text-gray-400"
          }`}
        >
          <svg
            className="w-6 h-6"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"
            />
          </svg>
          Spesa
        </a>
        <a
          href="#/stats"
          className={`flex-1 flex flex-col items-center py-3 gap-0.5 text-xs font-medium transition-colors ${
            onStats ? "text-[#2d7a3a]" : "text-gray-400"
          }`}
        >
          <svg
            className="w-6 h-6"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"
            />
          </svg>
          Statistiche
        </a>
      </nav>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
