/* global React */
const { useState } = React;

// ---------- i18n strings ----------
const STRINGS = {
  'pt-BR': {
    code: 'PT-BR',
    eyebrow: 'Resposta imediata',
    h1A: 'Site personalizado',
    h1B: 'e de alta performance',
    h1From: 'a partir de',
    price: 'R$867',
    sub: 'Somos especialistas em sites com alto nível de performance e qualidade, focados em',
    subAccent: 'resultados',
    stats: [
      { k: '2.400+', v: 'projetos realizados' },
      { k: '12%', v: 'taxa média de conversão' },
      { k: '1.9s', v: 'tempo médio de carregamento' },
    ],
    statsMobile: [
      { k: '2.400+', v: 'projetos\nrealizados' },
      { k: '12%', v: 'conversão\nmédia' },
      { k: '1.9s', v: 'tempo de\ncarregamento' },
    ],
    step1Title: ['Por onde a gente ', 'começa', '?'],
    step2Title: ['Como a gente ', 'te chama', '?'],
    goalA: 'Preciso de um site para o meu negócio.',
    goalB: 'Já tenho um site e quero apenas melhorar ele.',
    fNome: 'Nome',
    fNomePh: 'João da Silva',
    fEmail: 'E-mail',
    fEmailPh: 'voce@empresa.com',
    fFone: 'WhatsApp',
    fFonePh: '(11) 90000-0000',
    errNome: 'preencha seu nome',
    errEmail: 'e-mail inválido',
    errFone: 'número incompleto',
    errGoal: 'selecione uma opção acima',
    cta: 'Falar no WhatsApp',
    ctaSent: 'Abrindo conversa…',
    ctaHelper: 'Ao enviar, abrimos uma conversa direto no WhatsApp.',
    back: 'voltar',
    rights: 'Todos os direitos reservados.',
    waMsg: (g, name, email, phone) =>
      `Olá! Sou ${name}.\nObjetivo: ${g === 'novo' ? 'Site novo' : 'Melhorar site existente'}\nE-mail: ${email}\nTelefone: ${phone}`,
  },
  'pt-PT': {
    code: 'PT-PT',
    eyebrow: 'Resposta imediata',
    h1A: 'Site personalizado',
    h1B: 'e de alta performance',
    h1From: 'a partir de',
    price: '€300',
    sub: 'Somos especialistas em sites com elevado desempenho e qualidade, focados em',
    subAccent: 'resultados',
    stats: [
      { k: '2.400+', v: 'projetos realizados' },
      { k: '12%', v: 'taxa média de conversão' },
      { k: '1.9s', v: 'tempo médio de carregamento' },
    ],
    statsMobile: [
      { k: '2.400+', v: 'projetos\nrealizados' },
      { k: '12%', v: 'conversão\nmédia' },
      { k: '1.9s', v: 'tempo de\ncarregamento' },
    ],
    step1Title: ['Por onde ', 'começamos', '?'],
    step2Title: ['Como te ', 'tratamos', '?'],
    goalA: 'Preciso de um site para o meu negócio.',
    goalB: 'Já tenho um site e quero apenas melhorá-lo.',
    fNome: 'Nome',
    fNomePh: 'João Silva',
    fEmail: 'E-mail',
    fEmailPh: 'tu@empresa.com',
    fFone: 'WhatsApp',
    fFonePh: '+351 900 000 000',
    errNome: 'preenche o teu nome',
    errEmail: 'e-mail inválido',
    errFone: 'número incompleto',
    errGoal: 'seleciona uma opção acima',
    cta: 'Falar no WhatsApp',
    ctaSent: 'A abrir conversa…',
    ctaHelper: 'Ao enviar, abrimos uma conversa diretamente no WhatsApp.',
    back: 'voltar',
    rights: 'Todos os direitos reservados.',
    waMsg: (g, name, email, phone) =>
      `Olá! Sou o ${name}.\nObjetivo: ${g === 'novo' ? 'Site novo' : 'Melhorar site existente'}\nE-mail: ${email}\nTelemóvel: ${phone}`,
  },
};

