// Contact page — CRO-optimized lead form

// ← Paste your Apps Script Web App URL here after deploying (see README / setup instructions)
const WEBHOOK_URL = 'https://script.google.com/macros/s/AKfycbwvjYBBewj_rHSLQk0R3Sw9F559_EbvaqobuZbOa-w03_UjoLm_Ld4Z0yv9UXdH_8Jm/exec';

const { useState: useStateC } = React;

const DIAL_CODES = [
  { code: '+91',  label: 'IN +91',  country: 'India',      min: 10, max: 10 },
  { code: '+1',   label: 'US +1',   country: 'USA/Canada', min: 10, max: 10 },
  { code: '+44',  label: 'UK +44',  country: 'UK',         min: 10, max: 10 },
  { code: '+971', label: 'AE +971', country: 'UAE',        min: 9,  max: 9  },
  { code: '+61',  label: 'AU +61',  country: 'Australia',  min: 9,  max: 9  },
  { code: '+65',  label: 'SG +65',  country: 'Singapore',  min: 8,  max: 8  },
  { code: '+974', label: 'QA +974', country: 'Qatar',      min: 8,  max: 8  },
  { code: '+965', label: 'KW +965', country: 'Kuwait',     min: 8,  max: 8  },
  { code: '+968', label: 'OM +968', country: 'Oman',       min: 8,  max: 8  },
  { code: '+973', label: 'BH +973', country: 'Bahrain',    min: 8,  max: 8  },
];

const TYPO_TLDS = ['ocm','cmo','con','cpm','nte','ogr','coim','comn','cob','gmai','gamil','yahooo','gnail'];

function validatePhone(digits, dialInfo) {
  if (!digits) return 'Phone number is required';
  if (digits.length !== dialInfo.min) return `Enter a valid ${dialInfo.min}-digit mobile number`;
  if (dialInfo.code === '+91' && !/^[6-9]/.test(digits)) return 'Indian mobile numbers must start with 6, 7, 8 or 9';
  // Reject all same digit: 9999999999
  if (/^(.)\1+$/.test(digits)) return 'Enter a real mobile number';
  // Reject sequential ascending / descending: 1234567890, 9876543210
  const d = digits.split('').map(Number);
  const asc  = d.every((n, i) => i === 0 || n === (d[i-1] + 1) % 10);
  const desc = d.every((n, i) => i === 0 || n === (d[i-1] - 1 + 10) % 10);
  if (asc || desc) return 'Enter a real mobile number';
  return null;
}

function validateEmail(v) {
  const s = v.trim().toLowerCase();
  if (!s) return 'Email is required';
  const atIdx = s.lastIndexOf('@');
  if (atIdx < 1) return 'Enter a valid email address';
  const local  = s.slice(0, atIdx);
  const domain = s.slice(atIdx + 1);
  if (!domain.includes('.')) return 'Enter a valid email address';
  const parts = domain.split('.');
  const tld  = parts[parts.length - 1];
  const host = parts[parts.length - 2] || '';
  if (!/^[a-z]{2,10}$/.test(tld)) return 'Enter a valid email address';
  if (host.length < 2) return 'Enter a valid email address';
  if (local.length < 2 || /^(.)\1+$/.test(local)) return 'Enter a valid email address';
  if (TYPO_TLDS.includes(tld)) {
    const fix = ['ocm','cmo','cob','comn','coim'].includes(tld) ? 'com' : tld === 'nte' ? 'net' : ['ogr','org'].includes(tld) ? 'org' : 'com';
    return `Did you mean .${fix}? Please check your email`;
  }
  return null;
}

const ContactHero = () => (
  <section className="pt-28 sm:pt-40 pb-12">
    <div className="mx-auto max-w-[1320px] px-5 sm:px-8">
      <div className="mb-10 reveal"><Eyebrow>Begin · A Conversation</Eyebrow></div>
      <h1 className="font-display text-[36px] sm:text-[56px] lg:text-[90px] leading-[0.96] tracking-tightest reveal">
        Start with a<br/><span className="italic text-accent-soft">single question.</span>
      </h1>
      <p className="mt-8 text-bone-50/60 text-[15px] leading-relaxed max-w-xl reveal">
        Tell us what you're imagining — a home, an investment, a brand collaboration — and we'll bring the rest.
      </p>
    </div>
  </section>
);

const Field = ({ label, error, ...rest }) => (
  <label className="block">
    <span className="block text-[11px] uppercase tracking-[0.22em] text-bone-50/45 mb-2">{label}</span>
    <input
      className="field w-full rounded-xl px-4 py-3.5 text-[15px]"
      style={error ? { borderColor: 'rgba(248,113,113,0.7)' } : {}}
      {...rest}
    />
    {error && <span className="block mt-1.5 text-[12px] text-red-400">{error}</span>}
  </label>
);

