// Longevium — Landing page design system
// Warm, sober, premium. Built on LPR teal but with cream backgrounds and serif display.

const LV = {
  // brand
  teal900: '#0f3937',
  teal800: '#0f5754',
  teal700: '#0f766e',
  teal600: '#0d9488',
  teal500: '#14b8a6',
  teal300: '#5eead4',
  teal200: '#99f6e4',
  teal100: '#ccfbf1',
  teal50:  '#f0fdfa',

  // warm neutrals
  ink:     '#0f1715',
  inkSoft: '#2a3331',
  text:    '#1c2421',
  textSoft:'#43504c',
  textMute:'#6e7872',
  textFaint:'#9aa39d',

  cream:   '#faf8f3',   // page bg
  creamWarm:'#f3efe6',  // alt section
  creamDeep:'#e9e3d4',  // borders
  paper:   '#ffffff',
  border:  '#e7e3da',
  borderStrong: '#d6d1c4',

  // accents (sparing)
  amber:   '#b45309',
  amberBg: '#fef3c7',
  rose:    '#b91c1c',
  roseBg:  '#fee2e2',

  // type
  fontUI: "'Inter', -apple-system, system-ui, sans-serif",
  fontDisplay: "'Instrument Serif', 'Times New Roman', serif",
  fontMono: "'JetBrains Mono', ui-monospace, monospace",
};

