// ContactForm.jsx
const { useState, useEffect, useRef } = React;

const REVENUE_OPTS = [
  'Below €500k',
  '€500k - €1M',
  '€1M - €3M',
  '€3M - €5M',
  '€5M+',
];
const OFFER_OPTS = [
  'Operational Diagnostic (€2,500)',
  'Fractional COO (€3k-€5k/mo)',
  'Scale Accelerator (€10k-€20k)',
  'Not sure yet',
];

var FORMSPREE_ID = 'mwvjvznl';

function ContactForm({ offer, setOffer }) {
  var initForm = {
    name: '',
    email: '',
    company: '',
    revenue: REVENUE_OPTS[0],
    challenge: '',
  };
  const [form, setForm] = useState(initForm);
  const [submitted, setSubmitted] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [tab, setTab] = useState('form');
  const calReady = useRef(false);

  const set = (k) => (e) =>
    setForm(Object.assign({}, form, { [k]: e.target.value }));

  const submit = (e) => {
    e.preventDefault();
    if (!form.name || !form.email) {
      setError('Please fill in your name and email.');
      return;
    }
    setError('');
    setLoading(true);
    var payload = Object.assign({}, form, { offer: offer });
    var xhr = new XMLHttpRequest();
    var url = 'https://formspree.io/f/' + FORMSPREE_ID;
    xhr.open('POST', url);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.setRequestHeader('Accept', 'application/json');
    xhr.onload = function () {
      setLoading(false);
      if (xhr.status === 200) {
        setSubmitted(true);
      } else {
        setError('Something went wrong. Please try again.');
      }
    };
    xhr.onerror = function () {
      setLoading(false);
      setError('Network error. Please try again.');
    };
    xhr.send(JSON.stringify(payload));
  };

  useEffect(() => {
    if (calReady.current || !window.Cal) return;
    calReady.current = true;
    Cal.ns['30min']('inline', {
      elementOrSelector: '#my-cal-inline-30min',
      config: {
        layout: 'month_view',
        useSlotsViewOnSmallScreen: true,
      },
      calLink: 'anyonecanscale/30min',
    });
    Cal.ns['30min']('ui', {
      hideEventTypeDetails: false,
      layout: 'month_view',
      theme: 'dark',
      cssVarsPerTheme: {
        dark: {
          'cal-brand': '#22C55E',
          'cal-brand-emphasis': '#16A34A',
          'cal-bg': '#0F1C2E',
          'cal-bg-subtle': '#080E1A',
          'cal-border': '#1E2D45',
          'cal-border-emphasis': '#334155',
          'cal-text': '#F1F5F9',
          'cal-text-emphasis': '#F1F5F9',
          'cal-text-muted': '#94A3B8',
        },
      },
    });
  }, []);

  const Success = (
    <div className="form-success">
      Thank you — your request has been received.
      We will be in touch within 24 hours.
    </div>
  );

  const revenueOpts = REVENUE_OPTS.map((o) => (
    <option key={o}>{o}</option>
  ));
  const offerOpts = OFFER_OPTS.map((o) => (
    <option key={o}>{o}</option>
  ));

  return (
    <section className="section">
      <SectionHeader
        id="contact"
        label="Discovery Call"
        title="Request a discovery call"
        sub="Book a 30-minute slot directly, or send your details and we will reach out within 24 hours."
      />
      <div style={{ maxWidth: 900 }}>
        <div className="booking-tabs">
          <button
            type="button"
            className={'booking-tab' + (tab === 'form' ? ' active' : '')}
            onClick={() => setTab('form')}
          >
            Send a request
          </button>
          <button
            type="button"
            className={'booking-tab' + (tab === 'cal' ? ' active' : '')}
            onClick={() => setTab('cal')}
          >
            Book directly
          </button>
        </div>

        <div style={{ display: tab === 'cal' ? 'block' : 'none' }}>
          <div className="form-box" style={{ padding: 0, overflow: 'hidden' }}>
            <div id="my-cal-inline-30min" className="cal-embed" />
          </div>
        </div>

        <div style={{ display: tab === 'form' ? 'block' : 'none' }}>
          <div className="form-box">
            {submitted ? Success : (
              <form onSubmit={submit}>
                <div className="form-row">
                  <div className="form-field">
                    <label>Full name</label>
                    <input
                      placeholder="Jane Smith"
                      value={form.name}
                      onChange={set('name')}
                    />
                  </div>
                  <div className="form-field">
                    <label>Work email</label>
                    <input
                      type="email"
                      placeholder="jane@yourbrand.com"
                      value={form.email}
                      onChange={set('email')}
                    />
                  </div>
                </div>
                <div className="form-row">
                  <div className="form-field">
                    <label>Brand / Company</label>
                    <input
                      placeholder="Your Brand Co."
                      value={form.company}
                      onChange={set('company')}
                    />
                  </div>
                  <div className="form-field">
                    <label>Annual revenue</label>
                    <select
                      value={form.revenue}
                      onChange={set('revenue')}
                    >
                      {revenueOpts}
                    </select>
                  </div>
                </div>
                <div className="form-field full">
                  <label>Offer of interest</label>
                  <select
                    value={offer}
                    onChange={(e) => setOffer(e.target.value)}
                  >
                    {offerOpts}
                  </select>
                </div>
                <div className="form-field full">
                  <label>Biggest operational challenge</label>
                  <textarea
                    placeholder="Describe your main pain point..."
                    value={form.challenge}
                    onChange={set('challenge')}
                  />
                </div>
                <button
                  type="submit"
                  className="form-submit"
                  disabled={loading}
                >
                  {loading ? 'Sending...' : 'Send request'}
                </button>
                {error && (
                  <div className="form-error">{error}</div>
                )}
              </form>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}

window.ContactForm = ContactForm;
