// Shared site shell — nav, footer, password gate, intro animation.
// Each page imports this and wraps its content in <SiteShell>.
//
// Active route is passed as `route` prop so nav can highlight it.

const ORANGE = '#E8633A';
const BLACK = '#0A0A0B';
const GREEN = '#1FB875';
const YELLOW = '#E5B100';

// ── theme ─────────────────────────────────────────
const THEME_KEY = 'evnted_theme';

function getInitialTheme() {
  try { return localStorage.getItem(THEME_KEY) || 'dark'; }
  catch (e) { return 'dark'; }
}

function applyTheme(t) {
  if (t === 'light') document.documentElement.classList.add('theme-light');
  else document.documentElement.classList.remove('theme-light');
  try { localStorage.setItem(THEME_KEY, t); } catch (e) {}
}

// Apply immediately so first paint matches stored preference
if (typeof document !== 'undefined') applyTheme(getInitialTheme());

function useTheme() {
  const [theme, setTheme] = React.useState(getInitialTheme);
  React.useEffect(() => { applyTheme(theme); }, [theme]);
  return [theme, setTheme];
}

function ThemeToggle({ theme, onChange }) {
  const isLight = theme === 'light';
  return (
    <button
      onClick={() => onChange(isLight ? 'dark' : 'light')}
      aria-label={isLight ? t('themeToggle.switchToDark') : t('themeToggle.switchToLight')}
      style={{
        width: 56, height: 30, borderRadius: 999,
        background: 'var(--bg-soft)',
        border: '1px solid var(--hairline-strong)',
        position: 'relative', cursor: 'pointer', padding: 0,
        transition: 'background 0.2s ease',
      }}
    >
      <span style={{
        position: 'absolute', top: 2, left: isLight ? 28 : 2,
        width: 24, height: 24, borderRadius: '50%',
        background: isLight ? '#0A0A0B' : '#FBFAF7',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        transition: 'left 0.22s cubic-bezier(.4,1.4,.6,1)',
      }}>
        {isLight ? (
          <svg width="12" height="12" viewBox="0 0 24 24" fill="#FBFAF7">
            <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/>
          </svg>
        ) : (
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none"
               stroke="#0A0A0B" strokeWidth="2" strokeLinecap="round">
            <circle cx="12" cy="12" r="4" fill="#0A0A0B"/>
            <line x1="12" y1="3" x2="12" y2="5"/>
            <line x1="12" y1="19" x2="12" y2="21"/>
            <line x1="3" y1="12" x2="5" y2="12"/>
            <line x1="19" y1="12" x2="21" y2="12"/>
            <line x1="5.6" y1="5.6" x2="7" y2="7"/>
            <line x1="17" y1="17" x2="18.4" y2="18.4"/>
            <line x1="5.6" y1="18.4" x2="7" y2="17"/>
            <line x1="17" y1="7" x2="18.4" y2="5.6"/>
          </svg>
        )}
      </span>
    </button>
  );
}

function EvntdMark({ size = 26, color, dotColor }) {
  const dotSize = Math.max(4, size * 0.18);
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center',
      gap: size * 0.18, fontWeight: 800, fontSize: size,
      lineHeight: 1, letterSpacing: '-0.04em',
      color: color || 'var(--fg)',
      fontFamily: '"Geist", system-ui, sans-serif',
    }}>
      <span>Evnt</span>
      <span style={{
        width: dotSize, height: dotSize, borderRadius: '50%',
        background: dotColor || ORANGE, display: 'inline-block', marginBottom: size * 0.05,
      }}/>
      <span>d</span>
    </span>
  );
}

function TrafficDots({ size = 12, gap = 10 }) {
  const ring = (color) => ({
    width: size, height: size, borderRadius: '50%',
    border: `2px solid ${color}`, background: 'transparent',
  });
  return (
    <div style={{ display: 'inline-flex', gap, alignItems: 'center' }}>
      <div style={{ width: size, height: size, borderRadius: '50%', background: GREEN }}/>
      <div style={ring(YELLOW)}/>
      <div style={ring(ORANGE)}/>
    </div>
  );
}

// Build a path that respects the active locale.
// English → no prefix. Other locales → /{loc}/path
function locPath(p) {
  const loc = getActiveLocale();
  if (loc === 'en') return p;
  // p is expected to start with "/"
  return '/' + loc + p;
}

