// SponsorshipForm.jsx — interactive form with validation
function SponsorshipForm({ selectedTier, onSubmit }) {
  const { useState } = React;
  const [data, setData] = useState({
    name: '', company: '', email: '', phone: '',
    recognitionName: '', website: '',
    address: '', city: '', state: '', zip: '',
    customAmount: '', logoNotes: '',
    agree: false,
  });
  const [errors, setErrors] = useState({});
  const [loading, setLoading] = useState(false);

  const set = (k, v) => setData(d => ({ ...d, [k]: v }));
  const amount = selectedTier?.customAmount
    ? Number(String(data.customAmount).replace(/[^0-9.]/g, '')) || 0
    : selectedTier?.price || 0;
  const amountLabel = selectedTier?.customAmount
    ? (amount > 0 ? `$${amount.toLocaleString()}` : 'Custom amount')
    : `$${amount.toLocaleString()}`;

  const validate = () => {
    const e = {};
    if (selectedTier?.customAmount && amount < 1) e.customAmount = 'Enter a donation amount';
    if (!data.name.trim()) e.name = 'Required';
    if (!data.company.trim()) e.company = 'Required';
    if (!data.email.trim()) e.email = 'Required';
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data.email)) e.email = 'Invalid email';
    if (!data.phone.trim()) e.phone = 'Required';
    if (!data.agree) e.agree = 'You must agree to continue';
    return e;
  };

  const handleSubmit = async (ev) => {
    ev.preventDefault();
    const e = validate();
    setErrors(e);
    if (Object.keys(e).length) return;
    setLoading(true);

    const payload = {
      tier: {
        id: selectedTier.id,
        name: selectedTier.name,
        price: selectedTier.price,
        customAmount: !!selectedTier.customAmount,
      },
      amount,
      sponsor: {
        name: data.name.trim(),
        company: data.company.trim(),
        recognitionName: data.recognitionName.trim(),
        email: data.email.trim(),
        phone: data.phone.trim(),
        website: data.website.trim(),
        address: data.address.trim(),
        city: data.city.trim(),
        state: data.state.trim(),
        zip: data.zip.trim(),
        logoNotes: data.logoNotes.trim(),
      },
      submittedAt: new Date().toISOString(),
      source: window.location.href,
    };

    try {
      const res = await fetch('/api/sponsor', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });
      const result = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(result.error || 'Submission could not be sent. Please email sponsor@viperbasketball.co.');
      setLoading(false);
      onSubmit({ tier: selectedTier, amount, ...data, delivery: result });
    } catch (err) {
      const localPreview = ['localhost', '127.0.0.1', ''].includes(window.location.hostname) || window.location.protocol === 'file:';
      setLoading(false);
      if (localPreview) {
        onSubmit({
          tier: selectedTier,
          amount,
          ...data,
          delivery: { ok: true, emailed: false, mode: 'local-preview', message: 'Local preview submission.' },
        });
        return;
      }
      setErrors({ submit: err.message || 'Submission could not be sent. Please email sponsor@viperbasketball.co.' });
    }
  };

  if (!selectedTier) {
    return (
      <section className="section" data-anchor id="form" style={{ borderBottom: '1px solid var(--border)' }}>
        <div className="section-narrow" style={{ maxWidth: 720 }}>
          <div style={{
            border: '1px dashed var(--viper-steel)',
            borderRadius: 6,
            padding: '64px 32px',
            textAlign: 'center',
            background: 'rgba(0,0,0,0.4)',
          }}>
            <div className="eyebrow" style={{ marginBottom: 16 }}>Step 02</div>
            <h2 className="chrome-text" style={{ fontSize: 'clamp(36px, 5vw, 56px)', margin: 0 }}>
              Pick a Tier First
            </h2>
            <p style={{ marginTop: 16, color: 'var(--fg-3)' }}>
              Select a sponsorship tier above to unlock the form.
            </p>
            <a href="#tiers" className="viper-btn-ghost" style={{
              display: 'inline-block', marginTop: 18, textDecoration: 'none',
            }}>↑ Back to Tiers</a>
          </div>
        </div>
      </section>
    );
  }

  return (
    <section className="section" data-anchor id="form" style={{ borderBottom: '1px solid var(--border)' }}>
      <div className="section-narrow" style={{ maxWidth: 820 }}>
        <div style={{ textAlign: 'center', marginBottom: 40 }}>
          <div className="eyebrow" style={{ marginBottom: 12 }}>Step 02 · Complete Sponsorship</div>
          <h2 className="chrome-text" style={{ fontSize: 'clamp(40px, 5.5vw, 72px)', margin: 0 }}>
            Suit Up
          </h2>
        </div>

        {/* Selected tier callout */}
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          gap: 16, flexWrap: 'wrap',
          padding: '20px 24px',
          marginBottom: 32,
          background: 'linear-gradient(180deg, #1a1a1a 0%, #0a0a0a 100%)',
          border: '1px solid var(--viper-platinum)',
          borderRadius: 6,
          boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.18), 0 6px 20px rgba(0,0,0,0.6)',
        }}>
          <div>
            <div className="eyebrow" style={{ marginBottom: 6 }}>Selected Tier</div>
            <div style={{
              fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 26,
              textTransform: 'uppercase', letterSpacing: '0.02em',
              color: 'var(--viper-white)', lineHeight: 1,
            }}>{selectedTier.name}</div>
          </div>
          <div style={{
            fontFamily: 'var(--font-display)', fontWeight: 900,
            fontSize: 44, lineHeight: 1,
            background: 'var(--chrome-gradient)',
            WebkitBackgroundClip: 'text', backgroundClip: 'text', color: 'transparent',
            WebkitTextStroke: '0.5px #000',
          }}>{amountLabel}</div>
        </div>

        <form onSubmit={handleSubmit} noValidate>
          {selectedTier.customAmount && (
            <FormSection title="Open Shot Amount" step="00" subtitle="Flexible giving">
              <Field label="Donation Amount" required type="number" value={data.customAmount} error={errors.customAmount}
                onChange={v => set('customAmount', v)} />
              <p style={{ marginTop: 12, fontSize: 13, color: 'var(--fg-3)' }}>
                Examples: $750 earns Hole Sponsor benefits, $1,200 earns Game Day benefits,
                and $2,000 earns Three-Point benefits.
              </p>
            </FormSection>
          )}

          {/* Contact */}
          <FormSection title="Contact Information" step="01">
            <Grid2>
              <Field label="Full Name" required value={data.name} error={errors.name}
                onChange={v => set('name', v)} />
              <Field label="Business Name" required value={data.company} error={errors.company}
                onChange={v => set('company', v)} />
              <Field label="Recognition Name" value={data.recognitionName}
                onChange={v => set('recognitionName', v)} />
              <Field label="Website / Social" value={data.website}
                onChange={v => set('website', v)} />
              <Field label="Email" required type="email" value={data.email} error={errors.email}
                onChange={v => set('email', v)} />
              <Field label="Phone" required type="tel" value={data.phone} error={errors.phone}
                onChange={v => set('phone', v)} />
            </Grid2>
          </FormSection>

          {/* Address */}
          <FormSection title="Business Address" step="02" subtitle="Optional · for invoice & tax receipt">
            <div style={{ marginBottom: 14 }}>
              <Field label="Street Address" value={data.address}
                onChange={v => set('address', v)} />
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(150px, 1fr))', gap: 14 }}>
              <Field label="City" value={data.city} onChange={v => set('city', v)} />
              <Field label="State" value={data.state} onChange={v => set('state', v)} />
              <Field label="ZIP" value={data.zip} onChange={v => set('zip', v)} />
            </div>
          </FormSection>

          {/* Logo / brand notes */}
          <FormSection title="Brand Assets" step="03" subtitle="We'll follow up for logo files">
            <label className="viper-label">Notes for the booster team</label>
            <textarea
              className="viper-input"
              rows={3}
              value={data.logoNotes}
              onChange={e => set('logoNotes', e.target.value)}
              style={{ resize: 'vertical', fontFamily: 'var(--font-body)' }}
            />
          </FormSection>

          {/* Payment note — booster club follows up directly */}
          <FormSection title="Payment" step="04" subtitle="No payment collected here">
            <div style={{
              display: 'flex', gap: 16, alignItems: 'flex-start',
              padding: '20px 22px',
              background: 'linear-gradient(180deg, #161616 0%, #0a0a0a 100%)',
              border: '1px solid var(--border)',
              borderRadius: 4,
              boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.06)',
            }}>
              <span style={{
                flexShrink: 0,
                width: 32, height: 32, borderRadius: '50%',
                background: 'var(--chrome-gradient)',
                display: 'grid', placeItems: 'center',
                boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.4), 0 2px 6px rgba(0,0,0,0.6)',
                marginTop: 2,
              }}>
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
                  <path d="M12 8V12M12 16H12.01M22 12C22 17.5228 17.5228 22 12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12Z" stroke="#0a0a0a" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
              </span>
              <div>
                <div style={{
                  fontFamily: 'var(--font-heading)', fontWeight: 700, fontSize: 13,
                  textTransform: 'uppercase', letterSpacing: '0.16em',
                  color: 'var(--viper-white)', marginBottom: 6,
                }}>No payment required now</div>
                <div style={{ fontSize: 13, color: 'var(--fg-3)', lineHeight: 1.55 }}>
                  This page only collects sponsor information. After you submit, the booster club
                  will reach out directly to coordinate payment and confirm your sponsorship details.
                </div>
              </div>
            </div>
          </FormSection>

          {/* Agreement */}
          <div style={{ marginTop: 32, marginBottom: 24 }}>
            <label
              className={`checkbox-row ${data.agree ? 'checked' : ''}`}
              style={{ userSelect: 'none' }}
            >
              <input
                type="checkbox"
                checked={data.agree}
                onChange={e => set('agree', e.target.checked)}
                className="viper-checkbox"
              />
              <span style={{ fontSize: 13, color: 'var(--fg-2)', lineHeight: 1.55 }}>
                I agree to the terms and confirm this is a tax-deductible donation to the
                <strong style={{ color: 'var(--viper-white)' }}> VHS Boys Basketball Booster Club</strong>,
                a registered 501(c)(3) non-profit organization.
              </span>
            </label>
            {errors.agree && <div className="viper-error" style={{ marginLeft: 30 }}>{errors.agree}</div>}
          </div>

          {/* Submit */}
          <div style={{ display: 'flex', gap: 14, alignItems: 'center', flexWrap: 'wrap' }}>
            <button type="submit" disabled={loading}
              className="viper-btn-chrome"
              style={{ flex: 1, minWidth: 240, padding: '18px 28px', fontSize: 14 }}>
              {loading ? (
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 10 }}>
                  <Spinner /> Submitting...
                </span>
              ) : (
                <>Submit Sponsorship →</>
              )}
            </button>
            <div style={{
              fontFamily: 'var(--font-heading)', fontWeight: 600, fontSize: 11,
              textTransform: 'uppercase', letterSpacing: '0.18em', color: 'var(--fg-muted)',
            }}>
              Total · {amountLabel}
            </div>
          </div>
          {errors.submit && <div className="viper-error" style={{ marginTop: 12 }}>{errors.submit}</div>}
        </form>
      </div>
    </section>
  );
}

