/* global React, ArrowRight, useReveal, CtaStrip, PageBanner */
const { useState: useStateB, useEffect: useEffectB } = React;

// ============================================================
// PARTNERS PAGE — structured to mirror foxbusinessfunding.com/partners
//   1. Hero: "Let's make it happen" + Partner CTA
//   2. Headline: "Masters of quick and easy deal making" w/ tag amount
//   3. Four-feature grid: Quick Approval / Paperwork / Fast & Easy / Dedicated Underwriter
//   4. Partner testimonial
//   5. "We understand you" — funding rep card
//   6. Closing CTA
// ============================================================
function PartnersPage() {
  useReveal();
  const [submitted, setSubmitted] = useStateB(false);
  const [submitting, setSubmitting] = useStateB(false);
  const [form, setForm] = useStateB({
    name: '', firm: '', email: '', phone: '', volume: '', notes: '',
  });
  const [err, setErr] = useStateB({});

  // Same Apps Script endpoint as the apply form — submissions land in schneur@kbfundinggroup.com
  const FORM_ENDPOINT = 'https://script.google.com/macros/s/AKfycbxeyarB9KpwKLjVSbUoAqGvcV4ivo5mUvASuMkb0Hj0oIaUmmhSHHpUYwROSHOAWJFr/exec';

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

  const submit = () => {
    if (submitting) return;
    const e = {};
    if (!form.name.trim()) e.name = 'Required';
    if (!form.firm.trim()) e.firm = 'Required';
    if (!form.email.match(/^\S+@\S+\.\S+$/)) e.email = 'Valid email required';
    if (!form.phone.match(/^[0-9\-\s\(\)]{10,}$/)) e.phone = 'Valid phone required';
    setErr(e);
    if (Object.keys(e).length === 0) {
      const payload = { ...form, formType: 'partner' };

      setSubmitting(true);
      fetch(FORM_ENDPOINT, {
        method: 'POST',
        mode: 'no-cors',
        headers: { 'Content-Type': 'text/plain;charset=utf-8' },
        body: JSON.stringify(payload),
      }).catch((err) => {
        console.error('Partner form submit failed:', err);
      }).finally(() => {
        setSubmitting(false);
      });

      setSubmitted(true);
      document.getElementById('partner-form')?.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }
  };

  const scrollToForm = (e) => {
    e?.preventDefault();
    document.getElementById('partner-form')?.scrollIntoView({ behavior: 'smooth', block: 'start' });
  };

  return (
    <div className="page-fade">

      {/* 1. HERO ----------------------------------------------------- */}
      <section className="hero" style={{ padding: 0 }}>
        <div className="hero-grid-bg" />
        <div className="container">
          <div style={{
            position: 'relative',
            display: 'grid',
            gridTemplateColumns: '1.1fr 0.9fr',
            gap: 80,
            padding: '110px 0 120px',
            alignItems: 'center',
          }} className="partners-hero-grid">
            <div>
              <span className="eyebrow hero-eyebrow">For Brokers & Referral Partners</span>
              <h1 style={{ marginTop: 22, color: 'var(--white)' }}>
                Let's <em>make it happen.</em>
              </h1>
              <p style={{ fontSize: 22, color: 'rgba(255,255,255,0.85)', marginTop: 24, maxWidth: 540, lineHeight: 1.5, fontFamily: 'Cormorant Garamond, serif', fontStyle: 'italic', fontWeight: 400 }}>
                Be smart. Skip the drama and the nonsense — fund with KB.
              </p>
              <p style={{ color: 'rgba(255,255,255,0.7)', maxWidth: 520, marginTop: 16, marginBottom: 36 }}>
                We're an in-house funder built for the way brokers actually work.
                Submit a deal, talk to a real underwriter, and watch it close —
                often within the hour.
              </p>
              <div style={{ display: 'flex', gap: 14, flexWrap: 'wrap' }}>
                <a href="#partner-form" className="btn btn-primary btn-lg" onClick={scrollToForm}>
                  Partner with us <ArrowRight />
                </a>
                <a href="tel:13478814260" className="btn btn-ghost-light btn-lg">
                  (347) 881-4260
                </a>
              </div>
            </div>

            {/* Decorative emblem panel */}
            <div style={{ position: 'relative', minHeight: 460 }}>
              <div style={{
                position: 'absolute', inset: 0,
                border: '1px solid rgba(201,163,90,0.4)',
                background: 'rgba(255,255,255,0.03)',
                backdropFilter: 'blur(6px)',
              }}>
                <div style={{
                  position: 'absolute', top: -1, left: -1,
                  width: 48, height: 48,
                  borderTop: '2px solid var(--gold)',
                  borderLeft: '2px solid var(--gold)',
                }} />
                <div style={{
                  position: 'absolute', bottom: -1, right: -1,
                  width: 48, height: 48,
                  borderBottom: '2px solid var(--gold)',
                  borderRight: '2px solid var(--gold)',
                }} />
                <div style={{ padding: '60px 50px', textAlign: 'center', height: '100%', display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
                  <div style={{
                    fontSize: 11.5, color: 'var(--gold)',
                    letterSpacing: '0.28em', textTransform: 'uppercase',
                    marginBottom: 32,
                  }}>Partner Snapshot</div>
                  <div style={{ fontFamily: 'Cormorant Garamond, serif', fontSize: 88, color: 'var(--white)', lineHeight: 0.95, fontWeight: 500 }}>
                    $1M
                  </div>
                  <div style={{ fontSize: 13, color: 'rgba(255,255,255,0.65)', letterSpacing: '0.16em', textTransform: 'uppercase', marginTop: 14 }}>
                    Up to one million dollars
                  </div>
                  <div style={{ width: 60, height: 1, background: 'var(--gold)', margin: '36px auto' }} />
                  <div style={{ fontFamily: 'Cormorant Garamond, serif', fontSize: 56, color: 'var(--gold)', lineHeight: 0.95, fontWeight: 500 }}>
                    2 days
                  </div>
                  <div style={{ fontSize: 13, color: 'rgba(255,255,255,0.65)', letterSpacing: '0.16em', textTransform: 'uppercase', marginTop: 12 }}>
                    Funded, start to finish
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* 2. HEADLINE + 4-FEATURE GRID -------------------------------- */}
      <section style={{ padding: '110px 0 60px' }}>
        <div className="container">
          <div className="section-head" style={{ maxWidth: 880 }}>
            <span className="eyebrow reveal">Why brokers choose KB</span>
            <h2 className="reveal" style={{ marginTop: 18 }}>
              We are masters of quick and <em>easy deal-making.</em>
            </h2>
            <p className="reveal" style={{ fontSize: 19 }}>
              Business funding up to <strong style={{ color: 'var(--navy)', fontWeight: 600 }}>$1,000,000</strong> in
              as little as <strong style={{ color: 'var(--navy)', fontWeight: 600 }}>2 business days</strong>.
            </p>
          </div>

          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(4, 1fr)',
            gap: 0,
            borderTop: '1px solid var(--line-strong)',
            borderBottom: '1px solid var(--line-strong)',
          }} className="partner-features">
            {[
              {
                num: '01',
                title: 'Quick Approval',
                desc: 'Fast same-day approvals on one simple application and three most recent bank statements. No tax returns, no projections.',
              },
              {
                num: '02',
                title: 'Straightforward Paperwork',
                desc: 'A signed funding agreement and minimal supporting docs is all it takes to receive funding. We keep the file thin so it closes quick.',
              },
              {
                num: '03',
                title: 'Fast and Easy',
                desc: "We understand a prompt decision can make or break the deal — you can expect real answers in hours, not days.",
              },
              {
                num: '04',
                title: 'Dedicated Underwriter',
                desc: 'No red tape. Partners work directly with one named underwriter who knows your book and stops asking the same questions twice.',
              },
            ].map((f, i) => (
              <div key={f.num} className="reveal partner-feature" style={{
                padding: '48px 36px 48px 0',
                borderRight: i < 3 ? '1px solid var(--line-strong)' : 'none',
                paddingLeft: i > 0 ? 36 : 0,
                transitionDelay: `${i * 80}ms`,
              }}>
                <span style={{
                  fontFamily: 'Cormorant Garamond, serif',
                  fontSize: 56,
                  color: 'var(--gold)',
                  lineHeight: 1,
                  fontWeight: 500,
                  display: 'block',
                  marginBottom: 22,
                }}>{f.num}</span>
                <h3 style={{ fontSize: 26, marginBottom: 12, lineHeight: 1.2 }}>{f.title}</h3>
                <p style={{ fontSize: 14.5, color: 'var(--slate)', margin: 0 }}>{f.desc}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* 3. TESTIMONIAL --------------------------------------------- */}
      <section style={{ padding: '60px 0 100px' }}>
        <div className="container-narrow" style={{ textAlign: 'center' }}>
          <span className="quote-mark reveal" style={{ display: 'inline-block' }}>"</span>
          <blockquote className="reveal" style={{
            fontFamily: 'Cormorant Garamond, serif',
            fontSize: 'clamp(26px, 3vw, 36px)',
            lineHeight: 1.35,
            color: 'var(--navy)',
            margin: '0 0 32px',
            fontStyle: 'italic',
            fontWeight: 400,
          }}>
            Working with the KB team has been a no-brainer for our business. Their
            quick, no-nonsense approach to approvals and contracts means more time
            for my team to do what we do best — providing sensible and timely
            funding solutions for our clients.
          </blockquote>
          <div className="reveal" style={{ display: 'inline-flex', alignItems: 'center', gap: 14 }}>
            <div className="cite-avatar">A</div>
            <div style={{ textAlign: 'left' }}>
              <div className="cite-name" style={{ fontSize: 16 }}>Adrian Levitt</div>
              <div className="cite-role">Principal · ISO Partner since 2019</div>
            </div>
          </div>
        </div>
      </section>

      {/* 4. WE UNDERSTAND YOU --------------------------------------- */}
      <section className="section-cream" style={{ padding: '110px 0' }}>
        <div className="container">
          <div style={{
            display: 'grid',
            gridTemplateColumns: '0.9fr 1.1fr',
            gap: 80,
            alignItems: 'center',
          }} className="rep-grid">
            {/* Rep card */}
            <div className="reveal" style={{
              background: 'var(--white)',
              border: '1px solid var(--line)',
              padding: '48px 40px',
              textAlign: 'center',
              boxShadow: 'var(--shadow-soft)',
              position: 'relative',
            }}>
              <div style={{
                position: 'absolute', top: -1, left: -1,
                width: 36, height: 36,
                borderTop: '2px solid var(--gold)',
                borderLeft: '2px solid var(--gold)',
              }} />
              <div style={{
                position: 'absolute', bottom: -1, right: -1,
                width: 36, height: 36,
                borderBottom: '2px solid var(--gold)',
                borderRight: '2px solid var(--gold)',
              }} />
              <div style={{
                width: 160, height: 160, borderRadius: '50%',
                background: 'linear-gradient(135deg, var(--cream-2), var(--gold-soft))',
                margin: '0 auto 28px',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontFamily: 'Cormorant Garamond, serif',
                fontSize: 56, color: 'var(--navy)', fontWeight: 600,
                border: '2px solid var(--gold)',
              }}>MD</div>
              <div style={{ fontFamily: 'Cormorant Garamond, serif', fontSize: 32, color: 'var(--navy)', fontWeight: 500 }}>
                Mike Davis
              </div>
              <div style={{
                fontSize: 12, color: 'var(--gold-deep)',
                letterSpacing: '0.18em', textTransform: 'uppercase',
                marginTop: 6, fontWeight: 600,
              }}>Senior Funding Advisor</div>
              <div style={{ width: 40, height: 1, background: 'var(--gold)', margin: '24px auto' }} />
              <div style={{ fontSize: 13.5, color: 'var(--slate)', lineHeight: 1.6 }}>
                14 years in commercial finance. Direct line to your dedicated
                underwriter from the moment you sign on.
              </div>
            </div>

            {/* Right copy */}
            <div>
              <span className="eyebrow reveal">Our team</span>
              <h2 className="reveal" style={{ marginTop: 18 }}>
                We <em>understand</em> you.
              </h2>
              <p className="reveal" style={{ fontSize: 17, marginTop: 20, color: 'var(--slate)' }}>
                Only the very best are selected for our funding representative team.
              </p>
              <p className="reveal" style={{ fontSize: 17, color: 'var(--slate)' }}>
                Every advisor here has extensive experience in business funding, which
                lets them cut through the nonsense and get your deals approved without
                delay. They speak broker. They've been on your side of the table.
              </p>
              <p className="reveal" style={{ fontSize: 17, color: 'var(--slate)', marginBottom: 32 }}>
                Ready to make the smart move?
              </p>
              <a href="#partner-form" className="btn btn-primary btn-lg" onClick={scrollToForm}>
                Partner with us <ArrowRight />
              </a>
            </div>
          </div>
        </div>
      </section>

      {/* 5. APPLICATION FORM ---------------------------------------- */}
      <section id="partner-form" style={{ padding: '110px 0', scrollMarginTop: 130 }}>
        <div className="container-narrow">
          {submitted ? (
            <div className="form-card success-card">
              <div className="seal">✓</div>
              <span className="eyebrow" style={{ justifyContent: 'center' }}>Application Received</span>
              <h2 style={{ marginTop: 14 }}>Welcome aboard, {form.name.split(' ')[0]}.</h2>
              <p style={{ fontSize: 16.5, color: 'var(--slate)', maxWidth: 480, margin: '14px auto 24px' }}>
                Our partnerships team will reach out within one business day to {form.email} with onboarding paperwork and your portal credentials.
              </p>
              <a href="#/" className="btn btn-outline"
                 onClick={(e) => { e.preventDefault(); window.location.hash = '/'; }}>Back to home</a>
            </div>
          ) : (
            <div className="form-card">
              <div style={{ textAlign: 'center', marginBottom: 36 }}>
                <span className="eyebrow" style={{ justifyContent: 'center' }}>Partner Application</span>
                <h2 style={{ marginTop: 14, fontSize: 'clamp(32px, 4vw, 44px)' }}>
                  Become a <em style={{ color: 'var(--gold-deep)', fontStyle: 'italic', fontWeight: 400 }}>KB partner.</em>
                </h2>
                <p style={{ color: 'var(--slate)', fontSize: 15.5, marginTop: 14, maxWidth: 540, margin: '14px auto 0' }}>
                  Onboarded in under 24 hours. Non-exclusive agreement. No minimum volume.
                </p>
              </div>

              <div className="form-row">
                <div className="form-group">
                  <label className="field-label">Your name</label>
                  <input className={`input ${err.name ? 'error' : ''}`} value={form.name}
                         onChange={(e) => update('name', e.target.value)} placeholder="First and last" />
                  {err.name && <div className="error-msg">{err.name}</div>}
                </div>
                <div className="form-group">
                  <label className="field-label">Firm / Company</label>
                  <input className={`input ${err.firm ? 'error' : ''}`} value={form.firm}
                         onChange={(e) => update('firm', e.target.value)} placeholder="e.g. Meridian Capital Advisors" />
                  {err.firm && <div className="error-msg">{err.firm}</div>}
                </div>
              </div>

              <div className="form-row">
                <div className="form-group">
                  <label className="field-label">Email</label>
                  <input className={`input ${err.email ? 'error' : ''}`} type="email" value={form.email}
                         onChange={(e) => update('email', e.target.value)} placeholder="you@firm.com" />
                  {err.email && <div className="error-msg">{err.email}</div>}
                </div>
                <div className="form-group">
                  <label className="field-label">Phone</label>
                  <input className={`input ${err.phone ? 'error' : ''}`} value={form.phone}
                         onChange={(e) => update('phone', e.target.value)} placeholder="(555) 123-4567" />
                  {err.phone && <div className="error-msg">{err.phone}</div>}
                </div>
              </div>

              <div className="form-group">
                <label className="field-label">Expected monthly submission volume</label>
                <div className="option-grid">
                  {['Under $100K', '$100K–$500K', '$500K–$1M', '$1M–$3M', '$3M+', 'Just exploring'].map(o => (
                    <button key={o} className={`option ${form.volume === o ? 'selected' : ''}`}
                            onClick={() => update('volume', o)}>{o}</button>
                  ))}
                </div>
              </div>

              <div className="form-group">
                <label className="field-label">Anything we should know? (optional)</label>
                <textarea className="textarea" rows="4" value={form.notes}
                          onChange={(e) => update('notes', e.target.value)}
                          placeholder="Industries you specialize in, current funding partners, deals in flight, etc." />
              </div>

              <div className="form-actions" style={{ justifyContent: 'center' }}>
                <button className="btn btn-primary btn-lg" onClick={submit} disabled={submitting}>
                  {submitting ? 'Submitting…' : 'Partner with us'} <ArrowRight />
                </button>
              </div>

              <div style={{ textAlign: 'center', marginTop: 28, fontSize: 13.5, color: 'var(--slate)' }}>
                Prefer to talk? Call <a href="tel:13478814260" style={{ color: 'var(--gold-deep)', fontWeight: 600 }}>(347) 881-4260</a> or
                email <a href="mailto:Info@kbfundinggroup.com" style={{ color: 'var(--gold-deep)', fontWeight: 600 }}>Info@kbfundinggroup.com</a>
              </div>
            </div>
          )}
        </div>
      </section>

      <CtaStrip />
    </div>
  );
}

Object.assign(window, { PartnersPage });