// Top-nav language picker: pill with globe icon + current language label,
// opens a dropdown of all supported locales. Closes on outside click.
function LanguageDropdown() {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  const active = getActiveLocale();

  React.useEffect(() => {
    if (!open) return;
    function onDocClick(e) {
      if (ref.current && !ref.current.contains(e.target)) setOpen(false);
    }
    function onEsc(e) { if (e.key === 'Escape') setOpen(false); }
    document.addEventListener('mousedown', onDocClick);
    document.addEventListener('keydown', onEsc);
    return () => {
      document.removeEventListener('mousedown', onDocClick);
      document.removeEventListener('keydown', onEsc);
    };
  }, [open]);

  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <button
        onClick={() => setOpen(o => !o)}
        aria-label={t('footer.languageLabel')}
        aria-haspopup="listbox"
        aria-expanded={open}
        style={{
          height: 36, padding: '0 12px 0 14px', borderRadius: 999,
          background: open ? 'var(--bg-soft)' : 'transparent',
          border: '1px solid var(--hairline-strong)',
          color: 'var(--fg-soft)',
          display: 'inline-flex', alignItems: 'center', gap: 8,
          fontSize: 13.5, fontWeight: 500,
          cursor: 'pointer', fontFamily: 'inherit',
          transition: 'background .15s ease, color .15s ease',
        }}
      >
        {/* globe icon */}
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none"
             stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <circle cx="12" cy="12" r="10"/>
          <line x1="2" y1="12" x2="22" y2="12"/>
          <path d="M12 2a15 15 0 0 1 4 10 15 15 0 0 1-4 10 15 15 0 0 1-4-10 15 15 0 0 1 4-10z"/>
        </svg>
        <span>{LOCALE_LABELS[active]}</span>
        <svg width="10" height="10" viewBox="0 0 24 24" fill="none"
             stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"
             style={{ transform: open ? 'rotate(180deg)' : 'none', transition: 'transform .15s' }}>
          <polyline points="6 9 12 15 18 9"/>
        </svg>
      </button>
      {open && (
        <div role="listbox" style={{
          position: 'absolute', top: 'calc(100% + 6px)', right: 0,
          background: 'var(--bg)',
          border: '1px solid var(--hairline-strong)',
          borderRadius: 14,
          minWidth: 168, padding: 6,
          boxShadow: '0 12px 28px rgba(0,0,0,0.18)',
          zIndex: 60,
        }}>
          {SUPPORTED_LOCALES.map(loc => {
            const isActive = loc === active;
            return (
              <a
                key={loc}
                href="#"
                role="option"
                aria-selected={isActive}
                onClick={(e) => { e.preventDefault(); switchLocale(loc); }}
                style={{
                  display: 'block', padding: '10px 14px', borderRadius: 10,
                  fontSize: 14, fontWeight: isActive ? 600 : 400,
                  color: isActive ? 'var(--fg)' : 'var(--fg-soft)',
                  background: isActive ? 'var(--bg-soft)' : 'transparent',
                  textDecoration: 'none',
                }}
              >
                {LOCALE_LABELS[loc]}
              </a>
            );
          })}
        </div>
      )}
    </div>
  );
}

function SiteNav({ route, theme, setTheme }) {
  const items = [
    { href: locPath('/about/'),    label: t('nav.learn'),    key: 'about' },
    { href: locPath('/support/'),  label: t('nav.support'),  key: 'support' },
  ];
  return (
    <div style={{
      height: 72, padding: '0 48px', display: 'flex',
      alignItems: 'center', justifyContent: 'space-between',
      borderBottom: '1px dashed var(--hairline)',
      position: 'sticky', top: 0, background: 'var(--bg)', zIndex: 50,
    }}>
      <a href={locPath('/')} style={{ display: 'flex', alignItems: 'center',
        gap: 16, textDecoration: 'none' }}>
        <EvntdMark/>
      </a>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        {items.map(it => (
          <a key={it.key} href={it.href} style={{
            padding: '10px 16px', borderRadius: 999,
            fontSize: 14, fontWeight: 500, textDecoration: 'none',
            color: route === it.key ? 'var(--fg)' : 'var(--fg-soft)',
            background: route === it.key ? 'var(--bg-soft)' : 'transparent',
            transition: 'background .15s, color .15s',
          }}>{it.label}</a>
        ))}
        <span style={{ marginLeft: 12, marginRight: 4 }}>
          <ThemeToggle theme={theme} onChange={setTheme}/>
        </span>
        <span style={{ marginLeft: 4 }}>
          <LanguageDropdown/>
        </span>
        <a href={locPath('/download/')} style={{
          marginLeft: 8, padding: '10px 18px', borderRadius: 999,
          background: ORANGE, color: '#fff', fontSize: 13.5, fontWeight: 600,
          textDecoration: 'none',
        }}>{t('nav.getApp')}</a>
      </div>
    </div>
  );
}

