/**
 * Shared "Why SylvanFlow" / founder letter overlay - NuAsk-aligned glass, teal rim, ambient field; primary CTA uses NOW-hub glass stack (`SYLVAN_TECH_THEME.classes.founderOverlayPrimaryCta` + `stylePresets.founderOverlayPrimaryCta`).
 * Copy: SYS_MESSAGES_KV keys `sys:ui:founder_overlay_*` + title `sys:ui:app_drawer_why_sylvanflow` (10 langs).
 * Used by PowerUp (first-run gate) and AppShell menu. Exposes `window.FounderVisionOverlay`.
 */
(function () {
  'use strict';

  const { useEffect, useState } = React;

  const FALLBACK = {
    title: 'Why SylvanFlow',
    subtitle: 'A few words on why we built this',
    p1: "What you're about to see isn't a standard travel app. It was built for moments when decisions matter - when everything is loud, unclear, or pulling you in different directions. Travel does that often. So do doubt, anxiety, feeling alone, feeling small, or feeling like you've lost your footing.",
    p2: "That's why SylvanFlow exists - not as another itinerary planner, and not as a rigid list of must-sees.",
    p3: "It's a flow that changes with you: one that reads the world around you, and reads you.",
    promiseTitle: 'The Promise',
    promiseBody:
      "We don't just move people through places. We move with them - moment by moment. We built SylvanFlow so your time isn't wasted, no one is left behind, and the journey still feels alive.",
    yours: 'Yours sincerely,',
    founderName: 'Fang Gui',
    founderRole: 'Founder of SylvanFlow',
    continue: 'Continue',
    close: 'Close',
    tapHint: 'Tap outside the card to close',
    backdropClose: 'Close'
  };

  function resolveLang() {
    try {
      const c = localStorage.getItem('sylvanflow_preferred_language');
      const valid = ['en', 'zh-CN', 'ja', 'ko', 'th', 'vi', 'id', 'ms', 'ar', 'fil'];
      if (c && valid.includes(c.trim())) return c.trim();
    } catch (_) {}
    return (typeof window !== 'undefined' && window.SylvanFlowState?.getLanguage?.()) || 'en';
  }

  function FounderVisionOverlay({ onDismiss, allowBackdropDismiss }) {
    const [copy, setCopy] = useState(null);
    const tc =
      typeof window !== 'undefined' && window.SYLVAN_TECH_THEME && window.SYLVAN_TECH_THEME.classes
        ? window.SYLVAN_TECH_THEME.classes
        : {};

    const C = copy || FALLBACK;
    const primaryLabel = allowBackdropDismiss ? C.close : C.continue;
    const ctaClass =
      tc.founderOverlayPrimaryCta ||
      'group relative mt-8 flex w-full min-h-[52px] flex-col items-center justify-center overflow-hidden rounded-2xl border border-white/10 px-4 py-3 text-center text-[15px] font-semibold tracking-tight text-slate-100 shadow-none backdrop-blur-lg transition duration-150 motion-safe:active:scale-[0.97] motion-safe:hover:brightness-110 focus:outline-none focus-visible:ring-2 focus-visible:ring-[#2DE2C5]/45 focus-visible:ring-offset-2 focus-visible:ring-offset-[#05080c] [touch-action:manipulation]';
    const ctaStyle =
      (typeof window !== 'undefined' &&
        window.SYLVAN_TECH_THEME &&
        window.SYLVAN_TECH_THEME.stylePresets &&
        window.SYLVAN_TECH_THEME.stylePresets.founderOverlayPrimaryCta) || {
        background: [
          'radial-gradient(96% 52% at 50% 108%, rgba(45,226,197,0.28), transparent 56%)',
          'radial-gradient(95% 54% at 50% -4%, rgba(255,255,255,0.09) 0%, transparent 46%)',
          'linear-gradient(168deg, rgba(255,255,255,0.078) 0%, rgba(255,255,255,0.03) 11%, rgba(18,24,34,0.58) 40%, rgba(4,6,10,0.94) 100%)'
        ].join(', '),
        boxShadow: [
          'inset 0 1px 0 rgba(255,255,255,0.13)',
          'inset 0 0 0 1px rgba(45,226,197,0.22)',
          'inset 0 14px 32px -10px rgba(0,0,0,0.32)',
          'inset 0 -36px 48px -12px rgba(0,0,0,0.48)',
          '0 16px 44px -16px rgba(45,226,197,0.28)',
          '0 1px 0 rgba(0,0,0,0.42)'
        ].join(', ')
      };

    useEffect(() => {
      if (window.SYLVAN_TECH_THEME && typeof window.SYLVAN_TECH_THEME.ensureKeyframes === 'function') {
        window.SYLVAN_TECH_THEME.ensureKeyframes();
      }
    }, []);

    useEffect(() => {
      let cancelled = false;
      const run = async () => {
        const lang = resolveLang();
        const g = window.getSysMessage;
        if (typeof g !== 'function') {
          if (!cancelled) setCopy(FALLBACK);
          return;
        }
        const load = async (key) => {
          try {
            const v = await g(key, lang);
            return v && String(v).trim() ? String(v).trim() : null;
          } catch (_) {
            return null;
          }
        };
        const [
          title,
          subtitle,
          p1,
          p2,
          p3,
          promiseTitle,
          promiseBody,
          yours,
          founderName,
          founderRole,
          continueB,
          closeB,
          tapHint,
          backdropClose
        ] = await Promise.all([
          load('ui:app_drawer_why_sylvanflow'),
          load('ui:founder_overlay_subtitle'),
          load('ui:founder_overlay_body_p1'),
          load('ui:founder_overlay_body_p2'),
          load('ui:founder_overlay_body_p3'),
          load('ui:founder_overlay_promise_title'),
          load('ui:founder_overlay_promise_body'),
          load('ui:founder_overlay_yours_sincerely'),
          load('ui:founder_overlay_founder_name'),
          load('ui:founder_overlay_founder_role'),
          load('ui:founder_overlay_continue'),
          load('ui:founder_overlay_close'),
          load('ui:founder_overlay_tap_outside_hint'),
          load('ui:founder_overlay_close_backdrop_aria')
        ]);
        if (cancelled) return;
        setCopy({
          title: title || FALLBACK.title,
          subtitle: subtitle || FALLBACK.subtitle,
          p1: p1 || FALLBACK.p1,
          p2: p2 || FALLBACK.p2,
          p3: p3 || FALLBACK.p3,
          promiseTitle: promiseTitle || FALLBACK.promiseTitle,
          promiseBody: promiseBody || FALLBACK.promiseBody,
          yours: yours || FALLBACK.yours,
          founderName: founderName || FALLBACK.founderName,
          founderRole: founderRole || FALLBACK.founderRole,
          continue: continueB || FALLBACK.continue,
          close: closeB || FALLBACK.close,
          tapHint: tapHint || FALLBACK.tapHint,
          backdropClose: backdropClose || FALLBACK.backdropClose
        });
      };
      void run();
      const onLang = () => {
        void run();
      };
      const S = typeof window !== 'undefined' ? window.SylvanFlowState : null;
      if (S && typeof S.on === 'function') {
        S.on('language', onLang);
      }
      return () => {
        cancelled = true;
        if (S && typeof S.off === 'function') {
          S.off('language', onLang);
        }
      };
    }, []);

    const onBackdrop = () => {
      if (allowBackdropDismiss && typeof onDismiss === 'function') onDismiss();
    };

    return (
      <div
        className="fixed inset-0 z-[265] flex items-center justify-center px-4 py-8 [padding-bottom:max(1.5rem,env(safe-area-inset-bottom))]"
        role="dialog"
        aria-modal="true"
        aria-labelledby="sf-founder-vision-title"
        aria-describedby="sf-founder-vision-body sf-founder-vision-promise"
      >
        <div className="absolute inset-0 bg-[#020508]" aria-hidden>
          <div
            className={tc.ambientBlobTL || 'pointer-events-none absolute -left-24 -top-24 h-72 w-72 rounded-full bg-cyan-500/15 blur-3xl'}
          />
          <div
            className={
              tc.ambientBlobBR ||
              'pointer-events-none absolute -bottom-28 -right-20 h-80 w-80 rounded-full bg-teal-500/12 blur-3xl'
            }
          />
          <div
            className="pointer-events-none absolute inset-0 opacity-[0.12]"
            style={{
              backgroundImage:
                'linear-gradient(rgba(45,226,197,0.07) 1px, transparent 1px), linear-gradient(90deg, rgba(45,226,197,0.07) 1px, transparent 1px)',
              backgroundSize: '40px 40px'
            }}
          />
          <div
            className="pointer-events-none absolute inset-0"
            style={{
              background:
                'radial-gradient(ellipse 75% 55% at 50% 18%, rgba(45,226,197,0.14), transparent 58%), radial-gradient(ellipse 90% 70% at 80% 100%, rgba(99,102,241,0.08), transparent 50%)'
            }}
          />
        </div>

        {allowBackdropDismiss ? (
          <button
            type="button"
            className="absolute inset-0 z-0 cursor-pointer border-0 bg-black/78 backdrop-blur-[2px]"
            aria-label={C.backdropClose}
            onClick={onBackdrop}
          />
        ) : (
          <div className="pointer-events-none absolute inset-0 z-0 bg-black/78 backdrop-blur-[2px]" aria-hidden />
        )}

        <div className="relative z-[1] flex w-full max-w-[min(92vw,26.5rem)] flex-col items-stretch pointer-events-none">
          <div
            className="pointer-events-auto max-h-[min(82dvh,680px)] w-full overflow-hidden rounded-[22px] p-[1.5px] shadow-[0_0_64px_-18px_rgba(45,226,197,0.38),0_24px_48px_-28px_rgba(0,0,0,0.85)]"
            style={{
              background:
                'linear-gradient(145deg, rgba(45,226,197,0.55) 0%, rgba(34,211,238,0.22) 35%, rgba(99,102,241,0.28) 72%, rgba(45,226,197,0.12) 100%)'
            }}
          >
            <div className="max-h-[min(82dvh,680px)] overflow-y-auto overscroll-y-contain rounded-[20.5px] bg-[#05080c]/[0.97] ring-1 ring-inset ring-white/[0.07]">
              <div className="px-5 pb-8 pt-7 sm:px-8 sm:pb-9 sm:pt-8">
                <div className="flex flex-col items-center text-center">
                  <div
                    className="relative flex h-[52px] w-[52px] items-center justify-center rounded-2xl bg-gradient-to-b from-white/[0.08] to-white/[0.02] p-2 ring-1 ring-[#2DE2C5]/30 shadow-[0_0_40px_-14px_rgba(45,226,197,0.45)]"
                    style={{ animation: 'nuask-edge-refract-ring 6.4s ease-in-out infinite' }}
                  >
                    <img
                      src="/assets/sylvanflow-logo.png"
                      alt=""
                      className="h-8 w-auto max-w-[120px] object-contain opacity-95"
                      decoding="async"
                    />
                  </div>
                  <div className="mt-4 h-px w-14 bg-gradient-to-r from-transparent via-[#2DE2C5]/55 to-transparent" aria-hidden />
                  <h2
                    id="sf-founder-vision-title"
                    className="mt-4 font-mono text-[10px] uppercase tracking-[0.32em] text-[#2DE2C5]/90"
                  >
                    {C.title}
                  </h2>
                  <p className="mt-1.5 max-w-[20rem] text-[11px] leading-snug text-slate-500">{C.subtitle}</p>
                </div>

                <div
                  id="sf-founder-vision-body"
                  className="mt-7 space-y-4 text-left text-[15px] leading-[1.65] text-slate-200/95 text-balance sm:text-base"
                >
                  <p>{C.p1}</p>
                  <p>{C.p2}</p>
                  <p>{C.p3}</p>
                </div>

                <div
                  id="sf-founder-vision-promise"
                  className="mt-8 rounded-xl border border-white/[0.08] bg-gradient-to-br from-[#2DE2C5]/[0.07] via-[#0c1018] to-[#0a1620] px-4 py-5 sm:px-5 sm:py-6"
                >
                  <div className="flex items-center gap-2 border-b border-white/[0.08] pb-3">
                    <span className="h-1.5 w-1.5 shrink-0 rounded-full bg-[#2DE2C5] shadow-[0_0_10px_rgba(45,226,197,0.75)]" aria-hidden />
                    <h3 className="font-mono text-[10px] uppercase tracking-[0.24em] text-[#2DE2C5]/88">{C.promiseTitle}</h3>
                  </div>
                  <p className="mt-4 text-left text-[15px] leading-[1.65] text-slate-100/95 sm:text-base">{C.promiseBody}</p>
                  <div className="mt-8 border-t border-white/[0.07] pt-6 text-left">
                    <p className="font-serif text-[15px] italic text-slate-400">{C.yours}</p>
                    <p className="mt-2 text-base font-semibold tracking-tight text-slate-100">{C.founderName}</p>
                    <p className="mt-0.5 text-xs font-medium uppercase tracking-[0.18em] text-[#2DE2C5]/75">{C.founderRole}</p>
                  </div>
                </div>

                <button type="button" className={ctaClass} style={ctaStyle} onClick={onDismiss}>
                  {primaryLabel}
                </button>
                {allowBackdropDismiss ? (
                  <p className="mt-3 text-center text-[10px] text-slate-500">{C.tapHint}</p>
                ) : null}
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  window.FounderVisionOverlay = FounderVisionOverlay;
})();