const ContactForm = () => {
  const [intent, setIntent]     = useStateC('Investor');
  const [dialCode, setDialCode] = useStateC('+91');
  const [phone, setPhone]       = useStateC('');
  const [errors, setErrors]     = useStateC({});
  const [submitting, setSubmitting] = useStateC(false);
  const [done, setDone]         = useStateC(false);
  const [err, setErr]           = useStateC(null);

  const dialInfo = DIAL_CODES.find(d => d.code === dialCode) || DIAL_CODES[0];

  const handlePhoneInput = (e) => {
    const digits = e.target.value.replace(/\D/g, '').slice(0, dialInfo.max);
    setPhone(digits);
    if (errors.phone) setErrors(prev => ({ ...prev, phone: null }));
  };

  const handleDialChange = (e) => {
    setDialCode(e.target.value);
    setPhone('');
    setErrors(prev => ({ ...prev, phone: null }));
  };

  const handlePhoneBlur = () => {
    const phoneErr = validatePhone(phone, dialInfo);
    setErrors(prev => ({ ...prev, phone: phoneErr }));
  };

  const handleEmailBlur = (e) => {
    const emailErr = validateEmail(e.target.value);
    setErrors(prev => ({ ...prev, email: emailErr }));
  };

  const handleEmailChange = () => {
    if (errors.email) setErrors(prev => ({ ...prev, email: null }));
  };

  const submit = async (e) => {
    e.preventDefault();
    if (submitting) return;

    const fd = new FormData(e.currentTarget);
    const newErrors = {};

    const phoneErr = validatePhone(phone, dialInfo);
    if (phoneErr) newErrors.phone = phoneErr;

    const emailErr = validateEmail(fd.get('email') || '');
    if (emailErr) newErrors.email = emailErr;

    if (Object.keys(newErrors).length > 0) {
      setErrors(newErrors);
      return;
    }

    setSubmitting(true);
    setErr(null);
    setErrors({});

    const payload = Object.fromEntries(fd.entries());
    payload.phone = `${dialCode} ${phone}`;
    payload.intent = intent;
    payload.source = 'amgrealty.in';
    payload.submitted_at = new Date().toISOString();

    try {
      await fetch(WEBHOOK_URL, {
        method: 'POST',
        mode: 'no-cors',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });
      window.dataLayer = window.dataLayer || [];
      window.dataLayer.push({ event: 'lead_submit', ...payload });
      setDone(true);
    } catch (ex) {
      setErr('Could not send. Please try again or call us directly.');
    } finally {
      setSubmitting(false);
    }
  };

  if (done) {
    return (
      <div className="glass rounded-3xl p-10 text-center" data-track="lead-submit-success">
        <div className="h-14 w-14 rounded-full bg-accent/15 grid place-items-center text-accent mx-auto"><Icon.Check size={22}/></div>
        <h3 className="font-display text-[40px] mt-6">Thank you.</h3>
        <p className="mt-3 text-bone-50/60 text-[15px] max-w-md mx-auto">A member of our team will be in touch within one working day.</p>
      </div>
    );
  }

  return (
    <form
      noValidate
      onSubmit={submit}
      data-track="lead-form"
      data-form="amg-lead-capture"
      data-webhook="n8n"
      className="glass rounded-3xl p-7 sm:p-10"
    >
      <div className="flex flex-wrap gap-2 mb-8" role="tablist" aria-label="Enquiry intent">
        {['Investor', 'Residence', 'Brand Partner', 'Press'].map((t) => (
          <button
            type="button"
            key={t}
            onClick={() => setIntent(t)}
            data-track={`lead-intent-${t.replace(/\s/g,'-').toLowerCase()}`}
            className={`px-4 py-2 rounded-full text-[12px] tracking-wide border transition ${intent === t ? 'border-accent text-accent bg-accent/10' : 'border-bone-50/15 text-bone-50/65 hover:text-bone-50 hover:border-bone-50/30'}`}
          >
            {t}
          </button>
        ))}
      </div>

      <input type="hidden" name="intent" value={intent}/>
      <input type="hidden" name="utm_source" value=""/>
      <input type="hidden" name="utm_medium" value=""/>
      <input type="hidden" name="utm_campaign" value=""/>
      <input type="hidden" name="fbclid" value=""/>
      <input type="text" name="company" tabIndex="-1" autoComplete="off" className="hidden" aria-hidden="true"/>

      <div className="grid sm:grid-cols-2 gap-5">
        <Field label="Full name" name="name" required placeholder="Your name" data-track="lead-field-name"/>

        {/* Phone — country code selector + digits-only input */}
        <div>
          <span className="block text-[11px] uppercase tracking-[0.22em] text-bone-50/45 mb-2">Phone</span>
          <div
            className="field flex rounded-xl overflow-hidden p-0"
            style={errors.phone ? { borderColor: 'rgba(248,113,113,0.7)' } : {}}
          >
            <select
              value={dialCode}
              onChange={handleDialChange}
              aria-label="Country dial code"
              className="bg-transparent border-r border-white/10 pl-3 pr-2 py-3.5 text-[13px] text-bone-50/80 focus:outline-none cursor-pointer flex-shrink-0 appearance-none"
            >
              {DIAL_CODES.map(d => (
                <option key={d.label} value={d.code} className="bg-ink-900 text-bone-50">{d.label}</option>
              ))}
            </select>
            <input
              type="tel"
              inputMode="numeric"
              value={phone}
              onChange={handlePhoneInput}
              onBlur={handlePhoneBlur}
              placeholder={`${dialInfo.min} digits`}
              className="flex-1 bg-transparent px-4 py-3.5 text-[15px] text-bone-50 placeholder-bone-50/30 focus:outline-none min-w-0"
              data-track="lead-field-phone"
              aria-label="Phone number"
            />
            <span className={`self-center pr-3 text-[11px] tabular-nums ${phone.length === dialInfo.min ? 'text-accent' : 'text-bone-50/30'}`}>
              {phone.length}/{dialInfo.min}
            </span>
          </div>
          {errors.phone && <span className="block mt-1.5 text-[12px] text-red-400">{errors.phone}</span>}
        </div>

        <Field
          label="Email"
          name="email"
          type="email"
          required
          placeholder="you@domain.com"
          error={errors.email}
          onBlur={handleEmailBlur}
          onChange={handleEmailChange}
          data-track="lead-field-email"
        />
        <label className="block">
          <span className="block text-[11px] uppercase tracking-[0.22em] text-bone-50/45 mb-2">City</span>
          <select name="city" className="field w-full rounded-xl px-4 py-3.5 text-[15px]" data-track="lead-field-city">
            <option value="" className="bg-ink-900">Select your city</option>
            <optgroup label="Punjab" className="bg-ink-900">
              <option className="bg-ink-900">Ludhiana</option>
              <option className="bg-ink-900">Chandigarh</option>
              <option className="bg-ink-900">Amritsar</option>
              <option className="bg-ink-900">Jalandhar</option>
              <option className="bg-ink-900">Patiala</option>
              <option className="bg-ink-900">Bathinda</option>
              <option className="bg-ink-900">Mohali</option>
            </optgroup>
            <optgroup label="North India" className="bg-ink-900">
              <option className="bg-ink-900">Delhi</option>
              <option className="bg-ink-900">Gurugram</option>
              <option className="bg-ink-900">Noida</option>
              <option className="bg-ink-900">Ghaziabad</option>
            </optgroup>
            <optgroup label="Other" className="bg-ink-900">
              <option className="bg-ink-900">Mumbai</option>
              <option className="bg-ink-900">Bengaluru</option>
              <option className="bg-ink-900">Hyderabad</option>
              <option className="bg-ink-900">Pune</option>
              <option className="bg-ink-900">Other</option>
            </optgroup>
          </select>
        </label>
      </div>

      <label className="block mt-5">
        <span className="block text-[11px] uppercase tracking-[0.22em] text-bone-50/45 mb-2">Project of interest</span>
        <select name="project" className="field w-full rounded-xl px-4 py-3.5 text-[15px]" data-track="lead-field-project">
          <option className="bg-ink-900">No preference</option>
          <option className="bg-ink-900">Palm Marina</option>
          <option className="bg-ink-900">One AMG</option>
          <option className="bg-ink-900">Palm City Ph II</option>
          <option className="bg-ink-900">Palm Heights</option>
          <option className="bg-ink-900">Maurya Greens</option>
          <option className="bg-ink-900">Palm Garden</option>
          <option className="bg-ink-900">Palm City</option>
          <option className="bg-ink-900">Florence</option>
        </select>
      </label>

      <label className="block mt-5">
        <span className="block text-[11px] uppercase tracking-[0.22em] text-bone-50/45 mb-2">A single question to begin</span>
        <textarea name="message" rows="4" placeholder="Tell us what you're imagining…" className="field w-full rounded-xl px-4 py-3.5 text-[15px] resize-none" data-track="lead-field-message"/>
      </label>

      <label className="mt-6 flex items-start gap-3 text-[12px] text-bone-50/55">
        <input type="checkbox" name="consent" required className="mt-0.5 accent-accent"/>
        <span>I consent to be contacted by Ashok Malhotra Group.</span>
      </label>

      {err && <div className="mt-5 text-[13px] text-red-300">{err}</div>}

      <div className="mt-8 flex items-center justify-between flex-wrap gap-4">
        <div className="text-[11px] uppercase tracking-[0.22em] text-bone-50/40">
          {submitting ? 'Sending…' : 'Replies within 1 working day'}
        </div>
        <button
          type="submit"
          disabled={submitting}
          data-track="lead-submit"
          data-form="amg-lead-capture"
          className="btn group inline-flex items-center gap-2 rounded-full bg-bone-50 text-ink-950 px-7 py-4 text-[13px] font-medium tracking-wide hover:bg-accent-soft disabled:opacity-60"
        >
          Start the Conversation
          <Icon.Send size={15} className="transition-transform group-hover:translate-x-0.5"/>
        </button>
      </div>
    </form>
  );
};