// ---------- GTM ----------
function gtmPush(event, params) {
  window.dataLayer = window.dataLayer || [];
  window.dataLayer.push({ event, ...params });
}

// ---------- Detecção automática de idioma ----------
function detectLang() {
  if (typeof window === 'undefined') return 'pt-BR';

  // 1. Hash na URL (link compartilhado)
  const h = (window.location.hash || '').toUpperCase();
  if (h.includes('PT-PT')) return 'pt-PT';
  if (h.includes('PT-BR')) return 'pt-BR';

  // 2. Preferência salva pelo usuário
  try {
    const saved = localStorage.getItem('gd-lang');
    if (saved === 'pt-PT' || saved === 'pt-BR') return saved;
  } catch (_) {}

  // 3. Idioma do browser
  const nav = (navigator.language || '').toLowerCase();
  if (nav === 'pt-pt' || nav.startsWith('pt-pt')) return 'pt-PT';

  // 4. Fuso horário
  try {
    const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
    if (['Europe/Lisbon', 'Atlantic/Azores', 'Atlantic/Madeira'].includes(tz)) return 'pt-PT';
  } catch (_) {}

  return 'pt-BR';
}

function saveLang(l) {
  try { localStorage.setItem('gd-lang', l); } catch (_) {}
}

// ---------- Logo ----------
const Logo = ({ height = 22, opacity = 1 }) => (
  <img src="logo-full.png" alt="Growth Design"
    style={{ height, width: 'auto', display: 'block', opacity }} />
);

// ---------- WhatsApp icon ----------
const WhatsIcon = ({ size = 18 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
    <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51l-.57-.01c-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 0 1-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 0 1-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 0 1 2.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0 0 12.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 0 0 5.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 0 0-3.48-8.413Z" />
  </svg>
);

// ---------- Lang switcher ----------
function LangSwitcher({ lang, setLang, compact = false }) {
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center', padding: 3,
      background: 'rgba(255,255,255,0.03)',
      border: '1px solid rgba(255,255,255,0.08)',
      borderRadius: 999,
      fontFamily: 'DM Sans, sans-serif',
    }}>
      {['pt-BR', 'pt-PT'].map((l) => {
        const active = lang === l;
        return (
          <button key={l} onClick={() => setLang(l)}
            style={{
              all: 'unset', cursor: 'pointer',
              padding: compact ? '5px 10px' : '6px 12px',
              borderRadius: 999,
              fontSize: compact ? 11.5 : 12.5,
              fontWeight: active ? 600 : 500,
              letterSpacing: '0.02em',
              color: active ? '#0A0A0B' : '#A6AAB3',
              background: active ? '#F4F5F7' : 'transparent',
              transition: 'all .2s',
            }}>
            {STRINGS[l].code}
          </button>
        );
      })}
    </div>
  );
}

// ---------- WhatsApp CTA — green animated gradient + glow ----------
function WhatsCTA({ onClick, disabled, label, sent, isMobile }) {
  return (
    <div style={{ position: 'relative', marginTop: isMobile ? 18 : 22 }}>
      {/* Outer glow halo */}
      <div className="wa-glow" style={{
        position: 'absolute', inset: -10, borderRadius: 14,
        background: 'linear-gradient(120deg, #25D366, #128C7E, #1F8A4C, #25D366)',
        backgroundSize: '300% 300%',
        filter: 'blur(18px)', opacity: disabled ? 0.25 : 0.55,
        pointerEvents: 'none',
        animation: 'waGradient 6s ease infinite',
        transition: 'opacity .3s',
      }} />
      <button
        onClick={onClick}
        disabled={sent}
        className="wa-cta"
        style={{
          all: 'unset',
          position: 'relative',
          cursor: sent ? 'default' : 'pointer',
          width: '100%',
          padding: isMobile ? '15px 20px' : '17px 22px',
          color: '#fff',
          fontFamily: 'DM Sans, sans-serif',
          fontWeight: 600,
          fontSize: 16,
          letterSpacing: '-0.005em',
          borderRadius: 8,
          textAlign: 'center',
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
          boxSizing: 'border-box',
          background: 'linear-gradient(120deg, #25D366, #128C7E, #1F8A4C, #25D366)',
          backgroundSize: '300% 300%',
          animation: 'waGradient 6s ease infinite',
          boxShadow: '0 1px 0 0 rgba(255,255,255,0.18) inset, 0 0 0 1px rgba(255,255,255,0.08) inset',
          transition: 'transform .15s, opacity .2s',
          opacity: disabled ? 0.55 : 1,
        }}
      >
        <WhatsIcon size={18} />
        <span>{sent ? STRINGS_FALLBACK_SENT(label) : label}</span>
      </button>
    </div>
  );
}
// helper: don't use, kept only so JSX parses; sent label passed in as `label`
const STRINGS_FALLBACK_SENT = (l) => l;

