/* global React, ReactDOM, bbH, I, BrandMark, SiteHeader, Hero, TrustBar, Features, HowItWorks, OnePayment, WhoWeAre, DebtSettlement, Promises, Testimonials, FAQ, CtaBand, Footer, LeadFields, validEmail, digits, useTweaks, TweaksPanel, TweakSection, TweakColor */
// ============================================================================
// BlueBorrow — app shell + embedded 2-step lead form
// ============================================================================
const h = window.bbH;
const { useState, useEffect, useCallback } = React;

const ACCENTS = { '#1E59A8': '#174C97', '#155E96': '#114B79', '#2C5BC0': '#23499C' };
const STORAGE_KEY = 'blueborrow_lead_v3';

const BLANK = {
  name: '', email: '', phone: '', amount: '', purpose: '', credit: '',
  residency: '', address: '', state: '', zip: '', country: 'United States', consent: false,
  website: '', // honeypot — humans never see it; bots auto-fill it
};
function loadSaved() {
  try { const s = JSON.parse(localStorage.getItem(STORAGE_KEY)); return s ? { ...BLANK, ...s } : BLANK; }
  catch (e) { return BLANK; }
}

const INTRO = {
  1: { title: 'See your options', sub: 'Tell us where you’re at. No judgment, just a clear next step. About 2 minutes, and no impact to your credit.' },
  2: { title: 'Where should we reach you?', sub: 'Last step. A real specialist follows up, usually within one business day.' },
};

// ── Ad attribution ──────────────────────────────────────────────────────────
// Capture click ids + UTMs from the landing URL immediately (they're gone if
// the visitor navigates) and keep them for the session. Without these, a lead
// in the CRM can never be tied back to the ad/campaign that produced it.
const ATTR_KEY = 'blueborrow_attr_v1';
const ATTR_PARAMS = ['fbclid', 'utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term'];
(function captureAttribution() {
  try {
    const qs = new URLSearchParams(window.location.search);
    const found = {};
    ATTR_PARAMS.forEach((k) => { const v = qs.get(k); if (v) found[k] = v.slice(0, 500); });
    if (Object.keys(found).length) {
      const prev = JSON.parse(sessionStorage.getItem(ATTR_KEY) || '{}');
      sessionStorage.setItem(ATTR_KEY, JSON.stringify({ ...prev, ...found, landing: window.location.pathname }));
    }
  } catch (e) {}
})();

function readCookie(name) {
  try {
    const m = document.cookie.match(new RegExp('(?:^|; )' + name + '=([^;]*)'));
    return m ? decodeURIComponent(m[1]).slice(0, 500) : null;
  } catch (e) { return null; }
}

function getTracking() {
  let attr = {};
  try { attr = JSON.parse(sessionStorage.getItem(ATTR_KEY) || '{}'); } catch (e) {}
  return {
    ...attr,
    fbp: readCookie('_fbp'),   // Meta browser id (set by the pixel)
    fbc: readCookie('_fbc'),   // Meta click id cookie
    page: window.location.href.split('?')[0],
  };
}

// POST the lead to our own endpoint (which forwards to the partner CRM).
// Resolves true on success, false on any failure so the UI can show a retry.
async function submitLead(data) {
  try {
    const res = await fetch('/api/lead', {
      method: 'POST',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify({
        ...data,
        ref: (typeof document !== 'undefined' ? document.referrer : ''),
        tracking: getTracking(),
      }),
    });
    return res.ok;
  } catch (e) {
    return false;
  }
}

