"use client";

/**
 * PartnerShell — native ljuska za BiznisPortal PARTNER app (klijenti koji
 * se oglašavaju). Isti vizuelni jezik kao consumer NativeAppShell (deli
 * .native-topbar/.native-tabbar/.native-tab CSS), ali tabovi vode u
 * KLIJENTSKI portal (`/portal/*`). Renderuje se SAMO u Capacitor native
 * ljusci I kada je varijanta `partner`. Na web-u / consumer-u → `null`.
 *
 * Portal stranice se renderuju hibridno u WebView-u (isti pristup kao
 * consumer detalj-stranice); ovde dajemo native top bar + bottom tab bar
 * + brending „Partner", i app se otvara direktno u `/portal`.
 */

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

import { nativeHaptic } from "@/components/native/CapacitorBootstrap";
import { getLocalePrefix, type Locale } from "@/lib/i18n/i18n";
import { isPartnerAuthPath } from "@/lib/native/app-variant";
import { setAppBadge } from "@/lib/native/badge";
import { usePoll } from "@/lib/native/use-poll";
import { usePartnerPreview } from "@/lib/native/preview-partner";

type TabKey = "overview" | "ads" | "inbox" | "messages" | "account";
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 "overview":
      return (
        <svg {...c}>
          <path d="M3 13h8V3H3zM13 21h8V3h-8zM3 21h8v-4H3z" />
        </svg>
      );
    case "ads":
      return (
        <svg {...c}>
          <path d="M3 11v2a1 1 0 0 0 1 1h2l5 4V6L6 10H4a1 1 0 0 0-1 1Z" />
          <path d="M16 9a4 4 0 0 1 0 6" />
        </svg>
      );
    case "inbox":
      return (
        <svg {...c}>
          <path d="M3 13h4l2 3h6l2-3h4" />
          <path d="M5 5h14l2 8v5a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1v-5z" />
        </svg>
      );
    case "messages":
      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 "account":
      return (
        <svg {...c}>
          <circle cx="12" cy="8" r="3.5" />
          <path d="M5 20c0-3.5 3-6 7-6s7 2.5 7 6" />
        </svg>
      );
  }
}

function buildTabs(prefix: string, d: Record<string, string>): Tab[] {
  const t = (k: string, fb: string) => d[k] ?? fb;
  return [
    { key: "overview", href: `${prefix}/portal`, label: t("partner.nav.overview", "Pregled") },
    { key: "ads", href: `${prefix}/portal/oglasi`, label: t("partner.nav.ads", "Oglasi") },
    { key: "inbox", href: `${prefix}/portal/upiti`, label: t("partner.nav.inbox", "Upiti") },
    { key: "messages", href: `${prefix}/portal/poruke`, label: t("partner.nav.messages", "Poruke") },
    { key: "account", href: `${prefix}/portal/plan`, label: t("partner.nav.account", "Nalog") },
  ];
}

export function PartnerShell({
  locale,
  dictionary,
  active,
}: {
  locale: Locale;
  dictionary: Record<string, string>;
  /** true samo kad je native + varijanta partner (odlučuje NativeLayer). */
  active: boolean;
}) {
  const pathname = usePathname();
  const router = useRouter();
  const prefix = getLocalePrefix(locale);
  const preview = usePartnerPreview();

  // Partner app se otvara direktno u portalu — ako smo na javnom root-u,
  // skreni u /portal (portal sam rešava auth → /portal/login).
  useEffect(() => {
    // U preview-u skretanje na /portal odbacuje `?previewPartner=` iz URL-a
    // i gasi preview (isti razlog kao u AdminShell-u).
    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}/portal`);
    }
  }, [active, preview.enabled, pathname, prefix, router]);

  /**
   * Brojači nepročitanog. Bez njih aplikacija ne zove korisnika — otvarao bi
   * je „za svaki slučaj". Isti broj ide i na ikonu aplikacije.
   */
  const [badges, setBadges] = useState<{ inbox: number; messages: number }>({
    inbox: 0,
    messages: 0,
  });

  const loadBadges = useCallback(async () => {
    try {
      const res = await fetch(
        preview.enabled
          ? "/api/app/partner/demo?kind=badges"
          : "/api/app/partner/badges",
        { cache: "no-store" },
      );
      if (!res.ok) return;
      const j = (await res.json()) as {
        inbox?: number;
        messages?: number;
        total?: number;
      };
      setBadges({ inbox: j.inbox ?? 0, messages: j.messages ?? 0 });
      void setAppBadge(j.total ?? 0);
    } catch {
      /* offline ili istekla sesija — badge nije kritičan */
    }
  }, [preview.enabled]);

  // Ređe od ekrana (30s): ljuska stoji montirana sve vreme. `immediate`
  // pokriva i prvo učitavanje, pa poseban mount efekat nije potreban.
  usePoll(loadBadges, 30_000, active, { immediate: true });

  if (!active) return null;

  const tabs = buildTabs(prefix, dictionary);
  const portalRoot = `${prefix}/portal`;

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

  // Tab-root = tačno na nekoj tab ruti (bez podstrane) → nema back dugmeta.
  const isTabRoot = tabs.some(
    (t) => pathname === t.href || pathname === `${t.href}/`,
  );
  const onTab = () => void nativeHaptic();

  /* Na login ekranu svih 5 tabova vraća na isti login — lažna navigacija.
     Uz to je traka svetla, a login strana tamna, pa je i kontrast pogrešan. */
  const isAuth = isPartnerAuthPath(pathname, prefix);

function badgeFor(key: TabKey): number {
    if (key === "inbox") return badges.inbox;
    if (key === "messages") return badges.messages;
    return 0;
  }


  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={portalRoot} className="native-topbar-brand" aria-label="BiznisPortal Partner" 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-partner-badge">Partner</span>
          </Link>
        </div>
        <div className="native-topbar-actions">
          <Link
            href={`${prefix}/portal/poruke`}
            className="native-topbar-btn"
            aria-label={dictionary["partner.nav.messages"] ?? "Poruke"}
            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="M21 15a2 2 0 0 1-2 2H8l-5 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
            </svg>
          </Link>
          <Link
            href={`${prefix}/portal/plan`}
            className="native-topbar-btn"
            aria-label={dictionary["partner.nav.account"] ?? "Nalog"}
            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>

      {isAuth ? 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={
                  badgeFor(tab.key) > 0
                    ? `${tab.label} (${badgeFor(tab.key)})`
                    : tab.label
                }
                onClick={onTab}
              >
                <Icon name={tab.key} active={act} />
                <span>{tab.label}</span>
                {badgeFor(tab.key) > 0 ? (
                  <span className="native-tab-badge" aria-hidden>
                    {badgeFor(tab.key) > 99 ? "99+" : badgeFor(tab.key)}
                  </span>
                ) : null}
              </Link>
            );
          })}
        </div>
      </nav>
      )}
    </>
  );
}

export default PartnerShell;
