// IntakeForm.jsx — Multi-step application form for 503.health
// Qualification gate: tier selection + financing commitment
// Cal.com link only shown on qualified success screen

const SUPABASE_URL = 'https://gfbmoqxrpnqxelqfpvdl.supabase.co';
const SUPABASE_ANON_KEY = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImdmYm1vcXhycG5xeGVscWZwdmRsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NDQ2NjUyNDEsImV4cCI6MjA2MDI0MTI0MX0.zbmfNVMBOKhxSF0t6_MRZ0FH2ymqJCAoYFnCKwpYB9I';
const CAL_LINK = 'https://cal.com/caleb-canales-e4lndt/30min?layout=mobile';

// Tiers that count as qualified (anything except "not sure")
const QUALIFIED_TIERS = [
  'Done-With-You Blueprint',
  'Done-For-You Build',
  'Convert & Exit',
];

const STEPS = [
  { id: 'q1',  field: 'name',             title: "What's your name?",                                                                    type: 'text',     placeholder: 'First and last name' },
  { id: 'q2',  field: 'email',            title: "What's your email?",                subtitle: "We'll only use this to follow up.",     type: 'email',    placeholder: 'you@company.com' },
  { id: 'q2b', field: 'phone',            title: 'Phone number?',                                                                        type: 'text',     placeholder: '(555) 555-5555' },
  { id: 'q3',  field: 'website',          title: 'Current brand website?',            subtitle: 'Your RUO site, telehealth site, or whatever you are running now.', type: 'url', placeholder: 'https://yourbrand.com' },
  { id: 'q4',  field: 'business_stage',   title: 'Where are you at right now?',                                                          type: 'single',   options: ['Running an RUO brand, want to convert to telehealth', 'Already doing telehealth but need better infrastructure', 'Have capital, want to enter the peptide/telehealth space', 'Running a supplement brand, want to add telehealth', 'Exploring options, doing research'] },
  { id: 'q5',  field: 'monthly_revenue',  title: 'Current monthly revenue?',                                                             type: 'single',   options: ['Pre-launch (no revenue yet)', 'Under $50K/month', '$50K to $100K/month', '$100K to $500K/month', '$500K to $1M/month', '$1M+/month'] },
  { id: 'q6',  field: 'payment_processor',title: 'Current payment processor?',                                                           type: 'single',   options: ['High-risk processor (NMI, Durango, etc.)', 'Stripe', 'PayPal', 'Shopify Payments', 'No processing set up yet', 'Processor recently dropped me'] },
  { id: 'q7',  field: 'help_needed',      title: 'What do you need the most help with?', subtitle: 'Select all that apply.',             type: 'multi',    options: ['Converting RUO brand to compliant telehealth', 'Prescriber network and physician oversight', 'Pharmacy partnerships (503A/503B)', 'Payment processing that won\'t shut me down', 'State licensing and telehealth registration', 'Marketing compliance and funnel rebuild', 'Exit positioning and acquisition readiness', 'Full done-for-you telehealth build from scratch'] },
  // Qualification step 1 — tier
  { id: 'q8',  field: 'investment_ready', title: 'Which path fits your situation?',   subtitle: 'Pick the one that matches where you are.',  type: 'single',   options: ['Done-With-You Blueprint', 'Done-For-You Build', 'Convert & Exit', 'Not sure yet'] },
  // Qualification step 2 — financing commitment (only shown if tier is qualified)
  { id: 'q9',  field: 'can_commit',       title: 'Are you able to commit, with eligible financing, between $15,000–$45,000 to get started immediately?', type: 'single', options: ['Yes, I am ready to move forward', 'No, not at this time'] },
  // Optional final notes
  { id: 'q10', field: 'additional_notes', title: 'Anything else?',                    subtitle: 'Optional. Tell us about your brand, goals, or questions.', type: 'longtext', placeholder: 'Current situation, timeline, questions...', optional: true },
];

const INITIAL_STATE = {
  name: '', email: '', phone: '', website: '', business_stage: '', monthly_revenue: '',
  payment_processor: '', help_needed: [], investment_ready: '', can_commit: '',
  additional_notes: '',
  // legacy fields for Supabase schema compatibility
  store_platform: 'N/A', running_ads: [], banned_platforms: 'N/A',
  match_listed: 'N/A', gmc_status: 'N/A', catalog_size: 'N/A', sells_script_products: 'N/A', ad_budget: 'N/A',
};

