// Multi-step onboarding modal

const OB_STYLES = `
  @keyframes ob-in-r    { from { opacity:0; transform:translateX(20px); }   to { opacity:1; transform:none; } }
  @keyframes ob-in-l    { from { opacity:0; transform:translateX(-20px); }  to { opacity:1; transform:none; } }
  @keyframes ob-fadein  { from { opacity:0; transform:translateY(8px); }    to { opacity:1; transform:none; } }
  @keyframes ob-sheet-in { from { transform:translateY(100%); } to { transform:translateY(0); } }

  @media (max-width: 640px) {
    .ob-overlay { align-items: flex-end !important; padding: 0 !important; }
    .ob-card {
      max-width: 100% !important;
      border-radius: 20px 20px 0 0 !important;
      max-height: 92dvh;
      overflow-y: auto;
      -webkit-overflow-scrolling: touch;
      animation: ob-sheet-in .32s cubic-bezier(.2,.8,.2,1) both !important;
      transform: none !important;
    }
    .ob-drag-handle {
      display: block !important;
    }
  }
`;

const OnboardingModal = ({ onClose }) => {
  const [step, setStep] = React.useState(0);
  const [animKey, setAnimKey] = React.useState(0);
  const dirRef = React.useRef(1);
  const [visible, setVisible] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [form, setForm] = React.useState({
    usBusiness: '', employees: '', investment: '', company: '', email: '',
  });

  const submitToAirtable = async () => {
    try {
      await fetch('https://api.airtable.com/v0/appdoa6nI3kqBnjXJ/tblYQ6cxF4D4tdVsZ', {
        method: 'POST',
        headers: {
          'Authorization': 'Bearer patGLGptUGEJRgsxI.0310c570e690e00dafb604b3c6e87bc88e28ad9aef28d95181e0d3f64862281e',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          fields: {
            email:      form.email,
            company:    form.company,
            usBusiness: form.usBusiness,
            employees:  form.employees,
            investment: form.investment,
            source:     new URLSearchParams(location.search).get('utm_source') || 'direct',
          }
        }),
      });
    } catch (e) {
      // 실패해도 사용자에겐 성공 화면 표시
    }
  };

  React.useEffect(() => { requestAnimationFrame(() => setVisible(true)); }, []);

  // lock body scroll
  React.useEffect(() => {
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => { document.body.style.overflow = prev; };
  }, []);

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const go = (next) => {
    dirRef.current = next > step ? 1 : -1;
    setAnimKey(k => k + 1);
    setStep(next);
  };

  const handleClose = () => {
    setVisible(false);
    setTimeout(onClose, 260);
  };

  const canNext = [
    !!(form.usBusiness && form.employees),
    !!form.investment,
    !!(form.company.trim() && /\S+@\S+\.\S+/.test(form.email)),
    true,
  ][step];

  const animName = dirRef.current > 0 ? 'ob-in-r' : 'ob-in-l';

  return (
    <>
      <style>{OB_STYLES}</style>
      <div
        className="ob-overlay"
        onClick={e => { if (e.target === e.currentTarget) handleClose(); }}
        style={{
          position: 'fixed', inset: 0, zIndex: 300,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          padding: '24px 16px',
          background: 'rgba(10,10,14,0.52)',
          backdropFilter: 'blur(8px)',
          WebkitBackdropFilter: 'blur(8px)',
          transition: 'opacity .26s ease',
          opacity: visible ? 1 : 0,
        }}
      >
        <div
          className="ob-card"
          style={{
            background: '#fff',
            borderRadius: 24,
            width: '100%',
            maxWidth: 460,
            boxShadow: '0 40px 80px -20px rgba(10,10,30,.3)',
            overflow: 'hidden',
            transition: 'transform .28s cubic-bezier(.2,.8,.2,1), opacity .28s ease',
            transform: visible ? 'translateY(0) scale(1)' : 'translateY(20px) scale(.97)',
            opacity: visible ? 1 : 0,
          }}
        >
          {/* Drag handle — 모바일에서만 표시 */}
          <div className="ob-drag-handle" style={{
            display: 'none', margin: '10px auto 0',
            width: 36, height: 4, borderRadius: 99,
            background: 'var(--line)',
          }} />

          {/* ── Header ── */}
          {step < 3 && (
            <div style={{ padding: '26px 28px 0', display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
              <div>
                <div style={{ fontSize: 11, letterSpacing: '.14em', textTransform: 'uppercase', color: 'var(--accent)', fontWeight: 600, marginBottom: 8 }}>
                  Part {step + 1} of 3
                </div>
                <h2 style={{ fontFamily: "'Newsreader', serif", fontWeight: 400, fontSize: 25, margin: 0, letterSpacing: '-0.015em', color: 'var(--ink)', lineHeight: 1.2 }}>
                  {['Tell us about your company', 'Funding background', 'Almost there'][step]}
                </h2>
              </div>
              <button onClick={handleClose} style={{
                width: 30, height: 30, borderRadius: '50%', border: '1px solid var(--line)',
                background: 'var(--paper)', display: 'grid', placeItems: 'center',
                cursor: 'pointer', flexShrink: 0, marginLeft: 16, color: 'var(--muted)',
                fontSize: 18, lineHeight: 1, fontFamily: 'inherit',
              }}>×</button>
            </div>
          )}

          {/* ── Progress bar ── */}
          {step < 3 && (
            <div style={{ padding: '14px 28px 0' }}>
              <div style={{ height: 3, background: 'var(--lavender)', borderRadius: 99 }}>
                <div style={{
                  height: '100%', borderRadius: 99, background: 'var(--accent)',
                  width: `${((step + 1) / 3) * 100}%`,
                  transition: 'width .4s cubic-bezier(.2,.8,.2,1)',
                }} />
              </div>
            </div>
          )}

          {/* ── Animated content ── */}
          <div
            key={animKey}
            style={{
              padding: step < 3 ? '24px 28px 28px' : 0,
              animation: `${step === 0 ? 'ob-fadein' : animName} .26s cubic-bezier(.2,.8,.2,1) both`,
            }}
          >
            {step === 0 && (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
                <OBSelect
                  label="Is this a US-registered business?"
                  value={form.usBusiness}
                  onChange={v => set('usBusiness', v)}
                  options={[
                    { value: 'yes',    label: 'Yes, incorporated in the US' },
                    { value: 'no',     label: 'No, registered outside the US' },
                    { value: 'unsure', label: 'Not sure' },
                  ]}
                />
                <OBSelect
                  label="How many full-time employees?"
                  value={form.employees}
                  onChange={v => set('employees', v)}
                  options={[
                    { value: '1-5',    label: '1 – 5' },
                    { value: '6-20',   label: '6 – 20' },
                    { value: '21-50',  label: '21 – 50' },
                    { value: '51-200', label: '51 – 200' },
                    { value: '200+',   label: '200+' },
                  ]}
                />
              </div>
            )}

            {step === 1 && (
              <OBSelect
                label="How much total investment has the company raised?"
                value={form.investment}
                onChange={v => set('investment', v)}
                options={[
                  { value: 'none',      label: 'Bootstrapped — no outside funding' },
                  { value: 'under500k', label: 'Under $500K' },
                  { value: '500k-2m',   label: '$500K – $2M' },
                  { value: '2m-10m',    label: '$2M – $10M' },
                  { value: '10m+',      label: '$10M+' },
                ]}
              />
            )}

            {step === 2 && (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
                <OBInput label="Company name"  value={form.company} onChange={v => set('company', v)} placeholder="Acme Inc." />
                <OBInput label="Your email"    value={form.email}   onChange={v => set('email', v)}   placeholder="you@company.com" type="email" />
              </div>
            )}

            {step === 3 && <OBSuccess />}
          </div>

          {/* ── Footer ── */}
          {step < 3 && (
            <div style={{ padding: '0 28px 26px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <button
                onClick={() => go(step - 1)}
                style={{
                  background: 'none', border: 'none', padding: 0, fontFamily: 'inherit',
                  fontSize: 13.5, color: 'var(--muted)', cursor: 'pointer',
                  opacity: step > 0 ? 1 : 0, pointerEvents: step > 0 ? 'auto' : 'none',
                  transition: 'opacity .2s, color .15s',
                }}
                onMouseEnter={e => e.target.style.color = 'var(--ink)'}
                onMouseLeave={e => e.target.style.color = 'var(--muted)'}
              >← Back</button>

              <button
                onClick={async () => {
                if (!canNext) return;
                if (step === 2) {
                  setSubmitting(true);
                  await submitToAirtable();
                  setSubmitting(false);
                }
                go(step + 1);
              }}
                style={{
                  background: canNext ? 'var(--ink)' : 'var(--lavender-2)',
                  color: canNext ? '#fff' : 'var(--muted-2)',
                  border: 'none', borderRadius: 999,
                  padding: '11px 26px', fontSize: 14, fontWeight: 500,
                  cursor: canNext ? 'pointer' : 'default',
                  fontFamily: 'inherit',
                  transition: 'background .2s, color .2s, transform .15s, box-shadow .2s',
                }}
                onMouseEnter={e => { if (canNext) { e.target.style.transform = 'translateY(-1px)'; e.target.style.boxShadow = '0 8px 20px rgba(0,0,0,.15)'; }}}
                onMouseLeave={e => { e.target.style.transform = ''; e.target.style.boxShadow = ''; }}
              >
                {submitting ? 'Submitting…' : step === 2 ? 'Submit' : 'Continue →'}
              </button>
            </div>
          )}
        </div>
      </div>
    </>
  );
};

const OBSelect = ({ label, value, onChange, options }) => (
  <div>
    <label style={{ display: 'block', fontSize: 12.5, fontWeight: 500, color: 'var(--ink-2)', marginBottom: 7 }}>{label}</label>
    <div style={{ position: 'relative' }}>
      <select
        value={value}
        onChange={e => onChange(e.target.value)}
        style={{
          width: '100%', appearance: 'none', WebkitAppearance: 'none',
          background: value ? '#fff' : 'var(--paper)',
          border: `1.5px solid ${value ? 'var(--accent)' : 'var(--line)'}`,
          borderRadius: 10, padding: '10px 36px 10px 13px',
          fontSize: 14, color: value ? 'var(--ink)' : 'var(--muted)',
          cursor: 'pointer', fontFamily: 'inherit', outline: 'none',
          transition: 'border-color .18s, background .18s',
        }}
        onFocus={e => { e.target.style.borderColor = 'var(--accent)'; e.target.style.background = '#fff'; }}
        onBlur={e => { if (!e.target.value) e.target.style.borderColor = 'var(--line)'; }}
      >
        <option value="" disabled>Select an option</option>
        {options.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
      </select>
      <span style={{ position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)', pointerEvents: 'none', color: 'var(--muted)', fontSize: 11 }}>▾</span>
    </div>
  </div>
);

const OBInput = ({ label, value, onChange, placeholder, type = 'text' }) => (
  <div>
    <label style={{ display: 'block', fontSize: 12.5, fontWeight: 500, color: 'var(--ink-2)', marginBottom: 7 }}>{label}</label>
    <input
      type={type}
      value={value}
      onChange={e => onChange(e.target.value)}
      placeholder={placeholder}
      style={{
        width: '100%', boxSizing: 'border-box',
        background: '#fff', border: '1.5px solid var(--line)',
        borderRadius: 10, padding: '10px 13px',
        fontSize: 14, color: 'var(--ink)',
        fontFamily: 'inherit', outline: 'none',
        transition: 'border-color .18s',
      }}
      onFocus={e => e.target.style.borderColor = 'var(--accent)'}
      onBlur={e => e.target.style.borderColor = 'var(--line)'}
    />
  </div>
);

const OBSuccess = () => {
  const [show, setShow] = React.useState(false);
  React.useEffect(() => { const t = setTimeout(() => setShow(true), 60); return () => clearTimeout(t); }, []);

  return (
    <div style={{ padding: '52px 28px 44px', display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center' }}>
      {/* Animated checkmark circle */}
      <div style={{
        width: 68, height: 68, borderRadius: '50%',
        background: 'var(--green-soft)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        marginBottom: 20,
        boxShadow: show ? '0 0 0 14px rgba(47,143,95,.07), 0 0 0 28px rgba(47,143,95,.03)' : '0 0 0 0px rgba(47,143,95,0)',
        transition: 'box-shadow .6s ease .1s',
      }}>
        <svg viewBox="0 0 24 24" fill="none" stroke="var(--green)" strokeWidth="2.5"
          strokeLinecap="round" strokeLinejoin="round"
          style={{
            width: 30, height: 30,
            strokeDasharray: 30,
            strokeDashoffset: show ? 0 : 30,
            transition: 'stroke-dashoffset .45s cubic-bezier(.2,.8,.2,1) .18s',
          }}>
          <polyline points="20 6 9 17 4 12" />
        </svg>
      </div>

      {/* Verified badge */}
      <div style={{
        display: 'inline-flex', alignItems: 'center', gap: 5,
        background: 'var(--green-soft)', color: 'var(--green)',
        padding: '4px 12px', borderRadius: 999, fontSize: 11.5, fontWeight: 600,
        letterSpacing: '.1em', textTransform: 'uppercase', marginBottom: 18,
        opacity: show ? 1 : 0, transition: 'opacity .4s ease .35s',
      }}>
        <span style={{ fontSize: 10 }}>✓</span> Verified
      </div>

      <h2 style={{
        fontFamily: "'Newsreader', serif", fontWeight: 400,
        fontSize: 26, margin: '0 0 10px', letterSpacing: '-0.015em', color: 'var(--ink)',
        opacity: show ? 1 : 0, transform: show ? 'none' : 'translateY(6px)',
        transition: 'opacity .4s ease .4s, transform .4s ease .4s',
      }}>
        You're on the list
      </h2>
      <p style={{
        fontSize: 14.5, color: 'var(--muted)', lineHeight: 1.65, margin: 0, maxWidth: '30ch',
        opacity: show ? 1 : 0, transform: show ? 'none' : 'translateY(6px)',
        transition: 'opacity .4s ease .5s, transform .4s ease .5s',
      }}>
        We'll be in touch shortly.
      </p>
    </div>
  );
};

window.OnboardingModal = OnboardingModal;