// ─────────────────────────────────────────────────────────────────────
// i18n — bilingual dictionary (PT-BR / EN), context + hook
// ─────────────────────────────────────────────────────────────────────
const LV_DICT = {
  pt: {
    meta: {
      title: 'Longevium — Plataforma híbrida para protocolos médicos',
      description: 'Longevium reúne dados do paciente, visão clínica do médico e operação dos protocolos em uma única plataforma. LPR é o primeiro protocolo disponível.',
    },
    nav: {
      items: [
        { href: '#produto',   label: 'Produto' },
        { href: '#pacientes', label: 'Pacientes' },
        { href: '#medicos',   label: 'Médicos' },
        { href: '#empresas',  label: 'Empresas' },
        { href: '#protocolo', label: 'Protocolo LPR' },
        { href: '#planos',    label: 'Planos' },
      ],
      login: 'Entrar',
      demo:  'Pedir demo',
    },
    hero: {
      kicker: 'Plataforma híbrida · saúde longitudinal',
      titlePart1: 'A medicina ',
      titleEm1: 'preventiva',
      titlePart2: ' e sua saúde só precisa de um único ',
      titleEm2: 'app',
      titleTail: '.',
      leadParts: ['Longevium reúne em um único lugar os ', 'dados de saúde do paciente', ', a ', 'visão clínica do médico', ' e a ', 'operação dos protocolos', ' — começando pelo LPR, o primeiro protocolo de reset metabólico baseado em estilo de vida.'],
      ctaPrimary: 'Pedir demo clínica',
      ctaSecondary: 'Ver para empresas',
      stats: [
        { v: '8',    l: 'domínios\nbiológicos' },
        { v: '47',   l: 'biomarcadores\nintegrados' },
        { v: '24/7', l: 'monitoramento\n+ safety' },
      ],
      safetyTitle: 'Safety Engine',
      safetyDesc:  'Bloqueio automático de combinações de risco antes de chegar no paciente.',
    },
    trust: { caption: 'Compatível e em conversa com' },
    product: {
      kicker: 'O produto',
      title1: 'Dois jeitos de usar.',
      titleEm: 'Uma única plataforma.',
      lead: 'Comece simples — guardando exames e sinais — ou ative um protocolo clínico completo. Você decide a profundidade. A plataforma cresce junto com a relação médico-paciente.',
      care: {
        title: 'Toda a saúde do paciente, em um só lugar.',
        desc:  'O hub do paciente. Exames, medicações, dispositivos vestíveis e histórico médico organizados — sem protocolo ativo. Acesso gratuito vitalício do paciente, com convite do médico ou empresa parceira.',
        features: [
          'Upload e leitura automática de exames (OCR + LLM)',
          'Conexão com Apple Health, Oura, Libre, Withings',
          'Histórico médico estruturado e exportável',
          'Compartilhamento granular com médicos vinculados',
        ],
        cta: 'Ver no detalhe',
      },
      protocols: {
        title: 'Protocolos clínicos com Safety Engine.',
        desc:  'A camada clínica. Médicos prescrevem protocolos versionados, monitoram pacientes em ciclos e contam com regras de segurança automáticas. O LPR é o primeiro protocolo disponível na plataforma.',
        features: [
          'Protocolos versionados e auditáveis',
          'Safety Engine: regras de segurança automáticas',
          'Score longitudinal por 8 domínios biológicos',
          'Relatórios clínicos e mensagens dentro do app',
        ],
        cta: 'Ver Protocolo LPR',
      },
    },
    audience: {
      kicker: 'Para quem é',
      title1: 'Construído para o triângulo',
      titleEm: 'paciente · médico · empresa.',
      tabs: [
        { id: 'pacientes', label: 'Para pacientes' },
        { id: 'medicos',   label: 'Para médicos' },
        { id: 'empresas',  label: 'Para empresas' },
      ],
    },
    patients: {
      kicker: 'Para pacientes',
      title1: 'A saúde como um ',
      titleEm: 'processo',
      title2: ',',
      title3: 'não como um número.',
      lead: 'Você acompanha o seu corpo nos 8 pilares — sono, glicemia, ritmo, atividade, mente, nutrição, ambiente e inflamação — com explicações claras e um plano diário leve.',
      blocks: [
        { t: 'Plano do dia, não checklist',
          d: 'Cada manhã: três coisas que importam hoje. Acompanhadas pela sua médica.' },
        { t: 'Score LPR explicado',
          d: 'Os números viram contexto: por que mudaram, o que mantém e o que está em atenção.' },
        { t: 'Seus dados, seu controle',
          d: 'Compartilhamento granular com a equipe clínica. Você revoga acesso quando quiser.' },
      ],
      testimonialName: 'Mariana, 44',
      testimonialMeta: 'Ciclo 2 · Dia 18 / 60 · LPR-LR-1',
      testimonialQuote: '"Pela primeira vez sinto que entendo o que está acontecendo no meu corpo. Não é mais um app de tarefas; é uma conversa."',
      stats: [
        { v: '47',     l: 'dias de streak médio',  s: 'em pacientes ativos' },
        { v: '8',      l: 'pilares biológicos',    s: 'todos visíveis no app' },
        { v: '92%',    l: 'consideram úteis',      s: 'os insights da semana' },
        { v: '< 3min', l: 'check-in diário',       s: 'leve e contextual' },
      ],
      carousel: {
        regionLabel: 'Telas do app do paciente',
        dotLabel:    (i, n) => `Mostrar tela ${i + 1} de ${n}`,
      },
    },
    doctors: {
      kicker: 'Para médicos',
      title1: 'Decisões clínicas ',
      titleEm: 'com contexto.',
      lead: 'Você vê todos os sinais do paciente — exames, vestíveis, questionários, adesão — em um único timeline. Ajusta protocolos versionados, dispara mensagens e recebe alertas críticos sem precisar agregar dados manualmente.',
      blocks: [
        { t: 'Protocolos versionados',
          d: 'Edite, publique e audite. Cada paciente fica vinculado a uma versão imutável.' },
        { t: 'Safety Engine',
          d: 'Regras automáticas pegam combinações de risco antes de você precisar olhar.' },
        { t: '8 domínios em um lugar',
          d: 'Score longitudinal por sistema, com drivers explícitos do que mudou.' },
        { t: 'Relatórios prontos',
          d: 'PDF clínico exportável a cada ciclo, com narrativa, biomarcadores e plano.' },
      ],
      chipLabel: 'Score',
      pill: 'Dashboard clínico',
      dashTitle: 'Sua manhã começa com a foto certa.',
      dashLead: 'Pacientes em atenção, alertas do Safety Engine, próximos retornos e quem caiu fora do ritmo do protocolo. Tudo o que você precisa antes da primeira consulta.',
      dashStat1Label: 'tempo entre consultas',
      dashStat2Label: 'mais sinais analisados',
    },
    companies: {
      kicker: 'Para empresas — B2B2C',
      title1: 'Saúde corporativa que ',
      titleEm: 'previne',
      title2: ',',
      title3: 'não que reage.',
      lead: 'Empresas oferecem o Longevium aos colaboradores — começando pelo Care e ativando o protocolo LPR para os grupos de maior risco metabólico. Sem fricção de implementação, sem tela de espera para o RH.',
      items: [
        { t: 'ROI mensurado',          d: 'Painel agregado e anonimizado para o RH: aderência, evolução de score, redução de afastamentos.' },
        { t: 'LGPD-first',             d: 'A empresa nunca vê dados individuais. O paciente decide o que compartilhar com sua médica.' },
        { t: 'Implementação em dias',  d: 'SSO via Google/Microsoft, convite por planilha, branding co-marcado opcional.' },
      ],
      ctaSales: 'Falar com vendas',
      ctaOnePager: 'Baixar one-pager',
      mock: {
        hr: 'RH · TechCorp',
        panel: 'Painel de saúde · Q2 2026',
        active: '1.247 ativos',
        score: 'Score corporativo',
        scoreSub: 'vs trimestre anterior',
        lpr: 'Em protocolo LPR',
        lprDenominator: '/ 1.247',
        lprSub: '14.8% da população',
        domainsLabel: 'Evolução por domínio',
        domains: [
          { l: 'Sono',      v: 72, d: '+8' },
          { l: 'Glicemia',  v: 64, d: '+6' },
          { l: 'Atividade', v: 58, d: '+3' },
          { l: 'Mente',     v: 51, d: '+1' },
        ],
        insightLabel: 'Insight do trimestre:',
        insightText:  ' grupos de turnos noturnos puxam o score de circadiano para baixo. Programa LPR-Reset Sono recomendado para 38 colaboradores.',
      },
      stats: [
        { v: '−R$ 4.200', l: 'custo médio anual evitado por colaborador em risco metabólico' },
        { v: '23%',       l: 'redução de afastamentos relacionados a sono e estresse' },
        { v: '7x',        l: 'detecção precoce de pré-diabetes vs check-up anual' },
        { v: '94%',       l: 'NPS de colaboradores em programas pilotos' },
      ],
    },
    protocol: {
      kicker: 'O primeiro protocolo · LPR',
      title1: 'Lifestyle Precision Reset.',
      titleEm: '60 dias para reescrever o metabolismo.',
      lead: 'Um protocolo clínico estruturado em ciclos de 60 dias, organizado por 8 domínios biológicos. Combina exames laboratoriais, monitoramento contínuo, intervenções nutricionais, sono e movimento — com acompanhamento médico semanal.',
      domains: [
        { id: 'metabolic', l: 'Metabólico',          desc: 'Glicemia contínua, HOMA-IR, ApoB' },
        { id: 'gut',       l: 'Intestinal',          desc: 'Microbiota, distensão, GI Symptom' },
        { id: 'mito',      l: 'Mitocondrial',        desc: 'VO₂, HRV, fadiga subjetiva' },
        { id: 'inflam',    l: 'Inflamatório',        desc: 'PCR-us, TG/HDL, IL-6' },
        { id: 'hormone',   l: 'Neuroendócrino',      desc: 'Cortisol, TSH, sexuais' },
        { id: 'circadian', l: 'Circadiano · Sono',   desc: 'Estágios, latência, jet-lag social' },
        { id: 'body',      l: 'Composição · Movim.', desc: 'Massa magra, força, zonas Z2-Z4' },
        { id: 'behavior',  l: 'Comportamental',      desc: 'Adesão, mood, ambiente' },
      ],
      cycleTitle1: 'Cada ciclo é uma ',
      cycleTitleEm: 'conversa estruturada',
      cycleTitle2: ' entre dados e clínica.',
      cycleLead: 'O paciente vive o protocolo como ritmo diário. A médica vê a evolução por domínio em tempo real. Ao final dos 60 dias, um relatório clínico recompõe o que mudou — e propõe o próximo ciclo.',
      phases: [
        { p: 'Fase 1', l: 'Reset Circadiano',          d: 'Dias 1–20' },
        { p: 'Fase 2', l: 'Reabilitação metabólica',   d: 'Dias 21–40' },
        { p: 'Fase 3', l: 'Composição & Resiliência',  d: 'Dias 41–60' },
      ],
      futureKicker: 'Em desenvolvimento',
      futureTitle:  'Mais protocolos chegam em 2026',
      futureSub:    'LPR-Cardio · LPR-Cognição · LPR-Reganho · LPR-Climatério',
      futureCta:    'Inscrever clínica',
    },
    how: {
      kicker: 'Como funciona',
      title1: 'De convite a relatório',
      title2: 'em ',
      titleEm: '60 dias.',
      lead: 'O fluxo é simples por dentro e rico por fora. Cada passo aparece para o paciente como uma ação leve. Para a clínica, vira dado estruturado.',
      steps: [
        { n: '01', t: 'Convite e primeiro vínculo',
          d: 'O paciente recebe o convite (do médico ou da empresa), conecta dispositivos, exames e dá os consentimentos granulares.' },
        { n: '02', t: 'Avaliação de baseline',
          d: 'Dados laboratoriais e questionários por domínio. A médica recebe um quadro estruturado das condições atuais.' },
        { n: '03', t: 'Plano clínico no protocolo',
          d: 'A médica seleciona uma versão do LPR e personaliza o plano. O paciente vê o que mudar a cada semana.' },
        { n: '04', t: 'Operação diária + Safety',
          d: 'Check-ins, mensagens, ajustes em adesão. O Safety Engine bloqueia combinações de risco automaticamente.' },
        { n: '05', t: 'Relatório de ciclo',
          d: 'A cada 60 dias um documento clínico exportável recompõe a evolução e propõe o próximo ciclo.' },
      ],
    },
    pricing: {
      kicker: 'Planos',
      title1: 'Um modelo simples,',
      titleEm: 'três entradas.',
      lead: 'O paciente nunca paga pela plataforma. Quem paga é a clínica ou a empresa que oferece o cuidado.',
      featured: 'Mais escolhido',
      plans: [
        { kind: 'Care',    audience: 'Para pacientes',
          price: 'Grátis',       sub: 'Por convite do médico ou empresa',
          desc: 'O hub de saúde do paciente. Sem protocolo ativo, sem tempo de uso.',
          features: ['Exames com leitura automática', 'Conexão com vestíveis', 'Histórico médico', 'Compartilhamento granular'],
          cta: 'Começar com convite' },
        { kind: 'Clínica', audience: 'Para médicos e clínicas',
          price: 'Sob consulta', sub: 'por médico ativo / mês',
          desc: 'Operação clínica completa. LPR + Safety Engine + relatórios. Pacientes ilimitados em Care.',
          features: ['Protocolo LPR e versionamento', 'Safety Engine + builder de regras', 'Dashboard clínico + alertas', 'Relatórios de ciclo exportáveis', 'Suporte clínico dedicado'],
          cta: 'Pedir demo clínica' },
        { kind: 'Empresa', audience: 'Para empresas — B2B2C',
          price: 'Sob consulta',  sub: 'A partir de 200 colaboradores',
          desc: 'Saúde corporativa preventiva, anonimizada e mensurável. Med-equipe parceira ou própria.',
          features: ['Painel agregado para o RH', 'SSO + onboarding em massa', 'LPR como benefício opcional', 'Programas por grupo de risco', 'SLA + sucesso dedicado'],
          cta: 'Falar com vendas' },
      ],
    },
    finalCta: {
      kicker: 'Pronto para começar',
      title1: 'Agende uma demo de 30 minutos',
      title2: 'com a equipe Longevium.',
      lead: 'Apresentamos a plataforma com um caso real, mostramos o Safety Engine ao vivo e desenhamos um plano para a sua clínica ou empresa.',
      ctaPrimary: 'Agendar demo',
      ctaSecondary: 'Falar pelo WhatsApp',
      badges: ['LGPD-first', 'ISO 27001 (em curso)', 'Hospedagem Brasil'],
    },
    footer: {
      tagline: 'A plataforma híbrida para protocolos médicos longitudinais. Construída em São Paulo, hospedada no Brasil.',
      cols: [
        { t: 'Produto',   items: ['Longevium Care', 'Longevium Protocols', 'Safety Engine', 'API & integrações'] },
        { t: 'Para quem', items: ['Pacientes', 'Médicos', 'Clínicas', 'Empresas'] },
        { t: 'Protocolo', items: ['LPR · Reset', 'LPR · Cardio (em breve)', 'LPR · Cognição (em breve)', 'Inscrever clínica'] },
        { t: 'Empresa',   items: ['Sobre', 'Ciência', 'Carreiras', 'Imprensa'] },
        { t: 'Legal',     items: ['Termos', 'Privacidade', 'LGPD', 'Status'] },
      ],
      copyright: '© 2026 Longevium Saúde Ltda. CNPJ 00.000.000/0001-00',
      made: 'Feito com cuidado em SP · Dados no Brasil',
    },
  },
  en: {
    meta: {
      title: 'Longevium — Hybrid platform for medical protocols',
      description: 'Longevium brings together patient health data, the clinician\'s view, and protocol operations in a single platform. LPR is the first protocol available.',
    },
    nav: {
      items: [
        { href: '#produto',   label: 'Product' },
        { href: '#pacientes', label: 'Patients' },
        { href: '#medicos',   label: 'Doctors' },
        { href: '#empresas',  label: 'Companies' },
        { href: '#protocolo', label: 'LPR Protocol' },
        { href: '#planos',    label: 'Pricing' },
      ],
      login: 'Sign in',
      demo:  'Request demo',
    },
    hero: {
      kicker: 'Hybrid platform · longitudinal health',
      titlePart1: 'Preventive ',
      titleEm1: 'medicine',
      titlePart2: ' and your health, in a single ',
      titleEm2: 'app',
      titleTail: '.',
      leadParts: ['Longevium brings the ', 'patient\'s health data', ', the ', 'clinician\'s view', ', and ', 'protocol operations', ' into one place — starting with LPR, the first lifestyle-based metabolic reset protocol.'],
      ctaPrimary: 'Request clinical demo',
      ctaSecondary: 'See for companies',
      stats: [
        { v: '8',    l: 'biological\ndomains' },
        { v: '47',   l: 'integrated\nbiomarkers' },
        { v: '24/7', l: 'monitoring\n+ safety' },
      ],
      safetyTitle: 'Safety Engine',
      safetyDesc:  'Risky combinations are blocked automatically before they reach the patient.',
    },
    trust: { caption: 'Compatible and in conversation with' },
    product: {
      kicker: 'The product',
      title1: 'Two ways to use it.',
      titleEm: 'One single platform.',
      lead: 'Start simple — keeping exams and signals — or activate a full clinical protocol. You decide the depth. The platform grows with the doctor-patient relationship.',
      care: {
        title: 'All of the patient\'s health, in one place.',
        desc:  'The patient hub. Exams, medications, wearables and medical history organized — without an active protocol. Free lifetime patient access, by invitation from a doctor or partner company.',
        features: [
          'Automatic exam upload & reading (OCR + LLM)',
          'Connect to Apple Health, Oura, Libre, Withings',
          'Structured, exportable medical history',
          'Granular sharing with linked clinicians',
        ],
        cta: 'See in detail',
      },
      protocols: {
        title: 'Clinical protocols with Safety Engine.',
        desc:  'The clinical layer. Doctors prescribe versioned protocols, monitor patients in cycles and rely on automatic safety rules. LPR is the first protocol available on the platform.',
        features: [
          'Versioned, auditable protocols',
          'Safety Engine: automatic safety rules',
          'Longitudinal score across 8 biological domains',
          'Clinical reports and in-app messaging',
        ],
        cta: 'See LPR Protocol',
      },
    },
    audience: {
      kicker: 'Who it\'s for',
      title1: 'Built for the triangle',
      titleEm: 'patient · doctor · company.',
      tabs: [
        { id: 'pacientes', label: 'For patients' },
        { id: 'medicos',   label: 'For doctors' },
        { id: 'empresas',  label: 'For companies' },
      ],
    },
    patients: {
      kicker: 'For patients',
      title1: 'Health as a ',
      titleEm: 'process',
      title2: ',',
      title3: 'not as a number.',
      lead: 'You follow your body across 8 pillars — sleep, glucose, rhythm, activity, mind, nutrition, environment and inflammation — with clear explanations and a light daily plan.',
      blocks: [
        { t: 'Daily plan, not a checklist',
          d: 'Every morning: three things that matter today. Followed by your physician.' },
        { t: 'LPR Score, explained',
          d: 'Numbers become context: why they moved, what holds, and what needs attention.' },
        { t: 'Your data, your control',
          d: 'Granular sharing with the clinical team. Revoke access whenever you want.' },
      ],
      testimonialName: 'Mariana, 44',
      testimonialMeta: 'Cycle 2 · Day 18 / 60 · LPR-LR-1',
      testimonialQuote: '"For the first time I feel I understand what\'s happening in my body. It\'s not a task app anymore; it\'s a conversation."',
      stats: [
        { v: '47',     l: 'avg streak (days)',     s: 'across active patients' },
        { v: '8',      l: 'biological pillars',    s: 'all visible in the app' },
        { v: '92%',    l: 'find them useful',      s: 'the weekly insights' },
        { v: '< 3min', l: 'daily check-in',        s: 'light and contextual' },
      ],
      carousel: {
        regionLabel: 'Patient app screens',
        dotLabel:    (i, n) => `Show screen ${i + 1} of ${n}`,
      },
    },
    doctors: {
      kicker: 'For doctors',
      title1: 'Clinical decisions, ',
      titleEm: 'with context.',
      lead: 'You see every signal from the patient — exams, wearables, questionnaires, adherence — in a single timeline. Tune versioned protocols, send messages and receive critical alerts without aggregating data by hand.',
      blocks: [
        { t: 'Versioned protocols',
          d: 'Edit, publish, audit. Each patient is bound to an immutable version.' },
        { t: 'Safety Engine',
          d: 'Automatic rules catch risky combinations before you have to look.' },
        { t: '8 domains in one place',
          d: 'Longitudinal score per system, with explicit drivers of what changed.' },
        { t: 'Reports, ready',
          d: 'Exportable clinical PDF every cycle, with narrative, biomarkers and plan.' },
      ],
      chipLabel: 'Score',
      pill: 'Clinical dashboard',
      dashTitle: 'Your morning starts with the right snapshot.',
      dashLead: 'Patients to watch, Safety Engine alerts, upcoming follow-ups and who fell off the protocol\'s rhythm. Everything you need before the first appointment.',
      dashStat1Label: 'time between visits',
      dashStat2Label: 'more signals analyzed',
    },
    companies: {
      kicker: 'For companies — B2B2C',
      title1: 'Corporate health that ',
      titleEm: 'prevents',
      title2: ',',
      title3: 'not that reacts.',
      lead: 'Companies offer Longevium to employees — starting with Care and activating the LPR protocol for the highest metabolic-risk groups. No rollout friction, no waiting room for HR.',
      items: [
        { t: 'Measured ROI',           d: 'Aggregated, anonymous HR panel: adherence, score evolution, reduction in absences.' },
        { t: 'Privacy-first',          d: 'The company never sees individual data. The patient decides what to share with their doctor.' },
        { t: 'Live in days',           d: 'SSO via Google/Microsoft, invite by spreadsheet, optional co-branding.' },
      ],
      ctaSales: 'Talk to sales',
      ctaOnePager: 'Download one-pager',
      mock: {
        hr: 'HR · TechCorp',
        panel: 'Health panel · Q2 2026',
        active: '1,247 active',
        score: 'Corporate score',
        scoreSub: 'vs prior quarter',
        lpr: 'On LPR protocol',
        lprDenominator: '/ 1,247',
        lprSub: '14.8% of population',
        domainsLabel: 'Evolution by domain',
        domains: [
          { l: 'Sleep',     v: 72, d: '+8' },
          { l: 'Glucose',   v: 64, d: '+6' },
          { l: 'Activity',  v: 58, d: '+3' },
          { l: 'Mind',      v: 51, d: '+1' },
        ],
        insightLabel: 'Insight of the quarter:',
        insightText:  ' night-shift teams pull the circadian score down. LPR-Reset Sleep program recommended for 38 employees.',
      },
      stats: [
        { v: '−R$ 4,200', l: 'avg annual cost avoided per at-risk metabolic employee' },
        { v: '23%',       l: 'reduction in sleep- and stress-related leaves' },
        { v: '7x',        l: 'earlier detection of pre-diabetes vs annual check-up' },
        { v: '94%',       l: 'employee NPS on pilot programs' },
      ],
    },
    protocol: {
      kicker: 'The first protocol · LPR',
      title1: 'Lifestyle Precision Reset.',
      titleEm: '60 days to rewrite metabolism.',
      lead: 'A clinical protocol structured in 60-day cycles, organized across 8 biological domains. It combines lab work, continuous monitoring, nutrition, sleep and movement — with weekly clinical follow-up.',
      domains: [
        { id: 'metabolic', l: 'Metabolic',         desc: 'Continuous glucose, HOMA-IR, ApoB' },
        { id: 'gut',       l: 'Gut',               desc: 'Microbiota, bloating, GI Symptom' },
        { id: 'mito',      l: 'Mitochondrial',     desc: 'VO₂, HRV, subjective fatigue' },
        { id: 'inflam',    l: 'Inflammatory',      desc: 'hs-CRP, TG/HDL, IL-6' },
        { id: 'hormone',   l: 'Neuroendocrine',    desc: 'Cortisol, TSH, sex hormones' },
        { id: 'circadian', l: 'Circadian · Sleep', desc: 'Stages, latency, social jet-lag' },
        { id: 'body',      l: 'Body · Movement',   desc: 'Lean mass, strength, Z2–Z4 zones' },
        { id: 'behavior',  l: 'Behavioral',        desc: 'Adherence, mood, environment' },
      ],
      cycleTitle1: 'Each cycle is a ',
      cycleTitleEm: 'structured conversation',
      cycleTitle2: ' between data and the clinic.',
      cycleLead: 'The patient lives the protocol as a daily rhythm. The doctor sees the evolution by domain in real time. At day 60, an exportable clinical report recomposes what changed — and proposes the next cycle.',
      phases: [
        { p: 'Phase 1', l: 'Circadian Reset',         d: 'Days 1–20' },
        { p: 'Phase 2', l: 'Metabolic Rehab',         d: 'Days 21–40' },
        { p: 'Phase 3', l: 'Body & Resilience',       d: 'Days 41–60' },
      ],
      futureKicker: 'In development',
      futureTitle:  'More protocols arrive in 2026',
      futureSub:    'LPR-Cardio · LPR-Cognition · LPR-Regain · LPR-Climacteric',
      futureCta:    'Enroll clinic',
    },
    how: {
      kicker: 'How it works',
      title1: 'From invite to report',
      title2: 'in ',
      titleEm: '60 days.',
      lead: 'The flow is simple inside and rich on the outside. Each step shows up to the patient as a light action. To the clinic, it becomes structured data.',
      steps: [
        { n: '01', t: 'Invite and first link',
          d: 'The patient receives the invite (from doctor or company), connects devices and exams, and gives granular consent.' },
        { n: '02', t: 'Baseline assessment',
          d: 'Lab data and questionnaires by domain. The doctor receives a structured snapshot of current conditions.' },
        { n: '03', t: 'Clinical plan in the protocol',
          d: 'The doctor selects an LPR version and personalizes the plan. The patient sees what changes each week.' },
        { n: '04', t: 'Daily ops + Safety',
          d: 'Check-ins, messages, adherence tweaks. Safety Engine blocks risky combinations automatically.' },
        { n: '05', t: 'Cycle report',
          d: 'Every 60 days an exportable clinical document recomposes the evolution and proposes the next cycle.' },
      ],
    },
    pricing: {
      kicker: 'Pricing',
      title1: 'A simple model,',
      titleEm: 'three entries.',
      lead: 'The patient never pays for the platform. The clinic or the company offering care does.',
      featured: 'Most chosen',
      plans: [
        { kind: 'Care',    audience: 'For patients',
          price: 'Free',         sub: 'By invite from doctor or company',
          desc: 'The patient\'s health hub. No active protocol, no time limit.',
          features: ['Exams with auto-reading', 'Wearable connections', 'Medical history', 'Granular sharing'],
          cta: 'Start with invite' },
        { kind: 'Clinic',  audience: 'For doctors and clinics',
          price: 'On request',   sub: 'per active doctor / month',
          desc: 'Full clinical operation. LPR + Safety Engine + reports. Unlimited patients on Care.',
          features: ['LPR protocol & versioning', 'Safety Engine + rule builder', 'Clinical dashboard + alerts', 'Exportable cycle reports', 'Dedicated clinical support'],
          cta: 'Request clinical demo' },
        { kind: 'Company', audience: 'For companies — B2B2C',
          price: 'On request',   sub: 'From 200 employees',
          desc: 'Preventive, anonymous, measurable corporate health. Partner or in-house medical team.',
          features: ['Aggregated HR panel', 'SSO + bulk onboarding', 'LPR as optional benefit', 'Programs by risk group', 'SLA + dedicated CSM'],
          cta: 'Talk to sales' },
      ],
    },
    finalCta: {
      kicker: 'Ready to start',
      title1: 'Book a 30-minute demo',
      title2: 'with the Longevium team.',
      lead: 'We walk through the platform on a real case, show the Safety Engine live, and draft a plan for your clinic or company.',
      ctaPrimary: 'Book demo',
      ctaSecondary: 'Chat on WhatsApp',
      badges: ['Privacy-first (LGPD)', 'ISO 27001 (in progress)', 'Hosted in Brazil'],
    },
    footer: {
      tagline: 'The hybrid platform for longitudinal medical protocols. Built in São Paulo, hosted in Brazil.',
      cols: [
        { t: 'Product',   items: ['Longevium Care', 'Longevium Protocols', 'Safety Engine', 'API & integrations'] },
        { t: 'For whom',  items: ['Patients', 'Doctors', 'Clinics', 'Companies'] },
        { t: 'Protocol',  items: ['LPR · Reset', 'LPR · Cardio (soon)', 'LPR · Cognition (soon)', 'Enroll clinic'] },
        { t: 'Company',   items: ['About', 'Science', 'Careers', 'Press'] },
        { t: 'Legal',     items: ['Terms', 'Privacy', 'LGPD', 'Status'] },
      ],
      copyright: '© 2026 Longevium Saúde Ltda. CNPJ 00.000.000/0001-00',
      made: 'Made with care in SP · Data in Brazil',
    },
  },
};

