// @ts-check

const SITE_CONFIG = window.SWIATOWID_SITE_CONFIG;

if (!SITE_CONFIG) {
  throw new Error('Missing SWIATOWID_SITE_CONFIG. Load site-config.js before site-chrome.jsx.');
}

/**
 * Resolve the initial language for the page. Precedence:
 *   1. URL query — supports `?lang=pl`, `?l=pl`, and bare shorthand `?pl`.
 *   2. localStorage (the site's persisted preference).
 *   3. Default 'en'.
 *
 * If a language was set from the URL, this also writes it back to localStorage
 * so subsequent navigation in the same session keeps the choice.
 *
 * @param {Record<string, unknown>} supportedDict — keys are valid lang codes.
 * @returns {string}
 */
function resolveInitialLang(supportedDict) {
  let resolved = null;

  try {
    const params = new URLSearchParams(window.location.search);
    const explicit = (params.get('lang') || params.get('l') || '').toLowerCase();
    if (explicit && supportedDict[explicit]) {
      resolved = explicit;
    } else {
      // Bare-key shorthand: e.g. /?pl, /?uk
      for (const code of Object.keys(supportedDict)) {
        if (params.has(code)) { resolved = code; break; }
      }
    }
  } catch (e) {}

  if (resolved) {
    try { localStorage.setItem(SITE_CONFIG.langStorageKey, resolved); } catch (e) {}
    return resolved;
  }

  try {
    const stored = localStorage.getItem(SITE_CONFIG.langStorageKey);
    if (stored && supportedDict[stored]) return stored;
  } catch (e) {}

  return 'en';
}

/**
 * Update the URL's `?lang=` param without reloading, so the visible URL
 * matches the active language and is shareable. Removes the param when the
 * lang is the default ('en') to keep canonical URLs clean.
 *
 * @param {string} lang
 */
function syncLangToUrl(lang) {
  if (typeof window === 'undefined' || !window.history?.replaceState) return;
  try {
    const url = new URL(window.location.href);
    // Drop the bare-shorthand variant if present, to avoid two sources of truth.
    ['en','pl','cs','sk','et','lt','uk'].forEach((c) => url.searchParams.delete(c));
    url.searchParams.delete('l');
    if (lang && lang !== 'en') {
      url.searchParams.set('lang', lang);
    } else {
      url.searchParams.delete('lang');
    }
    window.history.replaceState(null, '', url.toString());
  } catch (e) {}
}

/**
 * @typedef {'home' | 'capabilities' | 'blog' | 'careers' | null | undefined} SiteNavSection
 */

/**
 * @typedef {{
 *   key: 'home' | 'capabilities' | 'blog' | 'careers',
 *   href: string,
 *   label: string,
 * }} SiteNavItem
 */

/**
 * @typedef {{
 *   t: (key: string) => string,
 *   activeSection?: SiteNavSection,
 *   LanguageSwitcherComponent?: React.ComponentType | null,
 * }} SiteNavBarProps
 */

/**
 * @typedef {{
 *   t: (key: string) => string,
 *   requestAccessHref?: string,
 * }} SiteFooterProps
 */

/**
 * @typedef {'intake' | 'careers' | 'privacy' | 'legal'} SiteContactKey
 */

/**
 * @typedef {{
 *   contactKey: SiteContactKey,
 *   subject?: string,
 * }} SiteContactHrefOptions
 */

/**
 * @typedef {{
 *   contactKey: SiteContactKey,
 *   subject?: string,
 *   className?: string,
 *   children?: React.ReactNode,
 * }} SiteContactLinkProps
 */

/**
 * @typedef {{
 *   contactKey: SiteContactKey,
 *   label: React.ReactNode,
 *   subject?: string,
 *   className?: string,
 *   arrowClassName?: string,
 *   showArrow?: boolean,
 * }} SiteContactButtonProps
 */

/**
 * @param {SiteContactHrefOptions} options
 * @returns {string}
 */
function buildContactHref({ contactKey, subject }) {
  const contact = SITE_CONFIG.contacts[contactKey];
  if (!contact) {
    throw new Error(`Unknown contact key: ${contactKey}`);
  }
  if (!subject) return contact.mailto;
  return `${contact.mailto}?subject=${encodeURIComponent(subject)}`;
}

/**
 * @param {SiteContactLinkProps} props
 */
function SiteContactLink({ contactKey, subject, className, children }) {
  const contact = SITE_CONFIG.contacts[contactKey];
  return (
    <a href={buildContactHref({ contactKey, subject })} className={className}>
      {children ?? contact.email}
    </a>
  );
}

/**
 * @param {SiteContactButtonProps} props
 */