const ContactDetails = () => (
  <div className="space-y-6">
    <div className="glass-light rounded-3xl p-8">
      <div className="text-accent"><Icon.MapPin size={18}/></div>
      <div className="font-display text-[24px] mt-4">Corporate Office</div>
      <address className="not-italic text-bone-50/70 text-[14px] leading-relaxed mt-3">
        Shop No 14-15, Palm Heights,<br/>
        VPO Jaspal Bangar, Sidhwan Canal Road,<br/>
        Ludhiana – 141122
      </address>
      <a href="https://maps.google.com/?q=Palm+Heights+Ludhiana" target="_blank" rel="noreferrer" data-track="contact-directions" className="ulink mt-5 inline-flex items-center gap-2 text-[12px] text-bone-50/80">
        Get directions <Icon.ArrowUpRight size={13}/>
      </a>
    </div>

    <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
      <a href="tel:+917087215304" data-track="contact-call" className="glass-light rounded-3xl p-6 hover:bg-bone-50/[0.08] transition">
        <div className="text-accent"><Icon.Phone size={16}/></div>
        <div className="text-[11px] uppercase tracking-[0.22em] text-bone-50/45 mt-3">Call</div>
        <div className="font-display text-[18px] mt-2">+91 70872 15304</div>
      </a>
      <a href="mailto:info@amgrealty.in" data-track="contact-email" className="glass-light rounded-3xl p-6 hover:bg-bone-50/[0.08] transition">
        <div className="text-accent"><Icon.Mail size={16}/></div>
        <div className="text-[11px] uppercase tracking-[0.22em] text-bone-50/45 mt-3">Write</div>
        <div className="font-display text-[18px] mt-2 break-all">info@amgrealty.in</div>
      </a>
    </div>

    <div className="glass-light rounded-3xl p-8">
      <div className="text-[11px] uppercase tracking-[0.22em] text-bone-50/45">Studio hours</div>
      <ul className="mt-4 space-y-2 text-[14px] text-bone-50/75">
        <li className="flex justify-between"><span>Mon — Sat</span><span>09:30 — 18:00</span></li>
        <li className="flex justify-between text-bone-50/45"><span>Sunday</span><span>Closed</span></li>
      </ul>
    </div>
  </div>
);

