/* =========================================================
   UFIPL — Shared Navbar
   Exports window.UFNavbar — used across every page.
   Themes: 'dark' (hero) | 'light' (everywhere else)
   ========================================================= */

const { useState: nbUseState, useEffect: nbUseEffect, useRef: nbUseRef } = React;

const NAV_ITEMS = [
  { key: 'home', label: 'Home', href: 'index.html' },

  {
    key: 'about', label: 'About Us', href: 'about.html',
    children: [
      { label: 'Company Profile',     href: 'about.html#profile' },
      { label: 'Director\u2019s Desk', href: 'about.html#profile' },
    ],
  },

  {
    key: 'business', label: 'Business Lines', href: 'business.html',
    columns: [
      {
        title: 'Project Turnkey',
        items: [
          { label: 'Ethanol Plant Suppliers', href: 'business.html#ethanol' },
          { label: 'Power Generation',        href: 'business.html#boiler' },
          { label: 'Zero Liquid Discharge',   href: 'business.html#cpu' },
          { label: 'Biogas Plant',            href: 'business.html#cbg' },
          { label: 'Evaporation',             href: 'business.html#evaporation' },
          { label: 'RS / ENA Plant',          href: 'business.html#ethanol' },
        ],
      },
      {
        title: 'Manufacturing \u2014 Process Equipment',
        items: [
          { label: 'Heat Exchangers', href: 'business.html#critical' },
          { label: 'Tankages',        href: 'business.html#critical' },
          { label: 'Peso Storage',    href: 'business.html#critical' },
        ],
      },
      {
        title: 'Power Generation',
        items: [
          { label: 'Boilers', href: 'business.html#boiler' },
        ],
      },
    ],
  },

  {
    key: 'services', label: 'Services', href: 'services.html',
    columns: [
      {
        title: 'Design',
        items: [
          { label: 'PED',     href: 'services.html#design' },
          { label: 'Boilers', href: 'services.html#construction' },
        ],
      },
      {
        title: 'Consultancy',
        items: [
          { label: 'EPC', href: 'services.html#construction' },
        ],
      },
    ],
  },

  { key: 'blogs', label: 'Blogs', href: 'blogs.html' },

  {
    key: 'gallery', label: 'Gallery', href: 'gallery.html',
    children: [
      { label: 'Photo', href: 'gallery.html#photo' },
      { label: 'Video', href: 'gallery.html#video' },
    ],
  },

  {
    key: 'career', label: 'Career', href: 'career.html',
    children: [
      { label: 'Company Culture', href: 'career.html#culture' },
      { label: 'Openings',        href: 'career.html#openings' },
    ],
  },

  {
    key: 'contact', label: 'Contact Us', href: 'contact.html',
    children: [
      { label: 'Address',      href: 'contact.html#address' },
      { label: 'Enquiry Form', href: 'contact.html#enquiry' },
    ],
  },
];

function Caret({ className = '', theme = 'light' }) {
  return (
    <svg className={className} viewBox="0 0 12 8" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <path d="M1.5 1.5 6 6l4.5-4.5" />
    </svg>
  );
}

function SimpleDropdown({ items, theme }) {
  const isDark = theme === 'dark';
  return (
    <div
      className="min-w-[220px] rounded-xl overflow-hidden"
      style={{
        background: isDark ? 'rgba(14,14,14,0.92)' : 'rgba(255,255,255,0.96)',
        border: isDark ? '1px solid rgba(255,255,255,0.12)' : '1px solid rgba(0,0,0,0.06)',
        backdropFilter: 'blur(14px) saturate(160%)',
        WebkitBackdropFilter: 'blur(14px) saturate(160%)',
        boxShadow: isDark
          ? '0 30px 60px -30px rgba(0,0,0,0.6), inset 0 1px 0 rgba(255,255,255,0.06)'
          : '0 30px 60px -30px rgba(0,0,0,0.18), inset 0 1px 0 rgba(255,255,255,0.8)',
      }}
    >
      <ul className="py-2">
        {items.map((it) => (
          <li key={it.label}>
            <a
              href={it.href}
              className={
                'block px-4 py-2.5 text-sm transition-colors ' +
                (isDark
                  ? 'text-white/80 hover:text-white hover:bg-white/5'
                  : 'text-graphite/80 hover:text-graphite hover:bg-black/[0.04]')
              }
            >
              {it.label}
            </a>
          </li>
        ))}
      </ul>
    </div>
  );
}

