// Lead capture popup — hiển thị khi click bất kỳ nút "Đặt lịch" / "Liên hệ".
// Form submit qua /api/lead-relay (Laravel route) — backend mới attach
// X-CNV-Form-Secret rồi forward sang CNV webhook. Secret KHÔNG xuất hiện ở client.

const LEAD_PINK = '#FF688E';
const LEAD_PINK_DARK = '#E63E68';
const LEAD_INK = '#0A0E1A';
const LEAD_MUTED = 'rgba(10,14,26,0.62)';
const LEAD_LINE = 'rgba(10,14,26,0.12)';

function CnvLeadPopup() {
  const [open, setOpen] = React.useState(false);
  const [source, setSource] = React.useState('');
  const [submitting, setSubmitting] = React.useState(false);
  const [done, setDone] = React.useState(false);
  const [err, setErr] = React.useState('');

  React.useEffect(() => {
    window.openLeadPopup = (sourceLabel) => {
      setSource(sourceLabel || '');
      setDone(false);
      setErr('');
      setOpen(true);
    };
    window.closeLeadPopup = () => setOpen(false);

    // Click delegation: bắt mọi <button>/<a> chứa text "Đặt lịch" / "Liên hệ"
    const handler = (e) => {
      const target = e.target.closest('button, a');
      if (!target) return;
      if (target.dataset.cnvLeadHandled === '1') return;
      if (target.closest('#cnv-lead-popup')) return; // bỏ qua nút trong popup
      const txt = (target.innerText || target.textContent || '').trim().toLowerCase();
      if (!txt) return;
      const isLead = (
        txt.includes('đặt lịch') ||
        txt.includes('liên hệ nhận sách') ||
        txt.includes('liên hệ tư vấn')
      );
      if (!isLead) return;
      e.preventDefault();
      e.stopPropagation();
      window.openLeadPopup(txt);
    };
    document.addEventListener('click', handler, true);

    // ESC để đóng
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    document.addEventListener('keydown', onKey);

    return () => {
      document.removeEventListener('click', handler, true);
      document.removeEventListener('keydown', onKey);
    };
  }, []);

  const submit = async (e) => {
    e.preventDefault();
    if (submitting) return;
    setErr('');
    const fd = new FormData(e.target);
    const data = Object.fromEntries(fd);
    if (source) data.source = source;
    setSubmitting(true);
    try {
      const res = await fetch('/api/lead-relay', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
        body: JSON.stringify(data),
      });
      const body = await res.json().catch(() => ({}));
      if (!res.ok || !body.ok) {
        setErr('Gửi không thành công, vui lòng thử lại hoặc gọi hotline.');
      } else {
        setDone(true);
        e.target.reset();
      }
    } catch (_) {
      setErr('Không kết nối được máy chủ. Kiểm tra mạng và thử lại.');
    } finally {
      setSubmitting(false);
    }
  };

  if (!open) return null;

  return (
    <div id="cnv-lead-popup"
      onClick={(e) => { if (e.target === e.currentTarget) setOpen(false); }}
      style={{
        position: 'fixed', inset: 0, zIndex: 9999,
        background: 'rgba(6,7,11,0.7)', backdropFilter: 'blur(6px)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 16, fontFamily: 'Inter, -apple-system, sans-serif',
      }}>
      <div style={{
        width: '100%', maxWidth: 480, background: '#fff', color: LEAD_INK,
        borderRadius: 20, padding: 32, position: 'relative',
        boxShadow: '0 30px 80px rgba(0,0,0,0.4)',
        maxHeight: '92vh', overflowY: 'auto',
      }}>
        <button type="button" onClick={() => setOpen(false)} aria-label="Đóng"
          data-cnv-lead-handled="1"
          style={{
            position: 'absolute', top: 14, right: 14, width: 36, height: 36,
            borderRadius: '50%', border: 'none', background: 'rgba(10,14,26,0.06)',
            display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
            color: LEAD_INK,
          }}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
            <path d="M6 6l12 12M18 6L6 18" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
          </svg>
        </button>

        {done ? (
          <div style={{ textAlign: 'center', padding: '24px 8px' }}>
            <div style={{
              width: 64, height: 64, borderRadius: '50%',
              background: `${LEAD_PINK}20`, color: LEAD_PINK_DARK,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              margin: '0 auto 18px',
            }}>
              <svg width="32" height="32" viewBox="0 0 24 24" fill="none">
                <path d="M5 12l5 5 9-10" stroke="currentColor" strokeWidth="2.4" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            </div>
            <div style={{ fontSize: 22, fontWeight: 800, letterSpacing: '-0.02em', marginBottom: 8 }}>Đã nhận thông tin</div>
            <div style={{ fontSize: 15, color: LEAD_MUTED, lineHeight: 1.6 }}>
              Cảm ơn bạn — đội ngũ CNV sẽ liên hệ trong vòng 24 giờ.
            </div>
            <button type="button" onClick={() => setOpen(false)}
              data-cnv-lead-handled="1"
              style={{
                marginTop: 24, padding: '12px 28px', borderRadius: 999,
                background: LEAD_INK, color: '#fff', border: 'none',
                fontSize: 14, fontWeight: 600, cursor: 'pointer',
              }}>Đóng</button>
          </div>
        ) : (
          <>
            <div style={{ marginBottom: 22 }}>
              <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.14em', textTransform: 'uppercase', color: LEAD_PINK_DARK, marginBottom: 8 }}>CNV WORK</div>
              <h3 style={{ margin: 0, fontSize: 24, fontWeight: 800, letterSpacing: '-0.02em', lineHeight: 1.2 }}>
                Đặt lịch demo · Tư vấn miễn phí
              </h3>
              <p style={{ margin: '8px 0 0', fontSize: 14, color: LEAD_MUTED, lineHeight: 1.55 }}>
                Để lại thông tin — đội ngũ CNV sẽ gọi tư vấn lộ trình triển khai phù hợp với doanh nghiệp của bạn.
              </p>
            </div>

            <form onSubmit={submit} style={{ display: 'grid', gap: 12 }}>
              <Field name="full_name" placeholder="Họ và tên *" required/>
              <Field name="phone" placeholder="Số điện thoại *" required type="tel" inputMode="tel"/>
              <Field name="email" placeholder="Email" type="email"/>
              <Field name="company_name" placeholder="Tên công ty"/>
              <Field name="province" placeholder="Khu vực bạn muốn được tư vấn *" required select
                options={[
                  { value: 'Khu vực Hà Nội', label: 'Khu vực Hà Nội' },
                  { value: 'Khu vực Hồ Chí Minh', label: 'Khu vực Hồ Chí Minh' },
                ]}/>
              <Field name="note" placeholder="Bạn quan tâm sản phẩm/nghiệp vụ nào?" textarea/>

              {err && (
                <div style={{ fontSize: 13, color: '#B91C1C', background: '#FEE2E2', padding: '10px 14px', borderRadius: 10 }}>{err}</div>
              )}

              <button type="submit" disabled={submitting}
                data-cnv-lead-handled="1"
                style={{
                  marginTop: 6, padding: '14px 24px', borderRadius: 999,
                  background: submitting ? '#9ca3af' : `linear-gradient(135deg, ${LEAD_PINK}, ${LEAD_PINK_DARK})`,
                  color: '#fff', border: 'none', fontSize: 15, fontWeight: 700, cursor: submitting ? 'wait' : 'pointer',
                  letterSpacing: '0.01em',
                  boxShadow: submitting ? 'none' : `0 12px 28px ${LEAD_PINK}55`,
                }}>
                {submitting ? 'Đang gửi…' : 'Gửi thông tin'}
              </button>

              <div style={{ fontSize: 12, color: LEAD_MUTED, lineHeight: 1.5, textAlign: 'center', marginTop: 4 }}>
                Bằng việc gửi thông tin, bạn đồng ý với chính sách bảo mật của CNV.
              </div>
            </form>
          </>
        )}
      </div>
    </div>
  );
}

