/* global React, Icon */
// Form submits to a Google Apps Script Web App that appends a row
// to the Dynawins leads Google Sheet.
//
// Setup: see google-apps-script.gs in this folder for the full guide.
// Paste your deployed Web App URL into window.__DYNAWINS_FLOW_URL in index.html.
const FLOW_URL = window.__DYNAWINS_FLOW_URL || ''; // empty = simulate locally

const ContactPage = () => {
  const [form, setForm] = React.useState({ name: '', email: '', phone: '', product: 'Smart Panel AI', description: '' });
  const [status, setStatus] = React.useState('idle'); // idle | sending | sent | error
  const [errMsg, setErrMsg] = React.useState('');

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

  const submit = async (e) => {
    e.preventDefault();
    setStatus('sending');
    setErrMsg('');
    const payload = {
      "Name": form.name,
      "Email": form.email,
      "Phone": form.phone,
      "Interested Product": form.product,
      "Description": form.description,
      // bonus: timestamp for the flow to write to a hidden col if you add one
      "SubmittedAt": new Date().toISOString(),
    };
    try {
      if (!FLOW_URL) {
        // No URL configured — simulate so prototype still demos.
        await new Promise((r) => setTimeout(r, 800));
        console.log('[Dynawins] Form payload (would POST to Google Sheets):', payload);
        setStatus('sent');
        return;
      }
      // Apps Script Web Apps return a 302 redirect that browsers can't follow
      // with a POST + JSON body in CORS mode. Use no-cors: the request fires
      // and Google appends the row, but we get an opaque response.
      await fetch(FLOW_URL, {
        method: 'POST',
        mode: 'no-cors',
        headers: { 'Content-Type': 'text/plain;charset=utf-8' },
        body: JSON.stringify(payload),
      });
      console.log('[Dynawins] POST sent to Sheet (opaque response)');
      setStatus('sent');
    } catch (err) {
      setStatus('error');
      setErrMsg(err.message || 'Something went wrong. Please email us instead.');
    }
  };

  return (
    <div className="page-enter">
      {/* HERO — split: text on left, image on right (image fills full hero height) */}
      <section className="contact-hero">
        <div className="container">
          <div className="contact-hero-grid">
            <div className="contact-hero-text">
              <span className="eyebrow">Contact</span>
              <h1 style={{ fontSize: 'clamp(36px, 5vw, 56px)', marginBottom: 20, lineHeight: 1.05 }}>Talk to a maker, not a bot.</h1>
              <p className="lead" style={{ marginBottom: 24, maxWidth: '46ch' }}>Tell us about your D365 setup and what you're trying to fix. We'll reply with a tailored demo and a sandbox link within one business day.</p>
              <div style={{ display: 'flex', alignItems: 'center', gap: 14, fontSize: 13, color: 'var(--ink-3)' }}>
                <span className="dot-live" aria-hidden="true"/>
                <span>Currently replying within <strong style={{ color: 'var(--ink-1)' }}>4 hours</strong> on weekdays.</span>
              </div>
            </div>
            <div className="contact-hero-image">
              <img
                src="https://images.unsplash.com/photo-1556761175-5973dc0f32e7?auto=format&fit=crop&w=1400&q=80"
                alt="A working session inside a modern office"
                loading="eager"
                onError={(e) => { e.currentTarget.parentElement.style.display = 'none'; }}
              />
            </div>
          </div>
        </div>
      </section>

      {/* CONTACT METHODS — three cards, horizontal */}
      <section className="section-tight" style={{ paddingTop: 0 }}>
        <div className="container">
          <div className="contact-methods">
            <ContactCard
              iconName="zap"
              label="Email"
              value="contact@dynawins.com"
              href="mailto:contact@dynawins.com"
              hint="We reply in plain text — no marketing autoresponder."
            />
            <ContactCard
              iconName="users"
              label="WhatsApp"
              value="+91 95118 04590"
              href="https://wa.me/9511804590"
              hint="Quickest path. Voice notes welcome."
            />
            <ContactCard
              iconName="clock"
              label="Office hours"
              value="Mon–Fri · 09:00–18:00 IST"
              hint="Outside hours? Drop a message — we'll reply at 9:00 IST."
            />
          </div>
        </div>
      </section>

      {/* FORM — centered, full-width inside a max-width column */}
      <section className="section section-alt">
        <div className="container">
          <div className="contact-form-wrap">
            <div style={{ textAlign: 'center', marginBottom: 32 }}>
              <span className="eyebrow">Get a demo</span>
              <h2 style={{ marginBottom: 12, maxWidth: '22ch', marginLeft: 'auto', marginRight: 'auto' }}>Tell us what you're trying to fix.</h2>
              <p style={{ color: 'var(--ink-3)', fontSize: 15, maxWidth: '52ch', margin: '0 auto' }}>Two minutes of typing. One business day to a sandbox link.</p>
            </div>

            <div className="card" style={{ padding: 'clamp(24px, 4vw, 40px)' }}>
              {status === 'sent' ? (
                <div style={{ padding: '32px 0', textAlign: 'center' }}>
                  <div style={{ width: 56, height: 56, borderRadius: 999, background: 'var(--accent-tint)', color: 'var(--accent)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 20px' }}>
                    <Icon name="check" size={28}/>
                  </div>
                  <h3 style={{ fontSize: 22, marginBottom: 8 }}>Got it — talk soon.</h3>
                  <p style={{ fontSize: 14, color: 'var(--ink-3)', maxWidth: '38ch', margin: '0 auto' }}>Your details are now a row in our leads workbook. We'll reply within one business day.</p>
                </div>
              ) : (
                <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
                  <Field label="Name" required value={form.name} onChange={upd('name')} placeholder="Marcus Tan"/>
                  <div className="contact-form-row">
                    <Field label="Email" required type="email" value={form.email} onChange={upd('email')} placeholder="you@company.com"/>
                    <Field label="Phone" type="tel" value={form.phone} onChange={upd('phone')} placeholder="+91 95118 04590"/>
                  </div>
                  <SelectField
                    label="Interested product"
                    value={form.product}
                    onChange={upd('product')}
                    options={['Smart Panel AI', 'Kanban Board', 'Gantt Chart', 'Video Playlist', 'The full bundle', 'Just exploring']}
                  />
                  <Field
                    label="What are you trying to fix?"
                    multiline
                    value={form.description}
                    onChange={upd('description')}
                    placeholder="Which entities? Roughly how many users? What's the pain?"
                  />

                  <button
                    type="submit"
                    className="btn btn-primary btn-lg"
                    style={{ justifyContent: 'center', marginTop: 8, opacity: status === 'sending' ? 0.7 : 1 }}
                    disabled={status === 'sending'}
                  >
                    {status === 'sending' ? 'Sending…' : <>Send message <Icon name="arrow-right" size={16}/></>}
                  </button>

                  {status === 'error' && (
                    <div style={{ fontSize: 13, color: '#B91C1C', background: '#FEF2F2', border: '1px solid #FECACA', borderRadius: 8, padding: '10px 14px' }}>
                      {errMsg}
                    </div>
                  )}
                  <div style={{ fontSize: 12, color: 'var(--ink-4)', textAlign: 'center', marginTop: 4 }}>By submitting, you agree to our privacy policy. We'll never share your details.</div>
                </form>
              )}
            </div>

            <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 24, padding: '14px 18px', background: 'var(--surface-1)', border: '1px solid var(--border)', borderRadius: 'var(--radius-3)', fontSize: 13, color: 'var(--ink-3)' }}>
              <span style={{ width: 28, height: 28, borderRadius: 8, background: 'var(--accent-tint)', color: 'var(--accent)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                <Icon name="lock" size={14}/>
              </span>
              <span>Submissions land in our Dynawins leads workbook. No third-party CRM, no forwarding, no leaks.</span>
            </div>
          </div>
        </div>
      </section>
    </div>
  );
};

