/* Baltimore Car Accident lander — Hero with native lead form + GHL direct contact creation */

const GHL_API = 'https://services.leadconnectorhq.com/contacts/';
const GHL_TOKEN = 'pit-e2cf6fd4-710c-4dd8-bfad-882f61b378d3';
const GHL_LOCATION = 'a5NoNGgEvRAwYpT4brRM';
const GHL_WEBHOOK = 'https://services.leadconnectorhq.com/hooks/a5NoNGgEvRAwYpT4brRM/webhook-trigger/lp-form-submit';

function getTrackingParams() {
  const p = new URLSearchParams(window.location.search);
  const g = k => p.get(k) || '';
  return {
    utm_source: g('utm_source'), utm_medium: g('utm_medium'), utm_campaign: g('utm_campaign'),
    utm_content: g('utm_content'), utm_term: g('utm_term'),
    gclid: g('gclid'), gbraid: g('gbraid'), wbraid: g('wbraid'),
    fbclid: g('fbclid'), msclkid: g('msclkid'),
  };
}

function LeadCard() {
  const [step, setStep] = React.useState('form');
  const [errors, setErrors] = React.useState({});

  const validate = (fd) => {
    const errs = {};
    if (!fd.get('name') || fd.get('name').trim().length < 2) errs.name = 'Enter your name';
    if (!fd.get('phone') || fd.get('phone').replace(/\D/g,'').length < 10) errs.phone = 'Enter a valid phone number';
    if (!fd.get('email') || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(fd.get('email').trim())) errs.email = 'Enter a valid email address';
    if (!fd.get('accident_type')) errs.accident_type = 'Select the type of accident';
    if (!fd.get('message') || fd.get('message').trim().length < 5) errs.message = 'Tell us briefly what happened';
    return errs;
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    const fd = new FormData(e.target);
    const errs = validate(fd);
    if (Object.keys(errs).length) { setErrors(errs); return; }
    setErrors({});
    setStep('sending');

    const tracking = getTrackingParams();
    const now = new Date().toISOString();
    const nameParts = fd.get('name').trim().split(' ');

    const contactPayload = {
      locationId: GHL_LOCATION,
      firstName: nameParts[0],
      lastName: nameParts.slice(1).join(' ') || '',
      phone: fd.get('phone').trim(),
      email: fd.get('email') ? fd.get('email').trim() : '',
      source: 'bigal-baltimore-lp',
      tags: ['LP Lead', 'Meta Campaign', 'Baltimore DMV'],
      customFields: [
        { id: '8M5YynRHCRvWSRhk4nx0', field_value: fd.get('accident_type') || '' },
        { id: 'cjrCACaWtG7tTWAxwzN6', field_value: fd.get('message') || '' }
      ],
    };
    if (tracking.gclid) contactPayload.gclid = tracking.gclid;

    try {
      /* Primary: Create contact via GHL API */
      await fetch(GHL_API, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer ' + GHL_TOKEN,
          'Version': '2021-07-28',
        },
        body: JSON.stringify(contactPayload),
      });

      /* Backup: Fire webhook for workflow automations */
      fetch(GHL_WEBHOOK, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          full_name: fd.get('name').trim(),
          phone: fd.get('phone').trim(),
          email: fd.get('email') ? fd.get('email').trim() : '',
          accident_type: fd.get('accident_type') || '',
          message: fd.get('message') || '',
          ...tracking,
          page_url: window.location.href,
          landing_page: window.location.pathname,
          referrer: document.referrer || '',
          lead_source: 'bigal-baltimore-lp',
          submitted_at: now,
        }),
        mode: 'no-cors',
      }).catch(() => {});

      /* Fire Meta conversion event */
      if (window.fbq) {
        fbq('track', 'Lead', { content_name: 'Free Case Review', content_category: fd.get('accident_type') || 'General' });
      }
      /* Fire GTM event */
      if (window.dataLayer) {
        dataLayer.push({ event: 'form_submission', form_name: 'free_case_review', accident_type: fd.get('accident_type') || '' });
      }
      /* Fire Google Ads conversion */
      if (typeof gtag === 'function') {
        gtag('event', 'conversion', { send_to: 'AW-BIGALBALTIMORE/FORM', value: 50.0, currency: 'USD' });
      }

      setStep('done');
    } catch (err) {
      console.error('Form submit error:', err);
      /* Fallback: webhook only */
      try {
        await fetch(GHL_WEBHOOK, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            full_name: fd.get('name').trim(),
            phone: fd.get('phone').trim(),
            email: fd.get('email') ? fd.get('email').trim() : '',
            accident_type: fd.get('accident_type') || '',
            ...tracking,
            page_url: window.location.href,
            lead_source: 'bigal-baltimore-lp',
            submitted_at: now,
          }),
          mode: 'no-cors',
        });
      } catch (e2) { /* silent */ }
      setStep('done');
    }
  };

  const inputBase = {
    width: '100%', padding: '13px 16px',
    border: '2px solid var(--line)', borderRadius: 7,
    fontFamily: 'var(--font-body)', fontSize: 15, color: 'var(--ink)',
    background: '#fafafa', outline: 'none', boxSizing: 'border-box', transition: 'border-color .15s'
  };
  const inputFocusStyle = `
    .lead-input:focus { border-color: var(--red) !important; background: #fff !important; }
    .lead-input::placeholder { color: #999; }
    .lead-select { appearance: none; background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%23666' stroke-width='2.5'%3E%3Cpath d='M6 9l6 6 6-6'/%3E%3C/svg%3E"); background-repeat: no-repeat; background-position: right 14px center; padding-right: 36px; }
    .lead-select:invalid { color: #999; }
    .field-error { color: #d32f2f; font-size: 12px; margin-top: 4px; font-family: var(--font-body); }
  `;

  if (step === 'done') {
    return (
      <div id="form" style={{ background: '#fff', borderRadius: 10, boxShadow: '10px 10px 0 var(--red)', border: '3px solid var(--ink)', overflow: 'hidden' }}>
        <div style={{ background: 'var(--ink)', color: '#fff', padding: '40px 26px', textAlign: 'center' }}>
          <i data-lucide="circle-check-big" style={{ width: 56, height: 56, color: 'var(--gold)', marginBottom: 16 }}></i>
          <h2 style={{ fontFamily: 'var(--font-display)', textTransform: 'uppercase', fontSize: 28, lineHeight: .95, margin: '0 0 12px' }}>We got your case</h2>
          <p style={{ fontFamily: 'var(--font-body)', fontSize: 15, color: 'var(--fg-on-dark-2)', margin: 0, lineHeight: 1.5 }}>
            Our team is reviewing your info right now. Expect a call back within minutes, day or night.
          </p>
          <div style={{ marginTop: 24 }}>
            <a href="tel:+14107010554" onClick={fireCallConversion} style={{ display: 'inline-flex', alignItems: 'center', gap: 10, padding: '14px 28px', background: 'var(--red)', color: '#fff', borderRadius: 6, fontFamily: 'var(--font-headline)', textTransform: 'uppercase', fontWeight: 700, fontSize: 15, textDecoration: 'none', letterSpacing: '.04em' }}>
              <i data-lucide="phone" style={{ width: 18, height: 18 }}></i>Call Now: (410) 701-0554
            </a>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div id="form" style={{ background: '#fff', borderRadius: 10, boxShadow: '10px 10px 0 var(--red)', border: '3px solid var(--ink)', overflow: 'hidden' }}>
      <style dangerouslySetInnerHTML={{ __html: inputFocusStyle }} />
      <div style={{ background: 'var(--ink)', color: '#fff', padding: '20px 26px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
          <i data-lucide="badge-check" style={{ width: 20, height: 20, color: 'var(--red)' }}></i>
          <span style={{ fontFamily: 'var(--font-headline)', textTransform: 'uppercase', fontWeight: 600, fontSize: 12, letterSpacing: '.14em', color: 'var(--red)' }}>100% free · no obligation</span>
        </div>
        <h2 style={{ fontFamily: 'var(--font-display)', textTransform: 'uppercase', fontSize: 32, lineHeight: .95, margin: 0 }}>Free case review</h2>
        <p style={{ fontFamily: 'var(--font-body)', fontSize: 14, color: 'var(--fg-on-dark-2)', margin: '8px 0 0', lineHeight: 1.45 }}>
          Tell us what happened. We'll call you back fast, day or night.
        </p>
      </div>
      <form onSubmit={handleSubmit} style={{ padding: '20px 22px 16px', display: 'flex', flexDirection: 'column', gap: 12 }}>
        <div>
          <input className="lead-input" name="name" type="text" placeholder="Full Name *" style={inputBase} autoComplete="name" />
          {errors.name && <div className="field-error">{errors.name}</div>}
        </div>
        <div>
          <input className="lead-input" name="phone" type="tel" placeholder="Phone Number *" style={inputBase} autoComplete="tel" />
          {errors.phone && <div className="field-error">{errors.phone}</div>}
        </div>
        <div>
          <input className="lead-input" name="email" type="email" placeholder="Email Address *" style={inputBase} autoComplete="email" required />
          {errors.email && <div className="field-error">{errors.email}</div>}
        </div>
        <div>
          <select className="lead-input lead-select" name="accident_type" style={inputBase} defaultValue="" required>
            <option value="Car Accident">Car Accident</option>
            <option value="Truck Accident">Truck / 18-Wheeler</option>
            <option value="Motorcycle Accident">Motorcycle Accident</option>
            <option value="Pedestrian Accident">Pedestrian / Bicycle</option>
            <option value="Rideshare Accident">Uber / Lyft Accident</option>
            <option value="Slip and Fall">Slip and Fall</option>
            <option value="Other">Other</option>
          </select>
          {errors.accident_type && <div className="field-error">{errors.accident_type}</div>}
        </div>
        <div>
          <textarea className="lead-input" name="message" placeholder="What happened? (required) *" style={{ ...inputBase, minHeight: 72, resize: 'vertical' }} required></textarea>
          {errors.message && <div className="field-error">{errors.message}</div>}
        </div>
        <button type="submit" disabled={step === 'sending'} className="pulse-cta"
          style={{
            width: '100%', padding: '16px 24px', background: 'var(--red)', color: '#fff', border: 'none', borderRadius: 7,
            fontFamily: 'var(--font-headline)', textTransform: 'uppercase', fontWeight: 700, fontSize: 17, letterSpacing: '.04em',
            cursor: step === 'sending' ? 'wait' : 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
            boxShadow: 'var(--shadow-red)', opacity: step === 'sending' ? .7 : 1, transition: 'opacity .15s'
          }}>
          <i data-lucide="send" style={{ width: 18, height: 18 }}></i>
          {step === 'sending' ? 'Sending...' : 'Get My Free Case Review'}
        </button>
        {step === 'error' && (
          <p style={{ color: '#d32f2f', fontSize: 13, textAlign: 'center', margin: '4px 0 0', fontFamily: 'var(--font-body)' }}>
            Something went wrong. Please call us directly at (410) 701-0554.
          </p>
        )}
      </form>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, padding: '12px 20px 18px', background: '#fff', borderTop: '1px solid var(--line)' }}>
        <i data-lucide="lock" style={{ width: 14, height: 14, color: 'var(--fg3)' }}></i>
        <span style={{ fontFamily: 'var(--font-body)', fontSize: 12.5, color: 'var(--fg3)' }}>Secure &amp; confidential · Your info is never sold.</span>
      </div>
    </div>
  );
}