// ---------- Form sub-components (module-level — stable references, sem perda de foco) ----------
function StepHeader({ title, onBack, isMobile, backLabel }) {
  return (
    <div style={{ marginBottom: isMobile ? 18 : 22 }}>
      {onBack && (
        <button onClick={onBack}
          style={{
            all: 'unset', cursor: 'pointer',
            display: 'inline-flex', alignItems: 'center', gap: 6,
            fontFamily: 'DM Sans, sans-serif',
            fontSize: 13, color: '#8A8E97',
            marginBottom: 14,
          }}
          onMouseEnter={(e) => e.currentTarget.style.color = '#F4F5F7'}
          onMouseLeave={(e) => e.currentTarget.style.color = '#8A8E97'}>
          ← {backLabel}
        </button>
      )}
      <h3 style={{
        margin: 0,
        fontFamily: 'DM Sans, sans-serif',
        fontSize: isMobile ? 16 : 17, fontWeight: 500,
        letterSpacing: '-0.005em', lineHeight: 1.3,
        color: '#A6AAB3',
      }}>
        {title}
      </h3>
    </div>
  );
}

function Field({ label, error, children }) {
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
      <span style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
        fontFamily: 'DM Sans, sans-serif',
        fontSize: 13, color: error ? '#E76F6F' : '#8A8E97',
        fontWeight: 500,
      }}>
        <span>{label}</span>
        {error && <span style={{ fontSize: 12.5, fontWeight: 400 }}>{error}</span>}
      </span>
      {children}
    </label>
  );
}

