// Form screen — Nhập thông tin
// Exports to window: FormScreen

const FORM_SG = '#14C560';
const FORM_SN = '#1E3888';

function isoToDMY(iso) {
  const s = String(iso || '').trim();
  const m = s.match(/^(\d{4})-(\d{2})-(\d{2})$/);
  if (!m) return s;
  return `${m[3]}/${m[2]}/${m[1]}`;
}

function dmyToIso(dmy) {
  const s = String(dmy || '').trim();
  const m = s.match(/^(\d{2})\/(\d{2})\/(\d{4})$/);
  if (!m) return '';
  const dd = Number(m[1]);
  const mm = Number(m[2]);
  const yyyy = Number(m[3]);
  const dt = new Date(yyyy, mm - 1, dd);
  if (dt.getFullYear() !== yyyy || dt.getMonth() !== mm - 1 || dt.getDate() !== dd) return '';
  return `${String(yyyy).padStart(4, '0')}-${String(mm).padStart(2, '0')}-${String(dd).padStart(2, '0')}`;
}

function normalizeDobTyping(v) {
  const digits = String(v || '').replace(/\D/g, '').slice(0, 8);
  if (!digits) return '';
  if (digits.length < 2) return digits;
  if (digits.length === 2) return `${digits}/`;
  if (digits.length < 4) return `${digits.slice(0, 2)}/${digits.slice(2)}`;
  if (digits.length === 4) return `${digits.slice(0, 2)}/${digits.slice(2, 4)}/`;
  return `${digits.slice(0, 2)}/${digits.slice(2, 4)}/${digits.slice(4)}`;
}

function dobCaretFromDigitIndex(digitIndex, formattedValue) {
  const i = Math.max(0, Math.min(8, Number(digitIndex) || 0));
  let pos = i;
  if (i >= 2) pos += 1;
  if (i >= 4) pos += 1;
  return Math.max(0, Math.min(String(formattedValue || '').length, pos));
}

function handleDobTextChange(e, setValue) {
  const raw = String(e.target.value || '');
  const caret = e.target.selectionStart == null ? raw.length : e.target.selectionStart;
  const digitsBeforeCaret = raw.slice(0, caret).replace(/\D/g, '').length;
  const next = normalizeDobTyping(raw);
  setValue(next);
  requestAnimationFrame(() => {
    try {
      const p = dobCaretFromDigitIndex(digitsBeforeCaret, next);
      e.target.setSelectionRange(p, p);
    } catch (_) {}
  });
}

function handleDobKeyDown(e, value, setValue) {
  if (e.key !== 'Backspace') return;
  const input = e.target;
  const start = input.selectionStart == null ? 0 : input.selectionStart;
  const end = input.selectionEnd == null ? start : input.selectionEnd;
  if (start !== end) return;
  if (start !== 3 && start !== 6) return;
  e.preventDefault();
  const digits = String(value || '').replace(/\D/g, '');
  const digitIndex = start === 3 ? 2 : 4;
  if (digitIndex <= 0 || digitIndex > digits.length) return;
  const nextDigits = `${digits.slice(0, digitIndex - 1)}${digits.slice(digitIndex)}`;
  const next = normalizeDobTyping(nextDigits);
  setValue(next);
  requestAnimationFrame(() => {
    try {
      const p = dobCaretFromDigitIndex(digitIndex - 1, next);
      input.setSelectionRange(p, p);
    } catch (_) {}
  });
}

function fireLeadWebhookFromForm(payload) {
  if (typeof window === 'undefined') return;
  try {
    fetch('/api/lead', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload || {}),
      keepalive: true,
    }).catch(() => {});
  } catch (e) {}
}

