// ContactPage.jsx — enquiry form + contact details for Terraforno.
(function () {
  const { useState } = React;

  const REASONS = ['Home installation', 'Restaurant / commercial', 'Resort / hotel', 'General enquiry'];

  // All enquiries are delivered to this inbox via FormSubmit's AJAX endpoint.
  // NOTE: the first-ever submission triggers a one-time activation email to this
  // address — it must be confirmed once before messages start arriving.
  const CONTACT_EMAIL = 'info@difab.co.in';
  const FORM_ENDPOINT = 'https://formsubmit.co/ajax/' + CONTACT_EMAIL;

  function Field({ label, children }) {
    return (
      <label style={{ display: 'block' }}>
        <span style={{ display: 'block', fontSize: 'var(--t-xs)', letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--fg-3)', fontWeight: 600, marginBottom: 8 }}>{label}</span>
        {children}
      </label>
    );
  }
  const inputStyle = {
    width: '100%', background: 'var(--bg)', border: '1.5px solid var(--border-strong)', borderRadius: 'var(--r-md)',
    padding: '13px 15px', color: 'var(--fg-1)', fontFamily: 'var(--font-body)', fontSize: 'var(--t-body)', outline: 'none',
  };

  function ContactPage({ go }) {
    const root = useReveal();
    const [reason, setReason] = useState(REASONS[0]);
    const [sent, setSent] = useState(false);
    const [sending, setSending] = useState(false);
    const [error, setError] = useState(false);

    const submit = async (e) => {
      e.preventDefault();
      const form = e.target;
      const data = Object.fromEntries(new FormData(form).entries());
      setSending(true); setError(false);
      try {
        const res = await fetch(FORM_ENDPOINT, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
          body: JSON.stringify({ _subject: 'Website enquiry — ' + reason, _template: 'table', 'Enquiry type': reason, ...data }),
        });
        if (!res.ok) throw new Error('send failed');
        setSent(true);
        form.reset();
      } catch (err) {
        setError(true);
      } finally {
        setSending(false);
      }
    };

    return (
      <div ref={root}>
        <section className="tf-section--tight tf-section">
          <div className="tf-wrap" style={{ display: 'grid', gridTemplateColumns: '1fr 1.1fr', gap: 'clamp(32px,6vw,80px)', alignItems: 'start' }}>
            {/* left: invitation + details */}
            <div>
              <h1 className="tf-h1" style={{ margin: '0 0 16px' }}>Get in touch.</h1>
              <p className="tf-lead" style={{ maxWidth: 420 }}>Tell us what you're looking for and where you're based. We'll get back to you within 2 working days with advice and a quote.</p>

              <div style={{ display: 'flex', flexDirection: 'column', gap: 4, marginTop: 36 }}>
                {[
                  { icon: 'mapPin', t: 'Our workshop', d: <>Terra Forno Ovens, C/O DIFAB Engineering Pvt Ltd<br />RS No 334, Majagaon Industrial Estate,<br />Udyambag, Belagavi 590008, Karnataka, India</>, href: 'https://goo.gl/maps/VV8TiLhXa23qgKyi9', linkLabel: 'Get directions' },
                  { icon: 'phone', t: 'Call us', d: '+91 63662 36376', href: 'tel:+916366236376' },
                  { icon: 'mail', t: 'Email us', d: CONTACT_EMAIL, href: 'mailto:' + CONTACT_EMAIL },
                  { icon: 'clock', t: 'Working hours', d: 'Mon–Sat, 9am – 6pm IST' },
                ].map((c) => (
                  <div key={c.t} style={{ display: 'flex', gap: 16, alignItems: 'center', padding: '16px 0', borderBottom: '1px solid var(--border)' }}>
                    <span style={{ width: 44, height: 44, borderRadius: '50%', flex: 'none', display: 'grid', placeItems: 'center', background: 'color-mix(in srgb, var(--accent) 12%, transparent)', color: 'var(--accent)' }}><Icon name={c.icon} size={20} /></span>
                    <div>
                      <div style={{ fontWeight: 700, fontSize: 'var(--t-sm)' }}>{c.t}</div>
                      <div className="tf-small">
                        {c.href && !c.linkLabel
                          ? <a href={c.href} style={{ color: 'inherit' }}>{c.d}</a>
                          : c.d}
                        {c.linkLabel && <><br /><a href={c.href} target="_blank" rel="noopener" style={{ color: 'var(--accent)', fontWeight: 600 }}>{c.linkLabel} →</a></>}
                      </div>
                    </div>
                  </div>
                ))}
              </div>

            </div>

            {/* right: form card */}
            <div className="tf-card" style={{ padding: 'clamp(24px,3vw,40px)' }}>
              {sent ? (
                <div style={{ textAlign: 'center', padding: '40px 12px' }}>
                  <span style={{ width: 64, height: 64, borderRadius: '50%', background: 'color-mix(in srgb, var(--accent) 16%, transparent)', display: 'grid', placeItems: 'center', margin: '0 auto 20px', color: 'var(--accent)' }}><Icon name="flame" size={30} /></span>
                  <h3 className="tf-h3" style={{ margin: '0 0 8px' }}>Your message is in.</h3>
                  <p className="tf-body" style={{ maxWidth: 320, margin: '0 auto 22px' }}>We'll be in touch within 2 working days. In the meantime, explore the ovens.</p>
                  <TFButton variant="outline" onClick={() => { setSent(false); go('product'); }} arrow>Browse the ovens</TFButton>
                </div>
              ) : (
                <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
                  <h2 className="tf-h3" style={{ margin: 0 }}>Send us a message</h2>
                  <Field label="What's the enquiry about?">
                    <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                      {REASONS.map((r) => (
                        <button type="button" key={r} onClick={() => setReason(r)}
                          style={{ cursor: 'pointer', padding: '9px 15px', borderRadius: 'var(--r-pill)', fontSize: 'var(--t-sm)', fontWeight: 600, fontFamily: 'var(--font-body)', whiteSpace: 'nowrap',
                            border: '1.5px solid ' + (reason === r ? 'var(--accent)' : 'var(--border-strong)'),
                            background: reason === r ? 'var(--accent)' : 'transparent', color: reason === r ? 'var(--accent-fg)' : 'var(--fg-2)' }}>{r}</button>
                      ))}
                    </div>
                  </Field>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                    <Field label="First name"><input name="First name" style={inputStyle} required placeholder="enter first name" /></Field>
                    <Field label="Last name"><input name="Last name" style={inputStyle} required placeholder="enter last name" /></Field>
                  </div>
                  <Field label="Email"><input name="Email" type="email" style={inputStyle} required placeholder="xyz@email.com" /></Field>
                  <Field label="Phone (optional)"><input name="Phone" type="tel" style={inputStyle} placeholder="enter phone number" /></Field>
                  <Field label="City / location"><input name="City / location" style={inputStyle} required placeholder="enter city / location" /></Field>
                  <Field label="Tell us more">
                    <textarea name="Message" rows={4} style={{ ...inputStyle, resize: 'vertical' }} placeholder="e.g. I'm interested in the Verona for my restaurant — we seat 60 covers and want to do wood-fired pizza and bread. What's the lead time and price?" />
                  </Field>
                  <TFButton type="submit" variant="primary" size="lg" block arrow disabled={sending}>{sending ? 'Sending…' : 'Send message'}</TFButton>
                  {error && (
                    <p className="tf-small" style={{ textAlign: 'center', margin: 0, color: 'var(--accent)' }}>
                      Something went wrong sending your message. Please email us directly at <a href={'mailto:' + CONTACT_EMAIL} style={{ color: 'var(--accent)', fontWeight: 600 }}>{CONTACT_EMAIL}</a>.
                    </p>
                  )}
                  <p className="tf-small" style={{ textAlign: 'center', margin: 0 }}>We read every message and respond personally.</p>
                </form>
              )}
            </div>
          </div>
        </section>
      </div>
    );
  }

  window.ContactPage = ContactPage;
})();
