import { NavLink, useLocation, useNavigate } from "react-router-dom";
import { __ } from "@wordpress/i18n";
import { MoveLeft } from "lucide-react";
import {
  findCurrentMenuGroup,
  getVisibleMenuItems,
} from "@libs/menu-visibility";

// Get menu items from PHP
const menuItems = getVisibleMenuItems(window.arraySubs?.menu?.items || []);

const TopHeader = ({ title, subtitle }) => {
  const location = useLocation();
  const navigate = useNavigate();
  const currentPath = location.pathname;

  // Find current parent menu item based on path
  const currentParent = findCurrentMenuGroup(currentPath, menuItems);

  // Get child items for current section (only if parent has children)
  const childItems = currentParent?.children || [];

  return (
    <>
      <header className="arraysubs-top-header">
        {/* Show tabs when there are children */}
        <nav>
          <ul className="arraysubs-tabs">
            {childItems.length === 0 && (
              <li className="arraysubs-tab">
                <a
                  aria-current="page"
                  className="arraysubs-tab-link arraysubs-tab-link--active"
                  href={`#${currentPath}`}
                  data-discover="true"
                >
                  {currentParent && currentParent.title
                    ? currentParent.title
                    : title}
                </a>
              </li>
            )}
            {childItems.length > 0 &&
              childItems.map((item) => (
                <li key={item.id} className="arraysubs-tab">
                  <NavLink
                    to={item.path}
                    end
                    className={({ isActive }) =>
                      `arraysubs-tab-link ${
                        isActive ? "arraysubs-tab-link--active" : ""
                      }`
                    }
                  >
                    {item.title}
                  </NavLink>
                </li>
              ))}
          </ul>
        </nav>

        <p className="arraysubs-page-subtitle">{subtitle && subtitle}</p>
      </header>

      {window.history.length > 1 && (
        <div>
          <a
            href="#"
            onClick={(e) => {
              e.preventDefault();
              navigate(-1);
            }}
            className="arraysubs-go-back"
          >
            <MoveLeft strokeWidth={1} absoluteStrokeWidth />
            {__("Go Back", "arraysubs")}
          </a>
        </div>
      )}
    </>
  );
};

export default TopHeader;
