const VF = {
  // Base palette — warm off-white + deep green
  bg: '#F5F2EB',
  bgAlt: '#EFEBE2',
  bgCream: '#FAF7F0',
  fg: '#1C1C1A',
  fgMuted: '#605E58',
  fgSubtle: '#8A8780',
  border: 'rgba(28,28,26,0.09)',
  borderStrong: 'rgba(28,28,26,0.16)',

  // Deep forest green (brand anchor)
  green: '#1F3A2E',
  greenDark: '#15281F',
  greenMid: '#2E5242',
  greenSoft: '#C8D6CE',
  greenFg: '#F0EBD8',

  // Accent — warm terracotta (used very sparingly)
  terracotta: '#B8593E',

  // Fonts
  serif: '"Fraunces", "Cormorant Garamond", Georgia, serif',
  sans: '"Inter", -apple-system, BlinkMacSystemFont, sans-serif',
  mono: '"JetBrains Mono", ui-monospace, monospace',
};

function ContactForm({ dark = false }) {
  const [sent, setSent] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState('');

  const [name, setName] = React.useState('');
  const [condo, setCondo] = React.useState('');
  const [units, setUnits] = React.useState('');
  const [contact, setContact] = React.useState('');
  const [areas, setAreas] = React.useState('');
  const endpoint = (window.VIVAFLOW_FORM_ENDPOINT || '').trim();
  const turnstileKey = (window.VIVAFLOW_TURNSTILE_SITEKEY || '').trim();
  const [turnstileToken, setTurnstileToken] = React.useState('');
  const turnstileElRef = React.useRef(null);
  const turnstileWidgetIdRef = React.useRef(null);

  const c = dark ? {
    bg: 'rgba(255,255,255,0.04)',
    border: 'rgba(240,235,216,0.18)',
    inputBg: 'rgba(255,255,255,0.06)',
    text: VF.greenFg,
    label: 'rgba(240,235,216,0.7)',
    placeholder: 'rgba(240,235,216,0.35)',
    btnBg: VF.greenFg,
    btnText: VF.green,
  } : {
    bg: '#fff',
    border: VF.border,
    inputBg: '#fff',
    text: VF.fg,
    label: VF.fgMuted,
    placeholder: VF.fgSubtle,
    btnBg: VF.green,
    btnText: VF.greenFg,
  };
  const pad = 'clamp(20px, 4vw, 36px)';
  const inputPad = '14px 16px';
  const inputStyle = {
    width: '100%', padding: inputPad, fontFamily: VF.sans,
    fontSize: 14, color: c.text, background: c.inputBg,
    border: `1px solid ${c.border}`, borderRadius: 4, outline: 'none',
    boxSizing: 'border-box',
  };
  const labelStyle = {
    fontFamily: VF.sans, fontSize: 11, fontWeight: 500,
    letterSpacing: '0.08em', textTransform: 'uppercase',
    color: c.label, marginBottom: 8, display: 'block',
  };

  if (sent) {
    return (
      <div style={{
        background: c.bg, border: `1px solid ${c.border}`,
        borderRadius: 6, padding: pad + 8, textAlign: 'center',
        color: c.text,
      }}>
        <div style={{ fontFamily: VF.serif, fontSize: 24, fontWeight: 400, marginBottom: 8, letterSpacing: '-0.01em' }}>
          Obrigado
        </div>
        <div style={{ fontFamily: VF.sans, fontSize: 14, color: c.label, lineHeight: 1.55 }}>
          Recebemos suas informações. O Icaro retorna em até 48h pelo canal que você preferir.
        </div>
      </div>
    );
  }

  React.useEffect(() => {
    if (!turnstileKey || sent) return;

    let cancelled = false;
    let tries = 0;

    function tryRender() {
      if (cancelled) return;
      const api = window.turnstile;
      const el = turnstileElRef.current;

      if (api && el && turnstileWidgetIdRef.current == null) {
        try {
          el.innerHTML = '';
          const id = api.render(el, {
            sitekey: turnstileKey,
            theme: dark ? 'dark' : 'light',
            callback: (token) => {
              setTurnstileToken(String(token || ''));
              // Se tinha erro de captcha, limpa ao validar.
              setError('');
            },
            'expired-callback': () => setTurnstileToken(''),
            'error-callback': () => setTurnstileToken(''),
          });
          turnstileWidgetIdRef.current = id;
          return;
        } catch {
          // Em caso de corrida (script ainda inicializando), tentamos novamente.
        }
      }

      tries += 1;
      if (tries < 120) setTimeout(tryRender, 100);
    }

    tryRender();

    return () => {
      cancelled = true;
      setTurnstileToken('');
      try {
        if (window.turnstile && turnstileWidgetIdRef.current != null) {
          window.turnstile.remove(turnstileWidgetIdRef.current);
        }
      } catch {}
      turnstileWidgetIdRef.current = null;
    };
  }, [turnstileKey, dark, sent]);

  async function onSubmit(e) {
    e.preventDefault();
    if (submitting) return;
    setError('');

    if (!endpoint) {
      setError('Endpoint do formulário não configurado. Defina window.VIVAFLOW_FORM_ENDPOINT no index.html.');
      return;
    }

    setSubmitting(true);
    try {
      const body = new URLSearchParams();
      body.set('name', name.trim());
      body.set('condo', condo.trim());
      body.set('units', units.trim());
      body.set('contact', contact.trim());
      body.set('areas', areas.trim());
      body.set('page', window.location.href);
      body.set('ts', new Date().toISOString());

      if (turnstileKey) {
        const token = (turnstileToken || '').trim();
        if (!token) {
          setError('Confirme o captcha para enviar.');
          return;
        }
        body.set('cf-turnstile-response', token);
      }

      const res = await fetch(endpoint, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
          'Accept': 'application/json',
        },
        body: body.toString(),
      });

      if (!res.ok) {
        let msg = `Falha ao enviar (HTTP ${res.status}).`;
        try {
          const data = await res.json();
          if (data && typeof data.error === 'string') msg = data.error;
        } catch {}
        setError(msg);
        try {
          if (turnstileKey && window.turnstile && turnstileWidgetIdRef.current != null) {
            window.turnstile.reset(turnstileWidgetIdRef.current);
          }
        } catch {}
        setTurnstileToken('');
        return;
      }

      // Em caso de sucesso, remove o widget para evitar exceções do Turnstile
      // quando o container sai do DOM.
      try {
        if (turnstileKey && window.turnstile && turnstileWidgetIdRef.current != null) {
          window.turnstile.remove(turnstileWidgetIdRef.current);
        }
      } catch {}
      turnstileWidgetIdRef.current = null;
      setTurnstileToken('');

      setSent(true);
    } catch (err) {
      setError('Não foi possível enviar agora. Tente novamente em instantes.');
      try {
        if (turnstileKey && window.turnstile && turnstileWidgetIdRef.current != null) {
          window.turnstile.reset(turnstileWidgetIdRef.current);
        }
      } catch {}
      setTurnstileToken('');
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <form
      onSubmit={onSubmit}
      action={endpoint || undefined}
      method={endpoint ? 'POST' : undefined}
      style={{
        background: c.bg, border: `1px solid ${c.border}`,
        borderRadius: 6, padding: pad,
      }}
    >
      <div style={{ display: 'grid', gap: 18 }}>
        <div>
          <label style={labelStyle}>Seu nome</label>
          <input
            name="name"
            required
            value={name}
            onChange={(e) => setName(e.target.value)}
            placeholder="Como devemos te chamar"
            style={inputStyle}
          />
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(160px, 1fr))', gap: 14 }}>
          <div>
            <label style={labelStyle}>Condomínio</label>
            <input
              name="condo"
              required
              value={condo}
              onChange={(e) => setCondo(e.target.value)}
              placeholder="Nome do condomínio"
              style={inputStyle}
            />
          </div>
          <div>
            <label style={labelStyle}>Unidades</label>
            <input
              name="units"
              required
              value={units}
              onChange={(e) => setUnits(e.target.value)}
              inputMode="numeric"
              placeholder="Ex: 120"
              style={inputStyle}
            />
          </div>
        </div>
        <div>
          <label style={labelStyle}>Melhor contato</label>
          <input
            name="contact"
            required
            value={contact}
            onChange={(e) => setContact(e.target.value)}
            placeholder="E-mail ou WhatsApp"
            style={inputStyle}
          />
        </div>
        <div>
          <label style={labelStyle}>Áreas disponíveis no prédio <span style={{ textTransform: 'none', letterSpacing: 0, opacity: 0.6 }}>(opcional)</span></label>
          <textarea
            name="areas"
            rows={2}
            value={areas}
            onChange={(e) => setAreas(e.target.value)}
            placeholder="Ex: piscina, academia, quadra, sala de massagem"
            style={{ ...inputStyle, resize: 'none' }}
          />
        </div>
        {turnstileKey ? (
          <div style={{
            padding: '10px 0 0',
            display: 'flex',
            justifyContent: 'center',
          }}>
            <div
              ref={turnstileElRef}
              aria-label="Captcha"
              style={{ minHeight: 65 }}
            />
          </div>
        ) : null}
        <button type="submit" disabled={submitting} style={{
          marginTop: 8,
          padding: '16px 24px',
          background: c.btnBg, color: c.btnText,
          fontFamily: VF.sans, fontSize: 14, fontWeight: 500,
          letterSpacing: '0.02em',
          border: 'none', borderRadius: 999, cursor: 'pointer',
          transition: 'opacity 0.2s',
          opacity: submitting ? 0.7 : 1,
          pointerEvents: submitting ? 'none' : 'auto',
        }}>
          {submitting ? 'Enviando...' : 'Enviar para avaliação'}
        </button>
        {error ? (
          <div style={{
            fontFamily: VF.sans, fontSize: 12, lineHeight: 1.5,
            color: dark ? 'rgba(255,255,255,0.9)' : '#8B1E1E',
            background: dark ? 'rgba(255,255,255,0.08)' : 'rgba(184,89,62,0.10)',
            border: `1px solid ${dark ? 'rgba(255,255,255,0.18)' : 'rgba(184,89,62,0.22)'}`,
            padding: '10px 12px',
            borderRadius: 6,
          }}>
            {error}
          </div>
        ) : null}
        <div style={{
          fontFamily: VF.sans, fontSize: 11, color: c.label, textAlign: 'center',
          letterSpacing: '0.02em',
        }}>
          Retorno em até 48h · Sem compromisso · Sem custo inicial
        </div>
      </div>
    </form>
  );
}