const LangContext = React.createContext(null);

function LangProvider({ children }) {
  const detect = () => {
    if (typeof window === 'undefined') return 'pt';
    try {
      const stored = localStorage.getItem('lv_lang');
      if (stored === 'pt' || stored === 'en') return stored;
    } catch (_) {}
    const nav = (typeof navigator !== 'undefined' && navigator.language || 'pt').toLowerCase();
    return nav.startsWith('pt') ? 'pt' : 'en';
  };
  const [lang, setLangState] = React.useState(detect);

  const setLang = React.useCallback((l) => {
    setLangState(l);
    try { localStorage.setItem('lv_lang', l); } catch (_) {}
  }, []);

  React.useEffect(() => {
    const dict = LV_DICT[lang] || LV_DICT.pt;
    document.documentElement.setAttribute('lang', lang === 'pt' ? 'pt-BR' : 'en');
    if (dict.meta) {
      document.title = dict.meta.title;
      const md = document.querySelector('meta[name="description"]');
      if (md) md.setAttribute('content', dict.meta.description);
    }
  }, [lang]);

  const value = React.useMemo(() => ({ lang, setLang }), [lang, setLang]);
  return <LangContext.Provider value={value}>{children}</LangContext.Provider>;
}

function useT() {
  const ctx = React.useContext(LangContext);
  if (!ctx) throw new Error('useT must be used within <LangProvider>');
  return LV_DICT[ctx.lang] || LV_DICT.pt;
}

