// Contact.jsx — form liên hệ GỬI THẬT vào cms_contacts (anon INSERT, 0035).
// Chống bot thô nhiều lớp (client-side): honeypot ẩn + thời gian mở form tối thiểu +
// phép tính ngẫu nhiên (+/−) + chặn gửi dồn 60s. (Chống bot chuyên nghiệp cần
// Turnstile + Edge Function verify — nợ kỹ thuật đã ghi nhận.)
function Contact() {
  const C = (window.SITE || SITE_DEFAULTS).contact;
  // captcha: phép tính ngẫu nhiên, đổi mới sau mỗi lần sai
  const genCap = () => {
    const x = Math.floor(Math.random() * 7) + 2, y = Math.floor(Math.random() * 7) + 2;
    return Math.random() < 0.5 ? { q: x + ' + ' + y, a: x + y } : { q: (x + y) + ' − ' + x, a: y };
  };
  const [cap, setCap] = React.useState(genCap);
  const [form, setForm] = React.useState({ name: '', email: '', msg: '', cap: '', hp: '' });
  const [sent, setSent] = React.useState(false);
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState('');
  const openedAt = React.useRef(Date.now());
  const set = (k) => (e) => setForm(f => ({ ...f, [k]: e.target.value }));
  const submit = async (e) => {
    e.preventDefault();
    if (busy) return;
    // honeypot: bot điền ô ẩn → giả vờ thành công, không ghi gì
    if (form.hp) { setSent(true); return; }
    if (!form.name.trim() || !form.email.trim() || !form.msg.trim()) { setErr('Vui lòng điền đầy đủ các trường (*).'); return; }
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email.trim())) { setErr('Email chưa đúng định dạng.'); return; }
    if (parseInt(form.cap, 10) !== cap.a) { setErr('Kết quả xác thực chưa đúng.'); setCap(genCap()); setForm(f => ({ ...f, cap: '' })); return; }
    if (Date.now() - openedAt.current < 4000) { setErr('Bạn thao tác quá nhanh — vui lòng thử lại.'); return; }
    try { const last = +localStorage.getItem('swo-site-contact-ts') || 0; if (Date.now() - last < 60000) { setErr('Bạn vừa gửi một yêu cầu — vui lòng chờ 1 phút.'); return; } } catch (e2) {}
    setErr(''); setBusy(true);
    const cfg = window.SITE_CONFIG || {};
    try {
      const r = await fetch(cfg.SUPABASE_URL + '/rest/v1/cms_contacts', {
        method: 'POST',
        headers: { apikey: cfg.SUPABASE_ANON_KEY, Authorization: 'Bearer ' + cfg.SUPABASE_ANON_KEY, 'Content-Type': 'application/json', Prefer: 'return=minimal' },
        body: JSON.stringify({ name: form.name.trim().slice(0, 120), email: form.email.trim().slice(0, 160), message: form.msg.trim().slice(0, 2000) }),
      });
      if (!r.ok) throw new Error('HTTP ' + r.status);
      try { localStorage.setItem('swo-site-contact-ts', String(Date.now())); } catch (e3) {}
      setSent(true);
    } catch (e4) { setErr('Gửi không thành công — vui lòng thử lại hoặc email ' + C.email + '.'); }
    finally { setBusy(false); }
  };
  const info = [
    { ic: 'mapPin', lbl: 'Địa chỉ', val: C.address },
    { ic: 'phone', lbl: 'Điện thoại', val: C.phone },
    { ic: 'mail', lbl: 'Email', val: C.email },
  ];
  const headingLines = String(C.heading || '').split('\n');
  return (
    <Section id="contact" tone="ink">
      <div className="swk-contact">
        <div>
          <Eyebrow light>{C.eyebrow}</Eyebrow>
          <h2 className="swk-h2" style={{ color: '#fff' }}>
            {headingLines.map((ln, i) => <React.Fragment key={i}>{i > 0 && <br />}{ln}</React.Fragment>)}
          </h2>
          <p className="swk-lead">{C.lead}</p>
          <div className="info">
            {info.map(r => (
              <div className="swk-irow" key={r.lbl}>
                <div className="ic"><Icon name={r.ic} size={20} /></div>
                <div><div className="lbl">{r.lbl}</div><div className="val">{r.val}</div></div>
              </div>
            ))}
          </div>
        </div>

        <form className="swk-form" onSubmit={submit}>
          {sent ? (
            <div style={{ padding: '20px 0' }}>
              <div className="ok"><Icon name="check" size={22} /> Cảm ơn {form.name || 'bạn'}! Yêu cầu đã được gửi.</div>
              <p style={{ color: 'var(--fg-3)', fontSize: 14, marginTop: 16 }}>S.W.O sẽ phản hồi tới {form.email} trong vòng 24 giờ.</p>
              <a className="swk-btn v-secondary" style={{ marginTop: 8 }} href="#contact"
                 onClick={(e) => { e.preventDefault(); setSent(false); setCap(genCap()); openedAt.current = Date.now(); setForm({ name: '', email: '', msg: '', cap: '', hp: '' }); }}>Gửi yêu cầu khác</a>
            </div>
          ) : (
            <React.Fragment>
              <div className="frow"><label>Họ và tên (*)</label><input value={form.name} onChange={set('name')} placeholder="Nguyễn Văn A" maxLength={120} /></div>
              <div className="frow"><label>Email (*)</label><input value={form.email} onChange={set('email')} placeholder="ban@congty.vn" maxLength={160} /></div>
              <div className="frow"><label>Nội dung (*)</label><textarea value={form.msg} onChange={set('msg')} placeholder="Tôi muốn tư vấn về..." maxLength={2000} /></div>
              {/* honeypot — người thật không thấy; bot auto-fill sẽ lộ */}
              <div style={{ position: 'absolute', left: -9999, top: -9999 }} aria-hidden="true">
                <label>Website</label><input tabIndex={-1} autoComplete="off" value={form.hp} onChange={set('hp')} />
              </div>
              <div className="frow">
                <label>Xác thực: {cap.q} = ?</label>
                <div className="captcha">
                  <input style={{ maxWidth: 120 }} value={form.cap} onChange={set('cap')} placeholder="?" inputMode="numeric" />
                  <span className="q">{cap.q}</span>
                </div>
              </div>
              {err && <div style={{ color: 'var(--danger)', fontSize: 13.5, marginBottom: 12, fontWeight: 500 }}>{err}</div>}
              <button type="submit" className="swk-btn v-gradient" disabled={busy} style={{ width: '100%', justifyContent: 'center', opacity: busy ? .7 : 1 }}>
                <span>{busy ? 'Đang gửi…' : 'Gửi yêu cầu'}</span><Icon name="send" size={18} />
              </button>
            </React.Fragment>
          )}
        </form>
      </div>
    </Section>
  );
}
Object.assign(window, { Contact });
