// SiteNav — shared, site-wide traditional navigation (header.site-nav).
// Single source of truth for the approved Power Texas navigation: logo, the
// Service Areas / Providers / Business / Resources dropdowns (desktop hover +
// click with a brief close delay), phone number, and the mobile hamburger
// drawer. Styling lives in nav-footer.css (scoped to .site-nav). Self-contained
// (no page-specific deps); every public page loads this and renders <SiteNav/>.

const NAV_ITEMS = [
  { label: 'Service Areas', items: [
    // Canonical launch-city subset. Only cities with a live Power Texas page get a
    // real href; the rest render as non-clickable text (href: null) — never dead
    // links. Built: Houston, Dallas, Fort Worth, Arlington, Plano, Irving, Grand
    // Prairie, Killeen, Waco. Nav shows a curated subset, not all of them.
    { label: 'Texas', href: 'texas-electricity-rates.html' },
    { label: 'Houston', href: 'houston-electricity-rates.html' },
    { label: 'Dallas', href: 'dallas-electricity-rates.html' },
    { label: 'Fort Worth', href: 'fort-worth-electricity-rates.html' },
    { label: 'Arlington', href: 'arlington-electricity-rates.html' },
    { label: 'Corpus Christi', href: 'corpus-christi-electricity-rates.html' }
  ], viewAll: { label: 'View All Cities', href: 'texas-electricity-rates.html' } },
  { label: 'Providers', items: [
    { label: 'Energy Texas', href: 'energy-texas-electricity.html' },
    { label: 'Rhythm Energy', href: 'rhythm-energy-electricity.html' },
    { label: 'Gexa Energy', href: 'gexa-energy-electricity.html' },
    { label: 'TXU Energy', href: 'txu-energy-electricity.html' },
    { label: 'Reliant Energy', href: 'reliant-electricity.html' },
    { label: 'Champion Energy', href: 'champion-energy-electricity.html' }
  ], viewAll: { label: 'View All Providers', href: 'texas-electricity-providers.html' } },
  { label: 'Business', items: [
    { label: 'Business Energy Overview', href: 'texas-business-electricity.html' },
    { label: 'Small Business Plans', href: 'small-business-electricity-plans.html' }
  ] },
  { label: 'Resources', items: [
    // The six approved MVP guides. "How to Compare Plans" keeps the existing
    // how-to-choose-electricity-plan-texas URL: same intent, and preserving the
    // permanent URL keeps its inbound links working.
    { label: 'Moving to Texas', href: 'moving-to-texas-electricity.html' },
    { label: 'How to Compare Plans', href: 'how-to-choose-electricity-plan-texas.html' },
    { label: 'How Switching Works', href: 'how-to-switch-electricity-providers.html' },
    { label: 'How to Read an EFL', href: 'how-to-read-electricity-facts-label.html' },
    { label: 'No Deposit Electricity', href: 'no-deposit-electricity-plans.html' }
  ], viewAll: { label: 'View All Electricity Guides', href: '/electricity-guides' } }
];

const PHONE_DISPLAY = '(800) 555-0000';   // PLACEHOLDER — Power Texas has no customer-service number on file yet.
const PHONE_TEL = 'tel:+18005550000';
const SiteNavPhoneIcon = () => (
  <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M6.6 3h-2A1.6 1.6 0 0 0 3 4.6C3 13.06 9.94 20 18.4 20a1.6 1.6 0 0 0 1.6-1.6v-2a1 1 0 0 0-.76-.97l-3-.75a1 1 0 0 0-1 .34l-.66.82A12.3 12.3 0 0 1 8.9 9.4l.82-.66a1 1 0 0 0 .34-1l-.75-3A1 1 0 0 0 8.34 4Z" /></svg>
);
const SiteNavChevron = () => (
  <svg className="site-nav__chev" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M6 9l6 6 6-6" /></svg>
);

function SiteNavMobileItem({ item, onNavigate }) {
  const [open, setOpen] = React.useState(false);
  if (!item.items) {
    return <li><a className="site-nav__mlink" href={item.href} onClick={onNavigate}>{item.label}</a></li>;
  }
  return (
    <li>
      <button type="button" className={'site-nav__mlink site-nav__mtoggle' + (open ? ' is-open' : '')} aria-expanded={open} onClick={() => setOpen(!open)}>
        {item.label}<SiteNavChevron />
      </button>
      {open && (
        <ul className="site-nav__msub">
          {item.items.map((s) => <li key={s.label}>{s.href ? <a href={s.href} onClick={onNavigate}>{s.label}</a> : <span className="site-nav__static">{s.label}</span>}</li>)}
          {item.viewAll && <li><a className="site-nav__mviewall" href={item.viewAll.href} onClick={onNavigate}>{item.viewAll.label} →</a></li>}
        </ul>
      )}
    </li>
  );
}

