/* ============================================
   MAIN NAVBAR COMPONENT - Logo, Nav Items, and Buttons
   ============================================ */
"use client";
import React, { useState } from "react";
import "./Navbar.css";
import { useRouter } from "next/navigation";
import { logout, getUserInfo } from "@/app/utils/token";
import Image from "next/image";
const NavbarAdvert = () => {
  const [isMenuOpen, setIsMenuOpen] = useState(false);
  const [isDropdownOpen, setIsDropdownOpen] = useState(false);
  const userInfo = getUserInfo();
  const userName =
    userInfo?.name || userInfo?.username || userInfo?.email || "U";
  const firstLetter = userName.charAt(0).toUpperCase();
  const userPhoto = userInfo?.photo
    ? `https://admin.eventx.fr/uploads/users/${userInfo.photo}`
    : null;
  const router = useRouter();
  const toggleMenu = () => {
    setIsMenuOpen(!isMenuOpen);
  };
  const redirectToLogin = () => {
    router.push("/login");
  };
  const handleLogout = () => {
    logout();
    router.push("/login");
    setIsDropdownOpen(false);
  };
  const handleProfile = () => {
    router.push("/home");
  };
  const handleTryForFree = () => {
    if (userInfo) {
      router.push("/home");
    } else {
      router.push("/register");
    }
  };
  const scrollToPricing = () => {
    const pricingSection = document.getElementById("pricing-section");
    if (pricingSection) {
      pricingSection.scrollIntoView({ behavior: "smooth", block: "start" });
      setIsMenuOpen(false); // Close mobile menu if open
    }
  };
  const scrollToBoosterCard = () => {
    const boosterCard = document.getElementById("booster-card");
    if (boosterCard) {
      boosterCard.scrollIntoView({ behavior: "smooth", block: "start" });
      setIsMenuOpen(false); // Close mobile menu if open
    }
  };
  const scrollToPricingTableCard = () => {
    const eventCard = document.getElementById("pricing-table-card");
    if (eventCard) {
      eventCard.scrollIntoView({ behavior: "smooth", block: "start" });
      setIsMenuOpen(false); // Close mobile menu if open
    }
  };
  return (
    <nav className="main-navbar-container">
      <div className="main-navbar-content">
        {/* Logo Section */}
        <div className="main-navbar-logo-wrapper">
          <div className="main-navbar-logo-text">
            <picture>
              <source
                srcSet="/advert-info/advertlogo.svg"
                type="image/svg+xml"
              />
              <img
                src="/advert-info/advertlogo.svg"
                alt="Logo"
                className="main-navbar-logo-img"
                width="130"
                height="45"
                loading="eager"
              />
            </picture>
          </div>
        </div>

        {/* Backdrop overlay */}
        {isMenuOpen && (
          <div
            className="main-navbar-backdrop"
            onClick={toggleMenu}
            aria-label="Close menu"
          />
        )}

        {/* Navigation Items */}
        <div
          className={`main-navbar-items-wrapper ${isMenuOpen ? "open" : ""}`}
        >
          {/* ✳️ Close button added here */}
          <button
            className="main-navbar-close"
            onClick={toggleMenu}
            aria-label="Close menu"
          >
            ×
          </button>

          <div
            className="main-navbar-item-dropdown"
            onClick={scrollToPricing}
            style={{ cursor: "pointer" }}
          >
            <span className="main-navbar-item-text">
              Ajoutez un événement - OFFERT
            </span>
            <span className="main-navbar-dropdown-icon">▼</span>
          </div>

          <div
            className="main-navbar-item-dropdown"
            onClick={scrollToBoosterCard}
            style={{ cursor: "pointer" }}
          >
            <span className="main-navbar-item-text">Proposez une activité</span>
            <span className="main-navbar-dropdown-icon">▼</span>
          </div>

          <div
            className="main-navbar-badge-wrapper"
            onClick={scrollToPricingTableCard}
            style={{ cursor: "pointer" }}
          >
            <span className="main-navbar-badge">NOUVEAU</span>
            <div className="main-navbar-item-dropdown">
              <span className="main-navbar-beta-icon">
                <Image
                  src={"/advert-info/megaphone.png"}
                  height={16}
                  width={16}
                  alt={`Bêta Test : Pub 100% Gratuite`}
                />
              </span>
              <span className="main-navbar-item-text">
                Bêta Test : Pub 100% Gratuite
              </span>
              <span className="main-navbar-dropdown-icon">▼</span>
            </div>
          </div>
          <div className="main-mob-navbar-small">
            <div className="main-navbar-buttons-wrapper">
              <button className="main-navbar-button-secondary">
                Se connecter
              </button>
              <button className="main-navbar-button-primary">
                Essayer gratuitement
              </button>
            </div>
          </div>
        </div>

        {/* Action Buttons - Always outside menu */}
        <div className="ActionButtons-Hamburger">
          {!userInfo ? (
            <div className="main-navbar-buttons-wrapper">
              <button
                className="main-navbar-button-secondary"
                onClick={redirectToLogin}
              >
                Se connecter
              </button>
              <button
                className="main-navbar-button-primary"
                onClick={handleTryForFree}
              >
                Essayer gratuitement
              </button>
            </div>
          ) : (
            <>
              <div className="relative">
                <div
                  className="flex items-center gap-4 cursor-pointer mr-3"
                  onClick={() => setIsDropdownOpen(!isDropdownOpen)}
                >
                  <p className="quaternary-heading">{userInfo?.name}</p>
                  {userPhoto ? (
                    <img
                      src={userPhoto}
                      alt={`${userName}'s profile`}
                      className="w-11 h-11 rounded-full object-cover border-2 border-gray-200"
                      onError={(e) => {
                        e.currentTarget.style.display = "none";
                      }}
                    />
                  ) : (
                    <div className="w-11 h-11 bg-blue-500 rounded-full flex items-center justify-center text-white font-semibold text-lg">
                      {firstLetter}
                    </div>
                  )}
                </div>

                {isDropdownOpen && (
                  <div className="absolute top-full right-0 mt-2 w-48 bg-white rounded-md shadow-lg py-1 z-50 border border-gray-200">
                    <button
                      onClick={handleProfile}
                      className="block w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 transition-colors duration-150"
                    >
                     Tableau de Bord
                    </button>
                    <button
                      onClick={handleLogout}
                      className="block w-full text-left px-4 py-2 text-sm text-red-600 hover:bg-red-50 transition-colors duration-150"
                    >
                     Se déconnecter
                    </button>
                  </div>
                )}
              </div>
              <button
                className="main-navbar-button-primary"
                onClick={handleTryForFree}
              >
                Essayer gratuitement
              </button>
            </>
          )}

          {/* Hamburger Menu Button */}
          <button
            className={`main-navbar-hamburger ${isMenuOpen ? "active" : ""}`}
            onClick={toggleMenu}
          >
            <span></span>
            <span></span>
            <span></span>
          </button>
        </div>
      </div>
    </nav>
  );
};

export default NavbarAdvert;
