"use client";

/**
 * NativeAppShell — native-feeling app ljuska (top app bar + bottom tab bar +
 * suptilna route tranzicija). Renderuje se SAMO unutar Capacitor native
 * aplikacije; na web-u vraća `null` (gating preko `Capacitor.isNativePlatform()`
 * uz dinamički import — SSR markup za web ostaje bajt-identičan).
 *
 * Tabovi reuse-uju MobileNav destinacije, i18n labele (nav.*) i active-route
 * logiku, uz poštovanje locale prefiksa.
 */

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

import { nativeHaptic } from "@/components/native/CapacitorBootstrap";
import { getNativeCoords } from "@/lib/native/geo";
import type { PublicFeatureFlags } from "@/lib/data/site-settings";
import { getLocalePrefix, type Locale } from "@/lib/i18n/i18n";

const NAVY = "#0c1828";

type TabKey = "home" | "companies" | "search" | "jobs" | "places" | "magazin";

type Tab = {
  key: string;
  href: string;
  label: string;
  icon: TabKey;
};

function Icon({ name, active }: { name: TabKey; active: boolean }) {
  const common = {
    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 "home":
      return (
        <svg {...common}>
          <path d="M3 10.5 12 3l9 7.5" />
          <path d="M5 9.5V21h14V9.5" />
        </svg>
      );
    case "companies":
      return (
        <svg {...common}>
          <rect x="4" y="3" width="11" height="18" rx="1" />
          <path d="M15 8h5v13h-5" />
          <path d="M7.5 7h4M7.5 11h4M7.5 15h4" stroke={active ? NAVY : "currentColor"} />
        </svg>
      );
    case "search":
      return (
        <svg {...common} fill="none">
          <circle cx="11" cy="11" r="7" />
          <path d="m20 20-3.5-3.5" />
        </svg>
      );
    case "jobs":
      return (
        <svg {...common}>
          <rect x="3" y="7" width="18" height="13" rx="2" />
          <path d="M9 7V5a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v2" stroke={active ? NAVY : "currentColor"} fill="none" />
        </svg>
      );
    case "places":
      return (
        <svg {...common}>
          <path d="M12 21s7-5.5 7-11a7 7 0 1 0-14 0c0 5.5 7 11 7 11Z" />
          <circle cx="12" cy="10" r="2.5" stroke={active ? NAVY : "currentColor"} fill="none" />
        </svg>
      );
    case "magazin":
      return (
        <svg {...common}>
          <path d="M4 5a2 2 0 0 1 2-2h6v18H6a2 2 0 0 1-2-2z" />
          <path d="M12 3h6a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-6" />
          <path
            d="M12 3v18M7 7.5h2.5M7 11h2.5M14.5 7.5H17M14.5 11H17"
            stroke={active ? NAVY : "currentColor"}
            fill="none"
          />
        </svg>
      );
  }
}

function buildTabs(
  locale: Locale,
  features: PublicFeatureFlags,
  dictionary: Record<string, string>,
): Tab[] {
  const p = getLocalePrefix(locale);
  return [
    { key: "home", href: `${p}/`, label: dictionary["nav.home"], icon: "home" },
    {
      key: "companies",
      href: `${p}/kompanije`,
      label: dictionary["nav.companies"],
      icon: "companies",
    },
    {
      key: "search",
      href: `${p}/pretraga`,
      label: dictionary["nav.search"],
      icon: "search",
    },
    features.jobsEnabled
      ? {
          key: "jobs",
          href: `${p}/poslovi`,
          label: dictionary["nav.jobs"],
          icon: "jobs",
        }
      : {
          key: "places",
          href: `${p}/mesta`,
          label: dictionary["nav.places"],
          icon: "places",
        },
    {
      key: "magazin",
      href: `${p}/magazin`,
      label: dictionary["nav.magazine"],
      icon: "magazin",
    },
  ];
}

