---
import '../styles/global.css';
import Header from '../components/Header.astro';
import Footer from '../components/Footer.astro';
import MobileTabBar from '../components/MobileTabBar.astro';
import ChatAssistant from '../components/ChatAssistant.astro';
import { site } from '../config/site';
import { LANGS, LANG_CODES, DEFAULT_LANG, alternates, langFromUrl, pick, type Lang } from '../i18n';
import { t } from '../i18n/ui';

interface Props {
  title?: string;
  description?: string;
  noindex?: boolean;
  jsonLd?: Record<string, unknown> | Record<string, unknown>[];
  ogType?: 'website' | 'article';
  ogImage?: string;
  ogImageAlt?: string;
  /** Page-specific search terms (merged with site.keywords) */
  keywords?: readonly string[] | string[];
  /** Blog posts: article meta (published / modified time, section, tags, author) */
  article?: { published?: string | null; modified?: string | null; section?: string | null; tags?: string[]; author?: string };
  /** Hide marketing footer (e.g. focused auth pages) */
  minimal?: boolean;
  /** Hide the site header (the page shows its own logo link, e.g. sign up) */
  noHeader?: boolean;
  /** Load Cloudflare Turnstile (only on pages with forms) */
  captcha?: boolean;
  /** Languages this page exists in (default: all). Blog articles are English only. */
  langs?: readonly Lang[];
}

const lang = langFromUrl(Astro.url);
const L = LANGS[lang];
const T = t(lang);
const tagline = pick(lang, { en: site.tagline, es: 'Hojas de viaje digitales, flota y pago de choferes para empresas de transporte' });
const siteDescription = pick(lang, { en: site.description,
  es: 'Software para flotas pequeñas: hojas de viaje en el teléfono, millas IFTA por estado, gastos con recibos y pago semanal de choferes. Prueba gratis.' });

const {
  title,
  description = siteDescription,
  noindex = false,
  jsonLd,
  ogType = 'website',
  ogImageAlt,
  keywords = [],
  article,
  ogImage = site.ogImage,
  minimal = false,
  noHeader = false,
  captcha = false,
  langs = LANG_CODES,
} = Astro.props;

/** the same page in the other languages (hreflang + remembered language) */
const alts = alternates(Astro.url.pathname, langs.includes(lang) ? langs : [lang]);
const altHref = Object.fromEntries(alts.map((a) => [a.lang, new URL(a.href, `${site.url}/`).href]));
const altPath = Object.fromEntries(alts.map((a) => [a.lang, a.href]));

const fullTitle = !title ? `${site.name}: ${tagline}` : (title.includes(site.name) || title.length + site.name.length + 3 > 65) ? title : `${title} | ${site.name}`;
const canonical = new URL(Astro.url.pathname, `${site.url}/`).href;
const ogImageUrl = new URL(ogImage, `${site.url}/`).href;
const allKeywords = [...new Set([...keywords, ...site.keywords])].slice(0, 20).join(', ');
const website = { '@context': 'https://schema.org', '@type': 'WebSite', name: site.name, url: site.url, inLanguage: LANG_CODES.map((l) => LANGS[l].hreflang),
  description: siteDescription, publisher: { '@type': 'Organization', name: site.name } };

