// Business lead-capture form — built on TanStack Form (window.TanStackForm),
// opened by every "for business" CTA. Bilingual: English by default, Arabic when
// ctx.lang === 'ar'. Submits to a Google Sheet via a bound Apps Script web app.

const { useState: leadS, useEffect: leadE } = React;

const LEAD_EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

// Signups are written to a Google Sheet via a bound Apps Script web app.
const SHEET_ENDPOINT = 'https://script.google.com/macros/s/AKfycbycvPmy-yr0EdPqjl7id36Iy06BJYVEf3e7hK2rziNrw9cjNp0WXD9mwxPrwIj2g9josQ/exec';
async function submitLead(payload) {
  // Apps Script sends no CORS headers and 302-redirects to its sandbox URL, so a
  // no-cors text/plain POST (a "simple request", no preflight) is what appends the row.
  await fetch(SHEET_ENDPOINT, {
    method: 'POST',
    mode: 'no-cors',
    headers: { 'Content-Type': 'text/plain;charset=utf-8' },
    body: JSON.stringify(payload),
  });
  return { ok: true };
}

const FORM_T = {
  en: {
    sub: 'A few details and a real person replies — usually within two days.',
    fields: {
      name:    { label: 'Your name',          ph: 'Maya Okafor' },
      email:   { label: 'Work email',         ph: 'you@brand.com' },
      company: { label: 'Company / brand',    ph: 'Your brand' },
      country: { label: "Where you're based", ph: 'e.g. UAE' },
      product: { label: 'What you make',      ph: 'e.g. cold-pressed olive oil' },
      message: { label: 'Anything else?',     ph: 'Volumes, timing, questions…' },
    },
    required: (l) => `${l} is required`, invalidEmail: 'Enter a valid email',
    send: 'Send to blyzr', sending: 'Sending…',
    error: "Couldn't send just now — please try again in a moment.",
    fine: "We'll only use this to reply to your enquiry. No spam, ever.",
    done_t: "Thanks — we've got it.", done_d: 'A real person from the blyzr team will be in touch, usually within two days.', close: 'Close',
    fallbackInterest: 'blyzr for business', fallbackTitle: 'Tell us what you make',
  },
  ar: {
    sub: 'تفاصيلُ قليلة ويردّ عليك شخصٌ حقيقي — خلال يومين عادةً.',
    fields: {
      name:    { label: 'اسمك',              ph: 'مثلًا: مايا' },
      email:   { label: 'البريد الإلكتروني', ph: 'you@brand.com' },
      company: { label: 'الشركة / العلامة',  ph: 'علامتك' },
      country: { label: 'أين مقرّك',         ph: 'مثلًا: الإمارات' },
      product: { label: 'ماذا تصنع',         ph: 'مثلًا: زيت زيتون معصور على البارد' },
      message: { label: 'أيُّ شيءٍ آخر؟',     ph: 'الكميات، التوقيت، الأسئلة…' },
    },
    required: (l) => `${l} مطلوب`, invalidEmail: 'أدخِل بريدًا إلكترونيًا صحيحًا',
    send: 'أرسِل إلى بليزر', sending: 'جارٍ الإرسال…',
    error: 'تعذّر الإرسال الآن — حاوِل مرة أخرى بعد لحظات.',
    fine: 'نستخدم هذا فقط للردّ على طلبك. لا رسائل مزعجة أبدًا.',
    done_t: 'شكرًا — وصلنا طلبك.', done_d: 'سيتواصل معك شخصٌ حقيقي من فريق بليزر، خلال يومين عادةً.', close: 'إغلاق',
    fallbackInterest: 'بليزر للأعمال', fallbackTitle: 'أخبِرنا بما تصنع',
  },
};

const BizLeadField = ({ form, name, label, type, required, placeholder, textarea, autoFocus, L }) => (
  <form.Field
    name={name}
    validators={{
      onChange: ({ value }) => {
        if (required && !String(value || '').trim()) return L.required(label);
        if (name === 'email' && value && !LEAD_EMAIL_RE.test(value)) return L.invalidEmail;
        return undefined;
      },
    }}
  >
    {(field) => {
      const err = field.state.meta.errors?.[0];
      const show = field.state.meta.isTouched && err;
      const common = {
        id: `lf-${name}`,
        value: field.state.value,
        placeholder,
        dir: name === 'email' ? 'ltr' : undefined,
        onChange: (e) => field.handleChange(e.target.value),
        onBlur: field.handleBlur,
        className: `lead-input ${textarea ? 'lead-textarea' : ''} ${show ? 'bad' : ''}`,
      };
      return (
        <div className="lead-field">
          <label className="lead-label" htmlFor={`lf-${name}`}>{label}{required && <span className="lead-req">*</span>}</label>
          {textarea ? <textarea rows={3} {...common}/> : <input type={type || 'text'} autoFocus={autoFocus} {...common}/>}
          {show && <div className="lead-err">{err}</div>}
        </div>
      );
    }}
  </form.Field>
);

