// Contact page
function PageContato({ setPage }) {
  useReveal();
  const t = useT();
  const [horizon, setHorizon] = React.useState('');
  const [service, setService] = React.useState([]);
  const [sent, setSent] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [error, setError] = React.useState(false);

  const toggle = (s) => setService(prev => prev.includes(s) ? prev.filter(x => x !== s) : [...prev, s]);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setSending(true);
    setError(false);
    const data = new FormData(e.target);
    if (service.length) data.append('servicos', service.join(', '));
    if (horizon) data.append('horizonte', horizon);
    try {
      const res = await fetch('https://formspree.io/f/mgorzzpq', {
        method: 'POST', body: data, headers: { Accept: 'application/json' }
      });
      if (res.ok) { setSent(true); } else { setError(true); }
    } catch { setError(true); }
    setSending(false);
  };

  return (
    <>
      <section style={{ padding: '80px 0 40px', position: 'relative', overflow: 'hidden' }}>
        <div className="tick-grid" />
        <div className="orb" style={{ width: 520, height: 520, background: 'var(--crimson)', top: -200, right: '20%', opacity: 0.35 }} />
        <div className="shell" style={{ position: 'relative' }}>
          <Eyebrow>{t('ct.ey')}</Eyebrow>
          <h1 className="display" style={{ fontSize: 'clamp(44px, 9vw, 124px)', margin: '24px 0 12px', maxWidth: '12ch', lineHeight: 0.98 }}>
            {t('ct.h1a')} <em className="display-italic" style={{ color: 'var(--crimson)' }}>{t('ct.h1em')}</em>
          </h1>
          <p style={{ fontSize: 20, maxWidth: 620, opacity: 0.78, lineHeight: 1.5 }}>
            {t('ct.sub')}
          </p>
        </div>
      </section>

      {/* Form */}
      <section className="section-pad-sm">
        <div className="shell" style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 80 }} >
          {!sent ? (
            <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: 36 }}>
              <Field label={t('ct.f1')}>
                <input name="nome" required placeholder={t('ct.f1ph')} style={inputStyle} />
              </Field>
              <Field label={t('ct.f2')}>
                <input name="email" required type="email" placeholder={t('ct.f2ph')} style={inputStyle} />
              </Field>
              <Field label={t('ct.f3')}>
                <input name="empresa_cargo" placeholder={t('ct.f3ph')} style={inputStyle} />
              </Field>

              <Field label={t('ct.f4')}>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10 }}>
                  {[t('ct.svc1'), t('ct.svc2'), t('ct.svc3'), t('ct.svc4'), t('ct.svc5')].map(s => (
                    <button type="button" key={s} onClick={() => toggle(s)} style={{
                      padding: '10px 16px',
                      borderRadius: 999,
                      fontSize: 13,
                      border: '1px solid ' + (service.includes(s) ? 'var(--ink)' : 'var(--line)'),
                      background: service.includes(s) ? 'var(--ink)' : 'transparent',
                      color: service.includes(s) ? 'var(--cream)' : 'var(--ink)',
                      transition: 'all 0.2s'
                    }}>{s}</button>
                  ))}
                </div>
              </Field>

              <Field label={t('ct.f5')}>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10 }}>
                  {[t('ct.h1opt'), t('ct.h2opt'), t('ct.h3opt'), t('ct.h4opt')].map(h => (
                    <button type="button" key={h} onClick={() => setHorizon(h)} style={{
                      padding: '10px 16px', borderRadius: 999, fontSize: 13,
                      border: '1px solid ' + (horizon === h ? 'var(--ink)' : 'var(--line)'),
                      background: horizon === h ? 'var(--ink)' : 'transparent',
                      color: horizon === h ? 'var(--cream)' : 'var(--ink)',
                      transition: 'all 0.2s',
                    }}>{h}</button>
                  ))}
                </div>
              </Field>

              <Field label={t('ct.f6')}>
                <textarea name="mensagem" rows={6} placeholder={t('ct.f6ph')} style={{ ...inputStyle, resize: 'vertical' }} />
              </Field>

              {error && <p style={{ color: 'var(--crimson)', fontSize: 13, margin: 0 }}>Algo deu errado. Tente novamente ou escreva direto para contato@atomforge.com.br</p>}
              <div style={{ display: 'flex', gap: 16, alignItems: 'center', marginTop: 12 }}>
                <button type="submit" disabled={sending} className="btn btn-primary" style={{ fontSize: 15, padding: '16px 28px', opacity: sending ? 0.7 : 1 }}>
                  {sending ? 'Enviando…' : t('c.send')}
                  {!sending && <ArrowIcon />}
                </button>
                <span style={{ opacity: 0.6, fontSize: 13, fontFamily: 'var(--mono)' }}>
                  {t('ct.or_email')} <a href="mailto:contato@atomforge.com.br" className="m-link">contato@atomforge.com.br</a>
                </span>
              </div>
            </form>
          ) : (
            <div style={{
              padding: 48, borderRadius: 22, background: 'var(--crimson)', color: 'var(--cream)',
              minHeight: 400, display: 'flex', flexDirection: 'column', justifyContent: 'center'
            }}>
              <Eyebrow dark>{t('ct.sent_ey')}</Eyebrow>
              <h2 className="display" style={{ fontSize: 56, margin: '20px 0' }}>
                {t('ct.sent_h2a')} <em className="display-italic" style={{ color: 'var(--crimson)' }}>{t('ct.sent_em')}</em>
              </h2>
              <p style={{ fontSize: 17, opacity: 0.72, lineHeight: 1.55, maxWidth: 500 }}>
                {t('ct.sent_p')}
              </p>
              <div style={{ marginTop: 32, display: 'flex', gap: 12 }}>
                <Btn variant="ghost" onClick={() => setPage('insights')}>{t('c.go_insights')}</Btn>
                <button onClick={() => setSent(false)} className="btn btn-ghost" style={{ color: 'var(--cream)', borderColor: 'rgba(244,239,230,0.2)' }}>
                  {t('c.send_another')} <ArrowIcon />
                </button>
              </div>
            </div>
          )}

          <aside style={{ display: 'flex', flexDirection: 'column', gap: 32 }}>
            <div style={{ padding: 28, border: '1px solid var(--line)', borderRadius: 18, background: 'var(--bg-2)' }}>
              <Eyebrow>{t('ct.how_ey')}</Eyebrow>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 18, marginTop: 20 }}>
                {[
                  ['24h', t('ct.how_t1')],
                  ['48h', t('ct.how_t2')],
                  ['5 dias', t('ct.how_t3')],
                ].map(([n, l]) => (
                  <div key={l} style={{ display: 'flex', alignItems: 'baseline', gap: 14 }}>
                    <div className="display" style={{ fontSize: 28, color: 'var(--crimson)', minWidth: 84 }}>{n}</div>
                    <div style={{ fontSize: 14, opacity: 0.75, lineHeight: 1.4 }}>{l}</div>
                  </div>
                ))}
              </div>
              <p style={{ fontSize: 13, opacity: 0.6, marginTop: 22, lineHeight: 1.55, borderTop: '1px solid var(--line)', paddingTop: 18, margin: '22px 0 0', fontFamily: 'var(--mono)' }}>
                {t('ct.how_note')}
              </p>
            </div>

            <ContatoDiretoCard />
            <HorarioForjaCard />
          </aside>
        </div>

        <style>{`
          @media (max-width: 980px) {
            .shell > div[style*="grid-template-columns: 1.5fr 1fr"] { grid-template-columns: 1fr !important; }
          }
        `}</style>
      </section>

      {/* Offices strip */}
      <section className="section-pad-sm" style={{ background: 'var(--bg-2)' }}>
        <div className="shell">
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 32, flexWrap: 'wrap', gap: 16 }}>
            <SectionHeader eyebrow={t('ct.off_ey')} title={<>{t('ct.off_h2a')} <em className="display-italic">{t('ct.off_h2em')}</em></>} />
          </div>
          <div className="grid grid-4">
            {[
              ['São Paulo', 'Rua Augusta, 2690', 'Jardins · SP'],
              ['Recife', 'Rua da Moeda, 68', 'Recife Antigo · PE'],
              ['Lisboa', 'R. do Alecrim, 12', 'Chiado · PT'],
              ['Berlim', 'Torstraße 140', 'Mitte · DE'],
            ].map(([c, a, b]) => (
              <div key={c} style={{
                padding: '28px 24px', background: 'var(--bg-2)', borderRadius: 18,
                border: '1px solid var(--line)'
              }}>
                <div className="display" style={{ fontSize: 28, marginBottom: 14 }}>{c}</div>
                <div style={{ fontSize: 14, opacity: 0.75, fontFamily: 'var(--mono)', lineHeight: 1.6 }}>
                  {a}<br />{b}
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>
    </>
  );
}

const inputStyle = {
  width: '100%',
  padding: '16px 20px',
  border: '1px solid var(--line)',
  borderRadius: 12,
  background: 'transparent',
  fontFamily: 'var(--sans)',
  fontSize: 15,
  color: 'var(--ink)',
  outline: 'none',
  transition: 'border-color 0.2s'
};

function Field({ label, children }) {
  return (
    <div>
      <label className="eyebrow" style={{ display: 'block', marginBottom: 14 }}>{label}</label>
      {children}
    </div>
  );
}

function ContatoDiretoCard() {
  const t = useT();
  const dotRef = React.useRef(null);

  React.useEffect(() => {
    if (!window.gsap || !dotRef.current) return;
    const ctx = gsap.context(() => {
      gsap.to(dotRef.current, {
        scale: 1.8, opacity: 0.4, duration: 1.1,
        repeat: -1, yoyo: true, ease: 'sine.inOut',
        transformOrigin: 'center center',
      });
    });
    return () => ctx.revert();
  }, []);

  return (
    <div style={{ padding: 28, border: '1px solid var(--line)', borderRadius: 18, background: 'var(--bg-2)' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 20 }}>
        <span ref={dotRef} style={{
          display: 'inline-block', width: 7, height: 7, borderRadius: '50%',
          background: 'var(--crimson)', flexShrink: 0,
        }} />
        <span className="eyebrow" style={{ margin: 0 }}>{t('ct.dir_ey')}</span>
      </div>
      <a href="mailto:contato@atomforge.com.br" className="m-link" style={{
        display: 'block', fontSize: 15,
      }}>
        contato@atomforge.com.br
      </a>
      <p style={{ fontSize: 13, opacity: 0.6, lineHeight: 1.55, marginTop: 12, fontFamily: 'var(--mono)' }}>
        {t('ct.dir_note')}
      </p>
    </div>
  );
}

function HorarioForjaCard() {
  const t = useT();
  const containerRef = React.useRef(null);

  React.useEffect(() => {
    if (!window.gsap) return;
    const el = containerRef.current;
    if (!el) return;

    const ctx = gsap.context(() => {
      const bars = el.querySelectorAll('.hf-bar');
      const cursor = el.querySelector('.hf-cursor');
      const dot = el.querySelector('.hf-dot');

      // Bars animate in sequentially from scaleX 0 → 1
      gsap.set(bars, { scaleX: 0, transformOrigin: 'left center' });
      const tl = gsap.timeline({ delay: 0.4 });
      const durations = [1.4, 0.45, 1.0];
      bars.forEach((bar, i) => {
        tl.to(bar, { scaleX: 1, duration: durations[i], ease: 'power3.out' }, i === 0 ? 0 : '-=0.1');
      });

      // Blinking cursor
      tl.set(cursor, { visibility: 'visible' })
        .to(cursor, { opacity: 0, duration: 0.5, repeat: -1, yoyo: true, ease: 'steps(1)' });

      // Pulse dot
      gsap.to(dot, {
        scale: 1.8, opacity: 0.4, duration: 1.1,
        repeat: -1, yoyo: true, ease: 'sine.inOut',
        transformOrigin: 'center center',
      });
    }, el);

    return () => ctx.revert();
  }, []);

  const rows = [
    { label: t('ct.hrs_seg'), value: t('ct.hrs_seg_v'), barW: '100%', barBg: 'rgba(244,239,230,0.45)' },
    { label: t('ct.hrs_sab'), value: t('ct.hrs_sab_v'), barW: '14%',  barBg: 'rgba(244,239,230,0.25)' },
    { label: t('ct.hrs_sla'), value: t('ct.hrs_sla_v'), barW: '100%', barBg: 'rgba(244,239,230,0.7)' },
  ];

  return (
    <div
      ref={containerRef}
      style={{
        padding: 28,
        background: 'var(--crimson)',
        color: '#f4efe6',
        borderRadius: 18,
        fontFamily: 'var(--mono)',
        position: 'relative',
        overflow: 'hidden',
      }}
    >
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 24 }}>
        <span className="hf-dot" style={{
          display: 'inline-block', width: 7, height: 7, borderRadius: '50%',
          background: '#4ade80', flexShrink: 0,
        }} />
        <span style={{ fontSize: 9, letterSpacing: '0.14em', textTransform: 'uppercase', opacity: 0.65 }}>
          {t('ct.hrs_label')}
        </span>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
        {rows.map(({ label, value, barW, barBg }) => (
          <div key={label}>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 7, fontSize: 13, lineHeight: 1 }}>
              <span style={{ opacity: 0.7 }}>{label}</span>
              <span style={{ fontWeight: 600, letterSpacing: '0.04em' }}>{value}</span>
            </div>
            <div style={{ height: 4, borderRadius: 99, background: 'rgba(244,239,230,0.12)', overflow: 'hidden' }}>
              <div className="hf-bar" style={{ height: '100%', width: barW, background: barBg, borderRadius: 99 }} />
            </div>
          </div>
        ))}
      </div>

      <span className="hf-cursor" style={{
        display: 'inline-block', width: 8, height: 14,
        background: '#f4efe6', marginTop: 18,
        borderRadius: 1, verticalAlign: 'middle',
        visibility: 'hidden',
      }} />
    </div>
  );
}

Object.assign(window, { PageContato });