// ---------- Form ----------
function StepForm({ variant = 'desktop', lang = 'pt-BR' }) {
  const t = STRINGS[lang];
  const [step, setStep] = useState(1);
  const [goal, setGoal] = useState(null);
  const [form, setForm] = useState({ name: '', email: '', phone: '' });
  const [sent, setSent] = useState(false);
  const [touched, setTouched] = useState({});
  const [shake, setShake] = useState(false);

  const isMobile = variant === 'mobile';

  const goalOptions = [
    { id: 'novo', label: t.goalA },
    { id: 'melhorar', label: t.goalB },
  ];

  const emailValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email);
  const phoneValid = form.phone.replace(/\D/g, '').length >= 9;
  const nameValid = form.name.trim().length >= 2;

  const formatPhone = (v) => {
    if (lang === 'pt-PT') {
      // simple PT format
      return v.replace(/[^\d+\s]/g, '').slice(0, 20);
    }
    const d = v.replace(/\D/g, '').slice(0, 11);
    if (d.length <= 2) return d.length ? `(${d}` : '';
    if (d.length <= 6) return `(${d.slice(0, 2)}) ${d.slice(2)}`;
    if (d.length <= 10) return `(${d.slice(0, 2)}) ${d.slice(2, 6)}-${d.slice(6)}`;
    return `(${d.slice(0, 2)}) ${d.slice(2, 7)}-${d.slice(7)}`;
  };

  const handleCTA = () => {
    // Step 1 — must select a goal
    if (step === 1) {
      if (!goal) {
        setTouched((tt) => ({ ...tt, goal: true }));
        setShake(true); setTimeout(() => setShake(false), 400);
        return;
      }
      gtmPush('form_step2', { goal, variant });
      setStep(2);
      return;
    }
    // Step 2 — submit
    setTouched({ name: true, email: true, phone: true });
    if (!(nameValid && emailValid && phoneValid)) {
      setShake(true); setTimeout(() => setShake(false), 400);
      return;
    }
    setSent(true);
    gtmPush('form_submit', { goal, variant, lang });
    fetch('https://script.google.com/macros/s/AKfycbx5-YqmGkzM7bC-rCQ4TUBaAaq_twFPrGhngSAH5F8FODeNVgmW87JC9vmzl3rYpq8H/exec', {
      method: 'POST',
      body: JSON.stringify({ name: form.name, email: form.email, phone: form.phone, goal, lang }),
    }).catch(() => {});
    setTimeout(() => {
      gtmPush('generate_lead', { goal, variant, lang, currency: 'BRL' });
      if (typeof fbq === 'function') fbq('track', 'Lead');
      const msg = encodeURIComponent('Olá, Acabei de me cadastrar no site, gostaria de atendimento.');
      window.open(`https://wa.me/5511941861778?text=${msg}`, '_blank');
    }, 600);
  };

  // ----- Step 1 -----
  const Step1 = () => (
    <div>
      <StepHeader
        title={<>{t.step1Title[0]}<span style={{ color: '#7CA4F2' }}>{t.step1Title[1]}</span>{t.step1Title[2]}</>}
        isMobile={isMobile}
        backLabel={t.back}
      />
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {goalOptions.map((opt, i) => {
          const selected = goal === opt.id;
          return (
            <button key={opt.id}
              onClick={() => { setGoal(opt.id); setTouched((tt) => ({ ...tt, goal: true })); gtmPush('form_goal_select', { goal: opt.id, variant }); }}
              style={{
                all: 'unset', cursor: 'pointer',
                display: 'flex', alignItems: 'center', gap: 14,
                padding: isMobile ? '15px 16px' : '16px 18px',
                borderRadius: 8,
                background: selected ? 'rgba(33, 89, 199, 0.10)' : 'rgba(255,255,255,0.015)',
                border: selected ? '1.5px solid #2159C7' : '1.5px solid #1E2025',
                transition: 'all .2s',
                boxSizing: 'border-box',
              }}
              onMouseEnter={(e) => { if (!selected) { e.currentTarget.style.borderColor = '#2F3035'; e.currentTarget.style.background = 'rgba(255,255,255,0.03)'; } }}
              onMouseLeave={(e) => { if (!selected) { e.currentTarget.style.borderColor = '#1E2025'; e.currentTarget.style.background = 'rgba(255,255,255,0.015)'; } }}>
              {/* radio */}
              <span style={{
                width: 18, height: 18, borderRadius: 999, flexShrink: 0,
                border: selected ? 'none' : '1.5px solid #2F3035',
                background: selected ? '#2159C7' : 'transparent',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                transition: 'all .2s',
              }}>
                {selected && <span style={{ width: 7, height: 7, borderRadius: 999, background: '#fff' }} />}
              </span>
              <span style={{
                flex: 1,
                fontFamily: 'DM Sans, sans-serif',
                fontSize: isMobile ? 14.5 : 15.5,
                fontWeight: selected ? 500 : 450,
                color: selected ? '#F4F5F7' : '#C5C8CD',
                lineHeight: 1.35,
                letterSpacing: '-0.005em',
              }}>
                {opt.label}
              </span>
            </button>
          );
        })}
      </div>
      {touched.goal && !goal && (
        <p style={{
          margin: '10px 0 0',
          fontFamily: 'DM Sans, sans-serif',
          fontSize: 12.5, color: '#E76F6F',
        }}>
          {t.errGoal}
        </p>
      )}
    </div>
  );

  // ----- Step 2 -----
  const inputBase = {
    all: 'unset',
    boxSizing: 'border-box',
    width: '100%',
    padding: isMobile ? '12px 0' : '14px 0',
    fontFamily: 'DM Sans, sans-serif',
    fontSize: 16,
    color: '#F4F5F7',
    background: 'transparent',
    borderBottom: '1px solid #25262A',
    borderRadius: 0,
    transition: 'border-color .2s',
  };

  const Step2 = () => (
    <div>
      <StepHeader
        title={<>{t.step2Title[0]}<span style={{ color: '#7CA4F2' }}>{t.step2Title[1]}</span>{t.step2Title[2]}</>}
        onBack={() => setStep(1)}
        isMobile={isMobile}
        backLabel={t.back}
      />
      <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
        <Field label={t.fNome} error={touched.name && !nameValid ? t.errNome : null}>
          <input type="text" value={form.name}
            onChange={(e) => setForm({ ...form, name: e.target.value })}
            onBlur={() => setTouched({ ...touched, name: true })}
            placeholder={t.fNomePh}
            style={{ ...inputBase,
              borderBottomColor: touched.name && !nameValid ? '#7A3838' : (form.name ? '#2159C7' : '#25262A'),
            }} />
        </Field>
        <Field label={t.fEmail} error={touched.email && !emailValid ? t.errEmail : null}>
          <input type="email" value={form.email}
            onChange={(e) => setForm({ ...form, email: e.target.value })}
            onBlur={() => setTouched({ ...touched, email: true })}
            placeholder={t.fEmailPh}
            style={{ ...inputBase,
              borderBottomColor: touched.email && !emailValid ? '#7A3838' : (emailValid ? '#2159C7' : '#25262A'),
            }} />
        </Field>
        <Field label={t.fFone} error={touched.phone && !phoneValid ? t.errFone : null}>
          <input type="tel" inputMode="tel" value={form.phone}
            onChange={(e) => setForm({ ...form, phone: formatPhone(e.target.value) })}
            onBlur={() => setTouched({ ...touched, phone: true })}
            placeholder={t.fFonePh}
            style={{ ...inputBase,
              borderBottomColor: touched.phone && !phoneValid ? '#7A3838' : (phoneValid ? '#2159C7' : '#25262A'),
            }} />
        </Field>
      </div>
    </div>
  );

  const ctaLabel = sent ? t.ctaSent : t.cta;

  return (
    <div style={{
      animation: shake ? 'shake .4s' : 'none',
    }}>
      <div key={step} style={{ animation: 'fadeSlide .35s ease' }}>
        {step === 1 ? Step1() : Step2()}
      </div>

      {/* Persistent CTA — visible on both steps */}
      <WhatsCTA
        onClick={handleCTA}
        disabled={false}
        sent={sent}
        label={ctaLabel}
        isMobile={isMobile}
      />

      <p style={{
        margin: '14px 0 0', textAlign: 'center',
        fontFamily: 'DM Sans, sans-serif',
        fontSize: 12.5, color: '#6B6F77', lineHeight: 1.5,
      }}>
        {t.ctaHelper}
      </p>
    </div>
  );
}

