/* v2 shared ContactForm — light theme. Posts to the same Apps Script
   endpoint as production; same validation, loading, error, success states. */

function Field({ label, required, error, children }) {
  return (
    <label className="block">
      <span className="block text-[12px] font-semibold text-[color:var(--ink-700)] mb-1.5">
        {label}{required && <span style={{ color: 'var(--brand)' }}> *</span>}
      </span>
      {children}
      {error && (
        <span className="block mt-1 text-[12px] font-medium text-rose-600">
          {error}
        </span>
      )}
    </label>
  );
}

function Spinner() {
  return (
    <span className="inline-block w-4 h-4 rounded-full border-2 border-white/40 border-t-white animate-spin" aria-hidden="true" />
  );
}

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const PHONE_RE = /^[+0-9()\-\s]{7,20}$/;

function validateClient(form, fields) {
  const errs = {};
  if (fields.includes('name')) {
    const v = (form.name || '').trim();
    if (!v) errs.name = 'Please enter your name.';
    else if (v.length < 2) errs.name = 'Name is too short.';
  }
  if (fields.includes('shop')) {
    if (!(form.shop || '').trim()) errs.shop = 'Please enter your shop or business name.';
  }
  if (fields.includes('phone')) {
    const v = (form.phone || '').trim();
    if (!v) errs.phone = 'Please enter a phone number.';
    else if (!PHONE_RE.test(v)) errs.phone = 'That phone number looks off.';
  }
  if (fields.includes('email')) {
    const v = (form.email || '').trim();
    if (v && !EMAIL_RE.test(v)) errs.email = 'That email address looks off.';
  }
  return errs;
}

function ContactForm(props) {
  const source = (props.source || 'home') + '-v2';
  const submitLabel = props.submitLabel || 'Book a consultation';
  const showMessage = props.showMessage !== false;
  const extra = props.extraField || null;

  const [form, setForm] = React.useState({
    name: '', shop: '', phone: '', email: '', message: '',
    ...(extra ? { [extra.key]: extra.defaultValue || '' } : {}),
  });
  const [errors, setErrors] = React.useState({});
  const [serverError, setServerError] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [submitted, setSubmitted] = React.useState(false);

  const set = (k, v) => {
    setForm(f => ({ ...f, [k]: v }));
    if (errors[k]) setErrors(e => ({ ...e, [k]: undefined }));
  };

  const onSubmit = async (e) => {
    e.preventDefault();
    setServerError('');
    const clientErrs = validateClient(form, ['name', 'shop', 'phone', 'email']);
    if (Object.keys(clientErrs).length) { setErrors(clientErrs); return; }
    setLoading(true);

    const endpoint = (window.AxiomConfig && window.AxiomConfig.FORM_ENDPOINT) || '';
    const payload = { ...form, source };

    if (!endpoint) {
      const subject = encodeURIComponent(`Website enquiry — ${form.name}${form.shop ? ' (' + form.shop + ')' : ''}`);
      const lines = [
        `Name: ${form.name}`,
        form.shop ? `Shop: ${form.shop}` : null,
        `Phone: ${form.phone}`,
        form.email ? `Email: ${form.email}` : null,
        extra && form[extra.key] ? `${extra.label}: ${form[extra.key]}` : null,
        form.message ? `\nMessage:\n${form.message}` : null,
      ].filter(Boolean).join('\n');
      const fallback = (window.AxiomConfig && window.AxiomConfig.CONTACT && window.AxiomConfig.CONTACT.emailHref) || 'mailto:hello@axiomds.co.za';
      window.location.href = `${fallback}?subject=${subject}&body=${encodeURIComponent(lines)}`;
      setLoading(false); setSubmitted(true); return;
    }

    try {
      const res = await fetch(endpoint, {
        method: 'POST',
        headers: { 'Content-Type': 'text/plain;charset=utf-8' },
        body: JSON.stringify(payload),
      });
      let data = {};
      try { data = await res.json(); } catch (_) {}
      if (!res.ok || data.ok === false) {
        setServerError((data.errors && data.errors[0]) || 'Something went wrong. Please try again, or WhatsApp us directly.');
        setLoading(false); return;
      }
      setSubmitted(true);
    } catch (err) {
      setServerError('Network error. Please check your connection and try again.');
    } finally {
      setLoading(false);
    }
  };

  if (submitted) {
    const firstName = (form.name || '').split(' ')[0] || 'there';
    const successTitle = props.successTitle ? props.successTitle(firstName) : `Thanks ${firstName} — we'll be in touch.`;
    const successBody = props.successBody ? props.successBody(form) : `We'll be in touch within one business day.`;
    return (
      <div className="py-8 text-center">
        <span className="inline-flex items-center justify-center w-14 h-14 rounded-full" style={{ background: 'var(--brand-soft)', color: 'var(--brand-hover)', border: '1px solid var(--brand-200)' }}>
          <Ax.Check className="w-7 h-7" strokeWidth={2.5} />
        </span>
        <h3 className="mt-4 text-[22px] font-semibold tracking-tight text-[color:var(--ink)]">{successTitle}</h3>
        <p className="mt-2 text-[14px] text-[color:var(--ink-500)] max-w-md mx-auto">{successBody}</p>
        <button
          type="button"
          onClick={() => {
            setSubmitted(false);
            setForm({ name: '', shop: '', phone: '', email: '', message: '', ...(extra ? { [extra.key]: extra.defaultValue || '' } : {}) });
            setErrors({}); setServerError('');
          }}
          className="mt-5 text-[13px] font-semibold text-[color:var(--ink-500)] hover:text-[color:var(--ink)] underline underline-offset-4"
        >
          Submit another
        </button>
      </div>
    );
  }

  return (
    <form onSubmit={onSubmit} noValidate className="space-y-4">
      <div className="grid sm:grid-cols-2 gap-3">
        <Field label="Your name" required error={errors.name}>
          <input type="text" value={form.name} onChange={e => set('name', e.target.value)} placeholder="Lerato Modise" className="ax-input" autoComplete="name" disabled={loading} />
        </Field>
        <Field label="Shop / business name" required error={errors.shop}>
          <input type="text" value={form.shop} onChange={e => set('shop', e.target.value)} placeholder="My Kota Place" className="ax-input" autoComplete="organization" disabled={loading} />
        </Field>
      </div>
      <div className="grid sm:grid-cols-2 gap-3">
        <Field label="Phone" required error={errors.phone}>
          <input type="tel" value={form.phone} onChange={e => set('phone', e.target.value)} placeholder="082 123 4567" className="ax-input" autoComplete="tel" disabled={loading} />
        </Field>
        <Field label="Email" error={errors.email}>
          <input type="email" value={form.email} onChange={e => set('email', e.target.value)} placeholder="you@example.co.za" className="ax-input" autoComplete="email" disabled={loading} />
        </Field>
      </div>

      {extra && extra.type === 'select' && (
        <Field label={extra.label}>
          <select value={form[extra.key]} onChange={e => set(extra.key, e.target.value)} className="ax-input" disabled={loading}>
            {(extra.options || []).map(o => <option key={o}>{o}</option>)}
          </select>
        </Field>
      )}
      {extra && extra.type === 'textarea' && (
        <Field label={extra.label}>
          <textarea rows="3" value={form[extra.key]} onChange={e => set(extra.key, e.target.value)} placeholder={extra.placeholder || ''} className="ax-input" disabled={loading} />
        </Field>
      )}

      {showMessage && (
        <Field label={props.messageLabel || 'Tell us a bit more (optional)'}>
          <textarea rows="3" value={form.message} onChange={e => set('message', e.target.value)} placeholder={props.messagePlaceholder || ''} className="ax-input" disabled={loading} />
        </Field>
      )}

      {serverError && (
        <div role="alert" className="rounded-lg px-4 py-3 text-[13px]" style={{ background: '#FEF2F2', border: '1px solid #FECACA', color: '#991B1B' }}>
          {serverError}
        </div>
      )}

      <div className="pt-2 flex flex-col sm:flex-row sm:items-center gap-3 sm:justify-between">
        <div className="text-[12px] text-[color:var(--ink-500)]">
          By submitting you agree to our{' '}
          <a href="privacy.html" className="underline text-[color:var(--ink-700)] hover:text-[color:var(--brand)]">Privacy Policy</a>.
        </div>
        <button type="submit" disabled={loading} className="btn-primary inline-flex items-center justify-center gap-2 rounded-full text-[15px] font-semibold px-6 py-3 disabled:opacity-70 disabled:cursor-not-allowed">
          {loading ? (<><Spinner />Sending…</>) : (<>{submitLabel}<Ax.ArrowRight className="w-4 h-4" /></>)}
        </button>
      </div>
    </form>
  );
}

