"use client";

/**
 * AdminShell — native ljuska za BiznisPortal ADMIN app (interni ops alat).
 * Isti vizuelni jezik kao consumer/partner native ljuska (deli
 * .native-topbar/.native-tabbar/.native-tab CSS), ali tabovi vode u
 * ADMIN web (`/admin/*`). Renderuje se SAMO u Capacitor native ljusci
 * I kada je varijanta `admin`. Na web-u / drugim varijantama → `null`.
 *
 * Admin app se otvara direktno u dashboard-u; ako smo na javnom root-u,
 * skreće u /admin (admin layout sam rešava auth → /admin/login).
 */

import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { useEffect } from "react";

import { nativeHaptic } from "@/components/native/CapacitorBootstrap";
import { getLocalePrefix, type Locale } from "@/lib/i18n/i18n";
import { useAdminPreview } from "@/lib/native/preview-admin";

type TabKey = "dashboard" | "chat" | "submissions" | "invoices" | "clients";
type Tab = { key: TabKey; href: string; label: string };

function Icon({ name, active }: { name: TabKey; active: boolean }) {
  const c = {
    width: 22,
    height: 22,
    viewBox: "0 0 24 24",
    fill: active ? "currentColor" : "none",
    stroke: "currentColor",
    strokeWidth: 1.8,
    strokeLinecap: "round" as const,
    strokeLinejoin: "round" as const,
    "aria-hidden": true,
  };
  switch (name) {
    case "dashboard":
      return (
        <svg {...c}>
          <path d="M3 13h8V3H3zM13 21h8V3h-8zM3 21h8v-4H3z" />
        </svg>
      );
    case "chat":
      return (
        <svg {...c}>
          <path d="M21 15a2 2 0 0 1-2 2H8l-5 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
        </svg>
      );
    case "submissions":
      return (
        <svg {...c}>
          <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
          <polyline points="14 2 14 8 20 8" />
          <line x1="9" y1="15" x2="15" y2="15" />
          <line x1="9" y1="11" x2="15" y2="11" />
        </svg>
      );
    case "invoices":
      return (
        <svg {...c}>
          <rect x="3" y="4" width="18" height="16" rx="2" />
          <line x1="3" y1="10" x2="21" y2="10" />
          <path d="M8 14h5M8 17h8" />
        </svg>
      );
    case "clients":
      return (
        <svg {...c}>
          <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" />
          <circle cx="9" cy="7" r="4" />
          <path d="M23 21v-2a4 4 0 0 0-3-3.87" />
          <path d="M16 3.13a4 4 0 0 1 0 7.75" />
        </svg>
      );
  }
}

function buildTabs(prefix: string, d: Record<string, string>): Tab[] {
  const t = (k: string, fb: string) => d[k] ?? fb;
  return [
    { key: "dashboard", href: `${prefix}/admin`, label: t("admin.nav.dashboard", "Pregled") },
    { key: "chat", href: `${prefix}/admin/live-chat`, label: t("admin.nav.chat", "Chat") },
    { key: "submissions", href: `${prefix}/admin/prijave`, label: t("admin.nav.submissions", "Prijave") },
    { key: "invoices", href: `${prefix}/admin/naplata`, label: t("admin.nav.invoices", "Računi") },
    { key: "clients", href: `${prefix}/admin/portal-nalozi`, label: t("admin.nav.clients", "Klijenti") },
  ];
}

export function AdminShell({
  locale,
  dictionary,
  active,
}: {
  locale: Locale;
  dictionary: Record<string, string>;
  /** true samo kad je native + varijanta admin. */
  active: boolean;
}) {
  const pathname = usePathname();
  const router = useRouter();
  const prefix = getLocalePrefix(locale);
  const preview = useAdminPreview();

  // Admin app se otvara direktno u /admin — ako smo na javnom root-u,
  // skreni u /admin (admin layout sam rešava auth → /admin/login).
  useEffect(() => {
    // U browser preview-u skretanje na /admin bi odbacilo `?previewAdmin=`
    // iz URL-a i ugasilo preview.
    if (!active || preview.enabled) return;
    const path =
      prefix && pathname.startsWith(prefix)
        ? pathname.slice(prefix.length)
        : pathname;
    const norm = path.replace(/\/+$/, "") || "/";
    if (norm === "/" || norm === "") {
      router.replace(`${prefix}/admin`);
    }
  }, [active, preview.enabled, pathname, prefix, router]);

  if (!active) return null;

  const tabs = buildTabs(prefix, dictionary);
  const adminRoot = `${prefix}/admin`;

  function isActive(href: string) {
    if (href === adminRoot) {
      return pathname === adminRoot || pathname === `${adminRoot}/`;
    }
    return pathname === href || pathname.startsWith(`${href}/`);
  }

  /* Na login ekranu svih 5 tabova samo vraća na isti login — traka je
     lažna navigacija. Kriju se dok admin nije ulogovan. */
  const isLogin = pathname.replace(/\/+$/, "").endsWith("/admin/login");

  const isTabRoot = tabs.some(
    (t) => pathname === t.href || pathname === `${t.href}/`,
  );
  const onTab = () => void nativeHaptic();

  const goBack = () => {
    void nativeHaptic();
    if (window.history.length > 1) window.history.back();
  };

  return (
    <>
      <header className="native-topbar" role="banner">
        <div className="native-topbar-lead">
          {!isTabRoot && (
            <button
              type="button"
              className="native-topbar-btn native-topbar-back"
              aria-label={dictionary["nav.back"] ?? "Nazad"}
              onClick={goBack}
            >
              <svg width={22} height={22} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" aria-hidden>
                <path d="m15 18-6-6 6-6" />
              </svg>
            </button>
          )}
          <Link href={adminRoot} className="native-topbar-brand" aria-label="BiznisPortal Admin" onClick={onTab}>
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img src="/icons/app-icon.png" alt="" width={28} height={28} className="native-topbar-logo" />
            <span className="native-topbar-word">BiznisPortal</span>
            <span className="native-admin-badge">Admin</span>
          </Link>
        </div>
        <div className="native-topbar-actions">
          <Link
            href={`${prefix}/admin/notifikacije`}
            className="native-topbar-btn"
            aria-label={dictionary["admin.nav.notifications"] ?? "Notifikacije"}
            onClick={onTab}
          >
            <svg width={22} height={22} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.9} strokeLinecap="round" strokeLinejoin="round" aria-hidden>
              <path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9" />
              <path d="M13.73 21a2 2 0 0 1-3.46 0" />
            </svg>
          </Link>
        </div>
      </header>

      {isLogin ? null : (
      <nav className="native-tabbar" aria-label={dictionary["nav.mainNav"] ?? "Glavna navigacija"}>
        <div className="native-tabbar-inner">
          {tabs.map((tab) => {
            const act = isActive(tab.href);
            return (
              <Link
                key={tab.key}
                href={tab.href}
                className="native-tab"
                data-active={act ? "true" : "false"}
                aria-current={act ? "page" : undefined}
                aria-label={tab.label}
                onClick={onTab}
              >
                <Icon name={tab.key} active={act} />
                <span>{tab.label}</span>
              </Link>
            );
          })}
        </div>
      </nav>
      )}
    </>
  );
}

export default AdminShell;
