/* bloo.app — shared site chrome: links, icons, style tokens, nav, footer.
   Loaded before each page's own script; exports via window.Site so other
   babel-scoped page scripts can read it. */

(function () {
const { Button } = window.BlooAppDesignSystem_ab7292;
const { useT } = window.I18n;
const SITE_CONFIG = window.BlooSiteConfig;
if (!SITE_CONFIG) throw new Error('site-config.js must load before shared.jsx');
const REGION = SITE_CONFIG.regions[SITE_CONFIG.regionKeyFromPath(window.location.pathname)];

function routeHref(routeKey, suffix = '', regionKey = REGION.key) {
  return `${SITE_CONFIG.pathForRoute(routeKey, regionKey)}${suffix}`;
}

function equivalentRegionHref(regionKey) {
  const url = new URL(window.location.href);
  url.searchParams.delete('lang');
  url.searchParams.delete('market');
  const routeKey = SITE_CONFIG.routeKeyFromPath(url.pathname);
  const query = url.searchParams.toString();
  return `${SITE_CONFIG.pathForRoute(routeKey, regionKey)}${query ? `?${query}` : ''}${url.hash}`;
}

/* ---- one product/release source of truth ---- */
const PRODUCT = window.BlooProductConfig;
if (!PRODUCT) throw new Error('product-config.js must load before shared.jsx');

const PRODUCT_ROUTES = new Set(['ai-code-review', 'benchmark', 'docs', 'changelog', 'license']);

/* ---- edit destinations here, not in individual pages ---- */
const LINKS = {
  checkoutApi: '/api/checkout',
  freeRepo: PRODUCT.freeRepoUrl,
  license: routeHref('license'),
  book: 'https://cal.com/bruno-luigi-wnqfwi/30min?overlayCalendar=true',
  companyEmail: 'contato@bloo.app',
  personalEmail: 'bruno@bloo.app',
  linkedin: 'https://www.linkedin.com/in/blooapp/',
  medium: 'https://medium.com/@blooapp',
  youtube: 'https://www.youtube.com/@FlutterUX',
};
const EXT = { target: '_blank', rel: 'noopener noreferrer' };

/* ---- attribution: first-touch UTM capture, persisted, attached to every event ----
   Launch channels (LinkedIn/TabNews/HN/PH/paid) tag links with utm_*; we keep the
   first campaign that brought each visitor and stamp it on every event so paid vs.
   community vs. organic can be told apart later. Browser-only; no server, no PII. */
const ATTR_KEY = 'bloo_attribution';
function getAttribution() {
  try { return JSON.parse(localStorage.getItem(ATTR_KEY) || '{}'); } catch (_) { return {}; }
}
function captureAttribution() {
  const a = getAttribution();
  const p = new URLSearchParams(window.location.search);
  const utm = {};
  ['utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term'].forEach((k) => {
    const v = p.get(k); if (v) utm[k] = v;
  });
  let changed = false;
  if (Object.keys(utm).length && !a.utm_source) { Object.assign(a, utm); changed = true; } // first-touch, once
  if (!a.first_seen) { a.first_seen = new Date().toISOString(); changed = true; }
  if (!a.referrer && document.referrer) { a.referrer = document.referrer; changed = true; }
  if (Object.keys(utm).length) { a.last = Object.assign({}, utm, { seen: new Date().toISOString() }); changed = true; } // last-touch
  if (changed) { try { localStorage.setItem(ATTR_KEY, JSON.stringify(a)); } catch (_) {} }
  return a;
}
try { captureAttribution(); } catch (_) {}

/** Fire a Vercel Analytics custom event, enriched with first-touch attribution. */
function trackEvent(name, data) {
  try {
    const a = getAttribution();
    const payload = Object.assign({
      product_version: PRODUCT.version,
      product_stage: PRODUCT.stage,
      region: REGION.key,
      market: REGION.market,
    }, data || {});
    ['utm_source', 'utm_medium', 'utm_campaign', 'utm_content'].forEach((k) => {
      if (a[k] != null && payload[k] == null) payload[k] = a[k];
    });
    if (typeof window.va === 'function') {
      window.va('event', Object.keys(payload).length ? { name, data: payload } : { name });
    }
  } catch (_) { /* analytics must never break UX */ }
}

/** Fire an event at most once per browser — for activation milestones
    (installation_confirmed, first_review_completed, second_review_completed). */
function trackOnce(key, name, data) {
  try {
    const k = 'bloo_evt_' + key;
    if (localStorage.getItem(k)) return false;
    localStorage.setItem(k, new Date().toISOString());
  } catch (_) {}
  trackEvent(name, data);
  return true;
}

/* ---- inline icons (Lucide-style paths) ---- */
const Icon = ({ d, size = 22, sw = 1.75 }) => (
  <svg viewBox="0 0 24 24" width={size} height={size} fill="none" stroke="currentColor"
       strokeWidth={sw} strokeLinecap="round" strokeLinejoin="round">{d}</svg>
);
const IconCode    = (p) => <Icon {...p} d={<><path d="M16 18l6-6-6-6"/><path d="M8 6l-6 6 6 6"/></>} />;
const IconLayers  = (p) => <Icon {...p} d={<><path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/></>} />;
const IconUsers   = (p) => <Icon {...p} d={<><path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 00-3-3.87"/><path d="M16 3.13a4 4 0 010 7.75"/></>} />;
const IconSpark   = (p) => <Icon {...p} d={<path d="M12 3l1.9 5.8L20 10l-6.1 1.2L12 17l-1.9-5.8L4 10l6.1-1.2L12 3z"/>} />;
const IconArrow   = (p) => <Icon {...p} d={<path d="M5 12h14M13 6l6 6-6 6"/>} />;
const IconCheck   = (p) => <Icon {...p} d={<path d="M20 6L9 17l-5-5"/>} />;
const IconExternal = (p) => <Icon {...p} d={<><path d="M18 13v6a2 2 0 01-2 2H5a2 2 0 01-2-2V8a2 2 0 012-2h6"/><path d="M15 3h6v6"/><path d="M10 14L21 3"/></>} />;
const IconMail    = (p) => <Icon {...p} d={<><rect x="2" y="4" width="20" height="16" rx="2"/><path d="M22 6l-10 7L2 6"/></>} />;
const IconPackage = (p) => <Icon {...p} d={<><path d="M16.5 9.4L7.5 4.21"/><path d="M21 16V8a2 2 0 00-1-1.73l-7-4a2 2 0 00-2 0l-7 4A2 2 0 003 8v8a2 2 0 001 1.73l7 4a2 2 0 002 0l7-4a2 2 0 001-1.73z"/><path d="M3.27 6.96L12 12.01l8.73-5.05"/><path d="M12 22.08V12"/></>} />;
const IconTarget  = (p) => <Icon {...p} d={<><circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="6"/><circle cx="12" cy="12" r="2"/></>} />;
const IconTrendUp = (p) => <Icon {...p} d={<><path d="M23 6l-9.5 9.5-5-5L1 18"/><path d="M17 6h6v6"/></>} />;
const IconGlobe   = (p) => <Icon {...p} d={<><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3a14 14 0 010 18M12 3a14 14 0 000 18"/></>} />;
const IconBrazilFlag = ({ width = 21, height = 15 }) => (
  <svg viewBox="0 0 28 20" width={width} height={height} aria-hidden="true" focusable="false" className="region-switcher__flag">
    <rect width="28" height="20" rx="2" fill="#009B3A"/>
    <path d="M14 2.7L25 10 14 17.3 3 10z" fill="#FFDF00"/>
    <circle cx="14" cy="10" r="4.25" fill="#002776"/>
    <path d="M10.1 9.25c2.7-.8 5.5-.35 7.8 1.2" fill="none" stroke="#fff" strokeWidth=".75" strokeLinecap="round"/>
  </svg>
);

const Icons = { IconCode, IconLayers, IconUsers, IconSpark, IconArrow, IconCheck, IconExternal, IconMail, IconPackage, IconTarget, IconTrendUp, IconGlobe, IconBrazilFlag };

/* ---- shared style tokens (spread/reused by each page's own style object) ---- */
const S = {
  container: { maxWidth: 1120, margin: '0 auto', padding: '0 var(--space-8)' },
  nav: { position: 'sticky', top: 0, zIndex: 20, background: 'rgba(255,255,255,.85)', backdropFilter: 'blur(10px)', borderBottom: '1px solid var(--border-subtle)' },
  navInner: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', height: 64, gap: 24 },
  brand: { fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 20, letterSpacing: '-.03em', color: 'var(--text-strong)', textDecoration: 'none', flex: 'none' },
  navLinks: { display: 'flex', gap: 26, flex: 1, justifyContent: 'center' },
  navLink: { fontSize: 14, color: 'var(--text-body)', textDecoration: 'none', fontWeight: 500, whiteSpace: 'nowrap' },
  navLinkActive: { color: 'var(--brand)' },

  section: { padding: 'var(--space-21) 0' },
  sectionHead: { textAlign: 'center', maxWidth: 640, margin: '0 auto var(--space-12)', display: 'flex', flexDirection: 'column', gap: 12, alignItems: 'center' },
  sectionHeadLeft: { textAlign: 'left', maxWidth: 680, margin: '0 0 var(--space-12)', display: 'flex', flexDirection: 'column', gap: 12, alignItems: 'flex-start' },
  eyebrow: { fontFamily: 'var(--font-mono)', fontSize: 12, letterSpacing: '.1em', color: 'var(--text-accent)', whiteSpace: 'nowrap' },
  h1: { fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 52, lineHeight: 1.08, letterSpacing: '-.03em', color: 'var(--text-strong)', margin: 0 },
  h2: { fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 40, lineHeight: 1.1, letterSpacing: '-.02em', color: 'var(--text-strong)', margin: 0 },
  h3: { fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 20, letterSpacing: '-.01em', color: 'var(--text-strong)', margin: 0 },
  sectionSub: { fontSize: 17, lineHeight: 1.55, color: 'var(--text-muted)', margin: 0 },

  cardBody: { fontSize: 14.5, lineHeight: 1.6, color: 'var(--text-body)', margin: 0, flex: 1 },
  cardLink: { fontSize: 14, fontWeight: 500, color: 'var(--text-link)', textDecoration: 'none', display: 'inline-flex', gap: 6, alignItems: 'center' },
  serviceIcon: { display: 'inline-flex', width: 44, height: 44, borderRadius: 'var(--radius-md)', background: 'var(--blue-50)', color: 'var(--brand)', alignItems: 'center', justifyContent: 'center', flex: 'none' },
  checkDot: { flex: 'none', width: 22, height: 22, borderRadius: '50%', background: 'var(--success-bg)', color: 'var(--success)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginTop: 1 },

  metricsBand: { background: 'var(--surface-sunken)', borderTop: '1px solid var(--border-subtle)', borderBottom: '1px solid var(--border-subtle)', padding: 'var(--space-10) 0' },
  metricsInner: { display: 'flex', justifyContent: 'space-around', gap: 24, flexWrap: 'wrap' },
  metricNum: { fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 40, letterSpacing: '-.02em', color: 'var(--brand)' },
  metricLabel: { fontSize: 14, color: 'var(--text-muted)', marginTop: 4, maxWidth: 150 },

  cta: { background: 'var(--surface-inverse)', padding: 'var(--space-21) 0' },
  ctaInner: { textAlign: 'center', display: 'flex', flexDirection: 'column', gap: 18, alignItems: 'center' },

  footer: { padding: 'var(--space-14) 0 var(--space-8)', background: 'var(--surface-card)', borderTop: '1px solid var(--border-subtle)' },
  footHead: { fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '.08em', color: 'var(--text-subtle)', marginBottom: 12, textTransform: 'uppercase' },
  footLink: { display: 'flex', alignItems: 'center', gap: 5, fontSize: 14, color: 'var(--text-body)', textDecoration: 'none', marginBottom: 8, width: 'fit-content', whiteSpace: 'nowrap' },
};

/* ---- nav ---- */
const PAGE_LABELS = {
  'ai-code-review': { en: 'AI Code Review', pt: 'AI Code Review' },
  benchmark: { en: 'Benchmark', pt: 'Benchmark' },
  docs: { en: 'Docs', pt: 'Docs' },
  changelog: { en: 'Changelog', pt: 'Changelog' },
  services: { en: 'Services', pt: 'Serviços' },
  'case-studies': { en: 'Case studies', pt: 'Estudos de caso' },
  products: { en: 'Products', pt: 'Produtos' },
  about: { en: 'About', pt: 'Sobre' },
  contact: { en: 'Contact', pt: 'Contato' },
};

function RegionSelector() {
  const { t } = useT();
  const label = t('Region, language, and currency', 'Região, idioma e moeda');
  function changeRegion(event, nextRegion) {
    if (nextRegion === REGION.key) {
      event.preventDefault();
      return;
    }
    trackEvent('switch_region', { from_region: REGION.key, to_region: nextRegion });
  }
  return (
    <nav className="region-switcher" aria-label={label}>
      <a
        className="region-switcher__option"
        href={equivalentRegionHref('intl')}
        aria-label={SITE_CONFIG.regions.intl.label}
        aria-current={REGION.key === 'intl' ? 'page' : undefined}
        title={SITE_CONFIG.regions.intl.label}
        onClick={(event) => changeRegion(event, 'intl')}
      >
        <IconGlobe size={19} sw={1.8} />
      </a>
      <a
        className="region-switcher__option"
        href={equivalentRegionHref('br')}
        aria-label={SITE_CONFIG.regions.br.label}
        aria-current={REGION.key === 'br' ? 'page' : undefined}
        title={SITE_CONFIG.regions.br.label}
        onClick={(event) => changeRegion(event, 'br')}
      >
        <IconBrazilFlag />
      </a>
    </nav>
  );
}

function SiteNav({ active }) {
  const { t, locale } = useT();
  const items = [
    [routeHref('case-studies'), t('Work', 'Trabalhos'), 'case-studies'],
    [routeHref('products'), PAGE_LABELS.products[locale], 'products'],
    [routeHref('services'), PAGE_LABELS.services[locale], 'services'],
    [routeHref('about'), PAGE_LABELS.about[locale], 'about'],
  ];
  const productItems = [
    [routeHref('ai-code-review'), t('Overview', 'Visão geral'), 'ai-code-review'],
    [routeHref('benchmark'), PAGE_LABELS.benchmark[locale], 'benchmark'],
    [routeHref('docs'), PAGE_LABELS.docs[locale], 'docs'],
    [routeHref('changelog'), PAGE_LABELS.changelog[locale], 'changelog'],
    [routeHref('license'), t('License', 'Licença'), 'license'],
  ];
  const inProduct = PRODUCT_ROUTES.has(active);
  return (
    <header style={S.nav}>
      <div style={S.container} className="site-container">
        <div style={S.navInner}>
          <a href={routeHref('home')} style={S.brand}>bloo<span style={{ color: 'var(--brand)' }}>.</span>app</a>
          <nav style={S.navLinks} className="site-nav-links" aria-label={t('Primary navigation', 'Navegação principal')}>
            {items.map(([href, label, key]) => (
              <a key={key} href={href} style={{ ...S.navLink, ...(active === key ? S.navLinkActive : {}) }}>{label}</a>
            ))}
          </nav>
          <div style={{ display: 'flex', gap: 10, alignItems: 'center', flex: 'none' }}>
            <RegionSelector />
            <Button as="a" href={routeHref('ai-code-review')} className="site-header-cta" size="sm" trailingIcon={<IconArrow size={15} />} onClick={() => trackEvent('click_product_cta', { from: 'global_nav' })}>AI Code Review</Button>
          </div>
        </div>
        <nav className="site-mobile-nav" aria-label={t('Primary navigation', 'Navegação principal')}>
          {items.map(([href, label, key]) => (
            <a key={key} href={href} style={{ ...S.navLink, ...(active === key ? S.navLinkActive : {}) }}>{label}</a>
          ))}
          <a href={routeHref('ai-code-review')} style={{ ...S.navLink, ...(active === 'ai-code-review' ? S.navLinkActive : {}) }}>AI Code Review</a>
        </nav>
      </div>
      {inProduct && (
        <div className="product-subnav" style={{ borderTop: '1px solid var(--border-subtle)', background: 'rgba(255,255,255,.94)' }}>
          <div style={{ ...S.container, display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 18, minHeight: 48 }} className="site-container product-subnav-inner">
            <nav className="product-subnav-links" aria-label={t('AI Code Review navigation', 'Navegação do AI Code Review')} style={{ display: 'flex', alignItems: 'center', gap: 22, overflowX: 'auto' }}>
              {productItems.map(([href, label, key]) => (
                <a key={key} href={href} style={{ ...S.navLink, fontSize: 13, ...(active === key ? S.navLinkActive : {}) }}>{label}</a>
              ))}
            </nav>
            <Button as="a" href={routeHref('ai-code-review', '#cohort')} size="sm" variant="secondary" onClick={() => trackEvent('join_beta', { from: 'product_nav' })}>
              {PRODUCT.stage === 'beta' ? t('Join beta', 'Participar do beta') : t('Get the system', 'Obter o sistema')}
            </Button>
          </div>
        </div>
      )}
    </header>
  );
}

/* ---- footer ---- */
function SiteFooter() {
  const { t, locale } = useT();
  return (
    <footer style={S.footer}>
      <div style={{ ...S.container, display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 32 }} className="site-container">
        <div style={{ maxWidth: 280 }}>
          <div style={S.brand}>bloo<span style={{ color: 'var(--brand)' }}>.</span>app</div>
          <p style={{ fontSize: 13, color: 'var(--text-muted)', marginTop: 10, lineHeight: 1.5 }}>{t("Bruno Luigi's independent product studio: useful software, practical AI systems, and the work behind them.", 'O estúdio independente de produtos de Bruno Luigi: software útil, sistemas práticos de IA e o trabalho por trás deles.')}</p>
        </div>
        <div style={{ display: 'flex', gap: 56, flexWrap: 'wrap' }} className="site-footer-cols">
          <div>
            <div style={S.footHead}>{t('Product', 'Produto')}</div>
            <a href={routeHref('ai-code-review')} style={S.footLink}>{PAGE_LABELS['ai-code-review'][locale]}</a>
            <a href={routeHref('benchmark')} style={S.footLink}>{PAGE_LABELS.benchmark[locale]}</a>
            <a href={routeHref('docs')} style={S.footLink}>{PAGE_LABELS.docs[locale]}</a>
            <a href={routeHref('changelog')} style={S.footLink}>{PAGE_LABELS.changelog[locale]}</a>
            <a href={routeHref('license')} style={S.footLink}>{t('License & updates', 'Licença e atualizações')}</a>
          </div>
          <div>
            <div style={S.footHead}>{t('Studio', 'Estúdio')}</div>
            <a href={routeHref('case-studies')} style={S.footLink}>{t('Work', 'Trabalhos')}</a>
            <a href={routeHref('products')} style={S.footLink}>{PAGE_LABELS.products[locale]}</a>
            <a href={routeHref('services')} style={S.footLink}>{PAGE_LABELS.services[locale]}</a>
            <a href={routeHref('about')} style={S.footLink}>{PAGE_LABELS.about[locale]}</a>
            <a href={routeHref('contact')} style={S.footLink}>{PAGE_LABELS.contact[locale]}</a>
          </div>
          <div>
            <div style={S.footHead}>{t('Connect', 'Redes')}</div>
            <a href={`mailto:${LINKS.companyEmail}`} style={S.footLink}>{LINKS.companyEmail}</a>
            <a href={LINKS.linkedin} {...EXT} style={S.footLink}>LinkedIn</a>
            <a href={LINKS.medium} {...EXT} style={S.footLink}>Medium</a>
            <a href={LINKS.youtube} {...EXT} style={S.footLink}>YouTube</a>
          </div>
        </div>
      </div>
      <div style={{ ...S.container, borderTop: '1px solid var(--border-subtle)', marginTop: 32, paddingTop: 20, fontSize: 12, color: 'var(--text-subtle)', fontFamily: 'var(--font-mono)' }} className="site-container">
        {t('© 2026 bloo.app — an independent product studio by Bruno Luigi.', '© 2026 bloo.app — um estúdio independente de produtos de Bruno Luigi.')}
      </div>
    </footer>
  );
}

/* ---- reusable bottom CTA band ---- */
function CTASection({ heading, body, primaryLabel, primaryHref = LINKS.book, secondary }) {
  const { t } = useT();
  const label = primaryLabel || t('Book a call', 'Agendar uma call');
  return (
    <section style={S.cta}>
      <div style={{ ...S.container, ...S.ctaInner }} className="site-container">
        <h2 style={{ ...S.h2, color: 'var(--text-onbrand)', maxWidth: 620 }}>{heading}</h2>
        {body && <p style={{ fontSize: 17, color: 'rgba(255,255,255,.75)', maxWidth: 520, lineHeight: 1.5, margin: '0 auto' }}>{body}</p>}
        <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', justifyContent: 'center', marginTop: 10 }}>
          <Button as="a" href={primaryHref} {...EXT} size="lg" trailingIcon={<IconExternal />}>{label}</Button>
          {secondary && (
            <Button as="a" href={secondary.href} size="lg" variant="secondary"
                    style={{ background: 'transparent', borderColor: 'rgba(255,255,255,.3)', color: 'var(--text-onbrand)' }}>
              {secondary.label}
            </Button>
          )}
        </div>
      </div>
    </section>
  );
}

window.Site = {
  PRODUCT,
  SITE_CONFIG,
  REGION,
  LINKS,
  EXT,
  Icons,
  Icon,
  S,
  SiteNav,
  SiteFooter,
  CTASection,
  PAGE_LABELS,
  routeHref,
  equivalentRegionHref,
  trackEvent,
  trackOnce,
  getAttribution,
};
})();
