/* global React */

const SITE_SEARCH_ITEMS = [
  {
    kind: 'Page',
    title: 'Home',
    href: '/',
    excerpt: 'Strategic clarity for complex digital transformation.',
    keywords: 'Ideligo consultancy transformation clarity',
  },
  {
    kind: 'Page',
    title: 'Services',
    href: '/services',
    excerpt: 'Four connected service pillars and ways to engage.',
    keywords: 'advisory architecture governance assurance engagement',
  },
  {
    kind: 'Service',
    title: 'Strategic Transformation & Decision Advisory',
    href: '/services#strategic-transformation-decision-advisory',
    excerpt: 'Direction, priorities, options and executive decision support.',
    keywords: 'strategy roadmap readiness maturity business case procurement value',
  },
  {
    kind: 'Service',
    title: 'Enterprise Architecture & Analysis',
    href: '/services#enterprise-architecture-analysis',
    excerpt: 'Connect business intent, operating models, processes, requirements and technology.',
    keywords: 'capability current state future state process workflow solution integration API data',
  },
  {
    kind: 'Service',
    title: 'AI, Governance & Digital Trust',
    href: '/services#ai-governance-digital-trust',
    excerpt: 'Governed, accountable and operationally integrated AI and digital capability.',
    keywords: 'AI adoption risk controls privacy cyber data licensing vendor decision rights',
  },
  {
    kind: 'Service',
    title: 'Transformation Delivery & Assurance',
    href: '/services#transformation-delivery-assurance',
    excerpt: 'Delivery governance, readiness, adoption, assurance and realised outcomes.',
    keywords: 'implementation oversight vendor post implementation benefits value leadership',
  },
  {
    kind: 'Page',
    title: 'Case Studies',
    href: '/case-studies',
    excerpt: 'Evidence from real engagements, generalised with care.',
    keywords: 'selected work proof outcomes engagements sectors',
  },
  {
    kind: 'Case studies',
    title: 'Engagement journey',
    href: '/case-studies#engagement-journey',
    excerpt: 'How complex situations move towards aligned action and realised value.',
    keywords: 'situation clarity direction confidence outcomes learn adapt',
  },
  {
    kind: 'Case studies',
    title: 'Selected engagements',
    href: '/case-studies#selected-engagements',
    excerpt: 'Challenge, contribution, capabilities, duration and outcomes across sectors.',
    keywords: 'ITSM requirements governance platform operating model process architecture',
  },
  {
    kind: 'Page',
    title: 'Insights',
    href: '/insights',
    excerpt: 'Frameworks and perspectives for complex transformation.',
    keywords: 'thinking enquiry articles perspectives frameworks',
  },
  {
    kind: 'Insight topic',
    title: 'AI & Digital Governance',
    href: '/insights#ai-digital-governance',
    excerpt: 'Purpose, ownership, human oversight, controls and value measures for AI.',
    keywords: 'AI innovation adoption regulation risk compliance',
  },
  {
    kind: 'Insight topic',
    title: 'Transformation & Decision Quality',
    href: '/insights#transformation-decision-quality',
    excerpt: 'Direction, priorities, readiness and decisions connected to outcomes.',
    keywords: 'change readiness value realisation assurance',
  },
  {
    kind: 'Insight topic',
    title: 'Architecture, Analysis & Operating Models',
    href: '/insights#architecture-analysis-operating-models',
    excerpt: 'Coherent, implementation-ready direction across organisational systems.',
    keywords: 'requirements workflow process business technology alignment',
  },
  {
    kind: 'Insight topic',
    title: 'Governance, Accountability & Assurance',
    href: '/insights#governance-accountability-assurance',
    excerpt: 'Controls, obligations and accountability made visible early enough to matter.',
    keywords: 'GRC procurement vendor regulation compliance assurance',
  },
  {
    kind: 'Framework',
    title: 'Transformation Readiness',
    href: '/insights#framework-transformation-readiness',
    excerpt: 'Test whether the conditions for a credible next commitment are in place.',
    keywords: 'direction outcomes ownership dependencies governance readiness',
  },
  {
    kind: 'Framework',
    title: 'Governance Visibility',
    href: '/insights#framework-governance-visibility',
    excerpt: 'Make ownership, authority, controls and escalation visible.',
    keywords: 'accountability decision rights operational practice',
  },
  {
    kind: 'Framework',
    title: 'Requirements & Traceability',
    href: '/insights#framework-requirements-traceability',
    excerpt: 'Connect intent to commitments, implementation evidence and acceptance.',
    keywords: 'business purpose procurement solution delivery outcome',
  },
  {
    kind: 'Framework',
    title: 'AI Governance / Adoption Readiness',
    href: '/insights#framework-ai-governance-adoption-readiness',
    excerpt: 'Move from AI experimentation to governed operational capability.',
    keywords: 'human oversight risk controls vendor obligations measurable value',
  },
  {
    kind: 'Framework',
    title: 'Stakeholder Alignment',
    href: '/insights#framework-stakeholder-alignment',
    excerpt: 'Surface influence, competing interests and missing voices.',
    keywords: 'people authority support users obligations delivery risk',
  },
  {
    kind: 'Framework',
    title: 'Transformation Assurance',
    href: '/insights#framework-transformation-assurance',
    excerpt: 'Maintain visibility of alignment, readiness, risk and realised value.',
    keywords: 'delivery evidence adoption outcomes independent review',
  },
  {
    kind: 'Page',
    title: 'About IDELIGO',
    href: '/about',
    excerpt: 'Who we are, our golden edge, experience, values and approach.',
    keywords: 'Melbourne boutique consultancy clarity accountability integrity',
  },
  {
    kind: 'Page',
    title: 'Contact',
    href: '/contact',
    excerpt: 'Start a direct conversation about a complex situation.',
    keywords: 'enquiry email engagement partnership office',
  },
];