const IntakeForm = () => {
  const [stepIndex, setStepIndex] = React.useState(0);
  const [direction, setDirection] = React.useState('forward');
  const [form, setForm] = React.useState(INITIAL_STATE);
  const [submitting, setSubmitting] = React.useState(false);
  const [submitted, setSubmitted] = React.useState(false);
  const [qualified, setQualified] = React.useState(false);
  const [error, setError] = React.useState(null);

  const step = STEPS[stepIndex];
  const isLast = stepIndex === STEPS.length - 1;
  const progress = ((stepIndex + 1) / STEPS.length) * 100;
  const currentValue = form[step.field];
  const currentIsMulti = step.type === 'multi';

  // Determine if applicant is qualified based on answers so far
  const isQualifiedTier = QUALIFIED_TIERS.some(t => form.investment_ready.startsWith(t));
  const isCommitted = form.can_commit === 'Yes, I am ready to move forward';

  const canAdvance = (() => {
    if (step.optional) return true;
    if (currentIsMulti) return currentValue.length > 0;
    const v = (currentValue || '').trim();
    if (!v) return false;
    if (step.type === 'email') return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v);
    if (step.type === 'url') return v.length > 3;
    return true;
  })();

  const goNext = () => {
    if (!canAdvance) return;
    if (isLast) { submit(); return; }

    // After tier selection: if "Not sure yet", skip the financing question and go to notes
    if (step.field === 'investment_ready' && form.investment_ready === 'Not sure yet') {
      setDirection('forward');
      // Skip q9 (can_commit), jump to q10 (additional_notes)
      setStepIndex(STEPS.findIndex(s => s.field === 'additional_notes'));
      return;
    }

    setDirection('forward');
    setStepIndex(i => Math.min(i + 1, STEPS.length - 1));
  };

  const goBack = () => {
    if (stepIndex === 0) return;
    setDirection('back');
    // If we're on additional_notes and tier was "Not sure yet", skip back over can_commit
    if (step.field === 'additional_notes' && form.investment_ready === 'Not sure yet') {
      setStepIndex(STEPS.findIndex(s => s.field === 'investment_ready'));
      return;
    }
    setStepIndex(i => Math.max(i - 1, 0));
  };

  const setSingle = (val) => setForm(f => ({ ...f, [step.field]: val }));
  const toggleMulti = (val) => {
    setForm(f => {
      const arr = f[step.field] || [];
      const next = arr.includes(val) ? arr.filter(x => x !== val) : [...arr, val];
      return { ...f, [step.field]: next };
    });
  };
  const setText = (val) => setForm(f => ({ ...f, [step.field]: val }));

  const submit = async () => {
    setSubmitting(true);
    setError(null);
    // Determine qualification before submitting
    const tierQualified = QUALIFIED_TIERS.some(t => form.investment_ready.startsWith(t));
    const commitQualified = form.can_commit === 'Yes, I am ready to move forward';
    const isQualified = tierQualified && commitQualified;
    setQualified(isQualified);
    try {
      const res = await fetch(`${SUPABASE_URL}/functions/v1/submit-consulting-lead`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${SUPABASE_ANON_KEY}`,
          'apikey': SUPABASE_ANON_KEY,
        },
        body: JSON.stringify({ ...form, qualified: isQualified }),
      });
      const data = await res.json();
      if (!res.ok || (data && !data.success)) throw new Error(data.error || 'Submission failed');
      setSubmitted(true);
    } catch (err) {
      setError(err.message || 'Something went wrong. Please try again.');
    } finally {
      setSubmitting(false);
    }
  };

  const handleKeyDown = (e) => {
    if (e.key === 'Enter' && step.type !== 'longtext') { e.preventDefault(); goNext(); }
  };

  // ── SUCCESS SCREENS ──────────────────────────────────────────────────────────
  if (submitted && qualified) {
    return (
      <div style={{
        background: 'var(--bg)', borderRadius: 16,
        border: '1px solid var(--border)',
        padding: 'clamp(40px, 8vw, 72px) clamp(20px, 5vw, 48px)',
        textAlign: 'center', maxWidth: 560, margin: '0 auto'
      }}>
        <div style={{ width: 56, height: 56, borderRadius: '50%', background: 'rgba(5,150,105,0.1)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 24 }}>
          <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="var(--green)" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"></polyline></svg>
        </div>
        <h3 style={{ fontSize: 'clamp(20px, 5vw, 26px)', fontWeight: 700, marginBottom: 12 }}>You qualify. Book your call.</h3>
        <p style={{ fontSize: 15, color: 'var(--fg-2)', maxWidth: 420, margin: '0 auto 32px' }}>
          We reviewed your answers. You are a fit for the 503 Protocol. Book a 30-minute discovery call below and we will walk through exactly how we can convert your brand.
        </p>
        <a
          href={CAL_LINK}
          target="_blank"
          rel="noopener noreferrer"
          className="btn btn-primary"
          style={{ textDecoration: 'none', fontSize: 15, padding: '14px 28px', display: 'inline-flex' }}
        >
          Book your discovery call
        </a>
        <div style={{ marginTop: 12, fontSize: 13, color: 'var(--fg-3)' }}>
          30 minutes. No pitch, just a real conversation about your situation.
        </div>
      </div>
    );
  }

  if (submitted && !qualified) {
    return (
      <div style={{
        background: 'var(--bg)', borderRadius: 16,
        border: '1px solid var(--border)',
        padding: 'clamp(40px, 8vw, 72px) clamp(20px, 5vw, 48px)',
        textAlign: 'center', maxWidth: 560, margin: '0 auto'
      }}>
        <div style={{ width: 56, height: 56, borderRadius: '50%', background: 'rgba(100,116,139,0.1)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 24 }}>
          <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="var(--fg-2)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
        </div>
        <h3 style={{ fontSize: 'clamp(20px, 5vw, 26px)', fontWeight: 700, marginBottom: 12 }}>Not the right time — but keep us in mind.</h3>
        <p style={{ fontSize: 15, color: 'var(--fg-2)', maxWidth: 420, margin: '0 auto' }}>
          We have received your application. Right now the investment commitment isn't there, and we only work with operators who are ready to move. When your situation changes, come back and apply again.
        </p>
      </div>
    );
  }

  // ── FORM ─────────────────────────────────────────────────────────────────────
  return (
    <div style={{
      background: 'var(--bg)', borderRadius: 16,
      border: '1px solid var(--border)',
      overflow: 'hidden', maxWidth: 640, margin: '0 auto'
    }}>
      {/* Progress bar */}
      <div style={{ height: 3, background: 'var(--border)' }}>
        <div style={{ height: '100%', background: 'var(--navy)', width: `${progress}%`, transition: 'width 320ms cubic-bezier(0.2,0,0,1)' }}></div>
      </div>

      <div style={{ padding: 'clamp(24px, 5vw, 48px) clamp(16px, 4vw, 40px)', minHeight: 380, display: 'flex', flexDirection: 'column' }}>
        {step.optional && <div className="eyebrow" style={{ color: 'var(--fg-3)', marginBottom: 8 }}>Optional</div>}

        <div key={step.id} className={direction === 'forward' ? 'intake-anim-fwd' : 'intake-anim-back'} style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
          <h3 style={{ fontSize: 'clamp(16px, 4vw, 22px)', fontWeight: 700, lineHeight: 1.3, marginBottom: 8 }}>{step.title}</h3>
          {step.subtitle && <p style={{ fontSize: 14, color: 'var(--fg-2)', marginBottom: 24, maxWidth: 500 }}>{step.subtitle}</p>}
          {!step.subtitle && <div style={{ marginBottom: 24 }}></div>}

          <div style={{ flex: 1 }}>
            {(step.type === 'text' || step.type === 'email' || step.type === 'url') && (
              <input
                autoFocus
                type={step.type === 'email' ? 'email' : step.type === 'url' ? 'url' : 'text'}
                value={currentValue || ''}
                onChange={e => setText(e.target.value)}
                onKeyDown={handleKeyDown}
                placeholder={step.placeholder}
                style={{
                  width: '100%', padding: '14px 16px',
                  border: '1px solid var(--border)', borderRadius: 8,
                  fontFamily: 'var(--font-sans)', fontSize: 16,
                  outline: 'none', background: 'var(--bg)',
                  color: 'var(--fg)', boxSizing: 'border-box'
                }}
              />
            )}

            {step.type === 'longtext' && (
              <textarea
                autoFocus
                value={currentValue || ''}
                onChange={e => setText(e.target.value)}
                placeholder={step.placeholder}
                rows={4}
                style={{
                  width: '100%', padding: '14px 16px',
                  border: '1px solid var(--border)', borderRadius: 8,
                  fontFamily: 'var(--font-sans)', fontSize: 16,
                  outline: 'none', background: 'var(--bg)',
                  color: 'var(--fg)', resize: 'none', boxSizing: 'border-box'
                }}
              />
            )}

            {step.type === 'single' && step.options && (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {step.options.map(opt => {
                  const selected = currentValue === opt;
                  return (
                    <button type="button" key={opt}
                      onClick={() => {
                        setSingle(opt);
                        setTimeout(() => {
                          // After tier selection: skip financing if "Not sure yet"
                          if (step.field === 'investment_ready' && opt === 'Not sure yet') {
                            setDirection('forward');
                            setStepIndex(STEPS.findIndex(s => s.field === 'additional_notes'));
                          } else {
                            setDirection('forward');
                            setStepIndex(i => Math.min(i + 1, STEPS.length - 1));
                          }
                        }, 180);
                      }}
                      style={{
                        width: '100%', textAlign: 'left',
                        padding: '12px 16px', borderRadius: 8,
                        border: selected ? '1.5px solid var(--navy)' : '1px solid var(--border)',
                        background: selected ? 'rgba(30,58,138,0.04)' : 'var(--bg)',
                        cursor: 'pointer', display: 'flex',
                        alignItems: 'center', justifyContent: 'space-between',
                        gap: 12, fontFamily: 'var(--font-sans)',
                        fontSize: 14, fontWeight: 500,
                        color: selected ? 'var(--navy)' : 'var(--fg)',
                        transition: 'all 150ms cubic-bezier(0.2,0,0,1)',
                        minHeight: 44
                      }}>
                      <span>{opt}</span>
                      <span style={{
                        width: 18, height: 18, borderRadius: '50%',
                        border: selected ? '2px solid var(--navy)' : '1.5px solid var(--border)',
                        background: selected ? 'var(--navy)' : 'transparent',
                        display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0
                      }}>
                        {selected && <svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="3.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"></polyline></svg>}
                      </span>
                    </button>
                  );
                })}
              </div>
            )}

            {step.type === 'multi' && step.options && (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {step.options.map(opt => {
                  const arr = currentValue || [];
                  const selected = arr.includes(opt);
                  return (
                    <button type="button" key={opt}
                      onClick={() => toggleMulti(opt)}
                      style={{
                        width: '100%', textAlign: 'left',
                        padding: '12px 16px', borderRadius: 8,
                        border: selected ? '1.5px solid var(--navy)' : '1px solid var(--border)',
                        background: selected ? 'rgba(30,58,138,0.04)' : 'var(--bg)',
                        cursor: 'pointer', display: 'flex',
                        alignItems: 'center', justifyContent: 'space-between',
                        gap: 12, fontFamily: 'var(--font-sans)',
                        fontSize: 14, fontWeight: 500,
                        color: selected ? 'var(--navy)' : 'var(--fg)',
                        transition: 'all 150ms cubic-bezier(0.2,0,0,1)',
                        minHeight: 44
                      }}>
                      <span>{opt}</span>
                      <span style={{
                        width: 18, height: 18, borderRadius: 5,
                        border: selected ? '2px solid var(--navy)' : '1.5px solid var(--border)',
                        background: selected ? 'var(--navy)' : 'transparent',
                        display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0
                      }}>
                        {selected && <svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="3.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"></polyline></svg>}
                      </span>
                    </button>
                  );
                })}
              </div>
            )}
          </div>

          {error && (
            <div style={{ marginTop: 20, padding: '12px 16px', borderRadius: 8, background: '#FEF2F2', border: '1px solid #FECACA', color: '#DC2626', fontSize: 13, display: 'flex', gap: 8, alignItems: 'center' }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>
              <span>{error}</span>
            </div>
          )}

          <div style={{ marginTop: 32, display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16 }}>
            <button type="button" onClick={goBack} disabled={stepIndex === 0 || submitting}
              style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 14, fontWeight: 500, color: 'var(--fg-2)', background: 'none', border: 'none', cursor: 'pointer', opacity: stepIndex === 0 ? 0.4 : 1, fontFamily: 'var(--font-sans)', padding: '8px 0', width: 'auto' }}>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="19" y1="12" x2="5" y2="12"/><polyline points="12 19 5 12 12 5"/></svg>
              Back
            </button>

            {step.type !== 'single' && (
              <button type="button" onClick={goNext} disabled={!canAdvance || submitting}
                className="btn btn-primary"
                style={{ padding: '12px 24px', fontSize: 14, opacity: (!canAdvance || submitting) ? 0.5 : 1, cursor: (!canAdvance || submitting) ? 'not-allowed' : 'pointer', width: 'auto' }}>
                {submitting ? 'Submitting...' : isLast ? 'Submit application' : 'Next'}
              </button>
            )}
          </div>
        </div>
      </div>

      <style>{`
        @keyframes intakeFwd  { from { opacity: 0; transform: translateX(24px);  } to { opacity: 1; transform: translateX(0); } }
        @keyframes intakeBack { from { opacity: 0; transform: translateX(-24px); } to { opacity: 1; transform: translateX(0); } }
        .intake-anim-fwd  { animation: intakeFwd  320ms cubic-bezier(0.22,1,0.36,1) both; }
        .intake-anim-back { animation: intakeBack 320ms cubic-bezier(0.22,1,0.36,1) both; }
      `}</style>
    </div>
  );
};
window.IntakeForm = IntakeForm;