export function NativeAppShell({
  locale,
  dictionary,
  features = {
    jobsEnabled: true,
    storeEnabled: true,
    clientPortalEnabled: true,
    aiRecommendationsEnabled: true,
    mobileBootstrapEnabled: true,
    softLaunchEnabled: false,
  },
}: {
  locale: Locale;
  dictionary: Record<string, string>;
  features?: PublicFeatureFlags;
}) {
  const pathname = usePathname();
  const [isNative, setIsNative] = useState(false);

  useEffect(() => {
    let disposed = false;
    (async () => {
      try {
        const { Capacitor } = await import("@capacitor/core");
        if (!disposed && Capacitor.isNativePlatform()) setIsNative(true);
      } catch {
        /* no-op */
      }
    })();
    return () => {
      disposed = true;
    };
  }, []);

  if (!isNative) return null;

  const tabs = buildTabs(locale, features, dictionary);
  const prefix = getLocalePrefix(locale);
  const homeHref = `${prefix}/`;

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

  const onTab = () => {
    void nativeHaptic();
  };

  // ── Kontekstualni naslov + back affordance ───────────────────────────
  const tabRoots = new Set(tabs.map((t) => t.href));
  const isTabRoot =
    isActive(homeHref) || tabs.some((t) => t.href !== homeHref && isActive(t.href));
  const isHome = isActive(homeHref);

  function contextTitle(): string {
    const seg = pathname.replace(prefix, "").replace(/^\/+/, "").split("/");
    const root = `${prefix}/${seg[0] ?? ""}`.replace(/\/$/, "") || prefix;
    const titleMap: Record<string, string> = {
      kompanije: dictionary["nav.companies"],
      mesta: dictionary["nav.places"],
      pretraga: dictionary["nav.search"],
      poslovi: dictionary["nav.jobs"],
      magazin: dictionary["nav.magazine"],
      dogadjaji: dictionary["nav.events"],
      nekretnine: dictionary["nav.realEstate"],
      automobili: dictionary["nav.cars"],
      prodavnica: dictionary["nav.store"],
      // `nav.submit` je "Prijava" (prijava firme) — kao naslov naloga je
      // pogrešan. Ostale rute su nedostajale pa su padale na "Početna".
      nalog: dictionary["app.nav.account"] ?? "Nalog",
      favoriti: dictionary["app.nav.saved"] ?? "Sačuvano",
      kategorije: dictionary["app.nav.categories"] ?? "Kategorije",
      kategorija: dictionary["app.nav.categories"] ?? "Kategorije",
      "prijavi-se": dictionary["app.nav.login"] ?? "Prijava",
      registracija: dictionary["app.nav.register"] ?? "Registracija",
      privatnost: dictionary["app.nav.privacy"] ?? "Privatnost",
      "uslovi-koriscenja": dictionary["app.nav.terms"] ?? "Uslovi korišćenja",
    };
    const base = titleMap[seg[0] ?? ""] ?? dictionary["nav.home"];
    // Detalj strana (npr. /kompanije/<slug>) → generički "detalj" naslov.
    if (seg.length > 1 && seg[1] && !tabRoots.has(root)) {
      return base;
    }
    return base;
  }

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

  const onNearMe = async () => {
    void nativeHaptic();
    const coords = await getNativeCoords();
    if (!coords) return;
    window.location.assign(
      `${prefix}/kompanije?lat=${coords.lat}&lng=${coords.lng}&near=1`,
    );
  };

  return (
    <>
      {/* ── Native top app bar ─────────────────────────────────────────── */}
      <header className="native-topbar" role="banner">
        {isHome ? (
          <Link
            href={homeHref}
            className="native-topbar-brand"
            aria-label="BiznisPortal"
          >
            {/* 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>
          </Link>
        ) : (
          <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>
            )}
            <span className="native-topbar-title">{contextTitle()}</span>
          </div>
        )}
        <div className="native-topbar-actions">
          <button
            type="button"
            className="native-topbar-btn"
            aria-label={dictionary["nearby.find"] ?? "U mojoj blizini"}
            onClick={() => void onNearMe()}
          >
            <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="M12 21s7-5.5 7-11a7 7 0 1 0-14 0c0 5.5 7 11 7 11Z" />
              <circle cx="12" cy="10" r="2.5" />
            </svg>
          </button>
          <Link
            href={`${prefix}/pretraga`}
            className="native-topbar-btn"
            aria-label={dictionary["nav.search"]}
            onClick={onTab}
          >
            <svg
              width={22}
              height={22}
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth={1.9}
              strokeLinecap="round"
              aria-hidden
            >
              <circle cx="11" cy="11" r="7" />
              <path d="m20 20-3.5-3.5" />
            </svg>
          </Link>
          <Link
            href={`${prefix}/nalog`}
            className="native-topbar-btn"
            aria-label={dictionary["nav.submit"] ?? "Account"}
            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
            >
              <circle cx="12" cy="8" r="3.5" />
              <path d="M5 20c0-3.5 3-6 7-6s7 2.5 7 6" />
            </svg>
          </Link>
        </div>
      </header>

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

export default NativeAppShell;
