// Two lead-capture forms — Contact + Valuation. No HTML <form> tags; onClick + state.

const { useState: useStateF } = React;

// Demo mode — leads are logged to the browser console.
// When the backend is ready, replace this with a real fetch() to /api/lead.
async function deliverLead(payload, subject) {
  console.log('[EC Lead]', subject, payload);
  await new Promise((r) => setTimeout(r, 600));
}

// ============================================================
// CONTACT FORM
// ============================================================
function ContactForm({ lang, t }) {
  const isKo = lang === 'ko';
  const [name, setName] = useStateF('');
  const [email, setEmail] = useStateF('');
  const [phone, setPhone] = useStateF('');
  const [interest, setInterest] = useStateF('');
  const [message, setMessage] = useStateF('');
  const [errors, setErrors] = useStateF({});
  const [submitted, setSubmitted] = useStateF(false);
  const [sending, setSending] = useStateF(false);
  const [sendError, setSendError] = useStateF('');

  const submit = async () => {
    const e = {};
    if (!name.trim()) e.name = t.contact.errors.name;
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email.trim())) e.email = t.contact.errors.email;
    if (!phone.trim()) e.phone = t.contact.errors.phone;
    if (!interest) e.interest = t.contact.errors.interest;
    setErrors(e);
    if (Object.keys(e).length > 0) return;
    setSending(true);
    setSendError('');
    try {
      await deliverLead(
        { name, email, phone, interest, message, source: 'EC Real Estate — Contact' },
        `New lead — ${name} · ${interest}`
      );
      setSubmitted(true);
    } catch (err) {
      setSendError(lang === 'ko' ? '전송 실패. 잠시 후 다시 시도해 주세요.' : 'Submission failed. Please try again.');
    } finally {
      setSending(false);
    }
  };

  const reset = () => {
    setName(''); setEmail(''); setPhone(''); setInterest(''); setMessage('');
    setErrors({}); setSubmitted(false); setSendError('');
  };

  return (
    <Section id="contact" className="py-24 md:py-32 lg:py-40">
      <div className="grid grid-cols-12 gap-8 md:gap-12">
        <div className="col-span-12 lg:col-span-5">
          <Reveal>
            <Eyebrow className="mb-8">{t.contact.eyebrow}</Eyebrow>
          </Reveal>
          <Reveal delay={140}>
            <h2 className={`display ${isKo ? 'lang-ko' : ''} text-ink text-[11vw] md:text-[7vw] lg:text-[4.6vw] xl:text-[4.2vw] leading-[0.98] mb-8`}>
              <span className="block">{t.contact.title}</span>
              <span className="block display-italic text-accent-deep">{t.contact.titleItalic}</span>
            </h2>
          </Reveal>
          <Reveal delay={260}>
            <p className={`text-ink/70 text-base md:text-lg leading-[1.6] max-w-md mb-10 ${isKo ? 'lang-ko' : ''}`}>
              {t.contact.sub}
            </p>
          </Reveal>
          <Reveal delay={340}>
            <div className="space-y-3">
              <a href="tel:+14698190066" className="flex items-center gap-4 text-ink hover:text-accent-deep transition-colors group">
                <IconPhone size={16} className="text-ink/40 group-hover:text-accent-deep" />
                <span className="num text-sm">(469) 819-0066 · Evelyn</span>
              </a>
              <a href="tel:+14692130049" className="flex items-center gap-4 text-ink hover:text-accent-deep transition-colors group">
                <IconPhone size={16} className="text-ink/40 group-hover:text-accent-deep" />
                <span className="num text-sm">(469) 213-0049 · Amy</span>
              </a>
            </div>
          </Reveal>
        </div>

        <div className="col-span-12 lg:col-span-7">
          <Reveal delay={200}>
            {submitted ? (
              <div className="bg-bone-soft p-10 md:p-14 lg:p-16 min-h-[420px] flex flex-col justify-center">
                <IconCheck size={40} className="text-accent-deep mb-6" strokeWidth={1} />
                <div className={`display ${isKo ? 'lang-ko' : ''} text-ink text-4xl md:text-5xl mb-4 leading-none`}>
                  {t.contact.successTitle}
                </div>
                <p className={`text-ink/70 text-base md:text-lg leading-[1.55] max-w-md mb-8 ${isKo ? 'lang-ko' : ''}`}>
                  {t.contact.successSub}
                </p>
                <button type="button" onClick={reset} className={`link-under self-start text-sm text-ink/70 hover:text-ink ${isKo ? 'lang-ko' : ''}`}>
                  {t.contact.reset} <span aria-hidden="true">→</span>
                </button>
              </div>
            ) : (
              <div className="bg-bone-soft p-8 md:p-12 lg:p-14">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-x-8 gap-y-6">
                  <div>
                    <label className={`eyebrow text-ink/55 block mb-2 ${isKo ? 'lang-ko' : ''}`}>{t.contact.name}</label>
                    <input
                      type="text"
                      value={name}
                      onChange={(e) => { setName(e.target.value); if (errors.name) setErrors({...errors, name: undefined}); }}
                      className={`field ${isKo ? 'lang-ko' : ''}`}
                      placeholder={isKo ? '홍길동' : 'Jane Doe'}
                    />
                    {errors.name ? <div className={`text-[11px] text-accent-deep mt-2 ${isKo ? 'lang-ko' : ''}`}>{errors.name}</div> : null}
                  </div>

                  <div>
                    <label className={`eyebrow text-ink/55 block mb-2 ${isKo ? 'lang-ko' : ''}`}>{t.contact.email}</label>
                    <input
                      type="email"
                      value={email}
                      onChange={(e) => { setEmail(e.target.value); if (errors.email) setErrors({...errors, email: undefined}); }}
                      className="field"
                      placeholder="you@email.com"
                    />
                    {errors.email ? <div className={`text-[11px] text-accent-deep mt-2 ${isKo ? 'lang-ko' : ''}`}>{errors.email}</div> : null}
                  </div>

                  <div>
                    <label className={`eyebrow text-ink/55 block mb-2 ${isKo ? 'lang-ko' : ''}`}>{t.contact.phone}</label>
                    <input
                      type="tel"
                      value={phone}
                      onChange={(e) => { setPhone(e.target.value); if (errors.phone) setErrors({...errors, phone: undefined}); }}
                      className="field num"
                      placeholder="(469) 000-0000"
                    />
                    {errors.phone ? <div className={`text-[11px] text-accent-deep mt-2 ${isKo ? 'lang-ko' : ''}`}>{errors.phone}</div> : null}
                  </div>

                  <div>
                    <label className={`eyebrow text-ink/55 block mb-2 ${isKo ? 'lang-ko' : ''}`}>{t.contact.interest}</label>
                    <div className="flex flex-wrap gap-2 pt-2">
                      {t.contact.interests.map((opt) => (
                        <button
                          key={opt}
                          type="button"
                          onClick={() => { setInterest(opt); if (errors.interest) setErrors({...errors, interest: undefined}); }}
                          className={`px-4 py-2 text-[12px] tracking-wider-2 uppercase border transition-all ${interest === opt ? 'bg-ink text-bone border-ink' : 'border-ink/15 text-ink/55 hover:border-ink/40 hover:text-ink'} ${isKo ? 'lang-ko' : ''}`}
                          aria-pressed={interest === opt}
                        >
                          {opt}
                        </button>
                      ))}
                    </div>
                    {errors.interest ? <div className={`text-[11px] text-accent-deep mt-2 ${isKo ? 'lang-ko' : ''}`}>{errors.interest}</div> : null}
                  </div>

                  <div className="md:col-span-2">
                    <label className={`eyebrow text-ink/55 block mb-2 ${isKo ? 'lang-ko' : ''}`}>{t.contact.message}</label>
                    <textarea
                      value={message}
                      onChange={(e) => setMessage(e.target.value)}
                      rows={3}
                      className={`field resize-none ${isKo ? 'lang-ko' : ''}`}
                      placeholder={isKo ? '관심 지역, 예산, 시기 등을 알려주세요.' : 'Tell us about your timeline, neighborhoods of interest, budget.'}
                    />
                  </div>
                </div>

                <div className="mt-10 flex flex-wrap items-center gap-6">
                  <button type="button" onClick={submit} disabled={sending} className={`btn-solid ${isKo ? 'lang-ko' : ''} ${sending ? 'opacity-60 pointer-events-none' : ''}`}>
                    {sending ? (isKo ? '전송 중…' : 'Sending…') : t.contact.submit}
                    <IconArrow size={14} />
                  </button>
                  {sendError ? (
                    <div className={`text-[11px] text-accent-deep tracking-wide ${isKo ? 'lang-ko' : ''}`}>{sendError}</div>
                  ) : (
                    <div className={`num text-[11px] text-ink/40 tracking-wide ${isKo ? 'lang-ko' : ''}`}>
                      {isKo ? '영업일 1일 이내 답변' : 'Reply within one business day'}
                    </div>
                  )}
                </div>
              </div>
            )}
          </Reveal>
        </div>
      </div>
    </Section>
  );
}