function SiteContactButton({
  contactKey,
  label,
  subject,
  className = 'btn',
  arrowClassName = 'arrow',
  showArrow = true,
}) {
  return (
    <SiteContactLink contactKey={contactKey} subject={subject} className={className}>
      <>
        {label}
        {showArrow ? <span className={arrowClassName}>→</span> : null}
      </>
    </SiteContactLink>
  );
}

/**
 * @param {(key: string) => string} t
 * @returns {SiteNavItem[]}
 */
function getPrimaryNavItems(t) {
  return [
    { key: 'home', href: SITE_CONFIG.routes.home, label: t('navHome') },
    { key: 'capabilities', href: SITE_CONFIG.routes.capabilities, label: t('navCapabilities') },
    { key: 'blog', href: SITE_CONFIG.routes.blog, label: t('navBlog') },
    { key: 'careers', href: SITE_CONFIG.routes.careers, label: t('navCareers') },
  ];
}

const THEME_STORAGE_KEY = 'swiatowid:theme';

function readStoredTheme() {
  try {
    const v = localStorage.getItem(THEME_STORAGE_KEY);
    if (v === 'dark' || v === 'bone' || v === 'steel' || v === 'blood') return v;
  } catch (e) {}
  return document.documentElement.getAttribute('data-theme') || 'dark';
}

function applyTheme(theme) {
  const html = document.documentElement;
  if (theme === 'dark') html.removeAttribute('data-theme');
  else html.setAttribute('data-theme', theme);
  try { localStorage.setItem(THEME_STORAGE_KEY, theme); } catch (e) {}
  window.dispatchEvent(new CustomEvent('swiatowid:theme', { detail: theme }));
}

function ThemeToggle() {
  const [theme, setTheme] = React.useState(readStoredTheme);

  React.useEffect(() => {
    const onChange = (e) => setTheme(e.detail);
    window.addEventListener('swiatowid:theme', onChange);
    return () => window.removeEventListener('swiatowid:theme', onChange);
  }, []);

  const toggle = () => {
    const next = theme === 'dark' ? 'bone' : 'dark';
    setTheme(next);
    applyTheme(next);
  };

  const isDark = theme === 'dark';
  const label = isDark ? 'Switch to light mode' : 'Switch to dark mode';

  return (
    <button
      type="button"
      className="theme-toggle"
      onClick={toggle}
      aria-label={label}
      title={label}
    >
      <svg className="icon-moon" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
        <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79Z" />
      </svg>
      <svg className="icon-sun" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
        <circle cx="12" cy="12" r="4" />
        <path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41" />
      </svg>
    </button>
  );
}

/**
 * @param {SiteNavBarProps} props
 */
function SiteNavBar({ t, activeSection = 'home', LanguageSwitcherComponent = null }) {
  const [menuOpen, setMenuOpen] = React.useState(false);
  const close = () => setMenuOpen(false);
  const navItems = getPrimaryNavItems(t);

  React.useEffect(() => {
    if (!menuOpen) return;
    const onKeyDown = (event) => {
      if (event.key === 'Escape') close();
    };
    document.addEventListener('keydown', onKeyDown);
    document.body.style.overflow = 'hidden';
    return () => {
      document.removeEventListener('keydown', onKeyDown);
      document.body.style.overflow = '';
    };
  }, [menuOpen]);

  return (
    <nav className={`top ${menuOpen ? 'menu-open' : ''}`}>
      <div className="brand">
        <a href={SITE_CONFIG.routes.home} className="brand-link" onClick={close}>
          <span className="brand-mark">
            <RotatingLogo size={26} color="var(--amber)" />
          </span>
          <span className="word">{SITE_CONFIG.brandName}</span>
        </a>
      </div>

      <div className="links">
        {navItems.map((item) => (
          <a key={item.key} href={item.href} className={item.key === activeSection ? 'active' : ''}>
            {item.label}
          </a>
        ))}
      </div>

      <div className="right">
        {LanguageSwitcherComponent ? <LanguageSwitcherComponent /> : null}
        <ThemeToggle />
        <a href={SITE_CONFIG.requestAccessHref} className="clearance" target="_blank" rel="noopener noreferrer">{t('navRequestAccess')}</a>
        <button
          type="button"
          className={`nav-burger ${menuOpen ? 'open' : ''}`}
          onClick={() => setMenuOpen((state) => !state)}
          aria-label="Menu"
          aria-expanded={menuOpen}
          aria-controls="nav-drawer"
        >
          <span /><span /><span />
        </button>
      </div>

      <div id="nav-drawer" className={`nav-drawer ${menuOpen ? 'open' : ''}`} aria-hidden={!menuOpen}>
        {navItems.map((item) => (
          <a key={item.key} href={item.href} onClick={close} className={item.key === activeSection ? 'active' : ''}>
            {item.label}
          </a>
        ))}
        <a href={SITE_CONFIG.requestAccessHref} onClick={close} className="drawer-cta" target="_blank" rel="noopener noreferrer">
          {t('navRequestAccess')}
        </a>
      </div>
    </nav>
  );
}