// ─────────────────────────────────────────────────────────────────────
// Responsive — single source of truth for breakpoints
// ─────────────────────────────────────────────────────────────────────
// Breakpoint set at 1024 because the embedded desktop platform screenshots
// (1280×760) can't share a 2-col layout below tablet width without overflow,
// even with the ScreenFrame auto-fit shrinking. Single-column kicks in below.
const LV_BP = { mobile: 1024, tablet: 1024 };

function useMediaQuery(query) {
  const get = () => typeof window !== 'undefined' && window.matchMedia
    ? window.matchMedia(query).matches : false;
  const [match, setMatch] = React.useState(get);
  React.useEffect(() => {
    const mq = window.matchMedia(query);
    const onChange = () => setMatch(mq.matches);
    onChange();
    if (mq.addEventListener) mq.addEventListener('change', onChange);
    else mq.addListener(onChange);
    return () => {
      if (mq.removeEventListener) mq.removeEventListener('change', onChange);
      else mq.removeListener(onChange);
    };
  }, [query]);
  return match;
}
const useIsMobile = () => useMediaQuery(`(max-width: ${LV_BP.mobile - 1}px)`);
// Currently aliased — both breakpoints sit at 1024 (single-col below).
// Kept as a separate name for callsite clarity ("hide nav on tablet vs hide login on mobile");
// when the breakpoints diverge again, change this to its own useMediaQuery call.
const useIsTablet = useIsMobile;