const org = {
  '@context': 'https://schema.org',
  '@type': 'Organization',
  name: site.name,
  legalName: site.legalName,
  url: site.url,
  logo: `${site.url}/logo-512.png`,
  email: site.supportEmail,
  telephone: site.supportPhone,
  sameAs: Object.values(site.social).filter(Boolean),
};
const ld = [org, website, ...(jsonLd ? (Array.isArray(jsonLd) ? jsonLd : [jsonLd]) : [])];
---
<!doctype html>
<html lang={L.code}>
  <head>
    <meta charset="utf-8" />
    {site.showLanguages && <script is:inline define:vars={{ pageLang: lang, altPath }}>
      // returning visitor who chose a language before (LangSwitch) → same page in that language.
      // Only when arriving from outside the site, so clicking a language link always wins. Crawlers keep no storage.
      try {
        var saved = localStorage.getItem('site-lang');
        var fromSite = document.referrer && new URL(document.referrer).origin === location.origin;
        if (saved && saved !== pageLang && altPath[saved] && !fromSite) location.replace(altPath[saved] + location.search + location.hash);
      } catch (e) { /* storage blocked */ }
    </script>}
    <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
    <title>{fullTitle}</title>
    <meta name="description" content={description} />
    <meta name="keywords" content={allKeywords} />
    <meta name="author" content={article?.author || site.name} />
    <meta name="application-name" content={site.name} />
    <meta name="apple-mobile-web-app-title" content={site.name} />
    <meta name="format-detection" content="telephone=no" />
    <meta name="referrer" content="strict-origin-when-cross-origin" />
    <meta name="geo.region" content="US-TX" />
    <meta name="geo.placename" content="Fort Worth, Texas" />
    <meta name="mobile-web-app-capable" content="yes" />
    <meta name="msapplication-TileColor" content={site.themeColor} />
    <link rel="sitemap" type="text/html" title={pick(lang, { en: "Site map", es: "Mapa del sitio" })} href={lang === DEFAULT_LANG ? "/sitemap/" : `/${lang}/sitemap/`} />
    <link rel="canonical" href={canonical} />
    {alts.length > 1 && alts.map((a) => <link rel="alternate" hreflang={a.hreflang} href={altHref[a.lang]} />)}
    {alts.length > 1 && <link rel="alternate" hreflang="x-default" href={altHref[DEFAULT_LANG]} />}
    {alts.length === 1 && <link rel="alternate" hreflang={L.hreflang} href={canonical} />}
    <link rel="alternate" type="application/rss+xml" title={`${site.name} blog`} href="/rss.xml" hreflang="en" />
    {noindex
      ? <meta name="robots" content="noindex, nofollow" />
      : <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1, max-video-preview:-1" />}
    {!noindex && <meta name="googlebot" content="index, follow, max-image-preview:large, max-snippet:-1" />}
    {!noindex && <meta name="bingbot" content="index, follow" />}
    <meta name="theme-color" content={site.themeColor} />
    <meta name="color-scheme" content="light dark" />
    <link rel="icon" href="/favicon.svg" type="image/svg+xml" />
    <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
    <link rel="sitemap" href="/sitemap-index.xml" />

    <!-- Open Graph / Twitter -->
    <meta property="og:type" content={ogType} />
    <meta property="og:site_name" content={site.name} />
    <meta property="og:title" content={fullTitle} />
    <meta property="og:description" content={description} />
    <meta property="og:url" content={canonical} />
    <meta property="og:image" content={ogImageUrl} />
    <meta property="og:image:width" content="1200" />
    <meta property="og:image:height" content="630" />
    <meta property="og:image:alt" content={ogImageAlt || fullTitle} />
    {ogImageUrl.startsWith('https://') && <meta property="og:image:secure_url" content={ogImageUrl} />}
    {/\.(png|jpe?g|webp)$/i.test(ogImageUrl) && <meta property="og:image:type" content={`image/${ogImageUrl.split('.').pop()!.toLowerCase().replace('jpg', 'jpeg')}`} />}
    {article?.published && <meta property="article:published_time" content={article.published} />}
    {article?.modified && <meta property="article:modified_time" content={article.modified} />}
    {article?.section && <meta property="article:section" content={article.section} />}
    {article?.tags?.map((t) => <meta property="article:tag" content={t} />)}
    {article?.author && <meta property="article:author" content={article.author} />}
    <meta property="og:locale" content={L.og} />
    {alts.filter((a) => a.lang !== lang).map((a) => <meta property="og:locale:alternate" content={a.og} />)}
    <meta name="twitter:card" content="summary_large_image" />
    <meta name="twitter:title" content={fullTitle} />
    <meta name="twitter:description" content={description} />
    <meta name="twitter:image" content={ogImageUrl} />
    <meta name="twitter:image:alt" content={ogImageAlt || fullTitle} />
    {site.twitter && <meta name="twitter:site" content={site.twitter} />}

    <!-- Fonts: preconnect + swap (no layout-blocking) -->
    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=Plus+Jakarta+Sans:wght@600;700;800&display=swap" />

    {captcha && (
      <>
        <link rel="preconnect" href="https://challenges.cloudflare.com" />
        <script is:inline src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>
      </>
    )}

    {ld.map((obj) => <script type="application/ld+json" set:html={JSON.stringify(obj)} />)}
    <slot name="head" />
  </head>
  <body class={noHeader ? '' : 'has-tabbar'}>
    <a class="skip-link" href="#main">{T.skip}</a>
    {!noHeader && <Header langs={langs} />}
    <main id="main">
      <slot />
    </main>
    {!minimal && <Footer langs={langs} />}
    {!noHeader && <MobileTabBar />}
    <ChatAssistant />
  </body>
</html>
