// whetstone-form.jsx
// Multi-step contact form: select services, then provide context, then info.
// Submits to /api/contact (Cloudflare Pages Function -> Resend).

const { useState: useStateF, useEffect: useEffectF, useRef: useRefF } = React;

// Turnstile site key — public, safe to ship in source.
// Replace with the real one from Cloudflare dashboard before deploy.
// (Falls back to test key in dev so the form still works locally.)
const TURNSTILE_SITE_KEY = window.__TURNSTILE_SITE_KEY || '1x00000000000000000000AA';

function ContactForm({ variant = 'editorial' }) {
  const [step, setStep] = useStateF(0);
  const [picked, setPicked] = useStateF([]);
  const [ctx, setCtx] = useStateF({ teamSize: '', timeline: '', notes: '' });
  const [info, setInfo] = useStateF({ name: '', email: '', org: '' });
  const [hp, setHp] = useStateF(''); // honeypot — bots fill it, humans don't see it
  const [submitted, setSubmitted] = useStateF(false);
  const [sending, setSending] = useStateF(false);
  const [errorMsg, setErrorMsg] = useStateF('');
  const [tsToken, setTsToken] = useStateF('');
  const tsRef = useRefF(null);

  // Load Turnstile when we hit step 2 (info step)
  useEffectF(() => {
    if (step !== 2 || tsToken) return;
    const renderWidget = () => {
      if (!window.turnstile || !tsRef.current) return;
      window.turnstile.render(tsRef.current, {
        sitekey: TURNSTILE_SITE_KEY,
        callback: (token) => setTsToken(token),
        'error-callback': () => setTsToken(''),
        'expired-callback': () => setTsToken(''),
        appearance: 'interaction-only',
      });
    };
    if (window.turnstile) {
      renderWidget();
    } else if (!document.getElementById('cf-turnstile-script')) {
      const s = document.createElement('script');
      s.id = 'cf-turnstile-script';
      s.src = 'https://challenges.cloudflare.com/turnstile/v0/api.js?onload=__onTurnstile';
      s.async = true;
      s.defer = true;
      window.__onTurnstile = renderWidget;
      document.head.appendChild(s);
    }
  }, [step, tsToken]);

  const togglePick = (id) => {
    setPicked(p => p.includes(id) ? p.filter(x => x !== id) : [...p, id]);
  };

  const next = () => setStep(s => Math.min(s + 1, 2));
  const back = () => setStep(s => Math.max(s - 1, 0));

  const submit = async () => {
    if (sending) return;
    setSending(true);
    setErrorMsg('');
    const payload = {
      services: picked,
      teamSize: ctx.teamSize,
      timeline: ctx.timeline,
      notes: ctx.notes,
      name: info.name,
      email: info.email,
      org: info.org,
      website: hp, // honeypot — server rejects if non-empty
      turnstileToken: tsToken || document.querySelector('[id$="_response"][id^="cf-chl"]')?.value || '',
      submittedAt: new Date().toISOString(),
      pageUrl: window.location.href,
    };
    try {
      const res = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error(data.error || `Server returned ${res.status}`);
      }
      setSubmitted(true);
    } catch (err) {
      setErrorMsg(err.message || 'Something went wrong.');
    } finally {
      setSending(false);
    }
  };

  const labelStyle = {
    fontFamily: 'var(--mono)',
    fontSize: 11,
    textTransform: 'uppercase',
    letterSpacing: '0.1em',
    color: 'var(--muted)',
    display: 'block',
    marginBottom: 8,
  };
  const inputStyle = {
    width: '100%',
    padding: '12px 14px',
    border: '1px solid var(--rule)',
    background: 'var(--bg)',
    color: 'var(--ink)',
    fontFamily: 'var(--sans)',
    fontSize: 15,
    outline: 'none',
    transition: 'border-color .15s',
  };

  if (submitted) {
    return (
      <div style={{
        padding: '48px 36px',
        border: '1px solid var(--rule)',
        background: 'color-mix(in oklab, var(--bg), var(--accent) 4%)',
      }}>
        <div style={{
          fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '0.12em',
          textTransform: 'uppercase', color: 'var(--accent)', marginBottom: 16,
        }}>✓ Received</div>
        <h3 style={{
          fontFamily: 'var(--display)', fontSize: 32, fontWeight: 500,
          letterSpacing: '-0.02em', marginBottom: 12, color: 'var(--ink)',
        }}>Thanks, {info.name.split(' ')[0] || 'there'}.</h3>
        <p style={{ color: 'var(--muted)', fontSize: 16, lineHeight: 1.6, maxWidth: 480 }}>
          We'll reply within one business day with a couple of times to talk.
          If it's more urgent than that, email <a style={{ color: 'var(--accent)' }} href="mailto:hello@whetstonegroup.ai">hello@whetstonegroup.ai</a>.
        </p>
      </div>
    );
  }

  return (
    <div style={{
      border: '1px solid var(--rule)',
      background: 'var(--bg)',
    }}>
      {/* Stepper */}
      <div style={{
        display: 'flex',
        borderBottom: '1px solid var(--rule)',
      }}>
        {['What you need', 'Context', 'Your info'].map((label, i) => (
          <button key={i}
            onClick={() => i < step && setStep(i)}
            disabled={i > step}
            style={{
              flex: 1,
              padding: '14px 16px',
              border: 0,
              borderRight: i < 2 ? '1px solid var(--rule)' : 0,
              background: i === step ? 'color-mix(in oklab, var(--bg), var(--accent) 5%)' : 'transparent',
              color: i === step ? 'var(--ink)' : 'var(--muted)',
              fontFamily: 'var(--mono)',
              fontSize: 11,
              textTransform: 'uppercase',
              letterSpacing: '0.1em',
              textAlign: 'left',
              cursor: i <= step ? 'pointer' : 'default',
            }}>
            <span style={{ color: i === step ? 'var(--accent)' : 'inherit', marginRight: 10 }}>0{i + 1}</span>
            {label}
          </button>
        ))}
      </div>

      <div style={{ padding: '32px 36px' }}>
        {step === 0 && (
          <div>
            <p style={{ color: 'var(--muted)', marginBottom: 24, fontSize: 15 }}>
              Pick anything that fits. We'll narrow it down together.
            </p>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 0, border: '1px solid var(--rule)' }}>
              {SERVICES.map((s, i) => {
                const on = picked.includes(s.id);
                return (
                  <button key={s.id}
                    onClick={() => togglePick(s.id)}
                    style={{
                      display: 'flex',
                      alignItems: 'flex-start',
                      gap: 18,
                      padding: '18px 20px',
                      border: 0,
                      borderTop: i > 0 ? '1px solid var(--rule)' : 0,
                      background: on ? 'color-mix(in oklab, var(--bg), var(--accent) 7%)' : 'transparent',
                      color: 'var(--ink)',
                      textAlign: 'left',
                      cursor: 'pointer',
                      fontFamily: 'var(--sans)',
                      transition: 'background .12s',
                    }}>
                    <span aria-hidden="true" style={{
                      width: 18, height: 18, marginTop: 3, flexShrink: 0,
                      border: `1.5px solid ${on ? 'var(--accent)' : 'var(--rule)'}`,
                      background: on ? 'var(--accent)' : 'transparent',
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      color: 'var(--bg)', fontSize: 12, fontWeight: 700,
                    }}>{on ? '✓' : ''}</span>
                    <span style={{ flex: 1 }}>
                      <span style={{
                        fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '0.12em',
                        textTransform: 'uppercase', color: 'var(--muted)', marginRight: 12,
                      }}>{s.n}</span>
                      <span style={{ fontWeight: 600, fontSize: 16 }}>{s.title}</span>
                      <span style={{ display: 'block', color: 'var(--muted)', fontSize: 14, marginTop: 4, lineHeight: 1.5 }}>
                        {s.blurb}
                      </span>
                    </span>
                  </button>
                );
              })}
            </div>
            <FormNav onNext={next} canNext={picked.length > 0} backHidden />
          </div>
        )}

        {step === 1 && (
          <div>
            <p style={{ color: 'var(--muted)', marginBottom: 24, fontSize: 15 }}>
              Helps us come prepared. None of this is required.
            </p>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20, marginBottom: 20 }}>
              <div>
                <label style={labelStyle}>Team size</label>
                <select value={ctx.teamSize} onChange={(e) => setCtx({ ...ctx, teamSize: e.target.value })} style={inputStyle}>
                  <option value="">Select…</option>
                  <option>Just me</option>
                  <option>2–5</option>
                  <option>6–20</option>
                  <option>21–100</option>
                  <option>100+</option>
                </select>
              </div>
              <div>
                <label style={labelStyle}>Timeline</label>
                <select value={ctx.timeline} onChange={(e) => setCtx({ ...ctx, timeline: e.target.value })} style={inputStyle}>
                  <option value="">Select…</option>
                  <option>This month</option>
                  <option>Next quarter</option>
                  <option>Just exploring</option>
                </select>
              </div>
            </div>
            <div>
              <label style={labelStyle}>What are you trying to do?</label>
              <textarea
                value={ctx.notes}
                onChange={(e) => setCtx({ ...ctx, notes: e.target.value })}
                rows={5}
                placeholder="A sentence or two is plenty."
                style={{ ...inputStyle, fontFamily: 'var(--sans)', resize: 'vertical', minHeight: 110 }} />
            </div>
            <FormNav onBack={back} onNext={next} canNext />
          </div>
        )}

        {step === 2 && (
          <div>
            <p style={{ color: 'var(--muted)', marginBottom: 24, fontSize: 15 }}>
              We reply within one business day.
            </p>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20, marginBottom: 20 }}>
              <div>
                <label style={labelStyle}>Your name</label>
                <input value={info.name} onChange={(e) => setInfo({ ...info, name: e.target.value })} style={inputStyle} />
              </div>
              <div>
                <label style={labelStyle}>Email</label>
                <input type="email" value={info.email} onChange={(e) => setInfo({ ...info, email: e.target.value })} style={inputStyle} />
              </div>
            </div>
            <div style={{ marginBottom: 20 }}>
              <label style={labelStyle}>Organization (optional)</label>
              <input value={info.org} onChange={(e) => setInfo({ ...info, org: e.target.value })} style={inputStyle} />
            </div>

            {/* Honeypot — visually hidden, off-screen, not focusable */}
            <div aria-hidden="true" style={{
              position: 'absolute', left: '-9999px', top: 'auto',
              width: 1, height: 1, overflow: 'hidden',
            }}>
              <label>
                Website (leave blank)
                <input
                  type="text"
                  tabIndex={-1}
                  autoComplete="off"
                  value={hp}
                  onChange={(e) => setHp(e.target.value)}
                />
              </label>
            </div>

            <PickedSummary picked={picked} />

            {/* Turnstile mount — invisible / interaction-only */}
            <div ref={tsRef} style={{ marginTop: 8, marginBottom: 8 }}></div>

            {errorMsg && (
              <div style={{
                marginTop: 12, marginBottom: 4, padding: '12px 14px',
                border: '1px solid color-mix(in oklab, var(--accent), red 30%)',
                background: 'color-mix(in oklab, var(--bg), red 4%)',
                fontSize: 14, color: 'var(--ink)', lineHeight: 1.5,
              }}>
                Couldn't send — {errorMsg}. Email us directly at{' '}
                <a style={{ color: 'var(--accent)' }} href={mailtoFallback(info, ctx, picked)}>
                  hello@whetstonegroup.ai
                </a>.
              </div>
            )}

            <FormNav onBack={back} onNext={submit}
              canNext={info.name && info.email && !sending}
              nextLabel={sending ? 'Sending…' : 'Send it →'} />
          </div>
        )}
      </div>
    </div>
  );
}