function LangToggle({ style }) {
  const ctx = React.useContext(LangContext);
  if (!ctx) throw new Error('<LangToggle/> must be used within <LangProvider>');
  const { lang, setLang } = ctx;
  const langs = [{ id: 'pt', label: 'PT' }, { id: 'en', label: 'EN' }];
  return (
    <div role="group" aria-label="Language" style={{
      display: 'inline-flex', alignItems: 'center',
      padding: 3, borderRadius: 999,
      background: LV.creamWarm,
      border: `1px solid ${LV.border}`,
      ...style,
    }}>
      {langs.map((l) => {
        const active = lang === l.id;
        return (
          <button key={l.id}
            type="button"
            aria-pressed={active}
            onClick={() => setLang(l.id)}
            style={{
              padding: '5px 11px', borderRadius: 999,
              border: 'none', cursor: 'pointer',
              fontSize: 11.5, fontWeight: 700, letterSpacing: 0.6,
              background: active ? LV.ink : 'transparent',
              color: active ? LV.cream : LV.textMute,
              transition: 'background .15s, color .15s',
            }}>
            {l.label}
          </button>
        );
      })}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────
// Inject base styles once
// ─────────────────────────────────────────────────────────────────────
(function injectLVStyles() {
  if (typeof document === 'undefined') return;
  if (document.getElementById('lv-base')) return;
  const link = document.createElement('link');
  link.rel = 'stylesheet';
  link.crossOrigin = 'anonymous';
  link.href = 'https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=Instrument+Serif:ital@0;1&family=JetBrains+Mono:wght@400;500&display=swap';
  document.head.appendChild(link);

  const s = document.createElement('style');
  s.id = 'lv-base';
  s.textContent = `
    html, body { margin:0; padding:0; background: ${LV.cream}; }
    html { overflow-x: hidden; }
    body { font-family: ${LV.fontUI}; color: ${LV.text}; -webkit-font-smoothing: antialiased; overflow-x: hidden; }
    *, *::before, *::after { box-sizing: border-box; }
    a { color: inherit; text-decoration: none; }
    button { font-family: inherit; cursor: pointer; }
    .lv-noise {
      position: relative;
    }
    .lv-noise::before {
      content:''; position: absolute; inset: 0; pointer-events: none;
      background-image: radial-gradient(rgba(15,118,110,0.04) 1px, transparent 1px);
      background-size: 16px 16px;
      opacity: 0.5;
      mask-image: linear-gradient(180deg, black, transparent);
    }
    .lv-rule {
      height: 1px; background: linear-gradient(90deg, transparent, ${LV.borderStrong}, transparent);
    }
    .lv-fade-bottom { mask-image: linear-gradient(180deg, black 60%, transparent); }
    .lv-fade-top { mask-image: linear-gradient(180deg, transparent, black 30%); }
    .lv-fade-edges { mask-image: linear-gradient(180deg, transparent, black 8%, black 92%, transparent); }
    .lv-marquee {
      animation: lv-marquee 60s linear infinite;
    }
    @keyframes lv-marquee {
      0% { transform: translateX(0); }
      100% { transform: translateX(-50%); }
    }
    @keyframes lv-pulse {
      0%, 100% { opacity: 0.6; transform: scale(1); }
      50% { opacity: 1; transform: scale(1.05); }
    }
    .lv-pulse { animation: lv-pulse 2.4s ease-in-out infinite; }
    .lv-grid-bg {
      background-image:
        linear-gradient(${LV.creamDeep} 1px, transparent 1px),
        linear-gradient(90deg, ${LV.creamDeep} 1px, transparent 1px);
      background-size: 56px 56px;
      background-position: -1px -1px;
    }
    /* Reset focus to teal */
    *:focus-visible { outline: 2px solid ${LV.teal600}; outline-offset: 2px; border-radius: 6px; }
    /* Scaled screen wrappers */
    .lv-scaled { transform-origin: top left; will-change: transform; }
  `;
  document.head.appendChild(s);
})();

// ─────────────────────────────────────────────────────────────────────
// Atoms
// ─────────────────────────────────────────────────────────────────────

function LVContainer({ children, style, narrow }) {
  const isMobile = useIsMobile();
  return (
    <div style={{
      maxWidth: narrow ? 1080 : 1280,
      margin: '0 auto',
      padding: isMobile ? '0 20px' : '0 32px',
      ...style,
    }}>{children}</div>
  );
}

function LVKicker({ children, color = LV.teal700, style }) {
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center', gap: 10,
      fontSize: 12, fontWeight: 600, color,
      letterSpacing: 1.4, textTransform: 'uppercase',
      ...style,
    }}>
      <span style={{ width: 22, height: 1, background: color, opacity: 0.6 }}/>
      {children}
    </div>
  );
}