function Field({ name, placeholder, required, type = 'text', textarea, select, options, inputMode }) {
  const baseStyle = {
    width: '100%', padding: '14px 16px', borderRadius: 12,
    border: `1px solid ${LEAD_LINE}`, background: '#fff', color: LEAD_INK,
    fontSize: 15, fontFamily: 'Inter, -apple-system, sans-serif', outline: 'none',
    transition: 'border-color .15s, box-shadow .15s',
    boxSizing: 'border-box',
  };
  const onFocus = (e) => {
    e.currentTarget.style.borderColor = LEAD_PINK;
    e.currentTarget.style.boxShadow = `0 0 0 3px ${LEAD_PINK}22`;
  };
  const onBlur = (e) => {
    e.currentTarget.style.borderColor = LEAD_LINE;
    e.currentTarget.style.boxShadow = 'none';
  };
  if (textarea) {
    return <textarea name={name} placeholder={placeholder} rows={3}
      onFocus={onFocus} onBlur={onBlur}
      style={{ ...baseStyle, resize: 'vertical', minHeight: 84 }}/>;
  }
  if (select) {
    const [value, setValue] = React.useState('');
    const placeholderColor = value ? LEAD_INK : 'rgba(10,14,26,0.45)';
    const caret = encodeURIComponent(`<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M6 9l6 6 6-6" stroke="${LEAD_INK}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>`);
    return (
      <select name={name} required={required}
        value={value} onChange={(e) => setValue(e.target.value)}
        onFocus={onFocus} onBlur={onBlur}
        style={{
          ...baseStyle, color: placeholderColor,
          appearance: 'none', WebkitAppearance: 'none', MozAppearance: 'none',
          backgroundImage: `url("data:image/svg+xml,${caret}")`,
          backgroundRepeat: 'no-repeat',
          backgroundPosition: 'right 16px center',
          paddingRight: 42,
        }}>
        <option value="" disabled>{placeholder}</option>
        {options.map(o => (
          <option key={o.value} value={o.value} style={{ color: LEAD_INK }}>{o.label}</option>
        ))}
      </select>
    );
  }
  return <input name={name} type={type} placeholder={placeholder} required={required} inputMode={inputMode}
    onFocus={onFocus} onBlur={onBlur}
    style={baseStyle}/>;
}

// Mount popup vào root mới — tách khỏi App chính, render độc lập trên mọi page.
(function mountLeadPopup() {
  const id = 'cnv-lead-popup-root';
  let host = document.getElementById(id);
  if (!host) {
    host = document.createElement('div');
    host.id = id;
    document.body.appendChild(host);
  }
  ReactDOM.createRoot(host).render(<CnvLeadPopup/>);
})();
