import React, {useRef, useState, useContext} from 'react'
import { LinkAria } from '$core-components'
import { Popover, PopoverBody } from 'reactstrap-wc'
import NavigationMenu from './NavigationMenu'
import urlGenerator from '$ustoreinternal/services/urlGenerator'
import { decodeStringForURL } from '$ustoreinternal/services/utils'
import { t } from '$themelocalization'
import { RootDocumentContext } from '$themeservices'
import './CategoriesNavbar.scss'
import { getVariableValue } from '$ustoreinternal/services/cssVariables'

const CategoriesNavbar = ({ categoriesTree }) => {
  const {documentRoot, rootElement} = useContext(RootDocumentContext)()
  const [hoveredItem, setHoveredItem] = useState(null)
  const [selectedCategory, setSelectedCategory] = useState(null)
  const containerRef = useRef(null)

  if (!(categoriesTree && categoriesTree.length > 0)) {
    return null
  }

  const onMouseEnter = (category) => {
    queueMicrotask(() => {
      setSelectedCategory(category)
      setHoveredItem(documentRoot.getElementById(`id-${category}`))
    })
  }

  const onMouseLeave = () => {
    setSelectedCategory(null)
    setHoveredItem(null)
  }

  // Build custom menu items array
  const addMenuPosition = getVariableValue('--cust-menu-position', 'End');
  const customMenus = [
    { text: getVariableValue('--cust-menu1-text', ''), url: getVariableValue('--cust-menu1-url', ''), id: 'custom-1' },
    { text: getVariableValue('--cust-menu2-text', ''), url: getVariableValue('--cust-menu2-url', ''), id: 'custom-2' },
    { text: getVariableValue('--cust-menu3-text', ''), url: getVariableValue('--cust-menu3-url', ''), id: 'custom-3' }
  ].filter(menu => menu.text.length > 0 && menu.url.substring(0,4).toLowerCase() === 'http')
   .map(menu => ({
     Category: {
       FriendlyID: menu.id,
       Name: menu.text,
       isCustom: true,
       customUrl: menu.url
     },
     SubCategories: []
   }))

  // Combine custom menus with categories based on position
  const allMenuItems = addMenuPosition.toLowerCase() === 'start'
    ? [...customMenus, ...categoriesTree]
    : [...categoriesTree, ...customMenus]

  return (
    <div className="categories-navbar" ref={containerRef}>
      <div
        className="categories-navbar-item"
        onMouseEnter={( e ) => onMouseEnter( 0 )}
        onMouseLeave={onMouseLeave}
      >
        <div className="category-title-wrapper view-show-all">
          <span className={`category-title ${selectedCategory === 0 ? 'highlight' : ''}`} id="id-0">
            {t( 'Header.All_Categories' )}
          </span>
          <span className="category-spacer"></span>
          {
            hoveredItem && selectedCategory === 0 &&
            <Popover className="" fade={false} isOpen={true} placement="bottom-start"
                     target={hoveredItem} container={hoveredItem} popperClassName="categories-navbar-popper">
              <PopoverBody>
                <NavigationMenu categoriesTree={categoriesTree} viewShowAll={true} selectedCategory={null} />
              </PopoverBody>
            </Popover>
          }
        </div>
      </div>
      {
        //categoriesTree.map( ( { Category, SubCategories }, i ) => {
        //  const { FriendlyID, Name } = Category
          
        allMenuItems.map( ( { Category, SubCategories }, i ) => {
          const { FriendlyID, Name, isCustom, customUrl } = Category

          // For custom menu items, use a regular anchor tag
          if (isCustom) {
            return (
              <div
                className="categories-navbar-item"
                key={i}
                onMouseEnter={() => onMouseEnter(FriendlyID)}
                onMouseLeave={onMouseLeave}
              >
                <a className="category-title-wrapper" href={customUrl} target="_blank" rel="noopener noreferrer">
                  <span className={`category-title ${selectedCategory === FriendlyID ? 'highlight' : ''}`} id={`id-${FriendlyID}`}>
                    <span className="link" dangerouslySetInnerHTML={{ __html: Name }} />
                  </span>
                </a>
              </div>
            )
          }

          // For regular category items, use LinkAria
          return (
            <div
              className="categories-navbar-item"
              key={i}
              onMouseEnter={( e ) => onMouseEnter( FriendlyID, e.target )}
              onMouseLeave={onMouseLeave}
            >
              <LinkAria className="category-title-wrapper"
                        to={urlGenerator.get( {
                          page: 'category',
                          id: FriendlyID,
                          name: decodeStringForURL( Name ),
                        } )}>
                <span className={`category-title ${selectedCategory === FriendlyID ? 'highlight' : ''}`}
                      key={i} id={`id-${FriendlyID}`}>
                  <span className="link" key={i} dangerouslySetInnerHTML={{ __html: Name }} />
                </span>
                {
                  hoveredItem && selectedCategory === FriendlyID && SubCategories?.length > 0 &&
                  <Popover fade={false} isOpen={true} placement="bottom-start"
                           target={hoveredItem} container={rootElement}
                           popperClassName="categories-navbar-popper">
                    <PopoverBody>
                      {/*<NavigationMenu categoriesTree={categoriesTree} viewShowAll={false} selectedCategory={Category} />*/}
                      <NavigationMenu categoriesTree={allMenuItems} viewShowAll={false} selectedCategory={Category} />
                    </PopoverBody>
                  </Popover>
                }
              </LinkAria>
            </div>
          )
        } )
      }
    </div>
  )
}

export default CategoriesNavbar