function FormSection({ title, subtitle, step, children }) {
  return (
    <div style={{ marginBottom: 32, paddingBottom: 28, borderBottom: '1px solid var(--border)' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 20 }}>
        <span style={{
          fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 13,
          color: 'var(--fg-muted)', letterSpacing: '0.1em',
        }}>{step}</span>
        <span style={{
          width: 24, height: 1, background: 'var(--viper-steel)',
        }}></span>
        <h3 style={{
          fontFamily: 'var(--font-heading)', fontWeight: 700, fontSize: 16,
          textTransform: 'uppercase', letterSpacing: '0.18em',
          color: 'var(--viper-white)', margin: 0,
        }}>{title}</h3>
        {subtitle && <span style={{
          fontFamily: 'var(--font-body)', fontSize: 12, color: 'var(--fg-muted)',
          marginLeft: 'auto',
        }}>{subtitle}</span>}
      </div>
      {children}
    </div>
  );
}

function Grid2({ children }) {
  return <div style={{
    display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(240px, 1fr))', gap: 14,
  }}>{children}</div>;
}

function Field({ label, required, value, onChange, error, type = 'text' }) {
  return (
    <div>
      <label className="viper-label">
        {label}{required && <span style={{ color: 'var(--viper-platinum)', marginLeft: 4 }}>*</span>}
      </label>
      <input
        type={type}
        value={value}
        onChange={e => onChange(e.target.value)}
        className={`viper-input ${error ? 'error' : ''}`}
      />
      {error && <div className="viper-error">{error}</div>}
    </div>
  );
}

function Spinner() {
  return (
    <span style={{
      width: 14, height: 14, borderRadius: '50%',
      border: '2px solid rgba(0,0,0,0.3)',
      borderTopColor: '#0a0a0a',
      animation: 'spin 0.8s linear infinite',
      display: 'inline-block',
    }}></span>
  );
}