function normaliseSearchText(value) {
  return value.toLocaleLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();
}

function GlobalSearch({ open, onClose, onNavigate }) {
  const [query, setQuery] = React.useState('');
  const inputRef = React.useRef(null);
  const dialogRef = React.useRef(null);

  React.useEffect(() => {
    if (!open) return undefined;
    const background = [
      document.querySelector('.nav'),
      document.querySelector('main'),
      document.querySelector('.footer'),
    ].filter(Boolean);
    document.body.style.overflow = 'hidden';
    background.forEach((element) => { element.inert = true; });
    requestAnimationFrame(() => inputRef.current?.focus({ preventScroll: true }));

    return () => {
      document.body.style.overflow = '';
      background.forEach((element) => { element.inert = false; });
    };
  }, [open]);

  React.useEffect(() => {
    if (!open) setQuery('');
  }, [open]);

  if (!open) return null;

  const terms = normaliseSearchText(query).split(' ').filter(Boolean);
  const results = SITE_SEARCH_ITEMS.filter((item) => {
    if (!terms.length) return item.kind === 'Page';
    const haystack = normaliseSearchText(`${item.title} ${item.excerpt} ${item.keywords}`);
    return terms.every((term) => haystack.includes(term));
  }).slice(0, 12);

  const handleKeyDown = (event) => {
    if (event.key === 'Escape') {
      event.preventDefault();
      onClose();
      return;
    }
    if (event.key !== 'Tab') return;
    const controls = Array.from(
      dialogRef.current?.querySelectorAll('button:not([disabled]), input, a[href]') || []
    );
    if (!controls.length) return;
    const first = controls[0];
    const last = controls[controls.length - 1];
    if (event.shiftKey && document.activeElement === first) {
      event.preventDefault();
      last.focus();
    } else if (!event.shiftKey && document.activeElement === last) {
      event.preventDefault();
      first.focus();
    }
  };

  return (
    <div
      className="search-overlay"
      onPointerDown={(event) => {
        if (event.target === event.currentTarget) onClose();
      }}
    >
      <section
        ref={dialogRef}
        className="search-dialog"
        role="dialog"
        aria-modal="true"
        aria-labelledby="site-search-title"
        onKeyDown={handleKeyDown}
      >
        <div className="search-dialog-head">
          <div>
            <span className="label section-eyebrow">Across IDELIGO</span>
            <h2 id="site-search-title">Search the website</h2>
          </div>
          <button type="button" className="search-close" onClick={onClose} aria-label="Close search">
            <span aria-hidden="true">×</span>
          </button>
        </div>

        <label className="search-field-label" htmlFor="site-search-input">What are you looking for?</label>
        <div className="search-field-wrap">
          <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>
          <input
            ref={inputRef}
            id="site-search-input"
            type="search"
            value={query}
            onChange={(event) => setQuery(event.target.value)}
            placeholder="Search services, insights, frameworks…"
            autoComplete="off"
          />
        </div>

        <p className="search-count" role="status" aria-live="polite" aria-atomic="true">
          {terms.length
            ? `${results.length} ${results.length === 1 ? 'result' : 'results'}`
            : 'Suggested destinations'}
        </p>

        <div className="search-results">
          {results.map((item) => (
            <a
              key={`${item.kind}-${item.title}`}
              className="search-result"
              href={item.href}
              onClick={(event) => {
                event.preventDefault();
                onNavigate(item.href);
              }}
            >
              <span className="search-result-kind">{item.kind}</span>
              <span className="search-result-title">{item.title}</span>
              <span className="search-result-excerpt">{item.excerpt}</span>
              <span className="search-result-arrow" aria-hidden="true">→</span>
            </a>
          ))}
          {!results.length && (
            <div className="search-empty">
              <h3>No matching result</h3>
              <p>Try a service, topic, challenge or framework name.</p>
            </div>
          )}
        </div>
      </section>
    </div>
  );
}

Object.assign(window, { GlobalSearch, SITE_SEARCH_ITEMS });