function SiteNav() {
  const [mobileOpen, setMobileOpen] = React.useState(false);
  const [openMenu, setOpenMenu] = React.useState(null); // desktop dropdown label
  const navRef = React.useRef(null);
  const closeTimer = React.useRef(null);

  // Desktop hover intent: open on hover, keep open while the cursor moves from
  // the label into the panel, and delay close so crossing the small gap (or
  // leaving briefly) doesn't dismiss it. Click support retained via onClick.
  const openDropdown = (label) => {
    if (closeTimer.current) { clearTimeout(closeTimer.current); closeTimer.current = null; }
    setOpenMenu(label);
  };
  const closeDropdownSoon = () => {
    if (closeTimer.current) clearTimeout(closeTimer.current);
    closeTimer.current = setTimeout(() => { setOpenMenu(null); closeTimer.current = null; }, 180);
  };

  React.useEffect(() => {
    const onDoc = (e) => { if (navRef.current && !navRef.current.contains(e.target)) setOpenMenu(null); };
    const onKey = (e) => { if (e.key === 'Escape') { setOpenMenu(null); setMobileOpen(false); } };
    document.addEventListener('click', onDoc);
    document.addEventListener('keydown', onKey);
    return () => {
      document.removeEventListener('click', onDoc);
      document.removeEventListener('keydown', onKey);
      if (closeTimer.current) clearTimeout(closeTimer.current);
    };
  }, []);

  React.useEffect(() => {
    document.body.style.overflow = mobileOpen ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [mobileOpen]);

  return (
    <header className="site-nav" ref={navRef}>
      <div className="site-nav__bar">
        <a className="site-nav__logo" href="/" aria-label="Power Texas home">
          <img src="assets/logo-colored.svg" alt="Power Texas" />
        </a>

        <nav className="site-nav__links" aria-label="Primary">
          <ul>
            {NAV_ITEMS.map((it) => (
              <li
                key={it.label}
                className={'site-nav__item' + (it.items ? ' has-menu' : '') + (openMenu === it.label ? ' is-open' : '')}
                onMouseEnter={it.items ? () => openDropdown(it.label) : undefined}
                onMouseLeave={it.items ? closeDropdownSoon : undefined}
              >
                {it.items ? (
                  <React.Fragment>
                    <button
                      type="button"
                      className="site-nav__link site-nav__toggle"
                      aria-haspopup="true"
                      aria-expanded={openMenu === it.label}
                      onClick={(e) => { e.stopPropagation(); setOpenMenu(openMenu === it.label ? null : it.label); }}
                    >
                      {it.label}<SiteNavChevron />
                    </button>
                    <ul className="site-nav__dropdown" role="menu">
                      {it.items.map((s) => (
                        <li key={s.label} role="none">
                          {s.href
                            ? <a role="menuitem" href={s.href} onClick={() => setOpenMenu(null)}>{s.label}</a>
                            : <span className="site-nav__static">{s.label}</span>}
                        </li>
                      ))}
                      {it.viewAll && (
                        <React.Fragment>
                          <li className="site-nav__divider" role="separator" />
                          <li role="none"><a role="menuitem" className="site-nav__viewall" href={it.viewAll.href} onClick={() => setOpenMenu(null)}>{it.viewAll.label} <span aria-hidden="true">→</span></a></li>
                        </React.Fragment>
                      )}
                    </ul>
                  </React.Fragment>
                ) : (
                  <a className="site-nav__link" href={it.href}>{it.label}</a>
                )}
              </li>
            ))}
          </ul>
        </nav>

        <a className="site-nav__phone" href={PHONE_TEL} aria-label={'Call customer service at ' + PHONE_DISPLAY}>
          <SiteNavPhoneIcon /><span>{PHONE_DISPLAY}</span>
        </a>

        <button type="button" className="site-nav__burger" aria-label="Open menu" aria-expanded={mobileOpen} onClick={() => setMobileOpen(true)}>
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" aria-hidden="true"><line x1="3" y1="6" x2="21" y2="6" /><line x1="3" y1="12" x2="21" y2="12" /><line x1="3" y1="18" x2="21" y2="18" /></svg>
        </button>
      </div>

      {mobileOpen && <div className="site-nav__backdrop" onClick={() => setMobileOpen(false)} />}
      <aside className={'site-nav__drawer' + (mobileOpen ? ' is-open' : '')} aria-label="Mobile navigation" aria-hidden={!mobileOpen}>
        <div className="site-nav__drawer-head">
          <img src="assets/logo-colored.svg" alt="Power Texas" />
          <button type="button" className="site-nav__close" aria-label="Close menu" onClick={() => setMobileOpen(false)}>
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" aria-hidden="true"><line x1="6" y1="6" x2="18" y2="18" /><line x1="18" y1="6" x2="6" y2="18" /></svg>
          </button>
        </div>
        <nav aria-label="Mobile primary">
          <ul className="site-nav__mlist">
            {NAV_ITEMS.map((it) => <SiteNavMobileItem key={it.label} item={it} onNavigate={() => setMobileOpen(false)} />)}
          </ul>
        </nav>
        <a className="site-nav__phone site-nav__phone--mobile" href={PHONE_TEL} onClick={() => setMobileOpen(false)}>
          <SiteNavPhoneIcon /><span>{PHONE_DISPLAY}</span>
        </a>
      </aside>
    </header>
  );
}

window.SiteNav = SiteNav;