/**
 * @param {SiteFooterProps} props
 */
function SiteFooter({ t, requestAccessHref = SITE_CONFIG.requestAccessHref }) {
  const year = new Date().getFullYear();

  return (
    <footer className="site-footer">
      <div className="site-footer-inner">
        <div className="footer-brand">
          <div className="footer-brand-row">
            <RotatingLogo size={56} interval={4000} />
            <span>{SITE_CONFIG.brandName}</span>
          </div>
        </div>

        <div className="footer-col">
          <div className="footer-col-head">Platform</div>
          <ul>
            <li><a href={SITE_CONFIG.routes.capabilities}>Capabilities</a></li>
            <li><a href={`${SITE_CONFIG.routes.capabilities}#deploy`}>Deployment</a></li>
            <li><a href={`${SITE_CONFIG.routes.capabilities}#models`}>Models</a></li>
            <li><a href={`${SITE_CONFIG.routes.capabilities}#heart`}>Compute</a></li>
          </ul>
        </div>

        <div className="footer-col">
          <div className="footer-col-head">Company</div>
          <ul>
            <li><a href={SITE_CONFIG.routes.home}>Home</a></li>
            <li><a href={SITE_CONFIG.routes.blog}>Dispatches</a></li>
            <li><a href={SITE_CONFIG.routes.careers}>Careers</a></li>
            <li><a href={requestAccessHref} target="_blank" rel="noopener noreferrer">Request access</a></li>
          </ul>
        </div>

        <div className="footer-col">
          <div className="footer-col-head">Legal</div>
          <ul>
            <li><a href="#">{t('footSecurity')}</a></li>
            <li><a href="#">{t('footExport')}</a></li>
            <li><a href="#">{t('footEthics')}</a></li>
            <li><a href="#">{t('footDisclosures')}</a></li>
          </ul>
        </div>

        <div className="footer-col">
          <div className="footer-col-head">Contact</div>
          <div className="footer-contact">
            <span className="footer-contact-k">Intake</span>
            <span className="footer-contact-v"><SiteContactLink contactKey="intake" /></span>
          </div>
          <div className="footer-contact">
            <span className="footer-contact-k">Careers</span>
            <span className="footer-contact-v"><SiteContactLink contactKey="careers" /></span>
          </div>
          <div className="footer-contact">
            <span className="footer-contact-k">HQ</span>
            <span className="footer-contact-v">{SITE_CONFIG.headquartersLabel}</span>
          </div>
        </div>
      </div>

      <div className="site-footer-bar">
        <div className="meta">
          <span>{SITE_CONFIG.brandName} © {year}</span>
        </div>
        <div className="legal-links">
          <a href={SITE_CONFIG.routes.privacy}>Privacy</a>
          <a href={SITE_CONFIG.routes.terms}>Terms</a>
          <a href={SITE_CONFIG.routes.cookies}>Cookies</a>
        </div>
      </div>
    </footer>
  );
}

// ── Request Access modal ──────────────────────────────────────────────
const REQUEST_ACCESS_AREAS = [
  'heavy_industry',
  'markets',
  'defense',
  'pharma',
  'general',
];

const RequestAccessContext = React.createContext({
  open: false,
  openModal: () => {},
  closeModal: () => {},
});

function useRequestAccess() {
  return React.useContext(RequestAccessContext);
}

function RequestAccessTriggerButton({ t, className = 'btn primary', children }) {
  return (
    <a
      href={SITE_CONFIG.requestAccessHref}
      target="_blank"
      rel="noopener noreferrer"
      className={className}
    >
      {children ?? (
        <>
          {t('reqaCtaOpen')} <span className="arrow">→</span>
        </>
      )}
    </a>
  );
}