// ---------- Animated Background ----------
function AnimatedBackground({ width, height, density = 1 }) {
  const canvasRef = React.useRef(null);
  const rafRef = React.useRef(0);

  React.useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const dpr = Math.min(window.devicePixelRatio || 1, 2);
    canvas.width = width * dpr;
    canvas.height = height * dpr;
    const ctx = canvas.getContext('2d');
    ctx.scale(dpr, dpr);

    const N = Math.round(28 * density);
    const particles = Array.from({ length: N }, () => ({
      x: Math.random() * width, y: Math.random() * height,
      vx: (Math.random() - 0.5) * 0.08, vy: (Math.random() - 0.5) * 0.08,
      r: Math.random() * 1.1 + 0.3, a: Math.random() * 0.35 + 0.15,
      pulse: Math.random() * Math.PI * 2,
    }));

    let t0 = performance.now();
    const tick = (now) => {
      const t = (now - t0) / 1000;
      ctx.clearRect(0, 0, width, height);
      ctx.fillStyle = '#0A0A0B';
      ctx.fillRect(0, 0, width, height);

      const ambient = ctx.createRadialGradient(
        width * 0.25, -height * 0.1, 0,
        width * 0.25, -height * 0.1, Math.max(width, height) * 0.7
      );
      ambient.addColorStop(0, 'rgba(33, 89, 199, 0.18)');
      ambient.addColorStop(0.5, 'rgba(33, 89, 199, 0.05)');
      ambient.addColorStop(1, 'rgba(33, 89, 199, 0)');
      ctx.fillStyle = ambient;
      ctx.fillRect(0, 0, width, height);

      const gridSize = 60;
      const offY = (t * 6) % gridSize;
      const offX = (t * 3) % gridSize;
      ctx.strokeStyle = 'rgba(255,255,255,0.022)';
      ctx.lineWidth = 1;
      ctx.beginPath();
      for (let x = -gridSize + offX; x < width + gridSize; x += gridSize) {
        ctx.moveTo(x, 0); ctx.lineTo(x, height);
      }
      for (let y = -gridSize + offY; y < height + gridSize; y += gridSize) {
        ctx.moveTo(0, y); ctx.lineTo(width, y);
      }
      ctx.stroke();

      particles.forEach((p) => {
        p.x += p.vx; p.y += p.vy; p.pulse += 0.012;
        if (p.x < -10) p.x = width + 10;
        if (p.x > width + 10) p.x = -10;
        if (p.y < -10) p.y = height + 10;
        if (p.y > height + 10) p.y = -10;
        const tw = (Math.sin(p.pulse) + 1) / 2;
        const alpha = p.a * (0.4 + tw * 0.6);
        ctx.fillStyle = `rgba(220, 228, 240, ${alpha})`;
        ctx.beginPath(); ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2); ctx.fill();
      });

      const vg = ctx.createRadialGradient(width / 2, height * 0.4, 0, width / 2, height * 0.4, Math.max(width, height) * 0.75);
      vg.addColorStop(0, 'rgba(10,10,11,0)');
      vg.addColorStop(1, 'rgba(8,8,10,0.6)');
      ctx.fillStyle = vg;
      ctx.fillRect(0, 0, width, height);

      rafRef.current = requestAnimationFrame(tick);
    };
    rafRef.current = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(rafRef.current);
  }, [width, height, density]);

  return (
    <canvas ref={canvasRef}
      style={{ position: 'absolute', inset: 0, width: '100%', height: '100%',
        pointerEvents: 'none', zIndex: 0 }} />
  );
}