function FaqItem({ q, a, defaultOpen }) {
  const [open, setOpen] = React.useState(!!defaultOpen);
  return (
    <div className={"border-b border-[color:var(--line)] " + (open ? "acc-open" : "")}>
      <button type="button" onClick={() => setOpen(v => !v)} className="w-full flex items-center justify-between gap-4 py-5 text-left group" aria-expanded={open}>
        <span className="text-[16px] sm:text-[17px] font-semibold tracking-tight text-[color:var(--ink)] pr-4 group-hover:text-[color:var(--brand-hover)] transition-colors">{q}</span>
        <span className={"acc-icon shrink-0 inline-flex items-center justify-center w-8 h-8 rounded-full border bg-white text-[color:var(--ink-700)] " + (open ? "" : "border-[color:var(--line)]")}>
          <Ax.ChevronDown className="w-4 h-4" />
        </span>
      </button>
      <div className="grid transition-all duration-300 ease-out" style={{ gridTemplateRows: open ? '1fr' : '0fr', opacity: open ? 1 : 0 }}>
        <div className="overflow-hidden">
          <p className="pb-6 pr-12 text-[15px] text-[color:var(--ink-700)] leading-relaxed">{a}</p>
        </div>
      </div>
    </div>
  );
}

function ContactDetails({ dark }) {
  const c = (window.AxiomConfig && window.AxiomConfig.CONTACT) || {};
  const linkCls = dark
    ? "flex items-center gap-3 text-[14px] text-white/90 hover:text-white"
    : "flex items-center gap-3 text-[14px] text-[color:var(--ink-700)] hover:text-[color:var(--ink)]";
  const plainCls = dark
    ? "flex items-center gap-3 text-[14px] text-white/90"
    : "flex items-center gap-3 text-[14px] text-[color:var(--ink-700)]";
  const iconColor = dark ? '#FFFFFF' : 'var(--brand)';
  return (
    <div className="mt-8 space-y-3">
      {c.phone && (
        <a href={c.phoneHref || '#'} className={linkCls}>
          <Ax.Phone className="w-4 h-4" style={{ color: iconColor }} />
          {c.phone}
        </a>
      )}
      {c.email && (
        <a href={c.emailHref || '#'} className={linkCls}>
          <Ax.Mail className="w-4 h-4" style={{ color: iconColor }} />
          {c.email}
        </a>
      )}
      {c.location && (
        <div className={plainCls}>
          <Ax.MapPin className="w-4 h-4" style={{ color: iconColor }} />
          {c.location}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { ContactForm, Field, FaqItem, ContactDetails });