function StoreBadge({ type, onDark = false }) {
  // onDark=true → white badge with black text (used on orange/dark backgrounds)
  // onDark=false → flips with theme
  const isApple = type === 'apple';
  const bg = onDark ? '#fff' : 'var(--fg)';
  const fg = onDark ? '#0A0A0B' : 'var(--bg)';
  return (
    <a href="#" style={{
      height: 56, padding: '0 22px', borderRadius: 14,
      background: bg, color: fg,
      display: 'inline-flex', alignItems: 'center', gap: 12,
      cursor: 'pointer', userSelect: 'none', minWidth: 200,
      textDecoration: 'none',
    }}>
      {isApple ? (
        <svg width="26" height="32" viewBox="0 0 24 28" fill="currentColor">
          <path d="M17.05 14.92c-.03-3 2.45-4.43 2.56-4.5-1.4-2.04-3.57-2.32-4.34-2.35-1.85-.19-3.6 1.08-4.54 1.08-.94 0-2.38-1.05-3.92-1.02-2.02.03-3.88 1.17-4.92 2.97-2.1 3.63-.54 9.01 1.51 11.97 1 1.45 2.2 3.07 3.74 3.01 1.5-.06 2.07-.97 3.88-.97 1.81 0 2.32.97 3.91.94 1.62-.03 2.64-1.47 3.63-2.93 1.14-1.69 1.61-3.31 1.64-3.4-.04-.02-3.14-1.21-3.17-4.79zM14 5.66C14.83 4.66 15.4 3.27 15.24 1.9c-1.2.05-2.66.8-3.52 1.8-.77.88-1.45 2.29-1.27 3.65 1.34.1 2.71-.69 3.55-1.69z"/>
        </svg>
      ) : (
        <svg width="26" height="28" viewBox="0 0 24 26" fill="currentColor">
          <path d="M3.6 1.3 13.4 11 3.6 20.7c-.4-.2-.6-.6-.6-1.1V2.4c0-.5.2-.9.6-1.1zm11 9.7L4.7 0 17 7c.7.4.7 1.4 0 1.8L14.6 11zm0 2L17 17c.7.4.7 1.4 0 1.8L4.7 26l9.9-13zm-9.9 13.7 9.9-9.7L17 19l-12.3 7z"/>
        </svg>
      )}
      <div>
        <div style={{ fontSize: 10, opacity: 0.7, textTransform: 'uppercase', letterSpacing: '0.05em' }}>
          {isApple ? t('storeBadge.appleSmall') : t('storeBadge.googleSmall')}
        </div>
        <div style={{ fontSize: 18, fontWeight: 700, marginTop: -2 }}>
          {isApple ? t('storeBadge.appleBig') : t('storeBadge.googleBig')}
        </div>
      </div>
    </a>
  );
}

function SiteFooter() {
  return (
    <div style={{
      padding: '60px 48px 40px',
      borderTop: '1px solid var(--hairline)',
      color: 'var(--fg)',
    }}>
      <div style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start',
        marginBottom: 60, gap: 40, flexWrap: 'wrap',
      }}>
        <div>
          <EvntdMark size={32}/>
          <div style={{
            color: 'var(--fg-mute)', fontSize: 14, marginTop: 14, maxWidth: 320,
          }}>
            {t('footer.tagline')}
          </div>
          <div style={{ marginTop: 16 }}>
            <TrafficDots/>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 56, fontSize: 14 }}>
          <FooterCol title={t('footer.colApp')} links={[
            [t('footer.app_getApp'), locPath('/download/')],
            [t('footer.app_learn'),  locPath('/about/')],
            [t('footer.app_support'),locPath('/support/')],
          ]}/>
          <FooterCol title={t('footer.colCompany')} links={[
            [t('footer.company_about'),    locPath('/about/')],
            [t('footer.company_contact'),  'mailto:hello@evnted.com'],
            [t('footer.company_press'),    locPath('/press/')],
          ]}/>
          <FooterCol title={t('footer.colLegal')} links={[
            [t('footer.legal_privacy'),  locPath('/privacy/')],
            [t('footer.legal_terms'),    locPath('/terms/')],
            [t('footer.legal_cookies'),  locPath('/cookies/')],
          ]}/>
        </div>
      </div>
      <div style={{
        display: 'flex', justifyContent: 'space-between',
        fontSize: 12, color: 'var(--fg-mute)',
        borderTop: '1px dashed var(--hairline)', paddingTop: 24,
      }}>
        <span>{t('footer.copyright')}</span>
        <span>evnted.com</span>
      </div>
    </div>
  );
}

