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

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

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

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

  const errors = {
    name: !name.trim() ? 'Vui lòng nhập họ và tên' : null,
    dob: !dob ? 'Vui lòng chọn ngày sinh' : (dob > today ? 'Ngày sinh không thể trong tương lai' : null),
    email: 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;
    setSubmitting(true);
    setTimeout(() => {
      setSubmitting(false);
      onSubmit && onSubmit({ name, dob, email, gender });
    }, 1800);
  };

  // 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 ? 28 : 36, lineHeight: 1.1,
            margin: 0, marginBottom: 12,
            letterSpacing: '-0.02em', textWrap: 'balance',
            color: 'var(--text-default)',
          }}>
            Hãy cho Saladin biết một chút về bạn
          </h1>
          <p style={{
            fontSize: mobile ? 14 : 16, lineHeight: 1.6,
            margin: 0, marginBottom: mobile ? 24 : 32,
            color: 'var(--text-support)',
          }}>
            Chỉ cần họ tên và ngày sinh — bạn sẽ nhận được kết quả phân tích chỉ trong 30 giây.
          </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}
              hint="Ghi đầy đủ như trên giấy khai sinh để kết quả chính xác."
            >
              <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="Saladin chỉ dùng để thống kê, không hiển thị trong kết quả."
            >
              <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>

            <Field
              label="Ngày sinh"
              required
              icon="ri-calendar-line"
              error={touched.dob ? errors.dob : null}
              hint="Định dạng dd / mm / yyyy"
            >
              <input
                type="date"
                value={dob}
                max={today}
                onChange={(e) => setDob(e.target.value)}
                onBlur={() => setTouched(t => ({ ...t, dob: true }))}
                style={inputStyle(touched.dob && errors.dob)}
                disabled={submitting}
              />
            </Field>

            <Field
              label="Email"
              optional
              icon="ri-mail-line"
              error={touched.email ? errors.email : null}
              hint="Tuỳ chọn — nhập nếu bạn muốn nhận báo cáo PDF và tip hàng tháng."
            >
              <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>

            <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 note */}
            <div style={{
              display: 'flex', alignItems: 'flex-start', 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,
            }}>
              <i className="ri-shield-check-line" style={{ fontSize: 16, color: FORM_SG, marginTop: 1, flexShrink: 0 }}></i>
              <span><strong style={{ color: 'var(--text-default)', fontWeight: 600 }}>Saladin không chia sẻ thông tin.</strong> Tên và ngày sinh dùng để tính toán. Giới tính tuỳ chọn, chỉ dùng cho thống kê nội bộ.</span>
            </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>

          {/* Method hint */}
          <div style={{
            marginTop: 20,
            padding: '14px 16px',
            background: 'var(--bg-variant)',
            borderRadius: 8,
            border: '1px dashed var(--border-default)',
            display: 'flex', gap: 10, alignItems: 'flex-start',
          }}>
            <i className="ri-information-line" style={{ fontSize: 16, color: FORM_SN, marginTop: 1, flexShrink: 0 }}></i>
            <div style={{ fontSize: 12, lineHeight: 1.55, color: 'var(--text-support)' }}>
              Saladin sử dụng phương pháp <strong style={{ color: 'var(--text-default)', fontWeight: 600 }}>Pythagorean</strong> — phổ biến nhất trong thần số học hiện đại. Kết quả mang tính tham khảo và giải trí.
            </div>
          </div>
        </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',
    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 });