const ContactCard = ({ iconName, label, value, href, hint }) => {
  const inner = (
    <>
      <div style={{ width: 40, height: 40, borderRadius: 10, background: 'var(--accent-tint)', color: 'var(--accent)', display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 14 }}>
        <Icon name={iconName} size={18}/>
      </div>
      <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.04em', marginBottom: 6 }}>{label}</div>
      <div style={{ fontSize: 17, fontWeight: 600, color: 'var(--ink-1)', marginBottom: 6 }}>{value}</div>
      {hint && <div style={{ fontSize: 13, color: 'var(--ink-3)', lineHeight: 1.55 }}>{hint}</div>}
    </>
  );
  return href
    ? <a href={href} className="card contact-card" style={{ display: 'block', color: 'inherit' }}>{inner}</a>
    : <div className="card contact-card">{inner}</div>;
};

const Field = ({ label, placeholder, type = 'text', multiline = false, value, onChange, required }) => (
  <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
    <label style={{ fontSize: 13, fontWeight: 500, color: 'var(--ink-2)' }}>{label}{required && <span style={{ color: '#B91C1C' }}> *</span>}</label>
    {multiline
      ? <textarea rows={4} placeholder={placeholder} value={value} onChange={onChange} required={required} style={{ fontFamily: 'inherit', fontSize: 14, padding: '10px 12px', border: '1px solid var(--border)', borderRadius: 4, background: '#FFF', color: 'var(--ink-1)', outline: 'none', resize: 'vertical' }}/>
      : <input type={type} placeholder={placeholder} value={value} onChange={onChange} required={required} style={{ fontFamily: 'inherit', fontSize: 14, padding: '10px 12px', border: '1px solid var(--border)', borderRadius: 4, background: '#FFF', color: 'var(--ink-1)', outline: 'none' }}/>
    }
  </div>
);

const SelectField = ({ label, options, value, onChange }) => (
  <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
    <label style={{ fontSize: 13, fontWeight: 500, color: 'var(--ink-2)' }}>{label}</label>
    <select value={value} onChange={onChange} style={{ fontFamily: 'inherit', fontSize: 14, padding: '10px 12px', border: '1px solid var(--border)', borderRadius: 4, background: '#FFF', color: 'var(--ink-1)', outline: 'none' }}>
      {options.map((o, i) => <option key={i}>{o}</option>)}
    </select>
  </div>
);

window.ContactPage = ContactPage;
