/* global React */
/* Navbar generado desde rules/menu.json — no editar a mano; usar rules/menu.json */
const { useState, useEffect } = React;

const NAV = window.ACMP_NAV || { logo_href: 'index.html', items: [], cta: null };
const PROMO = window.ACMP_PROMO_BANNER || { enabled: false };

function parsePromoDate(value) {
  if (!value) return null;
  const raw = String(value).trim();
  if (/^\d{4}-\d{2}-\d{2}$/.test(raw)) {
    return new Date(raw + 'T23:59:59-03:00');
  }
  const parsed = new Date(raw);
  return Number.isNaN(parsed.getTime()) ? null : parsed;
}

function usePromoCountdown(targetDate) {
  const [parts, setParts] = useState({ d: 0, h: 0, m: 0, s: 0, expired: true });

  useEffect(() => {
    const target = parsePromoDate(targetDate);
    if (!target) return undefined;

    const tick = () => {
      const diff = target.getTime() - Date.now();
      if (diff <= 0) {
        setParts({ d: 0, h: 0, m: 0, s: 0, expired: true });
        return;
      }
      setParts({
        d: Math.floor(diff / 86400000),
        h: Math.floor((diff % 86400000) / 3600000),
        m: Math.floor((diff % 3600000) / 60000),
        s: Math.floor((diff % 60000) / 1000),
        expired: false,
      });
    };

    tick();
    const id = setInterval(tick, 1000);
    return () => clearInterval(id);
  }, [targetDate]);

  return parts;
}

function PromoCountdownDisplay({ d, h, m, s }) {
  const pad = (n) => String(n).padStart(2, '0');
  const units = [
    { value: pad(d), label: 'd' },
    { value: pad(h), label: 'h' },
    { value: pad(m), label: 'm' },
    { value: pad(s), label: 's' },
  ];

  return (
    <div className="acmp-promo-countdown" aria-label="Cuenta regresiva">
      {units.map(unit => (
        <div key={unit.label} className="acmp-promo-countdown-unit">
          <span className="acmp-promo-countdown-num">{unit.value}</span>
          <span className="acmp-promo-countdown-label">{unit.label}</span>
        </div>
      ))}
    </div>
  );
}

function PromoBanner() {
  const cfg = PROMO;
  const countdown = cfg.countdown || {};
  const targetDate = countdown.target_date || countdown.target;
  // Hook SIEMPRE antes de cualquier return condicional (Rules of Hooks).
  const cd = usePromoCountdown(countdown.enabled ? targetDate : null);

  if (!cfg.enabled) return null;

  const hideAfter = parsePromoDate(cfg.hide_after);
  if (hideAfter && Date.now() > hideAfter.getTime()) return null;
  if (countdown.enabled && cfg.hide_when_countdown_ends !== false && cd.expired) {
    return null;
  }

  const link = cfg.link || {};
  const linkProps = link.href ? navLinkProps(link) : {};

  return (
    <div className="acmp-promo-banner" role="region" aria-label="Promoción">
      <div className="acmp-promo-inner">
        <p className="acmp-promo-text">
          {cfg.icon && <span className="acmp-promo-icon" aria-hidden="true">{cfg.icon} </span>}
          {cfg.message}{' '}
          {link.label && link.href && (
            <a className="acmp-promo-link" {...linkProps}>{link.label}</a>
          )}
        </p>
        {countdown.enabled && targetDate && !cd.expired && (
          <PromoCountdownDisplay d={cd.d} h={cd.h} m={cd.m} s={cd.s} />
        )}
      </div>
    </div>
  );
}

function navLinkProps(item) {
  if (!item) return {};
  const external = item.external || /^https?:\/\//.test(item.href || '');
  return {
    href: item.href,
    target: external ? '_blank' : undefined,
    rel: external ? 'noopener noreferrer' : undefined,
  };
}