// ── Embedded form card (hero centerpiece) ───────────────────────────────────
function FormCard({ data, set, errors, step, onNext, onBack, submitting, done }) {
  const pct = done ? 100 : step * 50;
  const intro = INTRO[step];
  return h('div', { className: 'formcard', id: 'get-started' },
    h('div', { className: 'formcard__head' },
      h('span', { className: 'modal__brand' }, h(BrandMark, { className: 'brand__mark' }), h('b', null, 'Blue', h('span', null, 'Borrow'))),
      done
        ? h('span', { className: 'formcard__free' }, I.shield(), '100% free')
        : h('span', { className: 'modal__step' }, 'Step ', h('b', null, step), ' of 2'),
    ),
    h('div', { className: 'modal__track' }, h('div', { className: 'modal__fill', style: { width: pct + '%' } })),
    done
      ? h('div', { className: 'formcard__body' }, h(Done, { data }))
      : h('div', { className: 'formcard__body' },
          h('div', { className: 'formcard__intro' },
            h('h3', null, intro.title),
            h('p', null, intro.sub),
          ),
          h(LeadFields, { step, data, set, errors }),
          // Honeypot: hidden from humans (off-screen, untabbable); bots that
          // auto-fill every field reveal themselves. Checked server-side.
          h('input', {
            type: 'text', name: 'website', value: data.website || '',
            onChange: (e) => set({ website: e.target.value }),
            autoComplete: 'off', tabIndex: -1, 'aria-hidden': 'true',
            style: { position: 'absolute', left: '-9999px', width: '1px', height: '1px', opacity: 0 },
          }),
          h('div', { className: 'formcard__foot' },
            step === 2 && h('button', { type: 'button', className: 'btn btn--soft', onClick: onBack }, I.arrowLeft(), 'Back'),
            h('button', { type: 'button', className: 'btn btn--primary btn--lg' + (step === 1 ? ' btn--block' : ' btn--grow'), onClick: onNext, disabled: submitting },
              step === 1 ? 'Continue' : (submitting ? 'Submitting…' : 'Submit my request'),
              step === 1 && I.arrowRight()),
          ),
          errors.submit && h('div', { className: 'field__err', style: { marginTop: '10px' } }, I.alert(), errors.submit),
          h('div', { className: 'leadform__sec' }, I.lock(), 'Secured with bank-level encryption · No impact to your credit to get matched'),
        ),
  );
}

function Done({ data }) {
  const first = (data.name || '').trim().split(/\s+/)[0] || 'friend';
  return h('div', { className: 'done step-enter' },
    h('div', { className: 'done__badge' }, I.check()),
    h('h2', null, 'You’re all set, ', first, '.'),
    h('p', null, 'Your request is in. A personal-loan specialist will reach out shortly, usually within one business day, by phone, text, or email.'),
    h('div', { className: 'done__summary' },
      h('div', { className: 'row' }, h('span', null, 'Loan amount'), h('b', null, data.amount || '–')),
      h('div', { className: 'row' }, h('span', null, 'Purpose'), h('b', null, data.purpose || '–')),
      h('div', { className: 'row' }, h('span', null, 'We’ll contact'), h('b', null, (data.name || '–'))),
    ),
    h('div', { className: 'done__next' }, h('span', { className: 'd' }), 'Nothing more to do right now. Keep an eye on your phone.'),
  );
}