function MegaMenu({ columns, theme }) {
  const isDark = theme === 'dark';
  return (
    <div
      className="rounded-2xl overflow-hidden"
      style={{
        background: isDark ? 'rgba(14,14,14,0.94)' : 'rgba(255,255,255,0.97)',
        border: isDark ? '1px solid rgba(255,255,255,0.12)' : '1px solid rgba(0,0,0,0.06)',
        backdropFilter: 'blur(16px) saturate(160%)',
        WebkitBackdropFilter: 'blur(16px) saturate(160%)',
        boxShadow: isDark
          ? '0 36px 80px -30px rgba(0,0,0,0.6), inset 0 1px 0 rgba(255,255,255,0.06)'
          : '0 36px 80px -30px rgba(0,0,0,0.2), inset 0 1px 0 rgba(255,255,255,0.85)',
        width: 'min(880px, calc(100vw - 64px))',
      }}
    >
      <div className="grid gap-8 p-6 md:p-8" style={{ gridTemplateColumns: `repeat(${columns.length}, minmax(0,1fr))` }}>
        {columns.map((c, i) => (
          <div key={i}>
            <div
              className="text-[10px] uppercase mb-3 whitespace-nowrap"
              style={{
                letterSpacing: '0.3em',
                color: isDark ? '#F6C431' : '#F7931E',
                fontFamily: 'Inter, sans-serif',
                fontWeight: 500,
              }}
            >
              {c.title}
            </div>
            <ul className="space-y-1">
              {c.items.map((it) => (
                <li key={it.label}>
                  <a
                    href={it.href}
                    className={
                      'block px-2.5 py-2 -mx-2.5 rounded-md text-sm transition-colors ' +
                      (isDark
                        ? 'text-white/80 hover:text-white hover:bg-white/5'
                        : 'text-graphite/80 hover:text-graphite hover:bg-black/[0.04]')
                    }
                  >
                    {it.label}
                  </a>
                </li>
              ))}
            </ul>
          </div>
        ))}
      </div>
    </div>
  );
}

function MobileMenu({ open, onClose, items, theme }) {
  const isDark = theme === 'dark';
  if (!open) return null;
  return (
    <div
      className="fixed inset-0 z-[100] lg:hidden"
      style={{ background: isDark ? 'rgba(5,5,5,0.96)' : 'rgba(250,249,246,0.98)' }}
    >
      <div className="flex items-center justify-between px-6 pt-6">
        <a href="index.html">
          <img src="assets/ufipl-logo-transparent.png" alt="UniversalForces" className="h-10 w-auto" />
        </a>
        <button
          type="button"
          onClick={onClose}
          aria-label="Close menu"
          className={
            'h-10 w-10 rounded-full flex items-center justify-center ' +
            (isDark ? 'text-white/80 hover:text-white border border-white/20' : 'text-graphite/80 hover:text-graphite border border-black/15')
          }
        >
          <svg className="h-5 w-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
            <path d="M6 6l12 12M18 6L6 18" />
          </svg>
        </button>
      </div>
      <div className="px-6 pt-8 pb-12 overflow-y-auto" style={{ maxHeight: 'calc(100vh - 60px)' }}>
        <ul className="space-y-6">
          {items.map((it) => (
            <li key={it.key}>
              <a
                href={it.href}
                className={
                  'block font-serif text-3xl ' +
                  (isDark ? 'text-white' : 'text-graphite')
                }
                style={{ letterSpacing: '-0.03em' }}
              >
                {it.label}
              </a>
              {(it.children || it.columns) && (
                <ul className="mt-3 pl-1 space-y-2">
                  {(it.children || []).map((c) => (
                    <li key={c.label}>
                      <a
                        href={c.href}
                        className={'text-sm ' + (isDark ? 'text-white/70' : 'text-graphite/70')}
                        style={{ fontFamily: 'Manrope, sans-serif' }}
                      >
                        {c.label}
                      </a>
                    </li>
                  ))}
                  {(it.columns || []).map((col) =>
                    col.items.map((c) => (
                      <li key={col.title + c.label}>
                        <a
                          href={c.href}
                          className={'text-sm ' + (isDark ? 'text-white/70' : 'text-graphite/70')}
                          style={{ fontFamily: 'Manrope, sans-serif' }}
                        >
                          {col.title} \u00b7 {c.label}
                        </a>
                      </li>
                    ))
                  )}
                </ul>
              )}
            </li>
          ))}
        </ul>
      </div>
    </div>
  );
}