const BackgroundFx = ({ width, height, density }) => (
  <AnimatedBackground width={width} height={height} density={density} />
);

// ---------- Footer ----------
const Footer = ({ isMobile, t }) => (
  <footer style={{
    width: '100%',
    padding: isMobile ? '28px 24px' : '32px 64px',
    borderTop: '1px solid rgba(255,255,255,0.06)',
    display: 'flex', alignItems: 'center',
    justifyContent: isMobile ? 'center' : 'space-between',
    gap: 16, flexDirection: isMobile ? 'column' : 'row',
    position: 'relative', zIndex: 1,
  }}>
    <Logo height={isMobile ? 24 : 28} opacity={0.85} />
    <span style={{
      fontFamily: 'DM Sans, sans-serif',
      fontSize: 13, color: '#6B6F77',
    }}>
      © {new Date().getFullYear()} Growth Design — {t.rights}
    </span>
  </footer>
);

// ---------- Headline (shared, fix price clipping) ----------
const Price = ({ size, value }) => (
  <span style={{
    display: 'inline-block',
    fontWeight: 600,
    color: '#7CA4F2',
    paddingBottom: Math.round(size * 0.08),
    lineHeight: 1.05,
  }}>
    {value}
  </span>
);

// =============== DESKTOP ===============
function Desktop() {
  const [lang, setLang] = useState(detectLang);
  const handleSetLang = (l) => { saveLang(l); setLang(l); gtmPush('lang_switch', { lang: l }); };
  React.useEffect(() => {
    try {
      const desired = `#/${lang}`;
      if ((window.location.hash || '').toUpperCase() !== desired.toUpperCase()) {
        window.history.replaceState({}, '', window.location.pathname + window.location.search + desired);
      }
    } catch (_) {}
  }, [lang]);
  const t = STRINGS[lang];
  return (
    <div style={{
      width: '100%', minHeight: '100vh',
      background: '#0A0A0B', color: '#F4F5F7',
      position: 'relative', overflow: 'hidden',
      fontFamily: 'DM Sans, sans-serif',
      display: 'flex', flexDirection: 'column',
    }}>
      <BackgroundFx width={typeof window !== 'undefined' ? window.innerWidth : 1440} height={typeof window !== 'undefined' ? window.innerHeight : 900} density={1} />

      <header style={{
        padding: '32px 64px',
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        position: 'relative', zIndex: 2,
      }}>
        <Logo height={40} />
        <LangSwitcher lang={lang} setLang={handleSetLang} />
      </header>

      <main style={{
        flex: 1,
        padding: '48px 64px 72px',
        display: 'grid',
        gridTemplateColumns: '1.1fr 0.9fr',
        gap: 80,
        alignItems: 'start',
        position: 'relative', zIndex: 1,
      }}>
        <div style={{ paddingTop: 8 }}>
          <div style={{
            display: 'inline-flex', alignItems: 'center',
            fontFamily: 'DM Sans, sans-serif',
            fontSize: 14, color: '#7CA4F2',
            fontWeight: 500,
            letterSpacing: '0.01em',
          }}>
            {t.eyebrow}
          </div>

          <h1 style={{
            margin: '24px 0 0',
            fontFamily: 'DM Sans, sans-serif',
            fontSize: 80, fontWeight: 600,
            lineHeight: 1.04,
            letterSpacing: '-0.035em',
            color: '#F4F5F7',
            textWrap: 'balance',
          }}>
            {t.h1A}<br />
            {t.h1B}{' '}
            <span style={{ color: '#7E828B', fontWeight: 500 }}>{t.h1From}</span>{' '}
            <Price size={80} value={t.price} />.
          </h1>

          <p style={{
            margin: '32px 0 0',
            maxWidth: 520,
            fontFamily: 'DM Sans, sans-serif',
            fontSize: 18, lineHeight: 1.55,
            color: '#A6AAB3', fontWeight: 400,
            textWrap: 'pretty',
          }}>
            {t.sub} <span style={{ color: '#F4F5F7', fontWeight: 500 }}>{t.subAccent}</span>.
          </p>

          <div style={{
            marginTop: 64, paddingTop: 32,
            borderTop: '1px solid #1A1B1F',
            display: 'grid',
            gridTemplateColumns: '1fr 1fr 1fr',
            gap: 0,
          }}>
            {t.stats.map((s, i) => (
              <div key={i} style={{
                display: 'flex', flexDirection: 'column', gap: 6,
                paddingLeft: i === 0 ? 0 : 32,
                paddingRight: i === t.stats.length - 1 ? 0 : 32,
                borderLeft: i === 0 ? 'none' : '1px solid #1A1B1F',
              }}>
                <span style={{
                  fontFamily: 'DM Sans, sans-serif',
                  fontSize: 40, fontWeight: 600, letterSpacing: '-0.025em',
                  lineHeight: 1, color: '#F4F5F7',
                }}>
                  {s.k}
                </span>
                <span style={{
                  fontFamily: 'DM Sans, sans-serif',
                  fontSize: 13.5, color: '#7E828B', lineHeight: 1.3,
                  fontWeight: 450,
                }}>
                  {s.v}
                </span>
              </div>
            ))}
          </div>
        </div>

        <div style={{ position: 'relative' }}>
          <div style={{
            position: 'absolute', inset: -2, borderRadius: 8,
            background: 'linear-gradient(180deg, rgba(33, 89, 199, 0.5), rgba(33, 89, 199, 0))',
            filter: 'blur(30px)', opacity: 0.5, pointerEvents: 'none',
          }} />
          <div style={{
            position: 'relative',
            padding: '36px 36px 32px',
            borderRadius: 8,
            background: '#0E0F12',
            border: '1px solid #1B1C20',
            boxShadow: '0 30px 80px -20px rgba(0,0,0,0.8), 0 1px 0 0 rgba(255,255,255,0.03) inset',
          }}>
            <StepForm variant="desktop" lang={lang} />
          </div>
        </div>
      </main>

      <Footer isMobile={false} t={t} />
    </div>
  );
}

