"use client";

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

import type { PortalNavIcon, PortalShellContext } from "@/lib/portal/shell";
import { PortalTopbarTools } from "@/components/portal/PortalTopbarTools";

/* ── SVG ikone (inline, currentColor) ───────────────────────────── */
const ICONS: Record<PortalNavIcon, ReactNode> = {
  dashboard: (
    <>
      <rect x="3" y="3" width="7" height="9" rx="1" />
      <rect x="14" y="3" width="7" height="5" rx="1" />
      <rect x="14" y="12" width="7" height="9" rx="1" />
      <rect x="3" y="16" width="7" height="5" rx="1" />
    </>
  ),
  analytics: (
    <>
      <line x1="18" y1="20" x2="18" y2="10" />
      <line x1="12" y1="20" x2="12" y2="4" />
      <line x1="6" y1="20" x2="6" y2="14" />
    </>
  ),
  inbox: (
    <>
      <path d="M6 4v8a6 6 0 0 0 12 0V4" />
      <path d="M6 4h4" />
      <path d="M14 4h4" />
    </>
  ),
  message: (
    <path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8z" />
  ),
  question: (
    <>
      <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
      <path d="M10.5 9.5a1.5 1.5 0 0 1 3 0c0 1-1.5 1.5-1.5 2.5" />
      <line x1="12" y1="14.5" x2="12.01" y2="14.5" />
    </>
  ),
  calendar: (
    <>
      <rect x="3" y="4" width="18" height="18" rx="2" />
      <line x1="16" y1="2" x2="16" y2="6" />
      <line x1="8" y1="2" x2="8" y2="6" />
      <line x1="3" y1="10" x2="21" y2="10" />
    </>
  ),
  boost: (
    <>
      <path d="M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z" />
      <path d="M12 15l-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z" />
    </>
  ),
  megaphone: (
    <>
      <path d="M3 11l18-5v12L3 14z" />
      <path d="M11.6 16.8a3 3 0 1 1-5.8-1.6" />
    </>
  ),
  pipeline: <path d="M22 3H2l8 9.46V19l4 2v-8.54z" />,
  exchange: (
    <>
      <polyline points="17 1 21 5 17 9" />
      <path d="M3 11V9a4 4 0 0 1 4-4h14" />
      <polyline points="7 23 3 19 7 15" />
      <path d="M21 13v2a4 4 0 0 1-4 4H3" />
    </>
  ),
  rfq: (
    <>
      <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="13" x2="15" y2="13" />
      <line x1="9" y1="17" x2="13" y2="17" />
    </>
  ),
  shield: (
    <>
      <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" />
      <polyline points="9 12 11 14 15 10" />
    </>
  ),
  invoice: (
    <>
      <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" />
      <path d="M12 11v6" />
      <path d="M9 14h6" />
    </>
  ),
  profile: (
    <>
      <circle cx="12" cy="8" r="4" />
      <path d="M4 21c0-4 4-6 8-6s8 2 8 6" />
    </>
  ),
  award: (
    <>
      <circle cx="12" cy="8" r="6" />
      <path d="M8.5 13.5L7 22l5-3 5 3-1.5-8.5" />
    </>
  ),
  store: (
    <>
      <circle cx="9" cy="21" r="1" />
      <circle cx="20" cy="21" r="1" />
      <path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6" />
    </>
  ),
  institution: (
    <>
      <path d="M3 21h18" />
      <path d="M5 21V10h14v11" />
      <path d="M3 10l9-6 9 6" />
      <path d="M9 14v3" />
      <path d="M15 14v3" />
    </>
  ),
  spark: (
    <>
      <path d="M9 11l3 3L22 4" />
      <path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11" />
    </>
  ),
};

function Icon({ name }: { name: PortalNavIcon }) {
  return (
    <svg
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth={2}
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      {ICONS[name]}
    </svg>
  );
}

/** Naslov strane iz putanje — za top bar. */
const TITLES: Record<string, string> = {
  "/portal": "Komandni centar",
  "/portal/optimizator": "Analitika i AI optimizacija",
  "/portal/upiti": "Inbox upita",
  "/portal/poruke": "Poruke",
  "/portal/pitanja": "Pitanja na profilu",
  "/portal/rezervacije": "Rezervacije",
  "/portal/boost": "Boost",
  "/portal/oglasi": "Oglasi i kampanje",
  "/portal/crm": "Mini CRM",
  "/portal/lead-exchange": "Berza lidova",
  "/portal/zahtevi": "Zahtevi za ponudu",
  "/portal/verifikacija": "Verifikacija",
  "/portal/plan": "Plan i naplata",
  "/portal/paketi": "Plan i naplata",
  "/portal/awards": "Nagrade",
  "/portal/podesavanja": "Podešavanja",
  "/portal/intelligence": "BP Intelligence",
  "/portal/partnerstva": "Predloženi partneri",
  "/portal/health-score": "Company Health Score",
  "/portal/verified-badge": "Verified Badge",
  "/portal/sales-crm": "Sales CRM",
  "/portal/referrals": "Referral program",
  "/portal/api-keys": "API ključevi",
  "/portal/webhooks": "Webhook-ovi",
  "/portal/poruke-podesavanja": "Podešavanja poruka",
  "/portal/univerzitet": "Univerzitetski centar",
  "/portal/univerzitet/paketi": "Institucionalni paket",
  "/portal/komora": "Komorski centar",
  "/portal/komora/paketi": "Komorski paket",
};