function UFNavbar({ theme = 'light', active = '' }) {
  const [open, setOpen] = nbUseState(null);
  const [mobileOpen, setMobileOpen] = nbUseState(false);
  const closeTimer = nbUseRef(null);
  const isDark = theme === 'dark';

  function scheduleClose() {
    if (closeTimer.current) clearTimeout(closeTimer.current);
    closeTimer.current = setTimeout(() => setOpen(null), 120);
  }
  function cancelClose() {
    if (closeTimer.current) {
      clearTimeout(closeTimer.current);
      closeTimer.current = null;
    }
  }
  function openItem(key) {
    cancelClose();
    setOpen(key);
  }

  const wrapperPadding = 'px-6 md:px-12 lg:px-16 pt-6';
  const navClass =
    (isDark ? 'liquid-glass' : 'light-glass') +
    ' rounded-xl px-4 py-2 flex items-center justify-between gap-6';

  const linkClass = (itemKey) => {
    const base = 'whitespace-nowrap transition-colors flex items-center gap-1.5';
    const isActive = itemKey === active;
    if (isDark) {
      return base + ' ' + (isActive ? 'text-white font-medium' : 'text-white/85 hover:text-white');
    }
    return base + ' ' + (isActive ? 'text-graphite font-medium' : 'text-graphite/70 hover:text-graphite');
  };

  return (
    <div className={wrapperPadding + ' relative z-50'}>
      <nav className={navClass}>
        {/* Logo */}
        <a
          href="index.html"
          className="flex items-center gap-2 whitespace-nowrap shrink-0"
          aria-label="UniversalForces Industries — Home"
        >
          <img
            src="assets/ufipl-logo-transparent.png"
            alt="UniversalForces Industries"
            className="h-11 md:h-12 w-auto"
            style={{ filter: isDark ? 'drop-shadow(0 4px 14px rgba(0,128,0,0.35))' : 'none' }}
          />
        </a>

        {/* Desktop nav */}
        <div className="hidden lg:flex items-center gap-7 text-[13px]">
          {NAV_ITEMS.map((it) => {
            const hasDrop = !!(it.children || it.columns);
            return (
              <div
                key={it.key}
                className="relative"
                onMouseEnter={() => hasDrop && openItem(it.key)}
                onMouseLeave={hasDrop ? scheduleClose : undefined}
              >
                <a
                  href={it.href}
                  className={linkClass(it.key)}
                  onFocus={() => hasDrop && openItem(it.key)}
                >
                  {it.label}
                  {hasDrop && (
                    <Caret
                      className={
                        'h-2.5 w-2.5 transition-transform duration-200 ' +
                        (open === it.key ? 'rotate-180' : '')
                      }
                    />
                  )}
                </a>
                {open === it.key && hasDrop && (
                  <div
                    className="absolute left-1/2 -translate-x-1/2 top-full pt-3 z-50"
                    onMouseEnter={cancelClose}
                  >
                    {it.children && <SimpleDropdown items={it.children} theme={theme} />}
                    {it.columns && <MegaMenu columns={it.columns} theme={theme} />}
                  </div>
                )}
              </div>
            );
          })}
        </div>

        {/* Right CTA + mobile button */}
        <div className="flex items-center gap-3">
          <a
            href="contact.html"
            className="hidden md:inline-flex whitespace-nowrap grad-energy text-graphite px-5 md:px-6 py-2 rounded-lg text-sm font-semibold hover:brightness-110 transition shadow-[0_8px_24px_-8px_rgba(247,147,30,0.55)]"
          >
            Start Your Project
          </a>
          <button
            type="button"
            onClick={() => setMobileOpen(true)}
            aria-label="Open menu"
            className={
              'lg:hidden h-10 w-10 rounded-lg flex items-center justify-center ' +
              (isDark ? 'text-white border border-white/20' : 'text-graphite border border-black/15')
            }
          >
            <svg className="h-5 w-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
              <path d="M4 7h16M4 12h16M4 17h16" />
            </svg>
          </button>
        </div>
      </nav>

      <MobileMenu open={mobileOpen} onClose={() => setMobileOpen(false)} items={NAV_ITEMS} theme={theme} />
    </div>
  );
}

window.UFNavbar = UFNavbar;