function FormScreen({ mobile, onSubmit, onBack, initialData, onDraftChange }) {
  const [name, setName] = React.useState((initialData && initialData.name) || '');
  const [gender, setGender] = React.useState((initialData && initialData.gender) || null);
  const [dob, setDob] = React.useState(() => isoToDMY((initialData && initialData.dob) || ''));
  const [email, setEmail] = React.useState((initialData && initialData.email) || '');
  const [touched, setTouched] = React.useState({ name: false, dob: false });
  const [submitting, setSubmitting] = React.useState(false);
  const dobPickerRef = React.useRef(null);

  React.useEffect(() => {
    if (!initialData) return;
    if (initialData.name != null) setName(initialData.name);
    if (initialData.gender !== undefined) setGender(initialData.gender);
    if (initialData.dob != null) setDob(isoToDMY(initialData.dob));
    if (initialData.email != null) setEmail(initialData.email);
  }, [initialData && initialData.name, initialData && initialData.gender, initialData && initialData.dob, initialData && initialData.email]);

  React.useEffect(() => {
    if (!onDraftChange) return;
    onDraftChange({ name, gender, dob: dmyToIso(dob), email });
  }, [name, gender, dob, email, onDraftChange]);

  const today = new Date().toISOString().slice(0, 10);
  const dobIso = dmyToIso(dob);

  const errors = {
    name: !name.trim() ? 'Vui lòng nhập họ và tên' : null,
    dob: !dob ? 'Vui lòng nhập ngày sinh' : (!dobIso ? 'Định dạng ngày sinh: dd/mm/yyyy' : (dobIso > today ? 'Ngày sinh không thể trong tương lai' : null)),
    email: !email.trim() ? 'Vui lòng nhập email' : (!/^\S+@\S+\.\S+$/.test(email) ? 'Email chưa đúng định dạng' : null),
  };
  const isValid = !errors.name && !errors.dob && !errors.email;

  const submit = (e) => {
    e.preventDefault();
    setTouched({ name: true, dob: true, email: true });
    if (!isValid) return;
    fireLeadWebhookFromForm({
      submitted_at: new Date().toISOString(),
      source: 'saladin-thansohoc-form-direct',
      page_url: typeof window !== 'undefined' ? window.location.href : '',
      name: name || '',
      dob: dobIso || '',
      gender: gender || '',
      email: email || '',
    });
    setSubmitting(true);
    setTimeout(() => {
      setSubmitting(false);
      onSubmit && onSubmit({ name, dob: dobIso, email, gender });
    }, 1800);
  };

  const openDobPicker = () => {
    const el = dobPickerRef.current;
    if (!el) return;
    try {
      if (typeof el.showPicker === 'function') {
        el.showPicker();
        return;
      }
    } catch (_) {}
    try { el.focus(); } catch (_) {}
    try { el.click(); } catch (_) {}
  };

  // Cycling number during loading
  const [loadNum, setLoadNum] = React.useState(1);
  React.useEffect(() => {
    if (!submitting) return;
    let n = 1;
    const id = setInterval(() => {
      n = (n % 9) + 1;
      setLoadNum(n);
    }, 140);
    return () => clearInterval(id);
  }, [submitting]);

  return (
    <div style={{
      minHeight: '100%',
      background: 'var(--hero-bg)',
      paddingTop: mobile ? 24 : 56,
      paddingBottom: mobile ? 48 : 80,
      position: 'relative',
      overflow: 'hidden',
    }}>
      {/* Decorative pattern */}
      {!mobile && <GridPattern size={480} opacity={0.05} color="var(--grid-color)" style={{ right: -120, top: 0 }} />}
      {!mobile && <GridPattern size={320} opacity={0.04} color="var(--grid-color)" style={{ left: -80, bottom: 40 }} />}

      <Container style={{ position: 'relative' }}>
        {/* Back link */}
        <button
          type="button"
          onClick={onBack}
          style={{
            background: 'transparent', border: 'none', cursor: 'pointer',
            display: 'inline-flex', alignItems: 'center', gap: 6,
            fontSize: 13, fontWeight: 500, color: 'var(--text-support)',
            padding: 0, marginBottom: mobile ? 20 : 24,
          }}
        >
          <i className="ri-arrow-left-line" style={{ fontSize: 16 }}></i>
          Quay lại trang chủ
        </button>

        <div style={{
          maxWidth: mobile ? '100%' : 560,
          margin: '0 auto',
        }}>
          {/* Progress */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 20 }}>
            <span style={{
              display: 'inline-flex', alignItems: 'center', gap: 6,
              padding: '4px 10px', background: 'var(--bg)',
              border: '1px solid var(--primary-95)',
              borderRadius: 50, fontSize: 11, fontWeight: 600, color: 'var(--badge-text)',
            }}>
              <span style={{ width: 5, height: 5, borderRadius: '50%', background: FORM_SG }}/>
              Bước 1 / 2 · Nhập thông tin
            </span>
          </div>

          <h1 style={{
            fontFamily: 'var(--font-display)', fontWeight: 700,
            fontSize: mobile ? 26 : 34, lineHeight: 1.15,
            margin: 0, marginBottom: 12,
            letterSpacing: '-0.01em', whiteSpace: 'nowrap',
            color: 'var(--text-default)',
          }}>
            Nhập thông tin của bạn
          </h1>
          <p style={{
            fontSize: mobile ? 13 : 15, lineHeight: 1.5,
            margin: 0, marginBottom: mobile ? 24 : 32,
            color: 'var(--text-support)',
          }}>
            Điền nhanh để xem kết quả ngay.
          </p>

          {/* Form card */}
          <form onSubmit={submit} style={{
            background: 'var(--bg)',
            border: '1px solid var(--border-default)',
            borderRadius: 12,
            padding: mobile ? 20 : 32,
            boxShadow: 'var(--shadow-md)',
            display: 'flex', flexDirection: 'column', gap: 20,
            position: 'relative',
            opacity: submitting ? 0.6 : 1,
            transition: 'opacity 200ms',
          }}>
            <Field label="Họ và tên" required icon="ri-user-line" error={touched.name ? errors.name : null}>
              <input
                type="text"
                value={name}
                onChange={(e) => setName(e.target.value)}
                onBlur={() => setTouched(t => ({ ...t, name: true }))}
                placeholder="VD: Nguyễn Hoài An"
                style={inputStyle(touched.name && errors.name)}
                disabled={submitting}
              />
            </Field>

            <Field
              label="Giới tính"
              optional
              icon="ri-user-heart-line"
              hint="Chỉ dùng cho thống kê nội bộ."
            >
              <div style={{
                display: 'inline-flex',
                padding: 4, borderRadius: 50,
                background: 'var(--bg-variant)',
                border: '1px solid var(--border-default)',
                gap: 2,
              }}>
                {[
                  { v: 'male', l: 'Nam' },
                  { v: 'female', l: 'Nữ' },
                  { v: 'other', l: 'Khác' },
                ].map(opt => {
                  const active = gender === opt.v;
                  return (
                    <button
                      key={opt.v}
                      type="button"
                      onClick={() => setGender(active ? null : opt.v)}
                      disabled={submitting}
                      style={{
                        padding: '7px 18px',
                        border: 'none', borderRadius: 50,
                        background: active ? FORM_SG : 'transparent',
                        color: active ? '#fff' : 'var(--text-support)',
                        fontSize: 13, fontWeight: 500,
                        cursor: submitting ? 'wait' : 'pointer',
                        transition: 'all 150ms',
                        fontFamily: 'inherit',
                      }}
                    >
                      {opt.l}
                    </button>
                  );
                })}
              </div>
            </Field>

            <div style={{ display: 'grid', gridTemplateColumns: mobile ? '1fr' : '1fr 1fr', gap: 16 }}>
              <Field
                label="Ngày sinh"
                required
                icon="ri-calendar-line"
                error={touched.dob ? errors.dob : null}
                hint="dd/mm/yyyy"
              >
                <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                  <input
                    type="text"
                    value={dob}
                    inputMode="text"
                    placeholder="dd/mm/yyyy"
                    onChange={(e) => handleDobTextChange(e, setDob)}
                    onKeyDown={(e) => handleDobKeyDown(e, dob, setDob)}
                    onBlur={() => setTouched(t => ({ ...t, dob: true }))}
                    style={{ ...inputStyle(touched.dob && errors.dob), flex: 1 }}
                    disabled={submitting}
                  />
                  <button
                    type="button"
                    onClick={openDobPicker}
                    disabled={submitting}
                    style={{
                      position: 'relative',
                      overflow: 'hidden',
                      width: 42, height: 42, borderRadius: 8, border: '1px solid var(--border-default)',
                      background: 'var(--bg)', color: 'var(--text-support)', cursor: 'pointer',
                      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                    }}
                    title="Chọn ngày"
                  >
                    <i className="ri-calendar-line" style={{ fontSize: 18 }} />
                  </button>
                  <input
                    ref={dobPickerRef}
                    type="date"
                    value={dobIso}
                    max={today}
                    onChange={(e) => setDob(isoToDMY(e.target.value))}
                    style={{ opacity: 0, width: 42, height: 42, marginLeft: -42, cursor: 'pointer', border: 0, padding: 0 }}
                    tabIndex={-1}
                    aria-hidden="true"
                  />
                </div>
              </Field>

              <Field
                label="Email"
                required
                icon="ri-mail-line"
                error={touched.email ? errors.email : null}
                hint="Email dùng để nhận báo cáo."
              >
                <input
                  type="email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  onBlur={() => setTouched(t => ({ ...t, email: true }))}
                  placeholder="ban@gmail.com"
                  style={inputStyle(touched.email && errors.email)}
                  disabled={submitting}
                />
              </Field>
            </div>

            <button
              type="submit"
              disabled={submitting}
              style={{
                background: FORM_SG, color: '#fff',
                padding: '14px 24px', borderRadius: 4, border: 'none',
                fontFamily: 'inherit', fontSize: 15, fontWeight: 600,
                cursor: submitting ? 'wait' : 'pointer',
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                width: '100%',
                boxShadow: '0 4px 12px -2px rgba(20,197,96,0.35)',
                transition: 'opacity 150ms',
                opacity: submitting ? 0.8 : 1,
                marginTop: 4,
              }}
            >
              {submitting ? (
                <>
                  <i className="ri-loader-4-line" style={{ fontSize: 18, animation: 'spin 800ms linear infinite' }}></i>
                  Đang phân tích con số của bạn...
                </>
              ) : (
                <>Tra cứu <i className="ri-arrow-right-line" style={{ fontSize: 18 }}></i></>
              )}
            </button>

            {/* Privacy + method note (single block, two distinct rows) */}
            <div style={{
              display: 'flex', flexDirection: 'column', gap: 8,
              padding: '10px 12px',
              background: 'var(--bg-variant)',
              border: '1px solid var(--border-default)',
              borderRadius: 8,
              fontSize: 12, color: 'var(--text-support)', lineHeight: 1.5,
            }}>
              <div style={{ display: 'flex', gap: 8, alignItems: 'flex-start' }}>
                <i className="ri-shield-check-line" style={{ fontSize: 16, color: FORM_SG, marginTop: 1, flexShrink: 0 }}></i>
                <div style={{ color: 'var(--text-support)' }}>
                  Thông tin bạn nhập được Saladin sử dụng cho tính toán, cá nhân hoá kết quả và cải thiện trải nghiệm theo{' '}
                  <a
                    href="https://www.saladin.vn/dieu-khoan-dieu-kien-chinh-sach#quyen-rieng-tu"
                    target="_blank"
                    rel="noopener noreferrer"
                    style={{ color: FORM_SG, fontWeight: 700, textDecoration: 'underline' }}
                  >
                    Chính sách quyền riêng tư
                  </a>.
                </div>
              </div>
              <div style={{ display: 'flex', gap: 8, alignItems: 'flex-start' }}>
                <i className="ri-information-line" style={{ fontSize: 16, color: FORM_SN, marginTop: 1, flexShrink: 0 }}></i>
                <div style={{ color: '#4B5563', fontSize: 11 }}>
                  Phương pháp Pythagorean. Kết quả mang tính tham khảo.
                </div>
              </div>
            </div>

            {/* Loading overlay with cycling number */}
            {submitting && (
              <div style={{
                position: 'absolute', inset: 0,
                background: 'var(--bg-overlay-light)',
                backdropFilter: 'blur(2px)',
                borderRadius: 12,
                display: 'flex', flexDirection: 'column',
                alignItems: 'center', justifyContent: 'center',
                gap: 16, pointerEvents: 'none',
              }}>
                <div style={{
                  fontFamily: 'var(--font-display)', fontWeight: 900,
                  fontSize: 96, lineHeight: 1, color: FORM_SG,
                  letterSpacing: '-0.05em',
                  fontVariantNumeric: 'tabular-nums',
                  textShadow: '0 4px 24px rgba(20,197,96,0.25)',
                }}>{loadNum}</div>
                <div style={{
                  fontSize: 13, fontWeight: 500, color: 'var(--text-default)',
                  fontFamily: 'var(--font-display)',
                }}>Đang ghép các con số...</div>
                {/* Skeleton bars */}
                <div style={{ display: 'flex', gap: 4, marginTop: 4 }}>
                  {[0,1,2,3,4].map(i => (
                    <span key={i} style={{
                      width: 24, height: 4, borderRadius: 2,
                      background: FORM_SG, opacity: 0.2 + (i % 3) * 0.25,
                      animation: `pulse 1.2s ease-in-out ${i * 0.12}s infinite`,
                    }}/>
                  ))}
                </div>
              </div>
            )}
          </form>

        </div>
      </Container>
    </div>
  );
}