function ContactPage() {
  useReveal();
  return (
    <main className="page-enter">
      <ContactHero/>
      <section className="pb-24">
        <div className="mx-auto max-w-[1320px] px-5 sm:px-8 grid lg:grid-cols-12 gap-8 items-start">
          <div className="lg:col-span-7 reveal"><ContactForm/></div>
          <div className="lg:col-span-5 reveal"><ContactDetails/></div>
        </div>
      </section>

      <section className="pb-24">
        <div className="mx-auto max-w-[1320px] px-5 sm:px-8">
          <div className="rounded-3xl overflow-hidden border border-bone-50/10" style={{ height: '450px' }}>
            <iframe
              src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d844.7840606852913!2d75.8936486345473!3d30.834193754543616!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x391a825b5d5de2ff%3A0x7729044119727a21!2sAshok%20Malhotra%20Group!5e1!3m2!1sen!2sin!4v1778740757495!5m2!1sen!2sin"
              width="100%"
              height="100%"
              style={{ border: 0, display: 'block' }}
              allowFullScreen=""
              loading="lazy"
              referrerPolicy="no-referrer-when-downgrade"
              title="Ashok Malhotra Group — Palm Heights, Ludhiana"
            />
          </div>
        </div>
      </section>
    </main>
  );
}

window.ContactPage = ContactPage;
