function CTA({ accent }) {
  const ref = React.useRef(null);
  const [submitted, setSubmitted] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [error, setError] = React.useState('');
  const [form, setForm] = React.useState({ name: '', email: '', phone: '', interest: 'Keukens', message: '' });

  React.useEffect(() => {
    const obs = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) e.target.classList.add('in'); });
    }, { threshold: 0.15 });
    ref.current.querySelectorAll('.reveal').forEach(el => obs.observe(el));
    return () => obs.disconnect();
  }, []);

  const submit = async (e) => {
    e.preventDefault();
    setSending(true);
    setError('');
    try {
      const res = await fetch('https://formsubmit.co/ajax/amersfoort@assosgroep.nl', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
        body: JSON.stringify({
          Naam: form.name,
          Email: form.email,
          Telefoon: form.phone || 'Niet opgegeven',
          Interesse: form.interest,
          Bericht: form.message || 'Geen bericht',
          _subject: `Nieuwe offerte aanvraag — ${form.interest}`,
          _template: 'table',
        }),
      });
      if (res.ok) {
        setSubmitted(true);
      } else {
        setError('Er is iets misgegaan. Probeer het opnieuw of mail ons direct.');
      }
    } catch {
      setError('Geen verbinding. Controleer uw internet en probeer opnieuw.');
    } finally {
      setSending(false);
    }
  };

  // styling now handled by .field-input / .field-textarea / .field-label classes

  return (
    <section id="offerte" ref={ref} data-screen-label="CTA" style={{
      padding: 'clamp(80px, 12vw, 160px) clamp(24px, 6vw, 80px)',
      background: 'var(--bg)',
      position: 'relative',
      borderTop: '1px solid var(--line)',
      overflow: 'hidden',
    }}>
      {/* Decorative serif "Q" */}
      <div className="serif" style={{
        position: 'absolute',
        top: '50%', left: '-40px',
        transform: 'translateY(-50%)',
        fontSize: 'clamp(300px, 50vw, 700px)',
        color: 'rgba(201,169,110,0.04)',
        fontStyle: 'italic',
        lineHeight: 1,
        pointerEvents: 'none',
        userSelect: 'none',
      }}>&amp;</div>

      <div style={{ maxWidth: 1100, margin: '0 auto', position: 'relative' }}>
        <div style={{
          display: 'grid',
          gridTemplateColumns: '1fr 1.2fr',
          gap: 'clamp(40px, 8vw, 100px)',
          alignItems: 'start',
        }} className="cta-grid">
          <div className="reveal" style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
            <span className="eyebrow">Offerte</span>
            <h2 className="serif" style={{
              fontSize: 'clamp(36px, 5vw, 64px)',
              fontWeight: 400, lineHeight: 1.05, letterSpacing: '-0.02em',
            }}>
              Vertel ons over uw <span style={{ fontStyle: 'italic', color: accent }}>project.</span>
            </h2>
            <p style={{ fontSize: 15, lineHeight: 1.7, color: 'var(--fg-dim)', maxWidth: 420 }}>
              Plan een vrijblijvend kennismakingsgesprek. We nemen binnen 24 uur contact met u op om uw wensen te bespreken.
            </p>
            <div style={{ marginTop: 24, paddingTop: 32, borderTop: '1px solid var(--line)', display: 'flex', flexDirection: 'column', gap: 20 }}>
              <div>
                <div style={{ fontSize: 12, color: 'var(--fg-mute)', marginBottom: 6, fontWeight: 500 }}>Bel ons</div>
                <a href="tel:+31332078060" className="ulink serif" style={{ fontSize: 24 }}>(033) 207 8060</a>
              </div>
              <div>
                <div style={{ fontSize: 12, color: 'var(--fg-mute)', marginBottom: 6, fontWeight: 500 }}>E-mail</div>
                <a href="mailto:amersfoort@assosgroep.nl" className="ulink serif" style={{ fontSize: 24 }}>amersfoort@assosgroep.nl</a>
              </div>
            </div>
          </div>

          <div className="reveal">
            {!submitted ? (
              <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }} className="cta-row">
                  <div className="field">
                    <label className="field-label">Naam</label>
                    <input className="field-input" placeholder="Uw volledige naam" value={form.name} onChange={e => setForm({...form, name: e.target.value})} required />
                  </div>
                  <div className="field">
                    <label className="field-label">Telefoon</label>
                    <input className="field-input" placeholder="06 12 34 56 78" value={form.phone} onChange={e => setForm({...form, phone: e.target.value})} />
                  </div>
                </div>
                <div className="field">
                  <label className="field-label">E-mail</label>
                  <input type="email" className="field-input" placeholder="naam@voorbeeld.nl" value={form.email} onChange={e => setForm({...form, email: e.target.value})} required />
                </div>
                <div className="field">
                  <label className="field-label">Ik ben geïnteresseerd in</label>
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginTop: 4 }}>
                    {['Keukens', 'Badkamers', 'PVC & Tegels', 'Interieurbouw', 'Verbouwing'].map(opt => (
                      <button key={opt} type="button" onClick={() => setForm({...form, interest: opt})}
                        className={`chip chip-toggle ${form.interest === opt ? 'is-active' : ''}`}>
                        {opt}
                      </button>
                    ))}
                  </div>
                </div>
                <div className="field">
                  <label className="field-label">Bericht</label>
                  <textarea className="field-textarea" placeholder="Vertel ons kort over uw project..." rows={3} value={form.message} onChange={e => setForm({...form, message: e.target.value})} />
                </div>
                {error && (
                  <p style={{ color: '#c0392b', fontSize: 14, margin: 0 }}>{error}</p>
                )}
                <button type="submit" className="btn btn-accent" disabled={sending} style={{ alignSelf: 'flex-start', marginTop: 8, opacity: sending ? 0.6 : 1 }}>
                  {sending ? 'Verzenden...' : 'Verstuur aanvraag'} {!sending && <span className="arrow">→</span>}
                </button>
              </form>
            ) : (
              <div className="card" style={{
                padding: '60px 40px', borderColor: accent,
                display: 'flex', flexDirection: 'column', gap: 16, alignItems: 'flex-start',
                background: 'rgba(184,149,106,0.04)',
              }}>
                <div className="serif" style={{ fontSize: 48, color: accent, fontStyle: 'italic' }}>Bedankt.</div>
                <p style={{ color: 'var(--fg-dim)', fontSize: 15, lineHeight: 1.6 }}>
                  We hebben uw aanvraag ontvangen en nemen binnen 24 uur contact met u op.
                </p>
              </div>
            )}
          </div>
        </div>
      </div>

      <style>{`
        @media (max-width: 860px) {
          .cta-grid { grid-template-columns: 1fr !important; }
          .cta-row { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </section>
  );
}

window.CTA = CTA;