function LVHeading({ children, size = 'lg', italic, style, as = 'h2' }) {
  const map = {
    xl: { fontSize: 'clamp(56px, 6.4vw, 92px)', lineHeight: 0.96, letterSpacing: -2.4 },
    lg: { fontSize: 'clamp(40px, 4vw, 60px)', lineHeight: 1.02, letterSpacing: -1.5 },
    md: { fontSize: 'clamp(28px, 2.4vw, 38px)', lineHeight: 1.1, letterSpacing: -0.8 },
    sm: { fontSize: 'clamp(22px, 1.8vw, 26px)', lineHeight: 1.2, letterSpacing: -0.4 },
  };
  const Tag = as;
  return (
    <Tag style={{
      margin: 0,
      fontFamily: LV.fontDisplay,
      fontWeight: 400,
      color: LV.ink,
      fontStyle: italic ? 'italic' : 'normal',
      ...map[size],
      ...style,
    }}>{children}</Tag>
  );
}

function LVLead({ children, style, size = 'md' }) {
  const map = {
    lg: { fontSize: 20, lineHeight: 1.55 },
    md: { fontSize: 17, lineHeight: 1.6 },
    sm: { fontSize: 15, lineHeight: 1.6 },
  };
  return <p style={{ margin: 0, color: LV.textSoft, fontWeight: 400, ...map[size], ...style }}>{children}</p>;
}

function LVButton({ children, kind = 'primary', size = 'md', full, onClick, style, icon, iconRight }) {
  const sizes = {
    sm: { padding: '8px 14px', fontSize: 13, height: 36 },
    md: { padding: '10px 18px', fontSize: 14, height: 44 },
    lg: { padding: '14px 24px', fontSize: 15, height: 52 },
  };
  const kinds = {
    primary: {
      background: LV.teal700, color: '#fff',
      border: `1px solid ${LV.teal700}`,
      boxShadow: '0 1px 0 rgba(15,55,55,0.18), inset 0 1px 0 rgba(255,255,255,0.12)',
    },
    secondary: {
      background: LV.paper, color: LV.ink,
      border: `1px solid ${LV.borderStrong}`,
    },
    ghost: {
      background: 'transparent', color: LV.ink,
      border: '1px solid transparent',
    },
    dark: {
      background: LV.ink, color: '#fff',
      border: `1px solid ${LV.ink}`,
    },
  };
  return (
    <button onClick={onClick} style={{
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
      fontWeight: 600, letterSpacing: -0.1,
      borderRadius: 999,
      width: full ? '100%' : 'auto',
      whiteSpace: 'nowrap',
      transition: 'transform .15s ease, box-shadow .15s ease, background .15s ease',
      ...sizes[size], ...kinds[kind], ...style,
    }}
    onMouseDown={(e) => e.currentTarget.style.transform = 'translateY(1px)'}
    onMouseUp={(e) => e.currentTarget.style.transform = 'translateY(0)'}
    onMouseLeave={(e) => e.currentTarget.style.transform = 'translateY(0)'}>
      {icon}
      {children}
      {iconRight}
    </button>
  );
}