const faqItems = [
  {
    q: 'Quem é responsável pelos profissionais que atendem no condomínio?',
    a: 'A Viva Flow faz a curadoria: seleciona profissionais, verifica documentação e valida experiência anterior. Não existe vínculo trabalhista entre o condomínio e os profissionais — cada um atua de forma independente, com o intermédio da nossa curadoria.',
  },
  {
    q: 'Como os moradores pagam pelas atividades?',
    a: 'Cada morador paga direto pela atividade que contratar — aula de natação, pilates, massagem, personal. O condomínio não movimenta dinheiro e não precisa fazer cobrança.',
  },
  {
    q: 'O que o condomínio precisa fazer para começar?',
    a: 'Uma conversa inicial com o síndico ou administradora, alinhamento das áreas disponíveis e autorização para começarmos a operar. A estruturação operacional é feita por nós.',
  },
  {
    q: 'E se não engrenar?',
    a: 'Encerramos a operação sem ônus nenhum. O combinado é transparente desde o início: se não funcionar para o condomínio, não continua.',
  },
];

function FAQ({ dark = false }) {
  const [open, setOpen] = React.useState(0);
  const c = dark ? {
    text: VF.greenFg, muted: 'rgba(240,235,216,0.65)', border: 'rgba(240,235,216,0.15)',
  } : {
    text: VF.fg, muted: VF.fgMuted, border: VF.border,
  };
  return (
    <div style={{ display: 'grid', gap: 0 }}>
      {faqItems.map((item, i) => {
        const isOpen = open === i;
        return (
          <div key={i} style={{ borderTop: i === 0 ? `1px solid ${c.border}` : 'none', borderBottom: `1px solid ${c.border}` }}>
            <button
              onClick={() => setOpen(isOpen ? -1 : i)}
              style={{
                width: '100%', textAlign: 'left', background: 'transparent', border: 'none',
                padding: '28px 0', cursor: 'pointer',
                display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between',
                gap: 24, color: c.text, fontFamily: VF.serif,
                fontSize: 22, fontWeight: 400, letterSpacing: '-0.01em', lineHeight: 1.3,
              }}
            >
              <span style={{ flex: 1 }}>{item.q}</span>
              <span style={{
                fontFamily: VF.sans, fontSize: 20, lineHeight: 1, fontWeight: 300,
                transform: isOpen ? 'rotate(45deg)' : 'none',
                transition: 'transform 0.2s',
                flexShrink: 0, marginTop: 2,
              }}>+</span>
            </button>
            {isOpen && (
              <div style={{
                paddingBottom: 28, paddingRight: 44,
                fontFamily: VF.sans, fontSize: 15, lineHeight: 1.65, color: c.muted,
              }}>
                {item.a}
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
}

function Eyebrow({ children, dark = false, style = {} }) {
  return (
    <span style={{
      fontFamily: VF.sans, fontSize: 11, fontWeight: 500,
      letterSpacing: '0.18em', textTransform: 'uppercase',
      color: dark ? 'rgba(240,235,216,0.6)' : VF.fgMuted,
      ...style,
    }}>{children}</span>
  );
}

Object.assign(window, { VF, ContactForm, FAQ, Eyebrow });