// ── App ─────────────────────────────────────────────────────────────────────
function App() {
  const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
    "accent": "#1E59A8"
  }/*EDITMODE-END*/;
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);

  const [data, setData] = useState(loadSaved);
  const [step, setStep] = useState(1);
  const [done, setDone] = useState(false);
  const [errors, setErrors] = useState({});
  const [submitting, setSubmitting] = useState(false);
  const [toast, setToast] = useState(false);

  const set = useCallback((patch) => setData((d) => ({ ...d, ...patch })), []);

  useEffect(() => { try { localStorage.setItem(STORAGE_KEY, JSON.stringify(data)); } catch (e) {} }, [data]);

  useEffect(() => {
    const r = document.documentElement;
    r.style.setProperty('--blue-600', t.accent);
    r.style.setProperty('--accent-deep', ACCENTS[t.accent] || '#174C97');
  }, [t.accent]);

  const formTop = useCallback((behavior) => {
    const el = document.getElementById('get-started');
    if (!el) return;
    const y = el.getBoundingClientRect().top + window.scrollY - 88;
    window.scrollTo({ top: Math.max(0, y), behavior: behavior || 'smooth' });
  }, []);

  const scrollToForm = useCallback(() => {
    formTop('smooth');
    if (window.innerWidth > 820) {
      const el = document.getElementById('get-started');
      const first = el && el.querySelector('input, select');
      if (first) { try { first.focus({ preventScroll: true }); } catch (e) {} }
    }
  }, [formTop]);

  function validateStep(s) {
    const e = {};
    if (s === 1) {
      if (!data.amount) e.amount = 'Choose an amount';
      if (!data.purpose) e.purpose = 'Choose a purpose';
      if (!data.credit) e.credit = 'Choose a rating';
      if (!data.residency) e.residency = 'Choose one';
    } else {
      if (!data.name.trim()) e.name = 'Add your name';
      else if (!/\s/.test(data.name.trim())) e.name = 'Add your first and last name';
      if (!validEmail(data.email)) e.email = data.email.trim() ? 'That email looks incomplete' : 'Add your email';
      if (digits(data.phone).length < 10) e.phone = digits(data.phone).length ? 'That number looks short, mind checking it?' : 'Add a phone number';
      if (!data.address.trim()) e.address = 'Add your address';
      if (!data.state) e.state = 'Choose your state';
      if (digits(data.zip).length !== 5) e.zip = 'Enter a 5-digit ZIP';
      if (!data.country) e.country = 'Choose a country';
      if (!data.consent) e.consent = 'Please check the box so a specialist can reach you';
    }
    return e;
  }

  function focusFirstError() {
    requestAnimationFrame(() => {
      const bad = document.querySelector('#get-started .field.err, #get-started .consent.err');
      if (bad) {
        const y = bad.getBoundingClientRect().top + window.scrollY - 120;
        window.scrollTo({ top: Math.max(0, y), behavior: 'smooth' });
        const ctrl = bad.querySelector('input, select');
        if (ctrl) { try { ctrl.focus({ preventScroll: true }); } catch (er) {} }
      }
    });
  }

  function next() {
    const e = validateStep(step);
    setErrors(e);
    if (Object.keys(e).length) { focusFirstError(); return; }
    if (step === 1) {
      try { if (window.fbq) window.fbq('track', 'InitiateCheckout'); } catch (err) {} // step-1 complete: mid-funnel signal
      setStep(2); setErrors({}); formTop('smooth'); return;
    }
    // submit
    setSubmitting(true);
    setErrors({});
    submitLead(data).then((ok) => {
      setSubmitting(false);
      if (!ok) {
        setErrors({ submit: 'Something went wrong sending your request. Please try again.' });
        focusFirstError();
        return;
      }
      try { if (window.fbq) window.fbq('track', 'Lead'); } catch (err) {}
      try { localStorage.removeItem(STORAGE_KEY); } catch (err) {} // don't keep PII on-device after submit
      setDone(true); setToast(true);
      setTimeout(() => setToast(false), 3600);
      formTop('smooth');
    });
  }

  function back() { if (step === 2) { setStep(1); setErrors({}); formTop('smooth'); } }

  const formCard = h(FormCard, { data, set, errors, step, onNext: next, onBack: back, submitting, done });

  return h(React.Fragment, null,
    h('div', { className: 'site' },
      h(SiteHeader, { onStart: scrollToForm }),
      h(Hero, { onStart: scrollToForm, form: formCard }),
      h(TrustBar, null),
      h(Features, null),
      h(HowItWorks, null),
      h(OnePayment, { onStart: scrollToForm }),
      h(DebtSettlement, { onStart: scrollToForm }),
      h(WhoWeAre, { onStart: scrollToForm }),
      h(Testimonials, null),
      h(FAQ, null),
      h(CtaBand, { onStart: scrollToForm }),
      h(Footer, null),
    ),
    h('div', { className: 'toast' + (toast ? ' show' : '') }, I.check(), 'Submitted. A specialist will reach out'),
    h(TweaksPanel, null,
      h(TweakSection, { label: 'Accent' }),
      h(TweakColor, { label: 'Trust blue', value: t.accent, options: ['#1E59A8', '#155E96', '#2C5BC0'], onChange: (v) => setTweak('accent', v) }),
    ),
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(h(App));
