/* global React, ReactDOM, useTweaks, TweaksPanel,
   TweakSection, TweakRadio, TweakSelect,
   Nav, Footer, HomePage, AboutPage, InsightsPage,
   CasesPage, ServicesPage, ContactPage,
   resolveRouteTarget, routeIdFromPath */

const { useState, useEffect, useRef } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "type": "newsreader",
  "density": "regular",
  "heroVariant": "clarity"
}/*EDITMODE-END*/;

const HERO_VARIANTS = {
  clarity: {
    eyebrow: "Ideligo · Strategic Systems & Transformation",
    line1: "Clarity",
    line2: "is a",
    line3: "discipline.",
    em: "",
  },
  complexity: {
    eyebrow: "Ideligo · Principal Analyst, Business Solutions Architect & Advisor",
    line1: "Complexity",
    line2: "doesn't have",
    line3: "to be ",
    em: "confusing.",
  },
  practice: {
    eyebrow: "Ideligo · Principal Business Systems Analyst",
    line1: "A practice",
    line2: "for the",
    line3: "difficult ",
    em: "middle.",
  },
};

function App() {
  const [tweak, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const readLocation = () => ({
    page: routeIdFromPath(window.location.pathname),
    path: window.location.pathname,
    hash: window.location.hash,
  });
  const [location, setLocation] = useState(readLocation);
  const mainRef = useRef(null);
  const shouldFocusMain = useRef(false);

  const page = location.page;
  const activeService = page === 'services'
    ? location.hash.replace(/^#/, '')
    : '';

  useEffect(() => {
    const root = document.documentElement;
    if (tweak.type === 'newsreader') root.removeAttribute('data-type');
    else root.setAttribute('data-type', tweak.type);

    const dens = tweak.density === 'compact' ? '0.82'
              : tweak.density === 'airy' ? '1.18'
              : '1';
    root.style.setProperty('--density', dens);
  }, [tweak.type, tweak.density]);

  const go = (target) => {
    const href = resolveRouteTarget(target);
    const nextUrl = new URL(href, window.location.origin);
    const currentHref = `${window.location.pathname}${window.location.hash}`;
    const nextHref = `${nextUrl.pathname}${nextUrl.hash}`;

    shouldFocusMain.current = true;
    if (currentHref !== nextHref) {
      window.history.pushState({}, '', nextHref);
      setLocation(readLocation());
      return;
    }

    setLocation({ ...readLocation() });
  };

  useEffect(() => {
    const onPopState = () => {
      shouldFocusMain.current = false;
      setLocation(readLocation());
    };
    window.addEventListener('popstate', onPopState);
    return () => window.removeEventListener('popstate', onPopState);
  }, []);

  useEffect(() => {
    if (window.location.pathname !== '/frameworks') return;
    window.history.replaceState({}, '', '/insights');
    setLocation(readLocation());
  }, []);

  useEffect(() => {
    const titles = {
      home: 'Ideligo — Strategic Systems & Transformation',
      about: 'About — Ideligo',
      insights: 'Insights — Ideligo',
      cases: 'Case Studies — Ideligo',
      services: 'Services — Ideligo',
      contact: 'Contact — Ideligo',
    };
    document.title = titles[page] || titles.home;

    requestAnimationFrame(() => {
      const fragmentId = location.hash.replace(/^#/, '');
      const fragmentTarget = fragmentId ? document.getElementById(fragmentId) : null;

      if (fragmentTarget) {
        fragmentTarget.scrollIntoView({ block: 'start', behavior: 'auto' });
        if (shouldFocusMain.current) {
          const heading = fragmentTarget.querySelector('[data-route-heading]');
          heading?.focus({ preventScroll: true });
        }
      } else {
        window.scrollTo({ top: 0, behavior: 'auto' });
        if (shouldFocusMain.current) {
          mainRef.current?.focus({ preventScroll: true });
        }
      }
      shouldFocusMain.current = false;
    });
  }, [page, location.hash]);

  const heroV = HERO_VARIANTS[tweak.heroVariant] || HERO_VARIANTS.clarity;

  const PageComponent = {
    home: HomePage,
    about: AboutPage,
    insights: InsightsPage,
    cases: CasesPage,
    services: ServicesPage,
    contact: ContactPage,
  }[page] || HomePage;

  const skipToMain = (event) => {
    event.preventDefault();
    window.scrollTo({ top: 0, behavior: 'auto' });
    mainRef.current?.focus({ preventScroll: true });
  };

  return (
    <React.Fragment>
      <a className="skip-link" href="#main-content" onClick={skipToMain}>Skip to main content</a>
      <Nav page={page} activeService={activeService} go={go} />

      <main id="main-content" ref={mainRef} tabIndex="-1" key={page}>
        <PageComponent go={go} hero={heroV} activeService={activeService} />
      </main>

      <Footer go={go} />

      <TweaksPanel title="Site tweaks">
        <TweakSection label="Typography" />
        <TweakRadio
          label="Serif"
          value={tweak.type}
          options={['newsreader', 'editorial']}
          onChange={(v) => setTweak('type', v)}
        />

        <TweakSection label="Density" />
        <TweakRadio
          label="Rhythm"
          value={tweak.density}
          options={['compact', 'regular', 'airy']}
          onChange={(v) => setTweak('density', v)}
        />

        <TweakSection label="Hero headline" />
        <TweakSelect
          label="Variant"
          value={tweak.heroVariant}
          options={[
            { value: 'clarity',    label: 'Clarity is a discipline.' },
            { value: 'complexity', label: "Complexity doesn't have to be confusing." },
            { value: 'practice',   label: 'A practice for the difficult middle.' },
          ]}
          onChange={(v) => setTweak('heroVariant', v)}
        />
      </TweaksPanel>
    </React.Fragment>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