function LVPill({ children, tone = 'teal', style }) {
  const tones = {
    teal:  { bg: LV.teal100, fg: LV.teal900, bd: LV.teal200 },
    amber: { bg: LV.amberBg, fg: LV.amber, bd: '#fde68a' },
    rose:  { bg: LV.roseBg, fg: LV.rose, bd: '#fecaca' },
    cream: { bg: LV.creamWarm, fg: LV.inkSoft, bd: LV.creamDeep },
    dark:  { bg: LV.ink, fg: '#fff', bd: LV.ink },
  };
  const t = tones[tone] || tones.teal;
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 6,
      padding: '4px 10px', borderRadius: 999,
      fontSize: 11.5, fontWeight: 600, letterSpacing: 0.2,
      background: t.bg, color: t.fg, border: `1px solid ${t.bd}`,
      ...style,
    }}>{children}</span>
  );
}

// ─────────────────────────────────────────────────────────────────────
// Brand mark
// ─────────────────────────────────────────────────────────────────────
function LVBrand({ size = 22, color = LV.ink, withMark = true }) {
  return (
    <a href="#top" style={{ display: 'inline-flex', alignItems: 'center', gap: 10 }}>
      {withMark ? (
        <svg width={size + 8} height={size + 8} viewBox="0 0 32 32" fill="none">
          {/* Stylized 'L' arc */}
          <circle cx="16" cy="16" r="14" stroke={LV.teal700} strokeWidth="2"/>
          <path d="M11 9 L11 22 L22 22" stroke={LV.teal700} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
          <circle cx="22" cy="22" r="2.2" fill={LV.teal700}/>
        </svg>
      ) : null}
      <span style={{
        fontFamily: LV.fontDisplay, fontSize: size, color,
        letterSpacing: -0.5, fontWeight: 400,
      }}>
        Longevium
      </span>
    </a>
  );
}

