function Contact() {
  const { lang, t } = useLang();
  const CONTACT_RECIPIENT = 'info@ofuq.tech';
  const CONTACT_EMAIL_LINK = `mailto:${CONTACT_RECIPIENT}`;

  const [form, setForm] = React.useState(() => {
    try {
      const saved = localStorage.getItem('ofuq.contactDraft');
      if (saved) return JSON.parse(saved);
    } catch (e) {}
    return { name: '', email: '', message: '' };
  });

  const [status, setStatus] = React.useState({ kind: 'idle', msg: '' });
  const [sending, setSending] = React.useState(false);

  React.useEffect(() => {
    try { localStorage.setItem('ofuq.contactDraft', JSON.stringify(form)); } catch (e) {}
  }, [form]);

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

  const submit = async (e) => {
    e.preventDefault();
    if (!form.name.trim() || !form.email.trim() || !form.message.trim()) {
      setStatus({ kind: 'error', msg: t.contact.error });
      return;
    }
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) {
      setStatus({ kind: 'error', msg: t.contact.invalidEmail });
      return;
    }
    setSending(true);
    setStatus({ kind: 'idle', msg: '' });

    try {
      const response = await fetch(`https://formsubmit.co/ajax/${encodeURIComponent(CONTACT_RECIPIENT)}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Accept: 'application/json',
        },
        body: JSON.stringify({
          name: form.name.trim(),
          email: form.email.trim(),
          message: form.message.trim(),
          _subject: `Website contact form - ${form.name.trim()}`,
          _replyto: form.email.trim(),
          _template: 'table',
          _captcha: 'false',
        }),
      });

      const result = await response.json();
      const submitOk = result?.success === true || result?.success === 'true';
      if (!response.ok || !submitOk) throw new Error('Failed to submit form');

      setStatus({ kind: 'success', msg: t.contact.success });
      setSending(false);
      setForm({ name: '', email: '', message: '' });
      try { localStorage.removeItem('ofuq.contactDraft'); } catch (e) {}
    } catch (error) {
      setSending(false);
      setStatus({ kind: 'error', msg: t.contact.sendFailed });
      window.location.href = `${CONTACT_EMAIL_LINK}?subject=${encodeURIComponent('Website contact form')}&body=${encodeURIComponent(
        `Name: ${form.name.trim()}\nEmail: ${form.email.trim()}\n\n${form.message.trim()}`,
      )}`;
    }
  };

  return (
    <section id="contact" className="relative py-28 lg:py-36 overflow-hidden">
      <div className="absolute inset-0 -z-10">
        <div className="absolute top-0 start-1/4 w-[520px] h-[520px] rounded-full"
          style={{ background: 'radial-gradient(circle, rgba(168,85,247,0.18) 0%, transparent 60%)', filter: 'blur(40px)' }} />
      </div>

      <div className="mx-auto max-w-7xl px-5 lg:px-8">
        <div className="text-center max-w-3xl mx-auto mb-14 reveal">
          <div className="text-[11px] tracking-[0.22em] uppercase text-cyan-300/80 mb-4" style={{ fontFamily: 'Inter, sans-serif' }}>
            — {t.contact.eyebrow}
          </div>
          <h2 className={`font-bold leading-[1.1] tracking-tight ${lang === 'ar' ? 'text-[clamp(2rem,4.6vw,3.6rem)]' : 'text-[clamp(2.2rem,4.7vw,3.8rem)]'}`}>
            <span className="text-grad-cool">{t.contact.title}</span>
          </h2>
          <p className={`mt-5 text-white/60 ${lang === 'ar' ? 'text-[16px]' : 'text-[17px]'}`}>{t.contact.subtitle}</p>
        </div>

        <div className="grid lg:grid-cols-12 gap-6 lg:gap-8">
          {/* info column */}
          <div className="lg:col-span-5 reveal space-y-4">
            <InfoCard
              icon={<I.WhatsApp size={18} className="text-emerald-300" />}
              label={t.contact.whatsappLabel}
              value="+966 58 116 4926"
              href={`https://wa.me/966581164926?text=${encodeURIComponent(t.contact.whatsappPrefill)}`}
              hue="#10B981"
              external
            />
            <InfoCard
              icon={<I.Mail size={18} className="text-blue-300" />}
              label={t.contact.emailLabel}
              value={CONTACT_RECIPIENT}
              href={CONTACT_EMAIL_LINK}
              hue="#3B82F6"
            />
            <InfoCard
              icon={<I.Globe2 size={18} className="text-purple-300" />}
              label={t.contact.websiteLabel}
              value="ofuq.tech"
              href="https://ofuq.tech"
              hue="#A855F7"
            />
            <InfoCard
              icon={<I.Layers size={18} className="text-cyan-300" />}
              label={t.contact.productLabel}
              value="taboor.ofuq.tech"
              href="https://taboor.ofuq.tech"
              hue="#06B6D4"
              external
            />

            {/* address-like card */}
            <div className="glass rounded-2xl p-6 mt-2">
              <div className="flex items-center gap-2 mb-3">
                <span className="w-1.5 h-1.5 rounded-full bg-emerald-400 pulse-dot" />
                <span className="text-[10px] uppercase tracking-[0.2em] text-emerald-300/85" style={{ fontFamily: 'Inter, sans-serif' }}>
                  {lang === 'ar' ? 'متاحون للعمل' : 'Available for work'}
                </span>
              </div>
              <p className="text-[14px] text-white/65 leading-relaxed">
                {lang === 'ar'
                  ? 'نتلقى مشاريع جديدة. شاركنا فكرتك وسنرد عليك بخطة مبدئية خلال يوم عمل.'
                  : 'We are taking on new projects. Send us your idea and we will come back with an initial plan within one business day.'}
              </p>
            </div>
          </div>

          {/* form column */}
          <form onSubmit={submit} className="lg:col-span-7 reveal glass-strong rounded-3xl p-7 lg:p-9 space-y-5">
            <div className="grid sm:grid-cols-2 gap-5">
              <Field label={t.contact.nameField}>
                <input
                  type="text"
                  value={form.name}
                  onChange={update('name')}
                  placeholder={t.contact.namePh}
                  className="field w-full rounded-xl px-4 py-3.5 text-[14.5px] text-white placeholder:text-white/30"
                />
              </Field>
              <Field label={t.contact.emailField}>
                <input
                  type="email"
                  value={form.email}
                  onChange={update('email')}
                  placeholder={t.contact.emailPh}
                  dir="ltr"
                  className="field w-full rounded-xl px-4 py-3.5 text-[14.5px] text-white placeholder:text-white/30"
                  style={{ fontFamily: 'Inter, sans-serif' }}
                />
              </Field>
            </div>
            <Field label={t.contact.messageField}>
              <textarea
                value={form.message}
                onChange={update('message')}
                placeholder={t.contact.messagePh}
                rows={6}
                className="field w-full rounded-xl px-4 py-3.5 text-[14.5px] text-white placeholder:text-white/30 resize-none"
              />
            </Field>

            {/* status */}
            {status.kind !== 'idle' && (
              <div className={`rounded-xl px-4 py-3 text-[13.5px] flex items-center gap-2 ${
                status.kind === 'success'
                  ? 'bg-emerald-500/10 border border-emerald-400/30 text-emerald-200'
                  : status.kind === 'info'
                    ? 'bg-amber-500/10 border border-amber-300/35 text-amber-100'
                  : 'bg-rose-500/10 border border-rose-400/30 text-rose-200'
              }`}>
                {status.kind === 'success' ? <I.Check size={14} /> : <span>!</span>}
                <span>
                  {status.msg}
                </span>
              </div>
            )}

            <div className="flex flex-wrap items-center justify-between gap-4 pt-2">
              <p className="text-[12px] text-white/40" style={{ fontFamily: lang === 'ar' ? 'Cairo' : 'Inter' }}>
                {lang === 'ar' ? 'بياناتك آمنة ولن تُشارك مع أي طرف ثالث.' : 'Your details are safe and never shared with third parties.'}
              </p>
              <button
                type="submit"
                disabled={sending}
                className="cta-glow inline-flex items-center gap-2.5 px-7 py-3.5 rounded-full text-white font-semibold text-[14.5px] disabled:opacity-60"
              >
                <I.Send size={14} />
                <span>{sending ? t.contact.sending : t.contact.send}</span>
              </button>
            </div>
          </form>
        </div>
      </div>
    </section>
  );
}

function InfoCard({ icon, label, value, href, hue, external }) {
  return (
    <a
      href={href}
      target={external ? '_blank' : undefined}
      rel={external ? 'noopener noreferrer' : undefined}
      className="card-hover block glass rounded-2xl p-5"
    >
      <div className="flex items-center gap-4">
        <div className="w-11 h-11 rounded-xl flex items-center justify-center"
          style={{ background: `${hue}15`, border: `1px solid ${hue}40` }}>
          {icon}
        </div>
        <div className="flex-1 min-w-0">
          <div className="text-[10px] uppercase tracking-[0.2em] text-white/45 mb-1" style={{ fontFamily: 'Inter, sans-serif' }}>{label}</div>
          <div className="text-[15px] font-semibold text-white truncate" style={{ fontFamily: 'Inter, sans-serif' }}>{value}</div>
        </div>
        {external && <I.External size={14} className="text-white/40 shrink-0" />}
      </div>
    </a>
  );
}

function Field({ label, children }) {
  return (
    <label className="block">
      <span className="block text-[12px] uppercase tracking-[0.18em] text-white/55 mb-2" style={{ fontFamily: 'Inter, sans-serif' }}>{label}</span>
      {children}
    </label>
  );
}

window.Contact = Contact;