function RequestAccessModal({ t }) {
  const { open, closeModal } = useRequestAccess();
  const [name, setName] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [org, setOrg] = React.useState('');
  const [area, setArea] = React.useState('heavy_industry');
  const [message, setMessage] = React.useState('');
  const [submitted, setSubmitted] = React.useState(false);

  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') closeModal(); };
    document.addEventListener('keydown', onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      document.removeEventListener('keydown', onKey);
      document.body.style.overflow = prev;
    };
  }, [open, closeModal]);

  React.useEffect(() => {
    if (open) setSubmitted(false);
  }, [open]);

  if (!open) return null;

  const onSubmit = (e) => {
    e.preventDefault();
    const subject = `${t('reqaMailSubjectPrefix')}, ${t(`reqaArea_${area}`)}`;
    const lines = [
      `${t('reqaFieldName')}: ${name}`,
      `${t('reqaFieldEmail')}: ${email}`,
      `${t('reqaFieldOrg')}: ${org}`,
      `${t('reqaFieldArea')}: ${t(`reqaArea_${area}`)}`,
      '',
      `${t('reqaFieldMessage')}:`,
      message,
    ];
    const body = lines.join('\n');
    const href = `mailto:${SITE_CONFIG.contacts.business.email}?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;
    window.location.href = href;
    setSubmitted(true);
  };

  const onBackdrop = (e) => {
    if (e.target === e.currentTarget) closeModal();
  };

  return (
    <div className="reqa-backdrop" onMouseDown={onBackdrop} role="dialog" aria-modal="true" aria-labelledby="reqa-title">
      <div className="reqa-modal">
        <button type="button" className="reqa-close" onClick={closeModal} aria-label={t('reqaClose')}>×</button>
        <div className="reqa-corner tl" />
        <div className="reqa-corner tr" />
        <div className="reqa-corner bl" />
        <div className="reqa-corner br" />

        <div className="reqa-head">
          <div className="reqa-kicker">{t('reqaKicker')}</div>
          <h2 id="reqa-title" className="reqa-title">{t('reqaTitle')}</h2>
          <p className="reqa-lede">{t('reqaLede')}</p>
        </div>

        <form className="reqa-form" onSubmit={onSubmit}>
          <div className="reqa-row">
            <label className="reqa-field">
              <span className="reqa-label">{t('reqaFieldName')}</span>
              <input
                type="text"
                value={name}
                onChange={(e) => setName(e.target.value)}
                required
                autoComplete="name"
              />
            </label>
            <label className="reqa-field">
              <span className="reqa-label">{t('reqaFieldEmail')}</span>
              <input
                type="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                required
                autoComplete="email"
              />
            </label>
          </div>

          <label className="reqa-field">
            <span className="reqa-label">{t('reqaFieldOrg')}</span>
            <input
              type="text"
              value={org}
              onChange={(e) => setOrg(e.target.value)}
              autoComplete="organization"
            />
          </label>

          <label className="reqa-field">
            <span className="reqa-label">{t('reqaFieldArea')}</span>
            <div className="reqa-select-wrap">
              <select value={area} onChange={(e) => setArea(e.target.value)} required>
                {REQUEST_ACCESS_AREAS.map((key) => (
                  <option key={key} value={key}>{t(`reqaArea_${key}`)}</option>
                ))}
              </select>
              <span className="reqa-select-caret" aria-hidden="true">▾</span>
            </div>
          </label>

          <label className="reqa-field">
            <span className="reqa-label">{t('reqaFieldMessage')}</span>
            <textarea
              value={message}
              onChange={(e) => setMessage(e.target.value)}
              rows={5}
              placeholder={t('reqaFieldMessagePh')}
            />
          </label>

          <div className="reqa-foot">
            <span className="reqa-routing">
              {t('reqaRoutedTo')} <b>{SITE_CONFIG.contacts.business.email}</b>
            </span>
            <button type="submit" className="btn primary">
              {submitted ? t('reqaSent') : t('reqaSend')} <span className="arrow">→</span>
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

function RequestAccessProvider({ t, children }) {
  const [open, setOpen] = React.useState(false);
  const openModal = React.useCallback(() => setOpen(true), []);
  const closeModal = React.useCallback(() => setOpen(false), []);

  // Note: we no longer intercept '#request-access' anchors. All "Request
  // access" CTAs link directly to the Calendly URL (SITE_CONFIG.requestAccessHref).
  // The modal stays available for any code that calls openModal() directly.

  return (
    <RequestAccessContext.Provider value={{ open, openModal, closeModal }}>
      {children}
      <RequestAccessModal t={t} />
    </RequestAccessContext.Provider>
  );
}

Object.assign(window, {
  SITE_CONFIG,
  resolveInitialLang,
  syncLangToUrl,
  buildContactHref,
  SiteContactLink,
  SiteContactButton,
  SiteNavBar,
  SiteFooter,
  ThemeToggle,
  applyTheme,
  readStoredTheme,
  RequestAccessProvider,
  RequestAccessTriggerButton,
  RequestAccessModal,
  useRequestAccess,
  REQUEST_ACCESS_AREAS,
});