function mailtoFallback(info, ctx, picked) {
  const labels = SERVICES.filter(s => picked.includes(s.id)).map(s => s.title).join(', ');
  const subject = `Whetstone inquiry — ${info.name || '(no name)'}`;
  const body = [
    `Name: ${info.name}`,
    `Email: ${info.email}`,
    `Organization: ${info.org || '—'}`,
    `Interested in: ${labels || '—'}`,
    `Team size: ${ctx.teamSize || '—'}`,
    `Timeline: ${ctx.timeline || '—'}`,
    '',
    'Notes:',
    ctx.notes || '—',
  ].join('\n');
  return `mailto:hello@whetstonegroup.ai?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;
}

function PickedSummary({ picked }) {
  if (!picked.length) return null;
  const labels = SERVICES.filter(s => picked.includes(s.id)).map(s => s.title);
  return (
    <div style={{
      padding: '12px 14px',
      background: 'color-mix(in oklab, var(--bg), var(--accent) 5%)',
      borderLeft: '2px solid var(--accent)',
      marginBottom: 8,
      fontFamily: 'var(--mono)',
      fontSize: 11.5,
      color: 'var(--muted)',
      letterSpacing: '0.04em',
    }}>
      <span style={{ color: 'var(--accent)', textTransform: 'uppercase', letterSpacing: '0.1em', marginRight: 10 }}>
        Interested in →
      </span>
      <span style={{ color: 'var(--ink)' }}>{labels.join(' · ')}</span>
    </div>
  );
}

function FormNav({ onBack, onNext, canNext, backHidden, nextLabel = 'Continue →' }) {
  return (
    <div style={{
      display: 'flex',
      justifyContent: backHidden ? 'flex-end' : 'space-between',
      alignItems: 'center',
      marginTop: 28,
      paddingTop: 20,
      borderTop: '1px solid var(--rule)',
    }}>
      {!backHidden && (
        <button onClick={onBack}
          style={{
            border: 0, background: 'transparent', cursor: 'pointer',
            color: 'var(--muted)', fontFamily: 'var(--mono)', fontSize: 12,
            textTransform: 'uppercase', letterSpacing: '0.12em', padding: '10px 0',
          }}>← Back</button>
      )}
      <button onClick={onNext} disabled={!canNext}
        style={{
          padding: '14px 24px',
          border: 0,
          background: canNext ? 'var(--accent)' : 'color-mix(in oklab, var(--rule), var(--ink) 10%)',
          color: 'var(--bg)',
          fontFamily: 'var(--mono)',
          fontSize: 12,
          textTransform: 'uppercase',
          letterSpacing: '0.12em',
          fontWeight: 600,
          cursor: canNext ? 'pointer' : 'not-allowed',
          opacity: canNext ? 1 : 0.5,
        }}>{nextLabel}</button>
    </div>
  );
}

window.ContactForm = ContactForm;
