"use client";

import { usePathname } from "next/navigation";
import { useEffect, useState } from "react";
import { Search, Settings, BookOpen } from "lucide-react";
import { useAuthStore } from "@/store/authStore";
import styles from "./Navbar.module.css";
import NotificationBell from "@/components/NotificationBell";

// 👇 NEW — reads the scheme (QRS or TQS) from the logged-in user.
//         For internal staff, reads from auth store user.primary_scheme.
//         For client portal, decodes the clientPortalToken JWT (which now
//         contains a "scheme" field thanks to the backend changes).
//         Falls back to 'QRS' if anything is missing.
function getSchemeFromToken(isClientPortal: boolean, user: any): 'QRS' | 'TQS' {
  try {
    if (typeof window === 'undefined') return 'QRS';

    // Internal staff — read primary_scheme from user object
    if (!isClientPortal) {
      const scheme = String((user as any)?.primary_scheme || 'QRS').toUpperCase();
      return scheme === 'TQS' ? 'TQS' : 'QRS';
    }

    // Client portal — decode JWT payload
    const token = localStorage.getItem('clientPortalToken') || '';
    if (!token) return 'QRS';
    const payload = JSON.parse(atob(token.split('.')[1]));
    const scheme = String(payload?.scheme || 'QRS').toUpperCase();
    return scheme === 'TQS' ? 'TQS' : 'QRS';
  } catch {
    return 'QRS';
  }
}

const PAGE_TITLES: Record<string, string> = {
  "/dashboard":             "Dashboard",
  "/users":                 "User Management",
  "/clients":               "Client Dashboard",
  "/client":                "Client Data",
  "/projects":              "Projects",
  "/reports":               "Reports",
  "/certifications":        "Certifications",
  "/new_certificates":      "New Certificates",
  "/expired-certificate":   "Expired Certificates",
  "/iso_draft_certificate": "ISO Certificate",
  "/previous-certificates": "Previous Certificates",
  "/audit":                 "Auditor Compliance",
  "/company":               "Company",
  "/schem/template":        "Templates",
  "/templates/templates_content": "Template Content",
  "/job-registrar":         "Job Registrar",
  "/code_book":             "Code Book",
  "/standard":              "Standards",
  "/countries":             "Countries",
};

interface NavbarProps {
  isClientPortal?: boolean;
}

export default function Navbar({ isClientPortal }: NavbarProps) {
  const pathname = usePathname();
  const title = PAGE_TITLES[pathname] ?? "CertifyHub  |  Certification & Audit Platform";
  const user = useAuthStore((s) => s.user);
  const hydrate = useAuthStore((s) => s.hydrate);

  // 👇 NEW — brand scheme (QRS or TQS) resolved from the logged-in user.
  //         Kept in state so it re-computes if the user changes.
  const [scheme, setScheme] = useState<'QRS' | 'TQS'>('QRS');

  useEffect(() => {
    if (!isClientPortal) {
      hydrate();
    }
  }, [isClientPortal]);

  // 👇 NEW — resolve scheme after mount (client portal needs localStorage which
  //         is only available in the browser, and internal user is set after hydrate).
  useEffect(() => {
    setScheme(getSchemeFromToken(!!isClientPortal, user));
  }, [isClientPortal, user]);

  // ✨ GET USER DISPLAY NAME (shows email for client, username for internal)
  const getUserDisplay = () => {
    if (isClientPortal) {
      try {
        const clientUser = JSON.parse(
          localStorage.getItem("clientUser") || "{}"
        );
        const fullName = [clientUser.firstName, clientUser.lastName]
          .filter(Boolean)
          .join(" ");
        return fullName || clientUser.email || clientUser.name || "Client";
      } catch {
        return "Client";
      }
    } else {
      return user?.username || "Admin User";
    }
  };

  // 📖 NEW — opens the User Guide HTML file in a new browser tab
  const openUserGuide = () => {
    window.open("/client-portal-guide.html", "_blank", "noopener,noreferrer");
  };

  return (
    <nav className={styles.navbar}>
      <div className={styles.left}>
        {/* 👇 CHANGED — was hardcoded "QRS & TQS", now shows the brand of the logged-in user */}
        <span className={styles.breadcrumb}>{scheme}</span>
        <span className={styles.divider}>›</span>
        <span className={styles.pageTitle}>{title}</span>
      </div>
      <div className={styles.right}>

        {/* 📖 NEW — User Guide button with text (visible for BOTH admin & client) */}
        <button
          type="button"
          onClick={openUserGuide}
          title="Open the step-by-step User Guide"
          style={{
            display: "inline-flex",
            alignItems: "center",
            gap: "6px",
            padding: "7px 14px",
            background: "linear-gradient(135deg, #4a0080 0%, #2d004d 100%)",
            color: "#fff",
            border: "none",
            borderRadius: "8px",
            fontSize: "12.5px",
            fontWeight: 600,
            cursor: "pointer",
            fontFamily: "inherit",
            letterSpacing: "-0.005em",
            boxShadow: "0 1px 2px rgba(74,0,128,0.2), 0 4px 12px -4px rgba(74,0,128,0.3)",
            transition: "all 0.15s ease",
          }}
          onMouseEnter={(e) => {
            e.currentTarget.style.transform = "translateY(-1px)";
            e.currentTarget.style.boxShadow = "0 2px 4px rgba(74,0,128,0.25), 0 6px 16px -4px rgba(74,0,128,0.4)";
          }}
          onMouseLeave={(e) => {
            e.currentTarget.style.transform = "translateY(0)";
            e.currentTarget.style.boxShadow = "0 1px 2px rgba(74,0,128,0.2), 0 4px 12px -4px rgba(74,0,128,0.3)";
          }}
        >
          <BookOpen size={14} />
          <span>User Guide</span>
        </button>

        {!isClientPortal && (
          <>
            <div className={styles.iconBtn}><Search size={15} /></div>
            <div className={styles.iconBtn}><Settings size={15} /></div>
            <NotificationBell />
          </>
        )}

        {/* ✅ REPLACED: old Bell icon → real NotificationBell with badge + click */}
        {isClientPortal && <NotificationBell />}

        <div className={styles.sep} />
        <div className={styles.avatarBtn}>
          <div className={styles.avatar}>
            {getUserDisplay()[0]?.toUpperCase() || "C"}
          </div>
          <div className={styles.avatarInfo}>
            <span className={styles.avatarName}>
              {getUserDisplay()}
            </span>
          </div>
        </div>
      </div>
    </nav>
  );
}