// ─────────────────────────────────────────────────────────────────────
// Inline icons (matching lucide style of LPR system)
// ─────────────────────────────────────────────────────────────────────
const LVIcon = {
  Arrow: (p) => <svg width={p.size||16} height={p.size||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></svg>,
  Check: (p) => <svg width={p.size||16} height={p.size||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>,
  Spark: (p) => <svg width={p.size||16} height={p.size||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 3v3M12 18v3M3 12h3M18 12h3M5.6 5.6l2.1 2.1M16.3 16.3l2.1 2.1M5.6 18.4l2.1-2.1M16.3 7.7l2.1-2.1"/></svg>,
  Heart: (p) => <svg width={p.size||16} height={p.size||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.29 1.51 4.04 3 5.5l7 7Z"/></svg>,
  Activity: (p) => <svg width={p.size||16} height={p.size||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></svg>,
  Shield: (p) => <svg width={p.size||16} height={p.size||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"/></svg>,
  Building: (p) => <svg width={p.size||16} height={p.size||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="4" y="2" width="16" height="20" rx="2"/><path d="M9 22v-4h6v4M8 6h.01M16 6h.01M12 6h.01M12 10h.01M12 14h.01M16 10h.01M16 14h.01M8 10h.01M8 14h.01"/></svg>,
  Stethoscope: (p) => <svg width={p.size||16} height={p.size||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M11 2v2M5 2v2M5 3H3a1 1 0 0 0-1 1v3a4 4 0 0 0 8 0V4a1 1 0 0 0-1-1Z"/><path d="M8 11v3a4 4 0 0 0 8 0v-3"/><circle cx="20" cy="10" r="2"/></svg>,
  User: (p) => <svg width={p.size||16} height={p.size||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>,
  Lock: (p) => <svg width={p.size||16} height={p.size||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>,
  Plug: (p) => <svg width={p.size||16} height={p.size||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 22v-5M9 8V2M15 8V2M18 8v3a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V8Z"/></svg>,
  Layers: (p) => <svg width={p.size||16} height={p.size||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m12.83 2.18-9 4a1 1 0 0 0 0 1.83l9 4a1 1 0 0 0 .83 0l9-4a1 1 0 0 0 0-1.83l-9-4a1 1 0 0 0-.83 0Z"/><path d="m22 17-9 4a1 1 0 0 1-.83 0l-9-4M22 12l-9 4a1 1 0 0 1-.83 0l-9-4"/></svg>,
  Brain: (p) => <svg width={p.size||16} height={p.size||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M9.5 2A2.5 2.5 0 0 1 12 4.5v15A2.5 2.5 0 0 1 9.5 22 2.5 2.5 0 0 1 7 19.5V18a2 2 0 0 1-2-2 2 2 0 0 1-2-2 2 2 0 0 1 .5-1.3A2 2 0 0 1 3 11a2 2 0 0 1 1.5-1.94A2 2 0 0 1 5 6a2 2 0 0 1 2-2 2 2 0 0 1 2.5-2Z"/><path d="M14.5 2A2.5 2.5 0 0 0 12 4.5v15A2.5 2.5 0 0 0 14.5 22 2.5 2.5 0 0 0 17 19.5V18a2 2 0 0 0 2-2 2 2 0 0 0 2-2 2 2 0 0 0-.5-1.3A2 2 0 0 0 21 11a2 2 0 0 0-1.5-1.94A2 2 0 0 0 19 6a2 2 0 0 0-2-2 2 2 0 0 0-2.5-2Z"/></svg>,
  Apple: (p) => <svg width={p.size||16} height={p.size||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 20.94c1.5 0 2.75 1.06 4 1.06 3 0 6-8 6-12.22A4.91 4.91 0 0 0 17 5c-2.22 0-4 1.44-5 2-1-.56-2.78-2-5-2a4.9 4.9 0 0 0-5 4.78C2 14 5 22 8 22c1.25 0 2.5-1.06 4-1.06Z"/><path d="M10 2c1 .5 2 2 2 5"/></svg>,
  Moon: (p) => <svg width={p.size||16} height={p.size||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79Z"/></svg>,
  Flame: (p) => <svg width={p.size||16} height={p.size||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M8.5 14.5A2.5 2.5 0 0 0 11 12c0-1.38-.5-2-1-3-1.072-2.143-.224-4.054 2-6 .5 2.5 2 4.9 4 6.5 2 1.6 3 3.5 3 5.5a7 7 0 1 1-14 0c0-1.153.433-2.294 1-3a2.5 2.5 0 0 0 2.5 2.5Z"/></svg>,
  Zap: (p) => <svg width={p.size||16} height={p.size||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>,
  Dumbbell: (p) => <svg width={p.size||16} height={p.size||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m6.5 6.5 11 11M21 21l-1-1M3 3l1 1M18 22l4-4M14 17l5-5M2 6l4-4M7 10l-2 2M22 7l-2 2M5 12l-2 2M17 7l5 5"/></svg>,
  Target: (p) => <svg width={p.size||16} height={p.size||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="6"/><circle cx="12" cy="12" r="2"/></svg>,
  Globe: (p) => <svg width={p.size||16} height={p.size||16} 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.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>,
  Trend: (p) => <svg width={p.size||16} height={p.size||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="23 6 13.5 15.5 8.5 10.5 1 18"/><polyline points="17 6 23 6 23 12"/></svg>,
  Sparkles: (p) => <svg width={p.size||16} height={p.size||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 3v3M12 18v3M3 12h3M18 12h3M5.6 5.6l2.1 2.1M16.3 16.3l2.1 2.1M5.6 18.4l2.1-2.1M16.3 7.7l2.1-2.1"/></svg>,
};

// ─────────────────────────────────────────────────────────────────────
// Sticky top nav
// ─────────────────────────────────────────────────────────────────────
function LVNav() {
  const t = useT();
  const isMobile = useIsMobile();
  const isTablet = useIsTablet();
  const [scrolled, setScrolled] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  return (
    <header style={{
      position: 'sticky', top: 0, zIndex: 100,
      backdropFilter: scrolled ? 'saturate(140%) blur(14px)' : 'none',
      WebkitBackdropFilter: scrolled ? 'saturate(140%) blur(14px)' : 'none',
      background: scrolled ? 'rgba(250, 248, 243, 0.78)' : 'transparent',
      borderBottom: `1px solid ${scrolled ? LV.border : 'transparent'}`,
      transition: 'background .2s, border-color .2s',
    }}>
      <LVContainer style={{ display: 'flex', alignItems: 'center', height: isMobile ? 56 : 68, gap: isMobile ? 12 : 24 }}>
        <LVBrand size={isMobile ? 18 : 20}/>
        {isTablet ? null : (
          <nav style={{ display: 'flex', alignItems: 'center', gap: 4, marginLeft: 24, flex: 1 }}>
            {t.nav.items.map((i) => (
              <a key={i.href} href={i.href} style={{
                padding: '8px 12px', borderRadius: 999,
                fontSize: 13.5, fontWeight: 500, color: LV.textSoft,
                whiteSpace: 'nowrap',
                transition: 'background .15s, color .15s',
              }}
              onMouseEnter={(e) => { e.currentTarget.style.background = LV.creamWarm; e.currentTarget.style.color = LV.ink; }}
              onMouseLeave={(e) => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = LV.textSoft; }}>
                {i.label}
              </a>
            ))}
          </nav>
        )}
        <div style={{ display: 'flex', alignItems: 'center', gap: isMobile ? 6 : 10, marginLeft: isTablet ? 'auto' : 0 }}>
          <LangToggle/>
          {isMobile ? null : (
            <a href="#login" style={{
              fontSize: 13.5, fontWeight: 500, color: LV.textSoft,
              padding: '8px 14px',
            }}>{t.nav.login}</a>
          )}
          <LVButton kind="dark" size="sm" iconRight={<LVIcon.Arrow size={14}/>}>{t.nav.demo}</LVButton>
        </div>
      </LVContainer>
    </header>
  );
}

// ─────────────────────────────────────────────────────────────────────
// Section wrapper
// ─────────────────────────────────────────────────────────────────────
function LVSection({ id, bg, children, style, divider }) {
  const isMobile = useIsMobile();
  return (
    <section id={id} style={{
      background: bg || 'transparent',
      paddingTop: isMobile ? 64 : 120,
      paddingBottom: isMobile ? 64 : 120,
      paddingLeft: 0,
      paddingRight: 0,
      position: 'relative',
      borderTop: divider ? `1px solid ${LV.border}` : 'none',
      overflowX: 'hidden',
      ...style,
    }}>
      {children}
    </section>
  );
}

// ─────────────────────────────────────────────────────────────────────
// Scaled screen wrapper — clips a real React screen at fixed dimensions
// and scales it to the container.
// ─────────────────────────────────────────────────────────────────────
function ScreenFrame({ width, height, scale = 0.5, radius = 14, shadow = true, border = true, children, style }) {
  // Auto-shrink: if the parent is narrower than `width * scale`, recompute scale
  // so the frame always fits its container. Prevents horizontal overflow on
  // viewports we didn't anticipate (Fold/SE 1st gen/etc.).
  const ref = React.useRef(null);
  const [actual, setActual] = React.useState(scale);

  React.useLayoutEffect(() => {
    const el = ref.current;
    if (!el || !el.parentElement) return;
    const parent = el.parentElement;
    const update = () => {
      // Use the parent's content-box width (clientWidth minus padding) so we
      // don't bleed into its padding when shrinking to fit.
      const cs = getComputedStyle(parent);
      const padL = parseFloat(cs.paddingLeft) || 0;
      const padR = parseFloat(cs.paddingRight) || 0;
      const inner = (parent.clientWidth || parent.getBoundingClientRect().width) - padL - padR;
      if (inner <= 0) return;
      const fitScale = inner / width;
      // Quantize to 3 decimals — avoids re-renders from sub-pixel parent jitter
      // (font swap, scrollbar reflow, tiny layout animations).
      const next = Math.round(Math.min(scale, fitScale) * 1000) / 1000;
      setActual((prev) => prev === next ? prev : next);
    };
    update();
    if (typeof ResizeObserver !== 'undefined') {
      const ro = new ResizeObserver(update);
      ro.observe(parent);
      return () => ro.disconnect();
    }
    window.addEventListener('resize', update);
    return () => window.removeEventListener('resize', update);
  }, [width, scale]);

  const W = width * actual, H = height * actual;
  return (
    <div ref={ref} style={{
      width: W, height: H,
      maxWidth: '100%',
      background: LV.paper, borderRadius: radius,
      overflow: 'hidden',
      border: border ? `1px solid ${LV.border}` : 'none',
      boxShadow: shadow ? '0 30px 60px -20px rgba(15,55,55,0.18), 0 8px 20px -8px rgba(15,55,55,0.10)' : 'none',
      position: 'relative',
      ...style,
    }}>
      <div className="lv-scaled" style={{
        width, height, transform: `scale(${actual})`,
      }}>
        {children}
      </div>
    </div>
  );
}

// expose
Object.assign(window, {
  LV, LVContainer, LVKicker, LVHeading, LVLead, LVButton, LVPill, LVBrand, LVIcon, LVNav, LVSection, ScreenFrame,
  LV_DICT, LangContext, LangProvider, useT, LangToggle,
  LV_BP, useMediaQuery, useIsMobile, useIsTablet,
});
