import { A, useLocation } from "@solidjs/router";
import type { RouteSectionProps } from "@solidjs/router";
import { createEffect, createSignal, For, onCleanup, onMount, Show } from "solid-js";
import { getDictionary, type LocaleCode } from "@ben-to/i18n/dictionary";
import { readAnalyticsConsent, writeAnalyticsConsent } from "../infra/cookie-consent-storage";
import { readWelcomeTourDismissed, writeWelcomeTourDismissed } from "../infra/welcome-tour-storage";
import { getMatomoRuntimeConfig, injectMatomoTracker, trackMatomoPageView } from "../infra/matomo";
import { bumpBuilderResetBus } from "./builder-reset-bus";
import { AppLocaleProvider, useAppLocale } from "./app-locale-context";
import { CookieConsentBanner } from "./CookieConsentBanner";
import { WelcomeTourModal } from "./WelcomeTourModal";
import { publicAssetHref } from "./builder-flow/public-asset";

const localeOptions: LocaleCode[] = ["fr", "en", "ko", "zh"];

const localeNativeNames: Record<LocaleCode, string> = {
  fr: "Français",
  en: "English",
  ko: "한국어",
  zh: "中文"
};

const localeFlags: Record<LocaleCode, string> = {
  fr: "🇫🇷",
  en: "🇬🇧",
  ko: "🇰🇷",
  zh: "🇨🇳"
};

function RootLayoutInner(props: RouteSectionProps) {
  const { locale, setLocale } = useAppLocale();
  const location = useLocation();
  const [menuOpen, setMenuOpen] = createSignal(false);
  const t = () => getDictionary(locale());
  const matomoCfg = getMatomoRuntimeConfig();
  const [matomoReady, setMatomoReady] = createSignal(false);
  const [consentBannerOpen, setConsentBannerOpen] = createSignal(readAnalyticsConsent() === "unknown");
  const [welcomeTourOpen, setWelcomeTourOpen] = createSignal(false);

  createEffect(() => {
    location.pathname;
    setMenuOpen(false);
  });

  createEffect(() => {
    location.pathname;
    location.search;
    if (!matomoReady()) return;
    trackMatomoPageView();
  });

  const acceptAnalyticsCookies = () => {
    writeAnalyticsConsent("analytics-accepted");
    setConsentBannerOpen(false);
    if (matomoCfg) {
      void injectMatomoTracker(matomoCfg).then(() => setMatomoReady(true));
    }
  };

  const rejectAnalyticsCookies = () => {
    writeAnalyticsConsent("analytics-rejected");
    setConsentBannerOpen(false);
  };

  const dismissWelcomeTour = () => {
    writeWelcomeTourDismissed();
    setWelcomeTourOpen(false);
  };

  createEffect(() => {
    location.pathname;
    consentBannerOpen();
    if (location.pathname !== "/" || consentBannerOpen()) {
      setWelcomeTourOpen(false);
      return;
    }
    if (readWelcomeTourDismissed()) {
      setWelcomeTourOpen(false);
      return;
    }
    setWelcomeTourOpen(true);
  });

  onMount(() => {
    const consent = readAnalyticsConsent();
    if (consent === "unknown") setConsentBannerOpen(true);
    if (consent === "analytics-accepted" && matomoCfg) {
      void injectMatomoTracker(matomoCfg).then(() => setMatomoReady(true));
    }
    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") {
        if (welcomeTourOpen()) {
          dismissWelcomeTour();
          return;
        }
        setMenuOpen(false);
      }
    };
    window.addEventListener("keydown", onKeyDown);
    onCleanup(() => window.removeEventListener("keydown", onKeyDown));
  });

  return (
    <>
      <header class="topbar">
        <button
          type="button"
          class="topbar__burger"
          aria-expanded={menuOpen()}
          aria-controls="site-nav-drawer"
          aria-label={t().menu}
          onClick={() => setMenuOpen((open) => !open)}
        >
          <span class="topbar__burger-line" aria-hidden="true" />
          <span class="topbar__burger-line" aria-hidden="true" />
          <span class="topbar__burger-line" aria-hidden="true" />
        </button>
        <h1 class="topbar__title">
          <A
            href="/"
            class="brand"
            aria-label={t().home}
            end
            onClick={(event) => {
              if (location.pathname === "/") {
                event.preventDefault();
                bumpBuilderResetBus();
              }
            }}
          >
            <img class="brand__logo" src={publicAssetHref("/branding/onigiri-logo.png")} width="40" height="40" alt="" />
            <span class="brand__wordmark" aria-hidden="true">
              <span class="brand__ben">Ben</span>
              <span class="brand__to">to</span>
            </span>
          </A>
        </h1>
        <div class="topbar__locale" role="radiogroup" aria-label={t().language}>
          <For each={localeOptions}>
            {(code) => (
              <button
                type="button"
                class="topbar__locale-btn"
                classList={{ "topbar__locale-btn--active": locale() === code }}
                role="radio"
                aria-checked={locale() === code}
                title={localeNativeNames[code]}
                onClick={() => setLocale(code)}
              >
                <span class="visually-hidden">{localeNativeNames[code]}</span>
                <span class="topbar__locale-flag" aria-hidden="true">
                  {localeFlags[code]}
                </span>
              </button>
            )}
          </For>
        </div>
      </header>

      {props.children}

      <Show when={menuOpen()}>
        <div
          class="nav-drawer__backdrop"
          role="presentation"
          onClick={() => setMenuOpen(false)}
        />
        <nav
          id="site-nav-drawer"
          class="nav-drawer"
          aria-label={t().menu}
          role="dialog"
          aria-modal="true"
        >
          <div class="nav-drawer__header">
            <span class="nav-drawer__title">{t().menu}</span>
            <button type="button" class="nav-drawer__close" onClick={() => setMenuOpen(false)}>
              {t().menuClose}
            </button>
          </div>
          <ul class="nav-drawer__list">
            <li>
              <A href="/a-propos" class="nav-drawer__link" onClick={() => setMenuOpen(false)}>
                {t().navAbout}
              </A>
            </li>
            <li>
              <A href="/cgu" class="nav-drawer__link" onClick={() => setMenuOpen(false)}>
                {t().navTerms}
              </A>
            </li>
            <li>
              <A href="/mentions-legales" class="nav-drawer__link" onClick={() => setMenuOpen(false)}>
                {t().navLegal}
              </A>
            </li>
            <li>
              <A href="/confidentialite" class="nav-drawer__link" onClick={() => setMenuOpen(false)}>
                {t().navPrivacy}
              </A>
            </li>
          </ul>
        </nav>
      </Show>

      <Show when={consentBannerOpen()}>
        <CookieConsentBanner t={t} onAccept={acceptAnalyticsCookies} onReject={rejectAnalyticsCookies} />
      </Show>

      <WelcomeTourModal t={t} open={welcomeTourOpen} onDismiss={dismissWelcomeTour} />
    </>
  );
}

/** Enveloppe : locale partagée + barre + menu latéral. */
export function RootLayout(props: RouteSectionProps) {
  return (
    <AppLocaleProvider>
      <RootLayoutInner {...props} />
    </AppLocaleProvider>
  );
}
