/* 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, onNavigate }) {
  return (
    <a
      className={`brand ${current ? 'active' : ''}`}
      href="/"
      onClick={(event) => {
        event.preventDefault();
        onNavigate?.();
        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' },
  privacy: { id: 'privacy', label: 'Privacy', href: '/privacy' },
  terms: { id: 'terms', label: 'Terms of use', href: '/terms' },
};

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.',
    challenges: [
      'Unclear or contested direction, strategy and priorities',
      'Major decisions needing structured options and evidence',
      'Readiness or maturity questions before further investment',
      'Business cases, procurement and vendor selection needing independent support',
    ],
  },
  {
    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.',
    challenges: [
      'Business objectives not translating into coherent design direction',
      'Current-state complexity obscuring redesign or platform choices',
      'Requirements lacking quality, traceability or prioritisation',
      'Business and technology teams working from different views',
    ],
  },
  {
    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.',
    challenges: [
      'AI adoption progressing without clear governance or accountability',
      'Licensing, vendor and process ownership remaining unclear',
      'Decision rights, human oversight and escalation not explicit',
      'Cyber, privacy, data and regulatory duties not embedded early',
    ],
  },
  {
    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.',
    challenges: [
      'Complex delivery lacking governance, coordination or visibility',
      'Vendor delivery requiring closer oversight and assurance',
      'Readiness, adoption impacts and dependencies remaining uncertain',
      'Post-implementation controls, workflows and value not holding',
    ],
  },
].map((service) => ({ ...service, href: `/services#${service.id}` }));

const PAGE_SECTIONS = {
  home: [
    { id: 'where-complexity-shows-up', title: 'Where complexity shows up', href: '/#where-complexity-shows-up' },
    { id: 'some-services', title: 'Our services', href: '/#some-services' },
    { id: 'latest-insights', title: 'Latest insights', href: '/#latest-insights' },
  ],
  services: [
    { id: 'engagement-start', title: 'How to engage with us', href: '/services#engagement-start' },
    { id: 'service-pillars-overview', title: 'Service pillars', href: '/services#service-pillars-overview' },
    { id: 'service-pillars', title: 'Service details', href: '/services#service-pillars' },
  ],
  cases: [
    { id: 'selected-engagements', title: 'Selected engagements', href: '/case-studies#selected-engagements' },
    { id: 'engagement-journey', title: 'Engagement journey', href: '/case-studies#engagement-journey' },
  ],
  insights: [
    { id: 'perspectives', title: 'Perspectives', href: '/insights#perspectives' },
    { id: 'frameworks', title: 'Frameworks', href: '/insights#frameworks' },
  ],
  about: [
    { id: 'who-we-are', title: 'Who we are', href: '/about#who-we-are' },
    { id: 'our-values', title: 'Our values', href: '/about#our-values' },
    { id: 'why-ideligo', title: 'Why IDELIGO?', href: '/about#why-ideligo' },
    { id: 'golden-edge', title: 'Our golden edge', href: '/about#golden-edge' },
    { id: 'how-we-work', title: 'How we work', href: '/about#how-we-work' },
  ],
};

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';
  if (path === '/privacy') return 'privacy';
  if (path === '/terms') return 'terms';
  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 SearchToggle({ onOpen, className = '' }) {
  return (
    <button
      type="button"
      className={`nav-search-toggle ${className}`.trim()}
      onClick={(event) => onOpen(event.currentTarget)}
      aria-label="Search the IDELIGO website"
      title="Search"
    >
      <svg viewBox="0 0 24 24" aria-hidden="true">
        <circle cx="10.75" cy="10.75" r="6.25" />
        <path d="m15.5 15.5 4 4" />
      </svg>
    </button>
  );
}

function Nav({ page, activeSection, go, onSearchOpen }) {
  const [menuOpen, setMenuOpen] = useState(false);
  const [desktopSectionOpen, setDesktopSectionOpen] = useState('');
  const [mobileSectionOpen, setMobileSectionOpen] = useState('');
  const toggleRef = useRef(null);
  const drawerRef = useRef(null);
  const desktopSectionRefs = useRef({});
  const desktopSectionToggleRefs = useRef({});
  const desktopCloseTimer = useRef(null);

  // Close disclosures whenever the route or fragment changes.
  useEffect(() => {
    setMenuOpen(false);
    setDesktopSectionOpen('');
    setMobileSectionOpen('');
  }, [page, activeSection]);

  useEffect(() => {
    if (!desktopSectionOpen) return;
    const onPointerDown = (event) => {
      if (!desktopSectionRefs.current[desktopSectionOpen]?.contains(event.target)) {
        setDesktopSectionOpen('');
      }
    };
    document.addEventListener('pointerdown', onPointerDown);
    return () => document.removeEventListener('pointerdown', onPointerDown);
  }, [desktopSectionOpen]);

  useEffect(() => () => {
    if (desktopCloseTimer.current) window.clearTimeout(desktopCloseTimer.current);
  }, []);

  // 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);
    setMobileSectionOpen('');
    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);
    setMobileSectionOpen('');
    go(target);
  };

  const closeDesktopSection = (pageId, restoreFocus = false) => {
    if (desktopCloseTimer.current) window.clearTimeout(desktopCloseTimer.current);
    setDesktopSectionOpen('');
    if (restoreFocus) {
      requestAnimationFrame(() => desktopSectionToggleRefs.current[pageId]?.focus({ preventScroll: true }));
    }
  };

  const openDesktopSection = (pageId) => {
    if (desktopCloseTimer.current) window.clearTimeout(desktopCloseTimer.current);
    setDesktopSectionOpen(pageId);
  };

  const scheduleDesktopSectionClose = (pageId) => {
    if (desktopCloseTimer.current) window.clearTimeout(desktopCloseTimer.current);
    desktopCloseTimer.current = window.setTimeout(() => {
      setDesktopSectionOpen((current) => current === pageId ? '' : current);
    }, 140);
  };

  const onDesktopSectionKeyDown = (event, pageId) => {
    if (event.key === 'Escape' && desktopSectionOpen === pageId) {
      event.preventDefault();
      closeDesktopSection(pageId, true);
    }
  };

  return (
    <React.Fragment>
      <nav className="nav">
        <div className="container">
          <div className="nav-inner">
            <div
              ref={(element) => { desktopSectionRefs.current.home = element; }}
              className="nav-brand-item"
              onKeyDown={(event) => onDesktopSectionKeyDown(event, 'home')}
              onMouseEnter={() => openDesktopSection('home')}
              onMouseLeave={() => scheduleDesktopSectionClose('home')}
              onFocus={() => openDesktopSection('home')}
              onBlur={(event) => {
                if (!event.currentTarget.contains(event.relatedTarget)) {
                  scheduleDesktopSectionClose('home');
                }
              }}
            >
              <span className="nav-brand-main">
                <Brand
                  current={page === 'home'}
                  go={go}
                  onNavigate={() => setDesktopSectionOpen('')}
                />
                <button
                  ref={(element) => { desktopSectionToggleRefs.current.home = element; }}
                  type="button"
                  className="nav-services-toggle nav-brand-toggle"
                  aria-label={`${desktopSectionOpen === 'home' ? 'Hide' : 'Show'} Home destinations`}
                  aria-expanded={desktopSectionOpen === 'home'}
                  aria-controls="desktop-home-submenu"
                  onClick={() => setDesktopSectionOpen((current) => current === 'home' ? '' : 'home')}
                >
                  <span aria-hidden="true">⌄</span>
                </button>
              </span>
              <ul
                id="desktop-home-submenu"
                className="nav-services-submenu nav-brand-submenu"
                hidden={desktopSectionOpen !== 'home'}
              >
                {PAGE_SECTIONS.home.map((section) => (
                  <li key={section.id} onClick={() => setDesktopSectionOpen('')}>
                    <InternalLink
                      href={section.href}
                      go={go}
                      className={page === 'home' && activeSection === section.id ? 'active' : ''}
                      aria-current={page === 'home' && activeSection === section.id ? 'location' : undefined}
                    >
                      {section.title}
                    </InternalLink>
                  </li>
                ))}
              </ul>
            </div>

            {/* Desktop: page links with optional section disclosures. */}
            <ul className="nav-links nav-links-pages">
              {PAGES.filter((p) => p.id !== 'home').map((p) => {
                const sections = PAGE_SECTIONS[p.id];
                if (!sections) {
                  return (
                    <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>
                  );
                }

                const open = desktopSectionOpen === p.id;
                return (
                  <li
                    key={p.id}
                    ref={(element) => { desktopSectionRefs.current[p.id] = element; }}
                    className="nav-services-item"
                    onKeyDown={(event) => onDesktopSectionKeyDown(event, p.id)}
                    onMouseEnter={() => openDesktopSection(p.id)}
                    onMouseLeave={() => scheduleDesktopSectionClose(p.id)}
                    onFocus={() => openDesktopSection(p.id)}
                    onBlur={(event) => {
                      if (!event.currentTarget.contains(event.relatedTarget)) {
                        scheduleDesktopSectionClose(p.id);
                      }
                    }}
                  >
                    <span className="nav-services-main">
                      <InternalLink
                        href={p.href}
                        go={go}
                        className={`nav-link ${page === p.id ? 'active' : ''}`}
                        aria-current={page === p.id ? 'page' : undefined}
                      >
                        {p.label}
                      </InternalLink>
                      <button
                        ref={(element) => { desktopSectionToggleRefs.current[p.id] = element; }}
                        type="button"
                        className="nav-services-toggle"
                        aria-label={`${open ? 'Hide' : 'Show'} ${p.label} destinations`}
                        aria-expanded={open}
                        aria-controls={`desktop-${p.id}-submenu`}
                        onClick={(event) => {
                          if (event.detail !== 0 && window.matchMedia('(hover: hover)').matches) {
                            openDesktopSection(p.id);
                            return;
                          }
                          setDesktopSectionOpen((current) => current === p.id ? '' : p.id);
                        }}
                      >
                        <span aria-hidden="true">⌄</span>
                      </button>
                    </span>
                    <ul
                      id={`desktop-${p.id}-submenu`}
                      className="nav-services-submenu"
                      hidden={!open}
                    >
                      {sections.map((section) => (
                        <li key={section.id} onClick={() => setDesktopSectionOpen('')}>
                          <InternalLink
                            href={section.href}
                            go={go}
                            className={page === p.id && activeSection === section.id ? 'active' : ''}
                            aria-current={page === p.id && activeSection === section.id ? 'location' : undefined}
                          >
                            {section.title}
                          </InternalLink>
                        </li>
                      ))}
                    </ul>
                  </li>
                );
              })}
            </ul>

            <SearchToggle onOpen={onSearchOpen} className="nav-search-toggle--desktop" />

            {/* Mobile: burger */}
            <div className="nav-mobile-controls">
              <SearchToggle onOpen={onSearchOpen} className="nav-search-toggle--mobile" />
              <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-home-sections">
            <ul className="nav-drawer-submenu nav-drawer-submenu--home" aria-label="Home page sections">
              {PAGE_SECTIONS.home.map((section) => (
                <li key={section.id}>
                  <InternalLink
                    href={section.href}
                    go={navigateAndClose}
                    className={page === 'home' && activeSection === section.id ? 'active' : ''}
                    aria-current={page === 'home' && activeSection === section.id ? 'location' : undefined}
                  >
                    {section.title}
                  </InternalLink>
                </li>
              ))}
            </ul>
          </li>
          {PAGES.filter((p) => p.id !== 'home').map((p) => {
            const sections = PAGE_SECTIONS[p.id];
            if (!sections) {
              return (
                <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>
              );
            }

            const open = mobileSectionOpen === p.id;
            return (
              <li key={p.id} className="nav-drawer-services">
                <div className="nav-drawer-service-row">
                  <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>
                  <button
                    type="button"
                    className="nav-drawer-disclosure"
                    aria-label={`${open ? 'Hide' : 'Show'} ${p.label} destinations`}
                    aria-expanded={open}
                    aria-controls={`mobile-${p.id}-submenu`}
                    onClick={() => setMobileSectionOpen((current) => current === p.id ? '' : p.id)}
                  >
                    <span aria-hidden="true">⌄</span>
                  </button>
                </div>
                <ul
                  id={`mobile-${p.id}-submenu`}
                  className="nav-drawer-submenu"
                  hidden={!open}
                >
                  {sections.map((section) => (
                    <li key={section.id}>
                      <InternalLink
                        href={section.href}
                        go={navigateAndClose}
                        className={page === p.id && activeSection === section.id ? 'active' : ''}
                        aria-current={page === p.id && activeSection === section.id ? 'location' : undefined}
                      >
                        {section.title}
                      </InternalLink>
                    </li>
                  ))}
                </ul>
              </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="/insights#frameworks" go={go}>Frameworks</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 className="footer-topic-list">
              <li><InternalLink href="/services#strategic-transformation-decision-advisory" go={go}>Strategic Transformation &amp; Decision Advisory</InternalLink></li>
              <li><InternalLink href="/services#enterprise-architecture-analysis" go={go}>Enterprise Architecture &amp; Analysis</InternalLink></li>
              <li><InternalLink href="/services#ai-governance-digital-trust" go={go}>AI, Governance &amp; Digital Trust</InternalLink></li>
              <li><InternalLink href="/services#transformation-delivery-assurance" go={go}>Transformation Delivery &amp; Assurance</InternalLink></li>
              <li><InternalLink href="/services#engagement-start" go={go}>Engage with us</InternalLink></li>
            </ul>
          </div>

          <div className="footer-col footer-col--connect">
            <div className="footer-col-title">Connect</div>
            <div className="footer-socials" aria-label="Connect with Ideligo">
              <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="M20.45 20.45h-3.56v-5.57c0-1.33-.02-3.04-1.85-3.04-1.85 0-2.14 1.45-2.14 2.94v5.67H9.34V9h3.42v1.56h.05c.48-.9 1.64-1.85 3.37-1.85 3.61 0 4.27 2.37 4.27 5.46v6.28ZM5.32 7.43a2.06 2.06 0 1 1 0-4.12 2.06 2.06 0 0 1 0 4.12ZM7.1 20.45H3.54V9H7.1v11.45Z" />
                </svg>
              </a>
              <a
                className="footer-social-icon"
                href="mailto:contact@ideligoconsulting.com"
                aria-label="Email Ideligo"
                title="Email Ideligo"
              >
                <svg viewBox="0 0 24 24" aria-hidden="true">
                  <path d="M3.5 5.75h17v12.5h-17z" />
                  <path d="m4.5 7 7.5 5.5L19.5 7" />
                </svg>
              </a>
            </div>
          </div>
        </div>

        <div className="footer-bottom">
          <span>© {year} Ideligo · All rights reserved</span>
          <div className="footer-legal" aria-label="Legal links">
            <InternalLink href={ROUTES.privacy.href} go={go}>Privacy</InternalLink>
            <span className="footer-legal-separator" aria-hidden="true">·</span>
            <InternalLink href={ROUTES.terms.href} go={go}>Terms of use</InternalLink>
          </div>
          <span>Strategic systems advisory</span>
          <span className="footer-version" aria-label="Website version 2.3.2">v2.3.2</span>
        </div>
      </div>
    </footer>
  );
}

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

function CTABlock({ go }) {
  return (
    <section className="cta-block">
      <div className="cta-inner">
        <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, PAGE_SECTIONS, resolveRouteTarget, routeIdFromPath,
});
