/* global React */
const { useState, useEffect, useRef } = React;

function Reveal({ children, as: As = 'div', className = '', delay = 0, ...rest }) {
  return (
    <As className={className} {...rest}>
      {children}
    </As>
  );
}

function Brand({ go, current = false }) {
  return (
    <a
      className={`brand ${current ? 'active' : ''}`}
      href="/"
      onClick={(event) => { event.preventDefault(); go('home'); }}
      aria-label="IDELIGO — Home"
      aria-current={current ? 'page' : undefined}
    >
      <img
        className="brand-logo"
        src="/assets/logo/ideligo-logo-horizontal-light.svg"
        alt=""
        aria-hidden="true"
      />
    </a>
  );
}

// ─── Navigation ──────────────────────────────────────────────
const ROUTES = {
  home: { id: 'home', label: 'Home', href: '/' },
  services: { id: 'services', label: 'Services', href: '/services' },
  cases: { id: 'cases', label: 'Case Studies', href: '/case-studies' },
  insights: { id: 'insights', label: 'Insights', href: '/insights' },
  about: { id: 'about', label: 'About', href: '/about' },
  contact: { id: 'contact', label: 'Contact', href: '/contact' },
};

const PAGES = [
  ROUTES.home,
  ROUTES.services,
  ROUTES.cases,
  ROUTES.insights,
  ROUTES.about,
  ROUTES.contact,
];

const SERVICE_PILLARS = [
  {
    id: 'strategic-transformation-decision-advisory',
    title: 'Strategic Transformation & Decision Advisory',
    summary: 'Create direction, clarify priorities and support high-quality executive decisions across complex transformation.',
    purpose: 'Help leaders establish direction, clarify intended outcomes, evaluate options and maintain strategic alignment through complex transformation.',
  },
  {
    id: 'enterprise-architecture-analysis',
    title: 'Enterprise Architecture & Analysis',
    summary: 'Connect business intent, operating models, processes, requirements and technology into coherent, implementation-ready direction.',
    purpose: 'Translate business intent into coherent operating, process, information and technology direction that can be understood, governed and implemented.',
  },
  {
    id: 'ai-governance-digital-trust',
    title: 'AI, Governance & Digital Trust',
    summary: 'Turn AI and digital capability into governed, accountable and operationally integrated capability with clear controls and measurable value.',
    purpose: 'Help organisations adopt AI and digital capability with clear ownership, authority, controls, accountability, regulatory alignment and measurable value.',
  },
  {
    id: 'transformation-delivery-assurance',
    title: 'Transformation Delivery & Assurance',
    summary: 'Maintain alignment through implementation, strengthen delivery governance and provide independent visibility of readiness, adoption, risk and outcomes.',
    purpose: 'Help organisations maintain alignment through implementation, strengthen delivery governance, support operational and organisational change readiness where it affects transformation success, and obtain independent visibility of risk, progress and realised outcomes.',
  },
].map((service) => ({ ...service, href: `/services#${service.id}` }));

function routeIdFromPath(pathname) {
  const path = pathname.length > 1 ? pathname.replace(/\/$/, '') : pathname;
  if (path === '/services') return 'services';
  if (path === '/case-studies') return 'cases';
  if (path === '/insights' || path === '/frameworks') return 'insights';
  if (path === '/about') return 'about';
  if (path === '/contact') return 'contact';
  return 'home';
}

function resolveRouteTarget(target) {
  if (typeof target === 'string' && target.startsWith('/')) return target;
  return ROUTES[target]?.href || '/';
}

function InternalLink({ href, go, children, className = '', onClick, ...rest }) {
  return (
    <a
      href={href}
      className={className}
      {...rest}
      onClick={(event) => {
        event.preventDefault();
        onClick?.(event);
        go(href);
      }}
    >
      {children}
    </a>
  );
}

// ─── Mobile burger toggle ─────────────────────────────────────
function BurgerToggle({ open, onToggle, buttonRef }) {
  return (
    <button
      ref={buttonRef}
      className={`nav-burger ${open ? 'is-open' : ''}`}
      onClick={onToggle}
      aria-label={open ? 'Close menu' : 'Open menu'}
      aria-expanded={open}
      aria-controls="mobile-navigation"
    >
      <span></span><span></span><span></span>
    </button>
  );
}