function titleFor(pathname: string): string {
  if (TITLES[pathname]) return TITLES[pathname];
  const match = Object.keys(TITLES)
    .filter((key) => key !== "/portal" && pathname.startsWith(`${key}/`))
    .sort((a, b) => b.length - a.length)[0];
  return match ? TITLES[match] : "Partner portal";
}

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

export function PortalShell({
  context,
  children,
}: {
  context: PortalShellContext | null;
  children: ReactNode;
}) {
  const pathname = usePathname() || "/portal";
  const [drawerOpen, setDrawerOpen] = useState(false);

  // Bez sesije (login, postavi-šifru) — bez shell-a.
  if (!context) {
    return <>{children}</>;
  }

  const { company, user, nav } = context;
  const tierClass = `is-${company.tierKey.toLowerCase().replace(/_/g, "-")}`;

  const sidebar = (
    <div className="portal-side-inner">
      <Link
        href="/portal"
        className="portal-brand"
        onClick={() => setDrawerOpen(false)}
      >
        {/* eslint-disable-next-line @next/next/no-img-element */}
        <img
          src="/images/biznisportal-logo-ondark.svg"
          alt="BiznisPortal"
          className="portal-brand-img"
        />
      </Link>

      <div className="portal-firm">
        <span className={`portal-firm-av${company.logoUrl ? " has-logo" : ""}`}>
          {company.logoUrl ? (
            // eslint-disable-next-line @next/next/no-img-element
            <img
              src={company.logoUrl}
              alt={company.name}
              className="portal-firm-logo"
            />
          ) : (
            company.initials
          )}
        </span>
        <div className="portal-firm-meta">
          <span className="portal-firm-name">{company.name}</span>
          <span className={`portal-tier ${tierClass}`}>
            ◆ {company.tierLabel}
          </span>
        </div>
      </div>

      <nav className="portal-nav">
        {nav.map((section) => (
          <div className="portal-nav-section" key={section.label}>
            <p className="portal-nav-label">{section.label}</p>
            {section.links.map((link) => {
              const active = !link.external && isActive(pathname, link.href);
              return (
                <Link
                  key={link.href}
                  href={link.href}
                  target={link.external ? "_blank" : undefined}
                  rel={link.external ? "noreferrer" : undefined}
                  className={`portal-nav-link${active ? " is-active" : ""}`}
                  onClick={() => setDrawerOpen(false)}
                >
                  <span className="portal-nav-ic">
                    <Icon name={link.icon} />
                  </span>
                  <span className="portal-nav-text">{link.label}</span>
                  {link.badge ? (
                    <span className="portal-nav-badge">{link.badge}</span>
                  ) : null}
                  {link.external ? (
                    <span className="portal-nav-ext" aria-hidden="true">
                      ↗
                    </span>
                  ) : null}
                </Link>
              );
            })}
          </div>
        ))}
      </nav>

      <div className="portal-side-foot">
        <span className="portal-side-foot-av">
          {user.name.slice(0, 2).toUpperCase()}
        </span>
        <div>
          <p className="portal-side-foot-name">{user.name}</p>
          <p className="portal-side-foot-role">{user.role}</p>
        </div>
      </div>
    </div>
  );

  return (
    <div className="portal-shell">
      {/* Desktop sidebar */}
      <aside className="portal-side">{sidebar}</aside>

      {/* Mobile drawer */}
      {drawerOpen ? (
        <>
          <button
            type="button"
            className="portal-drawer-scrim"
            aria-label="Zatvori meni"
            onClick={() => setDrawerOpen(false)}
          />
          <aside className="portal-side portal-side-drawer">{sidebar}</aside>
        </>
      ) : null}

      <div className="portal-main">
        <header className="portal-top">
          <button
            type="button"
            className="portal-burger"
            aria-label="Otvori meni"
            onClick={() => setDrawerOpen(true)}
          >
            <svg
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="2.2"
              strokeLinecap="round"
            >
              <line x1="3" y1="6" x2="21" y2="6" />
              <line x1="3" y1="12" x2="21" y2="12" />
              <line x1="3" y1="18" x2="21" y2="18" />
            </svg>
          </button>
          <div className="portal-top-titles">
            <h1 className="portal-top-title">{titleFor(pathname)}</h1>
            <p className="portal-top-sub">{company.name}</p>
          </div>
          <PortalTopbarTools
            publicHref={company.publicHref}
            notifications={context.topbar.notifications}
            messages={context.topbar.messages}
          />
        </header>

        <div className="portal-content">{children}</div>
      </div>
    </div>
  );
}