// ============================================================
// VALUATION FORM — inverted band, accent
// ============================================================
function ValuationForm({ lang, t }) {
  const isKo = lang === 'ko';
  const [address, setAddress] = useStateF('');
  const [beds, setBeds] = useStateF('');
  const [baths, setBaths] = useStateF('');
  const [name, setName] = useStateF('');
  const [email, setEmail] = useStateF('');
  const [phone, setPhone] = useStateF('');
  const [errors, setErrors] = useStateF({});
  const [submitted, setSubmitted] = useStateF(false);
  const [sending, setSending] = useStateF(false);
  const [sendError, setSendError] = useStateF('');

  const submit = async () => {
    const e = {};
    if (!address.trim()) e.address = true;
    if (!name.trim()) e.name = true;
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email.trim())) e.email = true;
    if (!phone.trim()) e.phone = true;
    setErrors(e);
    if (Object.keys(e).length > 0) return;
    setSending(true);
    setSendError('');
    try {
      await deliverLead(
        { address, beds, baths, name, email, phone, source: 'EC Real Estate — Home Valuation' },
        `Valuation request — ${address}`
      );
      setSubmitted(true);
    } catch (err) {
      setSendError(lang === 'ko' ? '전송 실패. 잠시 후 다시 시도해 주세요.' : 'Submission failed. Please try again.');
    } finally {
      setSending(false);
    }
  };

  const reset = () => {
    setAddress(''); setBeds(''); setBaths(''); setName(''); setEmail(''); setPhone('');
    setErrors({}); setSubmitted(false); setSendError('');
  };

  return (
    <Section id="valuation" dark className="py-24 md:py-32 lg:py-40">
      <div className="grid grid-cols-12 gap-8 md:gap-12">
        <div className="col-span-12 lg:col-span-5">
          <Reveal>
            <div className="flex items-center gap-2 mb-8">
              <div className="w-8 h-px bg-accent"></div>
              <span className="eyebrow text-accent">{t.valuation.eyebrow.replace('— ','')}</span>
            </div>
          </Reveal>
          <Reveal delay={140}>
            <h2 className={`display ${isKo ? 'lang-ko' : ''} text-bone text-[11vw] md:text-[7vw] lg:text-[4.6vw] xl:text-[4.2vw] leading-[0.98] mb-8`}>
              <span className="block">{t.valuation.title} <span className="display-italic text-accent">{t.valuation.titleItalic}</span></span>
              <span className="block">{t.valuation.titleB}</span>
            </h2>
          </Reveal>
          <Reveal delay={260}>
            <p className={`text-bone/70 text-base md:text-lg leading-[1.6] max-w-md mb-10 ${isKo ? 'lang-ko' : ''}`}>
              {t.valuation.sub}
            </p>
          </Reveal>
          <Reveal delay={340}>
            <div className="flex items-center gap-3 text-bone/55 num text-[11px] tracking-wider-2 uppercase">
              <IconHome size={14} className="text-accent" />
              <span>Comparable-Backed Estimate</span>
              <span className="w-1 h-1 rounded-full bg-bone/30"></span>
              <span>2-Day Turnaround</span>
            </div>
          </Reveal>
        </div>

        <div className="col-span-12 lg:col-span-7">
          <Reveal delay={200}>
            {submitted ? (
              <div className="p-10 md:p-14 lg:p-16 border hairline-bone min-h-[420px] flex flex-col justify-center">
                <IconCheck size={40} className="text-accent mb-6" strokeWidth={1} />
                <div className={`display ${isKo ? 'lang-ko' : ''} text-bone text-4xl md:text-5xl mb-4 leading-none`}>
                  {t.valuation.successTitle}
                </div>
                <p className={`text-bone/70 text-base md:text-lg leading-[1.55] max-w-md mb-8 ${isKo ? 'lang-ko' : ''}`}>
                  {t.valuation.successSub}
                </p>
                <button type="button" onClick={reset} className={`link-under self-start text-sm text-bone/70 hover:text-accent ${isKo ? 'lang-ko' : ''}`}>
                  {t.valuation.reset} <span aria-hidden="true">→</span>
                </button>
              </div>
            ) : (
              <div className="p-8 md:p-12 lg:p-14 border hairline-bone">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-x-8 gap-y-6">
                  <div className="md:col-span-2">
                    <label className={`eyebrow text-bone/55 block mb-2 ${isKo ? 'lang-ko' : ''}`}>{t.valuation.address}</label>
                    <input
                      type="text"
                      value={address}
                      onChange={(e) => { setAddress(e.target.value); if (errors.address) setErrors({...errors, address: undefined}); }}
                      className={`field field-dark ${errors.address ? '!border-accent' : ''}`}
                      placeholder={isKo ? '예) 123 Main St, Frisco, TX' : '123 Main St, Frisco, TX 75034'}
                    />
                  </div>

                  <div>
                    <label className={`eyebrow text-bone/55 block mb-2 ${isKo ? 'lang-ko' : ''}`}>{t.valuation.beds}</label>
                    <input type="text" value={beds} onChange={(e)=>setBeds(e.target.value)} className="field field-dark num" placeholder="4" />
                  </div>

                  <div>
                    <label className={`eyebrow text-bone/55 block mb-2 ${isKo ? 'lang-ko' : ''}`}>{t.valuation.baths}</label>
                    <input type="text" value={baths} onChange={(e)=>setBaths(e.target.value)} className="field field-dark num" placeholder="3" />
                  </div>

                  <div className="md:col-span-2 pt-2">
                    <div className="border-t hairline-bone"></div>
                  </div>

                  <div>
                    <label className={`eyebrow text-bone/55 block mb-2 ${isKo ? 'lang-ko' : ''}`}>{t.valuation.name}</label>
                    <input
                      type="text"
                      value={name}
                      onChange={(e) => { setName(e.target.value); if (errors.name) setErrors({...errors, name: undefined}); }}
                      className={`field field-dark ${errors.name ? '!border-accent' : ''} ${isKo ? 'lang-ko' : ''}`}
                      placeholder={isKo ? '홍길동' : 'Jane Doe'}
                    />
                  </div>

                  <div>
                    <label className={`eyebrow text-bone/55 block mb-2 ${isKo ? 'lang-ko' : ''}`}>{t.valuation.email}</label>
                    <input
                      type="email"
                      value={email}
                      onChange={(e) => { setEmail(e.target.value); if (errors.email) setErrors({...errors, email: undefined}); }}
                      className={`field field-dark ${errors.email ? '!border-accent' : ''}`}
                      placeholder="you@email.com"
                    />
                  </div>

                  <div className="md:col-span-2">
                    <label className={`eyebrow text-bone/55 block mb-2 ${isKo ? 'lang-ko' : ''}`}>{t.valuation.phone}</label>
                    <input
                      type="tel"
                      value={phone}
                      onChange={(e) => { setPhone(e.target.value); if (errors.phone) setErrors({...errors, phone: undefined}); }}
                      className={`field field-dark num ${errors.phone ? '!border-accent' : ''}`}
                      placeholder="(469) 000-0000"
                    />
                  </div>
                </div>

                <div className="mt-10 flex flex-wrap items-center gap-6">
                  <button
                    type="button"
                    onClick={submit}
                    disabled={sending}
                    className={`inline-flex items-center gap-3 bg-accent text-ink px-7 py-4 text-[13px] tracking-wider-2 uppercase font-medium hover:bg-bone transition-colors ${isKo ? 'lang-ko' : ''} ${sending ? 'opacity-60 pointer-events-none' : ''}`}
                  >
                    {sending ? (isKo ? '전송 중…' : 'Sending…') : t.valuation.submit}
                    <IconArrow size={14} />
                  </button>
                  {sendError ? (
                    <div className={`text-[11px] text-accent tracking-wide ${isKo ? 'lang-ko' : ''}`}>{sendError}</div>
                  ) : Object.keys(errors).length > 0 ? (
                    <div className={`text-[11px] text-accent tracking-wide ${isKo ? 'lang-ko' : ''}`}>
                      {isKo ? '필수 항목을 모두 입력해 주세요.' : 'Please fill in the required fields.'}
                    </div>
                  ) : (
                    <div className={`num text-[11px] text-bone/40 tracking-wide ${isKo ? 'lang-ko' : ''}`}>
                      {isKo ? '무료 · 비공개 · 영업일 2일 이내' : 'Free · Private · 2-day turnaround'}
                    </div>
                  )}
                </div>
              </div>
            )}
          </Reveal>
        </div>
      </div>
    </Section>
  );
}

Object.assign(window, { ContactForm, ValuationForm });