function Hero({ onForm }) {
  return (
    <section id="top" data-screen-label="Hero" style={{ background: 'var(--ink)', color: '#fff', position: 'relative', overflow: 'hidden' }}>
      <div style={{ position: 'absolute', top: 0, right: 0, width: '46%', height: '100%', background: 'var(--red)', clipPath: 'polygon(34% 0, 100% 0, 100% 100%, 0% 100%)', opacity: .12, pointerEvents: 'none' }}></div>
      <div style={{ position: 'absolute', inset: 0, opacity: .05, backgroundImage: 'repeating-linear-gradient(90deg, transparent 0 78px, #fff 78px 80px)', pointerEvents: 'none' }}></div>
      <Container style={{ position: 'relative', padding: '64px 28px 72px' }}>
        <div className="hero-grid" style={{ display: 'grid', gridTemplateColumns: 'minmax(0,1.05fr) minmax(0,.95fr)', gap: 56, alignItems: 'center' }}>
          <div>
            <Eyebrow style={{ color: 'var(--red)' }}>Baltimore Car Accident Lawyer</Eyebrow>
            <h1 style={{ fontFamily: 'var(--font-display)', textTransform: 'uppercase', lineHeight: .95, fontSize: 'clamp(3.4rem, 7.5vw, 6.4rem)', margin: '20px 0 0', letterSpacing: '-.01em' }}>
              Hurt on<br /><span style={{ color: 'var(--red)' }}>I-95, I-695</span> or <span style={{ color: 'var(--red)' }}>I-83?</span>
            </h1>
            <p style={{ fontFamily: 'var(--font-body)', fontSize: 'clamp(1.05rem,1.7vw,1.35rem)', color: 'var(--fg-on-dark-2)', maxWidth: 520, marginTop: 22, lineHeight: 1.5 }}>
              Before you call the insurance company, call Attorney Big Al. We fight for injured drivers throughout Maryland, Virginia, and DC, and you pay <strong style={{ color: '#fff' }}>nothing</strong> unless we win.
            </p>
            <div style={{ display: 'flex', gap: 16, marginTop: 34, flexWrap: 'wrap', alignItems: 'center' }}>
              <PhoneButton big />
              <GhostButton variant="outlineLight" icon="arrow-down" onClick={onForm}>Free Case Review</GhostButton>
            </div>
            <div style={{ display: 'flex', gap: 28, marginTop: 40, flexWrap: 'wrap' }}>
              {[['shield-check', 'No fee unless we win'], ['clock', 'Open 24/7'], ['languages', 'Hablamos Español']].map(([ic, tx]) => (
                <span key={tx} style={{ display: 'flex', alignItems: 'center', gap: 10, color: '#fff', fontFamily: 'var(--font-headline)', textTransform: 'uppercase', fontWeight: 600, fontSize: 14, letterSpacing: '.04em' }}>
                  <i data-lucide={ic} style={{ width: 21, height: 21, color: 'var(--red)' }}></i>{tx}
                </span>
              ))}
            </div>
          </div>
          <div className="hero-form"><LeadCard /></div>
        </div>
      </Container>
    </section>
  );
}

function StatsBar() {
  const stats = [['10K', '+', 'Cases Handled'], ['$250M', '+', 'Recovered'], ['30', '+', 'Years Fighting'], ['BBB', 'Accredited', 'Agency']];
  return (
    <section style={{ background: 'var(--bg-surface)', borderBottom: '3px solid var(--ink)' }}>
      <Container style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 18, padding: '40px 28px' }} className="stats-grid">
        {stats.map(([n, plus, label], i) => (
          <div key={label} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', borderLeft: i ? '1px solid var(--line)' : 'none' }} className="stat-cell">
            <span style={{ fontFamily: 'var(--font-display)', fontSize: 'clamp(2.4rem,5vw,4rem)', lineHeight: .85, color: 'var(--ink)' }}>
              {n}<span style={{ color: 'var(--red)' }}>{plus}</span>
            </span>
            <span style={{ fontFamily: 'var(--font-headline)', textTransform: 'uppercase', fontWeight: 600, fontSize: 12.5, letterSpacing: '.12em', color: 'var(--fg2)', marginTop: 10 }}>{label}</span>
          </div>
        ))}
      </Container>
    </section>
  );
}

Object.assign(window, { Hero, StatsBar, LeadCard });