const BusinessLeadForm = ({ ctx, onClose }) => {
  const [done, setDone] = leadS(false);
  const [sendError, setSendError] = leadS(false);
  const lang = ctx.lang === 'ar' ? 'ar' : 'en';
  const L = FORM_T[lang];
  const F = L.fields;
  const dir = lang === 'ar' ? 'rtl' : 'ltr';

  leadE(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    const canvas = document.querySelector('.canvas');
    const prev = canvas ? canvas.style.overflow : '';
    if (canvas) canvas.style.overflow = 'hidden';
    return () => { window.removeEventListener('keydown', onKey); if (canvas) canvas.style.overflow = prev; };
  }, []);

  const form = window.TanStackForm.useForm({
    defaultValues: { name: '', email: '', company: '', country: '', product: '', message: '' },
    onSubmit: async ({ value }) => {
      setSendError(false);
      try {
        await submitLead({ ...value, interest: ctx.interest || null, kind: ctx.kind || 'apply', summary: ctx.summary || null });
        setDone(true);
      } catch (err) {
        setSendError(true);
      }
    },
  });

  return (
    <div className="lead-overlay" onClick={onClose}>
      <div className="lead-card" dir={dir} onClick={(e) => e.stopPropagation()}>
        <button className="lead-close" onClick={onClose} aria-label="Close">×</button>

        {done ? (
          <div className="lead-success">
            <OrbMini/>
            <div className="lead-success-t">{L.done_t}</div>
            <div className="lead-success-d">{L.done_d}</div>
            <button className="btn btn-outline" onClick={onClose}>{L.close}</button>
          </div>
        ) : (
          <>
            <div className="eyebrow" style={{ marginBottom: 8 }}>{ctx.interest || L.fallbackInterest}</div>
            <h3 className="lead-title">{ctx.title || L.fallbackTitle}</h3>
            <p className="lead-sub">{L.sub}</p>
            {ctx.summary && <div className={`lead-summary ${lang === 'ar' ? '' : 'mono'}`} dir={lang === 'ar' ? 'rtl' : 'ltr'}>{ctx.summary}</div>}

            <form onSubmit={(e) => { e.preventDefault(); e.stopPropagation(); form.handleSubmit(); }}>
              <div className="lead-row">
                <BizLeadField form={form} name="name" label={F.name.label} required autoFocus placeholder={F.name.ph} L={L}/>
                <BizLeadField form={form} name="email" label={F.email.label} type="email" required placeholder={F.email.ph} L={L}/>
              </div>
              <div className="lead-row">
                <BizLeadField form={form} name="company" label={F.company.label} required placeholder={F.company.ph} L={L}/>
                <BizLeadField form={form} name="country" label={F.country.label} placeholder={F.country.ph} L={L}/>
              </div>
              <BizLeadField form={form} name="product" label={F.product.label} placeholder={F.product.ph} L={L}/>
              <BizLeadField form={form} name="message" label={F.message.label} textarea placeholder={F.message.ph} L={L}/>

              <form.Subscribe selector={(s) => [s.canSubmit, s.isSubmitting]}>
                {([canSubmit, isSubmitting]) => (
                  <button type="submit" className="btn btn-accent btn-lg" style={{ width: '100%', justifyContent: 'center', marginTop: 6 }} disabled={!canSubmit || isSubmitting}>
                    {isSubmitting ? L.sending : L.send} <Icon.arrow style={{ width: 14, height: 14, transform: dir === 'rtl' ? 'scaleX(-1)' : 'none' }}/>
                  </button>
                )}
              </form.Subscribe>
              {sendError && <div className="lead-err" style={{ textAlign: 'center', marginTop: 10 }}>{L.error}</div>}
              <p className="lead-fine">{L.fine}</p>
            </form>
          </>
        )}
      </div>
    </div>
  );
};

window.BusinessLeadForm = BusinessLeadForm;