function FooterCol({ title, links }) {
  return (
    <div>
      <div style={{ fontWeight: 600, marginBottom: 12, color: 'var(--fg)' }}>{title}</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8,
        color: 'var(--fg-soft)' }}>
        {links.map(([l, h]) => (
          <a key={l} href={h} style={{ color: 'inherit', textDecoration: 'none' }}>{l}</a>
        ))}
      </div>
    </div>
  );
}

// Generic legal page renderer — used by /privacy/, /terms/, /cookies/.
// `ns` is the i18n namespace key ('privacy' | 'terms' | 'cookies').
function LegalPage({ ns }) {
  const sections = t(ns + '.sections');
  return (
    <SiteShell route={ns}>
      <div style={{ padding: '80px 48px 80px', maxWidth: 820, margin: '0 auto' }}>
        <div style={{
          fontSize: 12, fontFamily: 'ui-monospace, Menlo, monospace',
          color: ORANGE, letterSpacing: '0.12em', marginBottom: 16,
        }}>{t(ns + '.sectionLabel')}</div>
        <h1 style={{
          fontSize: 88, lineHeight: 0.92, fontWeight: 800,
          letterSpacing: '-0.04em', margin: '0 0 12px',
        }}>
          {t(ns + '.h1line1')}<br/>
          <span style={{ color: ORANGE, fontStyle: 'italic',
            fontFamily: '"Fraunces", serif', fontWeight: 500 }}>
            {t(ns + '.h1line2')}
          </span>
        </h1>
        <div style={{
          fontSize: 13, color: 'var(--fg-mute)', marginBottom: 32,
          fontFamily: 'ui-monospace, Menlo, monospace', letterSpacing: '0.06em',
        }}>
          {t(ns + '.lastUpdated')}
        </div>
        <p style={{
          fontSize: 19, lineHeight: 1.55, color: 'var(--fg-soft)',
          marginBottom: 56, maxWidth: 720,
        }}>
          {t(ns + '.intro')}
        </p>
        {Array.isArray(sections) && sections.map(([heading, body], i) => (
          <div key={i} style={{ marginBottom: 36, maxWidth: 720 }}>
            <h2 style={{
              fontSize: 22, fontWeight: 700,
              letterSpacing: '-0.01em', marginBottom: 8, color: 'var(--fg)',
            }}>{heading}</h2>
            <div style={{
              fontSize: 15, lineHeight: 1.65, color: 'var(--fg-soft)',
              // honour "\n" inside translation strings as real line breaks
              // (used by the "Third-party services" bullet list)
              whiteSpace: 'pre-line',
            }}>
              {body}
            </div>
          </div>
        ))}
        <div style={{
          marginTop: 56, padding: 24,
          background: 'var(--bg-soft)',
          border: '1px dashed var(--hairline-strong)', borderRadius: 16,
          fontSize: 14, color: 'var(--fg-soft)', maxWidth: 720,
        }}>
          {t(ns + '.contact')}
        </div>
      </div>
    </SiteShell>
  );
}

function SiteShell({ route, children }) {
  const [theme, setTheme] = useTheme();
  // Keep <html lang="..."> in sync with the active locale (a11y / SEO)
  React.useEffect(() => {
    try { document.documentElement.lang = getActiveLocale(); } catch (e) {}
  }, []);
  return (
    <div style={{
      background: 'var(--bg)', color: 'var(--fg)', minHeight: '100vh',
      fontFamily: '"Geist", -apple-system, BlinkMacSystemFont, system-ui, sans-serif',
      letterSpacing: '-0.01em',
      transition: 'background 0.25s ease, color 0.25s ease',
    }}>
      <SiteNav route={route} theme={theme} setTheme={setTheme}/>
      {children}
      <SiteFooter/>
    </div>
  );
}

Object.assign(window, {
  ORANGE, BLACK, GREEN, YELLOW,
  EvntdMark, TrafficDots, SiteNav, StoreBadge, SiteFooter, FooterCol, SiteShell,
  ThemeToggle, useTheme, LanguageDropdown, locPath, LegalPage,
});