function navHomeHref() {
  return (NAV.logo_href || 'index.html').replace(/^\.\//, '');
}

function isLogoHomeItem(item) {
  if (!item || item.children) return false;
  const href = (item.href || '').replace(/^\.\//, '');
  return href === navHomeHref() || item.label.toLowerCase() === 'home';
}

function navItemsForBar(items) {
  return (items || []).filter(item => !isLogoHomeItem(item));
}

function NavLogo({ inverted = false }) {
  const homeHref = NAV.logo_href || 'index.html';
  return (
    <a
      className={'acmp-logo' + (inverted ? ' acmp-logo--inverted' : '')}
      href={homeHref}
      aria-label="Ir al inicio"
      style={{ display: 'flex', alignItems: 'center', textDecoration: 'none', cursor: 'pointer' }}
    >
      <img
        src={R('assets/logo-primary.webp')}
        alt="Academia Comunica de Mai Pistiner"
        className="acmp-nav-logo-img"
      />
    </a>
  );
}

function HamburgerIcon({ open }) {
  return (
    <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" aria-hidden="true">
      {open ? (
        <><line x1="6" y1="6" x2="18" y2="18" /><line x1="18" y1="6" x2="6" y2="18" /></>
      ) : (
        <><line x1="3" y1="7" x2="21" y2="7" /><line x1="3" y1="12" x2="21" y2="12" /><line x1="3" y1="17" x2="21" y2="17" /></>
      )}
    </svg>
  );
}

function ChevronDown() {
  return (
    <svg className="acmp-nav-chevron" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" aria-hidden="true">
      <polyline points="6 9 12 15 18 9" />
    </svg>
  );
}

function NavDropdown({ item, onNavigate }) {
  const [open, setOpen] = useState(false);
  const closeTimer = React.useRef(null);
  const rootRef = React.useRef(null);
  const children = item.children || [];
  const multiCol = children.length > 6;

  const clearCloseTimer = () => {
    if (closeTimer.current) {
      clearTimeout(closeTimer.current);
      closeTimer.current = null;
    }
  };

  const scheduleClose = () => {
    clearCloseTimer();
    closeTimer.current = setTimeout(() => setOpen(false), 280);
  };

  const handleEnter = () => {
    clearCloseTimer();
    setOpen(true);
  };

  useEffect(() => {
    if (!open) return undefined;
    const onDocClick = (event) => {
      if (rootRef.current && !rootRef.current.contains(event.target)) {
        setOpen(false);
      }
    };
    document.addEventListener('mousedown', onDocClick);
    return () => document.removeEventListener('mousedown', onDocClick);
  }, [open]);

  useEffect(() => () => clearCloseTimer(), []);

  return (
    <div
      ref={rootRef}
      className={
        'acmp-nav-dropdown'
        + (open ? ' is-open' : '')
        + (multiCol ? ' is-multi-col' : '')
      }
      onMouseEnter={handleEnter}
      onMouseLeave={scheduleClose}
    >
      <button
        type="button"
        className="acmp-nav-link acmp-nav-dropdown-toggle"
        aria-haspopup="true"
        aria-expanded={open}
        onClick={() => {
          clearCloseTimer();
          setOpen(v => !v);
        }}
      >
        {item.label}
        <ChevronDown />
      </button>
      <div className="acmp-nav-dropdown-menu" role="menu">
        {children.map(child => (
          <a
            key={child.label}
            className="acmp-nav-dropdown-link"
            role="menuitem"
            {...navLinkProps(child)}
            style={{ textDecoration: 'none' }}
            onClick={onNavigate}
          >
            {child.label}
          </a>
        ))}
      </div>
    </div>
  );
}

function NavMobileAccordion({ item, onNavigate }) {
  const [expanded, setExpanded] = useState(false);
  return (
    <div className={'acmp-nav-mobile-accordion' + (expanded ? ' is-open' : '')}>
      <button
        type="button"
        className="acmp-nav-mobile-accordion-toggle"
        aria-expanded={expanded}
        onClick={() => setExpanded(v => !v)}
      >
        <span>{item.label}</span>
        <ChevronDown />
      </button>
      {expanded && (
        <div className="acmp-nav-mobile-accordion-body">
          {(item.children || []).map(child => (
            <a
              key={child.label}
              className="acmp-nav-mobile-sublink"
              {...navLinkProps(child)}
              onClick={onNavigate}
            >
              {child.label}
            </a>
          ))}
        </div>
      )}
    </div>
  );
}

function NavMobileMenu({ items, cta, onClose }) {
  return (
    <div className="acmp-nav-mobile" role="dialog" aria-modal="true" aria-label="Menú de navegación">
      <div className="acmp-nav-mobile-header">
        <NavLogo inverted />
        <button
          type="button"
          className="acmp-nav-mobile-close"
          aria-label="Cerrar menú"
          onClick={onClose}
        >
          <HamburgerIcon open />
        </button>
      </div>
      <div className="acmp-nav-mobile-scroll">
        {navItemsForBar(items).map(item => (
          item.children ? (
            <NavMobileAccordion key={item.label} item={item} onNavigate={onClose} />
          ) : (
            <a
              key={item.label}
              className="acmp-nav-mobile-link"
              {...navLinkProps(item)}
              onClick={onClose}
            >
              {item.label}
              {item.badge && <span className="acmp-nav-mobile-badge">{item.badge}</span>}
            </a>
          )
        ))}
      </div>
      {cta && (
        <div className="acmp-nav-mobile-footer">
          <a
            className="acmp-btn acmp-nav-mobile-cta"
            {...navLinkProps(cta)}
            onClick={onClose}
          >
            {cta.label}
          </a>
        </div>
      )}
    </div>
  );
}

function Navbar() {
  const [open, setOpen] = useState(false);
  const close = () => setOpen(false);
  const items = NAV.items || [];
  const barItems = navItemsForBar(items);
  const cta = NAV.cta;

  useEffect(() => {
    if (!open) return undefined;
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      document.body.style.overflow = prev;
    };
  }, [open]);

  return (
    <>
      <PromoBanner />
      <nav className={'acmp-nav' + (open ? ' is-open' : '')}>
      <div className="acmp-nav-inner">
        <div className="acmp-nav-left"><NavLogo /></div>
        <div className="acmp-nav-links">
          {barItems.map(item => (
            item.children ? (
              <NavDropdown key={item.label} item={item} onNavigate={close} />
            ) : (
              <a
                key={item.label}
                className="acmp-nav-link"
                {...navLinkProps(item)}
                style={{ textDecoration: 'none' }}
                onClick={close}
              >
                {item.label}
              </a>
            )
          ))}
        </div>
        <div className="acmp-nav-right">
          {cta && (
            <a
              className="acmp-btn acmp-btn-primary acmp-nav-cta"
              {...navLinkProps(cta)}
              style={{ textDecoration: 'none', whiteSpace: 'nowrap' }}
            >
              {cta.label} <span aria-hidden="true">→</span>
            </a>
          )}
          <button
            className="acmp-nav-burger"
            aria-label={open ? 'Cerrar menú' : 'Abrir menú'}
            aria-expanded={open}
            onClick={() => setOpen(v => !v)}
          >
            <HamburgerIcon open={open} />
          </button>
        </div>
      </div>

      {open && <NavMobileMenu items={items} cta={cta} onClose={close} />}
    </nav>
    </>
  );
}

Object.assign(window, { Navbar, NavLogo, PromoBanner });