// ──────────────────────────────────────────────
// Field wrapper
// ──────────────────────────────────────────────
function Field({ label, required, optional, icon, error, hint, children }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 8 }}>
        <label style={{ fontSize: 13, fontWeight: 600, color: 'var(--text-default)' }}>
          {label}
          {required && <span style={{ color: '#BA1A1A', marginLeft: 4 }}>*</span>}
        </label>
        {optional && <span style={{ fontSize: 11, color: 'var(--text-support)' }}>Tuỳ chọn</span>}
      </div>
      <div style={{ position: 'relative' }}>
        {(() => {
          const childType = children && children.type;
          const isInput = childType === 'input' || childType === 'textarea' || childType === 'select';
          if (!icon || !isInput) return null;
          return (
            <i className={icon} style={{
              position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)',
              fontSize: 16, color: 'var(--text-support)', pointerEvents: 'none',
            }}></i>
          );
        })()}
        {(() => {
          // Only apply icon padding to input-like children
          const childType = children && children.type;
          const isInput = childType === 'input' || childType === 'textarea' || childType === 'select';
          if (isInput && icon) {
            return React.cloneElement(children, {
              style: { ...children.props.style, paddingLeft: 38 },
            });
          }
          return children;
        })()}
      </div>
      {error ? (
        <div style={{ display: 'flex', alignItems: 'center', gap: 4, fontSize: 12, color: '#BA1A1A' }}>
          <i className="ri-error-warning-fill" style={{ fontSize: 14 }}></i> {error}
        </div>
      ) : hint ? (
        <div style={{ fontSize: 12, color: 'var(--text-support)' }}>{hint}</div>
      ) : null}
    </div>
  );
}

function inputStyle(hasError) {
  return {
    width: '100%',
    boxSizing: 'border-box',
    padding: '12px 12px',
    minHeight: 44,
    border: `1px solid ${hasError ? '#BA1A1A' : 'var(--border-default)'}`,
    borderRadius: 8,
    background: 'var(--bg)',
    fontSize: 15, fontFamily: 'inherit',
    color: 'var(--text-default)',
    outline: 'none',
    transition: 'border-color 150ms, box-shadow 150ms',
  };
}

Object.assign(window, { FormScreen });