// =============== MOBILE ===============
function Mobile() {
  const [lang, setLang] = useState(detectLang);
  const handleSetLang = (l) => { saveLang(l); setLang(l); gtmPush('lang_switch', { lang: l }); };
  const t = STRINGS[lang];
  return (
    <div style={{
      width: '100%', minHeight: '100vh',
      background: '#0A0A0B', color: '#F4F5F7',
      position: 'relative', overflow: 'hidden',
      fontFamily: 'DM Sans, sans-serif',
      display: 'flex', flexDirection: 'column',
    }}>
      <BackgroundFx width={typeof window !== 'undefined' ? window.innerWidth : 390} height={typeof window !== 'undefined' ? window.innerHeight : 900} density={0.55} />

      <header style={{
        padding: '22px 24px',
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        position: 'relative', zIndex: 2,
      }}>
        <Logo height={32} />
        <LangSwitcher lang={lang} setLang={handleSetLang} compact />
      </header>

      <main style={{
        flex: 1,
        padding: '16px 24px 36px',
        position: 'relative', zIndex: 1,
        display: 'flex', flexDirection: 'column', gap: 28,
      }}>
        <div>
          <div style={{
            display: 'inline-flex', alignItems: 'center',
            fontFamily: 'DM Sans, sans-serif',
            fontSize: 13, color: '#7CA4F2',
            fontWeight: 500,
          }}>
            {t.eyebrow}
          </div>

          <h1 style={{
            margin: '14px 0 0',
            fontFamily: 'DM Sans, sans-serif',
            fontSize: 38, fontWeight: 600,
            lineHeight: 1.06,
            letterSpacing: '-0.025em',
            color: '#F4F5F7',
            textWrap: 'balance',
          }}>
            {t.h1A} {t.h1B}{' '}
            <span style={{ color: '#7E828B', fontWeight: 500 }}>{t.h1From}</span>{' '}
            <Price size={38} value={t.price} />.
          </h1>

          <p style={{
            margin: '18px 0 0',
            fontFamily: 'DM Sans, sans-serif',
            fontSize: 15.5, lineHeight: 1.55,
            color: '#A6AAB3',
          }}>
            {t.sub} <span style={{ color: '#F4F5F7', fontWeight: 500 }}>{t.subAccent}</span>.
          </p>
        </div>

        <div style={{ position: 'relative' }}>
          <div style={{
            position: 'absolute', inset: -2, borderRadius: 8,
            background: 'linear-gradient(180deg, rgba(33, 89, 199, 0.45), rgba(33, 89, 199, 0))',
            filter: 'blur(20px)', opacity: 0.5, pointerEvents: 'none',
          }} />
          <div style={{
            position: 'relative',
            padding: 22,
            borderRadius: 8,
            background: '#0E0F12',
            border: '1px solid #1B1C20',
            boxShadow: '0 20px 60px -20px rgba(0,0,0,0.8), 0 1px 0 0 rgba(255,255,255,0.03) inset',
          }}>
            <StepForm variant="mobile" lang={lang} />
          </div>
        </div>

        <div style={{
          paddingTop: 24, paddingBottom: 8,
          borderTop: '1px solid #1A1B1F',
          display: 'grid',
          gridTemplateColumns: 'repeat(3, 1fr)',
          gap: 12,
        }}>
          {t.statsMobile.map((s, i) => (
            <div key={i} style={{
              display: 'flex', flexDirection: 'column', gap: 4,
              paddingLeft: i === 0 ? 0 : 12,
              borderLeft: i === 0 ? 'none' : '1px solid #1A1B1F',
            }}>
              <span style={{
                fontFamily: 'DM Sans, sans-serif',
                fontSize: 24, fontWeight: 600, letterSpacing: '-0.02em',
                lineHeight: 1, color: '#F4F5F7',
              }}>
                {s.k}
              </span>
              <span style={{
                fontFamily: 'DM Sans, sans-serif',
                fontSize: 11.5, color: '#7E828B', lineHeight: 1.3,
                whiteSpace: 'pre-line',
              }}>
                {s.v}
              </span>
            </div>
          ))}
        </div>
      </main>

      <Footer isMobile={true} t={t} />
    </div>
  );
}

window.GrowthDesktop = Desktop;
window.GrowthMobile = Mobile;
