"use client";

/**
 * NativeOfflineScreen — full-screen brendirani offline state, SAMO unutar
 * Capacitor native aplikacije. Na web-u rano izlazi i ne renderuje ništa
 * (web koristi postojeći OfflineToast; web ostaje bajt-identičan).
 *
 * Sluša @capacitor/network; CapacitorBootstrap već emituje window
 * `online`/`offline` evente na native promenu, pa slušamo i njih kao
 * dodatni signal. Auto-dismiss na reconnect.
 */

import { useEffect, useState } from "react";

export function NativeOfflineScreen({
  dictionary,
}: {
  dictionary?: Record<string, string>;
}) {
  const t = (k: string, fb: string) => dictionary?.[k] ?? fb;
  const [isNative, setIsNative] = useState(false);
  const [offline, setOffline] = useState(false);

  useEffect(() => {
    let disposed = false;
    const cleanups: Array<() => void> = [];

    (async () => {
      try {
        const { Capacitor } = await import("@capacitor/core");
        if (disposed || !Capacitor.isNativePlatform()) return;
        setIsNative(true);

        // DEV bypass: emulator (10.0.2.2 / localhost) — wifi često stoji u
        // "checking for internet access" stanju koji Capacitor Network
        // prijavljuje kao offline, iako 10.0.2.2:3000 radi savršeno.
        // U dev modu potpuno preskačemo Capacitor Network plugin i
        // oslanjamo se samo na window 'online'/'offline' (browser navigator).
        const isDev =
          window.location.hostname === "10.0.2.2" ||
          window.location.hostname === "localhost" ||
          window.location.hostname.endsWith(".local");
        if (isDev) return;

        const { Network } = await import("@capacitor/network");
        const status = await Network.getStatus();
        if (!disposed) setOffline(!status.connected);

        const handle = await Network.addListener(
          "networkStatusChange",
          (s) => setOffline(!s.connected),
        );
        cleanups.push(() => handle.remove().catch(() => undefined));
      } catch {
        /* no-op */
      }
    })();

    const isDevOrigin =
      typeof window !== "undefined" &&
      (window.location.hostname === "10.0.2.2" ||
        window.location.hostname === "localhost" ||
        window.location.hostname.endsWith(".local"));
    const onOffline = () => {
      // Dev: ignoriši window 'offline' event — emulator wifi često nije
      // reliable, a 10.0.2.2 i dalje radi.
      if (!isDevOrigin) setOffline(true);
    };
    const onOnline = () => setOffline(false);
    window.addEventListener("offline", onOffline);
    window.addEventListener("online", onOnline);
    cleanups.push(() => {
      window.removeEventListener("offline", onOffline);
      window.removeEventListener("online", onOnline);
    });

    return () => {
      disposed = true;
      for (const fn of cleanups) {
        try {
          fn();
        } catch {
          /* no-op */
        }
      }
    };
  }, []);

  if (!isNative || !offline) return null;

  return (
    <div className="native-offline" role="alertdialog" aria-live="assertive">
      <div className="native-offline-card">
        {/* eslint-disable-next-line @next/next/no-img-element */}
        <img
          src="/icons/app-icon.png"
          alt="BiznisPortal"
          width={64}
          height={64}
          className="native-offline-logo"
        />
        <svg
          className="native-offline-icon"
          width="38"
          height="38"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth="1.8"
          strokeLinecap="round"
          strokeLinejoin="round"
          aria-hidden="true"
        >
          <path d="M1 1l22 22" />
          <path d="M16.7 11.7a8 8 0 0 1 3 1.6" />
          <path d="M5 12.6a11 11 0 0 1 5.6-2.8" />
          <path d="M2 8.8A16 16 0 0 1 8 5.7M14 5.3a16 16 0 0 1 8 3.5" />
          <path d="M8.5 16.1a4 4 0 0 1 5 .2" />
          <path d="M12 20h.01" />
        </svg>
        <h2 className="native-offline-title">
          {t("offline.title", "Nema internet veze")}
        </h2>
        <p className="native-offline-desc">
          {t(
            "offline.desc",
            "Proverite vezu i pokušajte ponovo. Vraćamo vas čim budete online.",
          )}
        </p>
        <button
          type="button"
          className="native-offline-retry"
          onClick={() => window.location.reload()}
        >
          {t("offline.retry", "Pokušaj ponovo")}
        </button>
      </div>
    </div>
  );
}

export default NativeOfflineScreen;
