// FastFund website — interactive multi-step "Apply" flow (modal)
// Submissions POST to Web3Forms -> emailed to FastFund inbox.
function ApplyFlow({ open, onClose }) {
  const { Button, Field, Select, Checkbox, Logo } = window.CapFrontDesignSystem_019e08;
  const { mobile } = window.useBreakpoint();
  const WEB3FORMS_KEY = '841d6bce-eb09-417b-8309-4db6c5f2ed48';

  const emptyForm = {
    business: '', name: '', email: '', phone: '',
    timeInBusiness: '2+ years', industry: 'Retail',
    amount: '', revenue: '$50K–$150K', useOfFunds: 'Working capital',
    agree: false,
  };
  const [step, setStep] = React.useState(0);        // 0,1 = form steps; 2 = confirmation
  const [form, setForm] = React.useState(emptyForm);
  const [status, setStatus] = React.useState('idle'); // idle | sending | error
  const [errors, setErrors] = React.useState({});

  React.useEffect(() => { if (open) { setStep(0); setForm(emptyForm); setStatus('idle'); setErrors({}); } }, [open]);
  React.useEffect(() => { window.lucide && window.lucide.createIcons(); });
  if (!open) return null;

  const set = (k) => (e) => {
    const v = e && e.target ? (e.target.type === 'checkbox' ? e.target.checked : e.target.value) : e;
    setForm((f) => ({ ...f, [k]: v }));
    setErrors((er) => ({ ...er, [k]: undefined }));
  };

  const steps = ['Your business', 'Funding need', 'Done'];

  const validateStep0 = () => {
    const er = {};
    if (!form.business.trim()) er.business = 'Required';
    if (!form.name.trim()) er.name = 'Required';
    if (!form.email.trim()) er.email = 'Required';
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) er.email = 'Enter a valid email';
    if (!form.phone.trim()) er.phone = 'Required';
    setErrors(er);
    return Object.keys(er).length === 0;
  };
  const validateStep1 = () => {
    const er = {};
    if (!form.amount.trim()) er.amount = 'Required';
    if (!form.agree) er.agree = 'Please accept to continue';
    setErrors(er);
    return Object.keys(er).length === 0;
  };

  const submit = async () => {
    if (!validateStep1()) return;
    setStatus('sending');
    try {
      const res = await fetch('https://api.web3forms.com/submit', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
        body: JSON.stringify({
          access_key: WEB3FORMS_KEY,
          subject: `New funding application — ${form.business || 'Unknown business'}`,
          from_name: 'FastFund Website',
          replyto: form.email,
          ccemail: 'r.weber@capfrontfunding.com',
          'Business name': form.business,
          'Contact name': form.name,
          Email: form.email,
          Phone: form.phone,
          'Time in business': form.timeInBusiness,
          Industry: form.industry,
          'Requested amount': form.amount ? `$${form.amount}` : '',
          'Monthly revenue': form.revenue,
          'Use of funds': form.useOfFunds,
        }),
      });
      const data = await res.json();
      if (data.success) { setStatus('idle'); setStep(2); }
      else setStatus('error');
    } catch (e) {
      setStatus('error');
    }
  };

  const Progress = () => (
    <div style={{ display: 'flex', gap: 8, marginBottom: 'var(--space-6)' }}>
      {steps.map((s, i) => (
        <div key={s} style={{ flex: 1 }}>
          <div style={{ height: 4, borderRadius: 999, background: i <= step ? 'var(--teal-500)' : 'var(--neutral-200)', transition: 'background var(--duration-normal) var(--ease-standard)' }} />
          <div style={{ fontFamily: 'var(--font-body)', fontSize: 11.5, fontWeight: 600, marginTop: 6, color: i <= step ? 'var(--violet-700)' : 'var(--text-subtle)' }}>{s}</div>
        </div>
      ))}
    </div>
  );

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 100, background: 'rgba(20,18,31,0.6)',
      backdropFilter: 'blur(4px)', display: 'flex', alignItems: mobile ? 'flex-start' : 'center', justifyContent: 'center', padding: mobile ? 12 : 24,
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        width: 'min(540px, 100%)', maxHeight: mobile ? '96vh' : '90vh', overflow: 'auto', background: 'var(--surface-card)',
        borderRadius: 'var(--radius-2xl)', boxShadow: 'var(--shadow-xl)', padding: mobile ? 'var(--space-6)' : 'var(--space-8)',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 'var(--space-6)' }}>
          <Logo size={24} />
          <button onClick={onClose} aria-label="Close" style={{ border: 'none', background: 'var(--neutral-100)', width: 34, height: 34, borderRadius: 'var(--radius-md)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <i data-lucide="x" style={{ width: 18, height: 18, color: 'var(--text-muted)' }}></i>
          </button>
        </div>

        <Progress />

        {step === 0 && (
          <div>
            <h3 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 24, color: 'var(--text-strong)', margin: '0 0 6px' }}>Tell us about your business</h3>
            <p style={{ fontFamily: 'var(--font-body)', fontSize: 14.5, color: 'var(--text-muted)', margin: '0 0 var(--space-6)' }}>Applying won't affect your credit score. A funding manager will follow up personally.</p>
            <div style={{ display: 'grid', gridTemplateColumns: mobile ? '1fr' : '1fr 1fr', gap: 'var(--space-4)' }}>
              <Field label="Business name" placeholder="Your company" value={form.business} onChange={set('business')} error={errors.business} />
              <Field label="Your name" placeholder="First and last" value={form.name} onChange={set('name')} error={errors.name} />
              <Field label="Email" type="email" placeholder="you@company.com" value={form.email} onChange={set('email')} error={errors.email} />
              <Field label="Phone" type="tel" placeholder="(555) 555-5555" value={form.phone} onChange={set('phone')} error={errors.phone} />
              <Select label="Time in business" options={['< 6 months', '6–12 months', '1–2 years', '2+ years']} value={form.timeInBusiness} onChange={set('timeInBusiness')} />
              <Select label="Industry" options={['Retail', 'Restaurant', 'Construction', 'Healthcare', 'Services', 'Other']} value={form.industry} onChange={set('industry')} />
            </div>
          </div>
        )}

        {step === 1 && (
          <div>
            <h3 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 24, color: 'var(--text-strong)', margin: '0 0 6px' }}>What do you need?</h3>
            <p style={{ fontFamily: 'var(--font-body)', fontSize: 14.5, color: 'var(--text-muted)', margin: '0 0 var(--space-6)' }}>We'll match you with the right products from our marketplace.</p>
            <div style={{ display: 'grid', gridTemplateColumns: mobile ? '1fr' : '1fr 1fr', gap: 'var(--space-4)' }}>
              <Field label="Requested amount" prefix="$" placeholder="150,000" value={form.amount} onChange={set('amount')} error={errors.amount} />
              <Select label="Monthly revenue" options={['< $10K', '$10K–$50K', '$50K–$150K', '$150K+']} value={form.revenue} onChange={set('revenue')} />
            </div>
            <div style={{ marginTop: 'var(--space-4)' }}>
              <Select label="Primary use of funds" options={['Working capital', 'Equipment purchase', 'Inventory', 'Expansion', 'Acquisition']} value={form.useOfFunds} onChange={set('useOfFunds')} />
            </div>
            <div style={{ marginTop: 'var(--space-6)' }}>
              <Checkbox label="I agree to FastFund's terms and privacy policy" checked={form.agree} onChange={set('agree')} />
              {errors.agree && <div style={{ fontFamily: 'var(--font-body)', fontSize: 12.5, color: 'var(--red-600)', marginTop: 6 }}>{errors.agree}</div>}
            </div>
            {status === 'error' && (
              <div style={{ marginTop: 'var(--space-4)', padding: '12px 14px', borderRadius: 'var(--radius-md)', background: 'var(--status-danger-bg, #fdecec)', color: 'var(--red-700, #8a2b2b)', fontFamily: 'var(--font-body)', fontSize: 13.5 }}>
                Something went wrong sending your application. Please try again, or call us at 844-466-6394.
              </div>
            )}
          </div>
        )}

        {step === 2 && (
          <div style={{ textAlign: 'center', padding: 'var(--space-4) 0 var(--space-2)' }}>
            <span style={{ width: 56, height: 56, borderRadius: '50%', background: 'var(--status-success-bg)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 'var(--space-4)' }}>
              <i data-lucide="check" style={{ width: 28, height: 28, color: 'var(--green-600)' }}></i>
            </span>
            <h3 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 24, color: 'var(--text-strong)', margin: '0 0 8px' }}>Application received</h3>
            <p style={{ fontFamily: 'var(--font-body)', fontSize: 15, color: 'var(--text-muted)', margin: '0 auto var(--space-6)', maxWidth: 380, lineHeight: 1.55 }}>
              Thanks{form.name ? `, ${form.name.split(' ')[0]}` : ''}. A FastFund funding manager will review your request and reach out within one business day to walk you through your options.
            </p>
            <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, padding: '10px 16px', borderRadius: 'var(--radius-md)', background: 'var(--surface-sunken)', fontFamily: 'var(--font-body)', fontSize: 13.5, color: 'var(--text-body)' }}>
              <i data-lucide="phone" style={{ width: 16, height: 16, color: 'var(--teal-600)' }}></i>
              Need it faster? Call 844-466-6394
            </div>
          </div>
        )}

        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 'var(--space-8)' }}>
          {step < 2 ? (
            <React.Fragment>
              <Button variant="ghost" onClick={step === 0 ? onClose : () => setStep(step - 1)} disabled={status === 'sending'}>
                {step === 0 ? 'Cancel' : 'Back'}
              </Button>
              {step === 0 ? (
                <Button variant="accent" onClick={() => { if (validateStep0()) setStep(1); }}
                  iconRight={<i data-lucide="arrow-right" style={{ width: 18, height: 18 }}></i>}>
                  Continue
                </Button>
              ) : (
                <Button variant="accent" onClick={submit} disabled={status === 'sending'}
                  iconRight={status === 'sending' ? null : <i data-lucide="send" style={{ width: 18, height: 18 }}></i>}>
                  {status === 'sending' ? 'Sending…' : 'Submit application'}
                </Button>
              )}
            </React.Fragment>
          ) : (
            <Button variant="accent" onClick={onClose} style={{ marginLeft: 'auto' }}>
              Done
            </Button>
          )}
        </div>
      </div>
    </div>
  );
}
window.ApplyFlow = ApplyFlow;