function Nav({ page, activeService, go }) {
  const [menuOpen, setMenuOpen] = useState(false);
  const [desktopServicesOpen, setDesktopServicesOpen] = useState(false);
  const [mobileServicesOpen, setMobileServicesOpen] = useState(false);
  const toggleRef = useRef(null);
  const drawerRef = useRef(null);
  const desktopServicesToggleRef = useRef(null);
  const desktopServicesRef = useRef(null);

  // Close drawer whenever the page changes
  useEffect(() => {
    setMenuOpen(false);
    setDesktopServicesOpen(false);
    setMobileServicesOpen(false);
  }, [page, activeService]);

  useEffect(() => {
    if (!desktopServicesOpen) return;
    const onPointerDown = (event) => {
      if (!desktopServicesRef.current?.contains(event.target)) {
        setDesktopServicesOpen(false);
      }
    };
    document.addEventListener('pointerdown', onPointerDown);
    return () => document.removeEventListener('pointerdown', onPointerDown);
  }, [desktopServicesOpen]);

  // Lock page scroll and disable only the background content while open.
  useEffect(() => {
    if (!menuOpen) return;
    const background = [document.querySelector('main'), document.querySelector('.footer')]
      .filter(Boolean);
    document.body.style.overflow = 'hidden';
    background.forEach((element) => { element.inert = true; });
    requestAnimationFrame(() => {
      drawerRef.current?.querySelector('a[href], button')?.focus({ preventScroll: true });
    });
    return () => {
      document.body.style.overflow = '';
      background.forEach((element) => { element.inert = false; });
    };
  }, [menuOpen]);

  const closeMenu = () => {
    setMenuOpen(false);
    setMobileServicesOpen(false);
    requestAnimationFrame(() => toggleRef.current?.focus({ preventScroll: true }));
  };

  // Close on Escape and keep keyboard focus within the open drawer.
  useEffect(() => {
    if (!menuOpen) return;
    const onKey = (e) => {
      if (e.key === 'Escape') {
        e.preventDefault();
        closeMenu();
        return;
      }
      if (e.key !== 'Tab') return;
      const controls = Array.from(
        drawerRef.current?.querySelectorAll('a[href], button:not([disabled])') || []
      ).filter((element) => !element.closest('[hidden]'));
      if (!controls.length) return;
      const first = controls[0];
      const last = controls[controls.length - 1];
      if (e.shiftKey && document.activeElement === first) {
        e.preventDefault();
        last.focus();
      } else if (!e.shiftKey && document.activeElement === last) {
        e.preventDefault();
        first.focus();
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [menuOpen]);

  const navigateAndClose = (target) => { setMenuOpen(false); go(target); };

  const closeDesktopServices = (restoreFocus = false) => {
    setDesktopServicesOpen(false);
    if (restoreFocus) {
      requestAnimationFrame(() => desktopServicesToggleRef.current?.focus({ preventScroll: true }));
    }
  };

  const onDesktopServicesKeyDown = (event) => {
    if (event.key === 'Escape' && desktopServicesOpen) {
      event.preventDefault();
      closeDesktopServices(true);
    }
  };

  return (
    <React.Fragment>
      <nav className="nav">
        <div className="container">
          <div className="nav-inner">
            <Brand current={page === 'home'} go={go} />

            {/* Desktop: inline page links */}
            <ul className="nav-links nav-links-pages">
              <li
                ref={desktopServicesRef}
                className="nav-services-item"
                onKeyDown={onDesktopServicesKeyDown}
              >
                <span className="nav-services-main">
                  <InternalLink
                    href={ROUTES.services.href}
                    go={go}
                    className={`nav-link ${page === 'services' ? 'active' : ''}`}
                    aria-current={page === 'services' ? 'page' : undefined}
                  >
                    Services
                  </InternalLink>
                  <button
                    ref={desktopServicesToggleRef}
                    type="button"
                    className="nav-services-toggle"
                    aria-label="Show Services destinations"
                    aria-expanded={desktopServicesOpen}
                    aria-controls="desktop-services-submenu"
                    onClick={() => setDesktopServicesOpen((open) => !open)}
                  >
                    <span aria-hidden="true">⌄</span>
                  </button>
                </span>
                <ul
                  id="desktop-services-submenu"
                  className="nav-services-submenu"
                  hidden={!desktopServicesOpen}
                >
                  {SERVICE_PILLARS.map((service) => (
                    <li key={service.id} onClick={() => setDesktopServicesOpen(false)}>
                      <InternalLink
                        href={service.href}
                        go={go}
                        className={activeService === service.id ? 'active' : ''}
                        aria-current={activeService === service.id ? 'location' : undefined}
                      >
                        {service.title}
                      </InternalLink>
                    </li>
                  ))}
                </ul>
              </li>
              {PAGES.filter((p) => !['home', 'services'].includes(p.id)).map((p) => (
                <li key={p.id}>
                  <InternalLink
                    href={p.href}
                    go={go}
                    className={`nav-link ${page === p.id ? 'active' : ''}`}
                    aria-current={page === p.id ? 'page' : undefined}
                  >
                    {p.label}
                  </InternalLink>
                </li>
              ))}
            </ul>

            {/* Mobile: burger */}
            <div className="nav-mobile-controls">
              <BurgerToggle
                open={menuOpen}
                buttonRef={toggleRef}
                onToggle={() => (menuOpen ? closeMenu() : setMenuOpen(true))}
              />
            </div>
          </div>
        </div>
      </nav>

      {/* Mobile drawer — sibling of nav so backdrop-filter on nav doesn't trap it */}
      {menuOpen && <div
        id="mobile-navigation"
        ref={drawerRef}
        className="nav-drawer is-open"
        role="dialog"
        aria-modal="true"
        aria-label="Site navigation"
      >
        <ul className="nav-drawer-list">
          <li className="nav-drawer-services">
            <div className="nav-drawer-service-row">
              <InternalLink
                href={ROUTES.services.href}
                go={navigateAndClose}
                className={`nav-drawer-link ${page === 'services' ? 'active' : ''}`}
                aria-current={page === 'services' ? 'page' : undefined}
              >
                <span className="nav-drawer-label">Services</span>
              </InternalLink>
              <button
                type="button"
                className="nav-drawer-disclosure"
                aria-label={`${mobileServicesOpen ? 'Hide' : 'Show'} Services destinations`}
                aria-expanded={mobileServicesOpen}
                aria-controls="mobile-services-submenu"
                onClick={() => setMobileServicesOpen((open) => !open)}
              >
                <span aria-hidden="true">⌄</span>
              </button>
            </div>
            <ul
              id="mobile-services-submenu"
              className="nav-drawer-submenu"
              hidden={!mobileServicesOpen}
            >
              {SERVICE_PILLARS.map((service) => (
                <li key={service.id}>
                  <InternalLink
                    href={service.href}
                    go={navigateAndClose}
                    className={activeService === service.id ? 'active' : ''}
                    aria-current={activeService === service.id ? 'location' : undefined}
                  >
                    {service.title}
                  </InternalLink>
                </li>
              ))}
            </ul>
          </li>
          {PAGES.filter((p) => !['home', 'services'].includes(p.id)).map((p) => (
            <li key={p.id}>
              <InternalLink
                href={p.href}
                go={navigateAndClose}
                className={`nav-drawer-link ${page === p.id ? 'active' : ''}`}
                aria-current={page === p.id ? 'page' : undefined}
              >
                <span className="nav-drawer-label">{p.label}</span>
              </InternalLink>
            </li>
          ))}
        </ul>
      </div>}
    </React.Fragment>
  );
}

// ─── Footer ──────────────────────────────────────────────────
function Footer({ go }) {
  const year = new Date().getFullYear();
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-top">
          <div className="footer-brand-block">
            <div className="footer-brand-lockup">
              <img
                className="footer-brand-logo"
                src="/assets/logo/ideligo-logo-stacked-inverse.svg"
                alt="IDELIGO"
              />
            </div>
            <div className="footer-tag">
              Strategic systems &amp; transformation advisory — for the organisations, programmes and leaders working in the difficult middle.
            </div>
          </div>

          <div className="footer-col">
            <div className="footer-col-title">Practice</div>
            <ul>
              <li><InternalLink href={ROUTES.about.href} go={go}>About</InternalLink></li>
              <li><InternalLink href={ROUTES.insights.href} go={go}>Insights</InternalLink></li>
              <li><InternalLink href={ROUTES.cases.href} go={go}>Case Studies</InternalLink></li>
              <li><InternalLink href={ROUTES.services.href} go={go}>Services</InternalLink></li>
            </ul>
          </div>

          <div className="footer-col">
            <div className="footer-col-title">Topics</div>
            <ul>
              <li><InternalLink href={ROUTES.insights.href} go={go}>Complexity &amp; Systems</InternalLink></li>
              <li><InternalLink href={ROUTES.insights.href} go={go}>Business Analysis</InternalLink></li>
              <li><InternalLink href={ROUTES.insights.href} go={go}>Human Dynamics</InternalLink></li>
              <li><InternalLink href={ROUTES.insights.href} go={go}>Governance &amp; Requirements</InternalLink></li>
              <li><InternalLink href={ROUTES.insights.href} go={go}>Discernment &amp; Meaning</InternalLink></li>
            </ul>
          </div>

          <div className="footer-col">
            <div className="footer-col-title">Direct</div>
            <ul>
              <li><a href="mailto:hello@ideligo.com">hello@ideligo.com</a></li>
              <li><InternalLink href={ROUTES.contact.href} go={go}>Begin a conversation</InternalLink></li>
            </ul>
            <div className="footer-socials" aria-label="Social media">
              <a
                className="footer-social-icon"
                href="https://www.linkedin.com/in/irina-dunayevsky-mba-pmp/"
                target="_blank"
                rel="noopener noreferrer"
                aria-label="LinkedIn"
                title="LinkedIn"
              >
                <svg viewBox="0 0 24 24" aria-hidden="true">
                  <path d="M6.5 8.25V18M6.5 5.5v.01M10.5 18v-5.25a3.25 3.25 0 0 1 6.5 0V18M10.5 8.25V18" />
                </svg>
              </a>
              <span
                className="footer-social-icon is-placeholder"
                aria-label="X — link coming soon"
                aria-disabled="true"
                title="X — link coming soon"
              >
                <svg viewBox="0 0 24 24" aria-hidden="true">
                  <path d="m7 6 10 12M17 6 7 18" />
                </svg>
              </span>
              <span
                className="footer-social-icon is-placeholder"
                aria-label="WhatsApp Business — link coming soon"
                aria-disabled="true"
                title="WhatsApp Business — link coming soon"
              >
                <svg viewBox="0 0 24 24" aria-hidden="true">
                  <path d="M6.5 18.25 7 15.7a7 7 0 1 1 2.3 2.05l-2.8.5Z" />
                  <path d="M9.4 9.1c.45 2.15 2.2 3.9 4.35 4.35" />
                </svg>
              </span>
            </div>
          </div>
        </div>

        <div className="footer-bottom">
          <span>© {year} Ideligo · All rights reserved</span>
          <div className="footer-legal" aria-label="Legal links">
            <span aria-disabled="true" title="Privacy — coming soon">Privacy</span>
            <span className="footer-legal-separator" aria-hidden="true">·</span>
            <span aria-disabled="true" title="Terms of use — coming soon">Terms of use</span>
          </div>
          <span>Strategic systems advisory</span>
        </div>
      </div>
    </footer>
  );
}

// ─── Section helpers ─────────────────────────────────────────
function SectionHead({ label, title, action }) {
  return (
    <div className="section-head">
      <span className="label section-eyebrow">{label}</span>
      <h2 className="display-3" dangerouslySetInnerHTML={{ __html: title }} />
      {action ? action : <span />}
    </div>
  );
}

function CTABlock({ go }) {
  return (
    <section className="cta-block">
      <div className="cta-inner">
        <span className="cta-label section-eyebrow">Engage</span>
        <h2 className="cta-h2">
          Ready to think<br />
          through something <em>complex?</em>
        </h2>
        <p className="cta-sub">
          Whether you are navigating a transformation, untangling a requirements problem, or trying to make sense of a situation that resists simple answers — a direct conversation is the right place to start.
        </p>
        <div className="cta-action">
          <button className="btn btn-primary" onClick={() => go('contact')}>
            Begin a conversation <span className="arrow">→</span>
          </button>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, {
  Reveal, Nav, Footer, Brand, SectionHead, CTABlock,
  ROUTES, PAGES, SERVICE_PILLARS, resolveRouteTarget, routeIdFromPath,
});
