
const { useState, useEffect } = React;

// ─── HUBSPOT FORM ─────────────────────────────────────────────────────────────
function HubSpotForm() {
  const [form, setForm] = React.useState({
    help: '', firstname: '', lastname: '', email: '', phone: '',
    company: '', jobtitle: '', state: '', agency_unit_division: '', consent: false,
  });
  const [status, setStatus] = React.useState('idle'); // idle | submitting | success | error

  const helpOptions = [
    'Get a Quote',
    'Learn More About our Non-Lethal Response',
    'Learn More About Non-Lethal Drone or Robotics Policy',
    'Stay Connected with Wrap',
    'Learn More About BolaWrap™',
    'Something Else',
    'Subscribe to CUAS (Drone) Project Updates',
  ];

  const us_states = ['Alabama','Alaska','Arizona','Arkansas','California','Colorado','Connecticut','Delaware','Florida','Georgia','Hawaii','Idaho','Illinois','Indiana','Iowa','Kansas','Kentucky','Louisiana','Maine','Maryland','Massachusetts','Michigan','Minnesota','Mississippi','Missouri','Montana','Nebraska','Nevada','New Hampshire','New Jersey','New Mexico','New York','North Carolina','North Dakota','Ohio','Oklahoma','Oregon','Pennsylvania','Rhode Island','South Carolina','South Dakota','Tennessee','Texas','Utah','Vermont','Virginia','Washington','West Virginia','Wisconsin','Wyoming','International / Other'];

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

  const submit = async (e) => {
    e.preventDefault();
    setStatus('submitting');
    try {
      const res = await fetch(
        'https://api.hsforms.com/submissions/v3/integration/submit/7267108/2c28441d-fe68-400f-b36a-0c33cc9e65de',
        {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            fields: [
              { name: 'how_can_we_help_you_', value: form.help },
              { name: 'firstname',            value: form.firstname },
              { name: 'lastname',             value: form.lastname },
              { name: 'email',                value: form.email },
              { name: 'phone',                value: form.phone },
              { name: 'company',              value: form.company },
              { name: 'jobtitle',             value: form.jobtitle },
              { name: 'state',                value: form.state },
              { name: 'agency_unit_division', value: form.agency_unit_division },
            ],
            context: { pageUri: window.location.href, pageName: 'Contact Sales' },
            legalConsentOptions: {
              consent: { consentToProcess: form.consent, text: 'I agree to receive communications from Wrap Technologies.' }
            },
          }),
        }
      );
      if (res.ok || res.status === 200) setStatus('success');
      else setStatus('error');
    } catch { setStatus('error'); }
  };

  const inputStyle = {
    width: '100%', background: 'var(--bg-2)',
    border: '1px solid var(--border-strong)',
    borderRadius: 6, padding: '11px 14px',
    color: 'var(--text)', fontFamily: 'DM Sans, sans-serif',
    fontSize: 14, outline: 'none', boxSizing: 'border-box',
  };
  const labelStyle = {
    display: 'block', fontSize: 11, fontWeight: 600,
    letterSpacing: '0.08em', textTransform: 'uppercase',
    color: 'var(--text-sub)', marginBottom: 6,
  };

  if (status === 'success') return (
    <div style={{ textAlign: 'center', padding: '48px 24px' }}>
      <div style={{ fontFamily: 'Barlow Condensed', fontWeight: 900, fontSize: 48, color: 'var(--accent)', marginBottom: 12 }}>✓</div>
      <div style={{ fontFamily: 'Barlow Condensed', fontWeight: 700, fontSize: 28, textTransform: 'uppercase', color: 'var(--text)', marginBottom: 12 }}>Message Sent</div>
      <p style={{ fontSize: 15, color: 'var(--text-sub)', lineHeight: 1.6 }}>Thank you — a member of our team will be in touch shortly.</p>
    </div>
  );

  return (
    <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      {/* How can we help */}
      <div>
        <label style={labelStyle}>How can we help you? <span style={{ color: 'var(--accent)' }}>*</span></label>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 4 }}>
          {helpOptions.map(opt => (
            <label key={opt} style={{ display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer', fontSize: 14, color: 'var(--text)', fontWeight: 400 }}>
              <input type="radio" name="help" value={opt} checked={form.help === opt} onChange={e => set('help', e.target.value)}
                style={{ width: 15, height: 15, accentColor: 'var(--accent)', flexShrink: 0 }} />
              {opt}
            </label>
          ))}
        </div>
      </div>

      {/* Name row */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        <div>
          <label style={labelStyle}>First Name <span style={{ color: 'var(--accent)' }}>*</span></label>
          <input required style={inputStyle} type="text" value={form.firstname} onChange={e => set('firstname', e.target.value)} />
        </div>
        <div>
          <label style={labelStyle}>Last Name <span style={{ color: 'var(--accent)' }}>*</span></label>
          <input required style={inputStyle} type="text" value={form.lastname} onChange={e => set('lastname', e.target.value)} />
        </div>
      </div>

      {/* Email / Phone */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        <div>
          <label style={labelStyle}>Email <span style={{ color: 'var(--accent)' }}>*</span></label>
          <input required style={inputStyle} type="email" value={form.email} onChange={e => set('email', e.target.value)} />
        </div>
        <div>
          <label style={labelStyle}>Phone Number <span style={{ color: 'var(--accent)' }}>*</span></label>
          <input required style={inputStyle} type="tel" value={form.phone} onChange={e => set('phone', e.target.value)} />
        </div>
      </div>

      {/* Agency / Title */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        <div>
          <label style={labelStyle}>Agency or Company <span style={{ color: 'var(--accent)' }}>*</span></label>
          <input required style={inputStyle} type="text" value={form.company} onChange={e => set('company', e.target.value)} />
        </div>
        <div>
          <label style={labelStyle}>Title <span style={{ color: 'var(--accent)' }}>*</span></label>
          <input required style={inputStyle} type="text" value={form.jobtitle} onChange={e => set('jobtitle', e.target.value)} />
        </div>
      </div>

      {/* State */}
      <div>
        <label style={labelStyle}>State / Region <span style={{ color: 'var(--accent)' }}>*</span></label>
        <select required style={{ ...inputStyle, appearance: 'none' }} value={form.state} onChange={e => set('state', e.target.value)}>
          <option value="">Please Select</option>
          {us_states.map(s => <option key={s} value={s}>{s}</option>)}
        </select>
      </div>

      {/* Agency Unit */}
      <div>
        <label style={labelStyle}>Agency Unit / Division</label>
        <input style={inputStyle} type="text" value={form.agency_unit_division} onChange={e => set('agency_unit_division', e.target.value)} />
      </div>

      {/* Privacy */}
      <div style={{ fontSize: 12, color: 'var(--text-muted)', lineHeight: 1.6, padding: '8px 0' }}>
        Wrap Technologies is committed to protecting and respecting your privacy, and we'll only use your personal information to administer your account and to provide the products and services you requested from us.
      </div>

      {/* Consent */}
      <label style={{ display: 'flex', alignItems: 'flex-start', gap: 10, cursor: 'pointer', fontSize: 13, color: 'var(--text-sub)', lineHeight: 1.5 }}>
        <input type="checkbox" checked={form.consent} onChange={e => set('consent', e.target.checked)}
          style={{ width: 15, height: 15, accentColor: 'var(--accent)', flexShrink: 0, marginTop: 2 }} />
        I agree to receive communications from Wrap Technologies. <span style={{ color: 'var(--accent)' }}>*</span>
      </label>

      <button type="submit" disabled={status === 'submitting' || !form.consent} style={{
        background: form.consent ? 'var(--accent)' : 'var(--bg-3)',
        color: form.consent ? '#000' : 'var(--text-muted)',
        border: 'none', cursor: form.consent ? 'pointer' : 'not-allowed',
        padding: '14px 32px', borderRadius: 4,
        fontFamily: 'DM Sans, sans-serif', fontWeight: 700, fontSize: 15,
        transition: 'all 0.2s', alignSelf: 'flex-start',
      }}>{status === 'submitting' ? 'Submitting...' : 'Submit'}</button>

      {status === 'error' && <p style={{ fontSize: 13, color: '#ff6b6b' }}>Something went wrong. Please try again or email us directly.</p>}
    </form>
  );
}

const TWEAKS = { theme: 'navy', heroLayout: 'split' };

// ─── STUB PAGES ───────────────────────────────────────────────────────────────
function StubPage({ title, desc, navigate }) {
  return (
    <main style={{ paddingTop: 72, minHeight: '100vh', background: 'var(--bg)' }}>
      <section style={{ maxWidth: 1200, margin: '0 auto', padding: '120px 48px' }}>
        <div style={{ fontFamily: 'DM Sans', fontSize: 12, fontWeight: 600, letterSpacing: '0.14em', color: 'var(--accent)', textTransform: 'uppercase', marginBottom: 20 }}>Coming Soon</div>
        <h1 style={{ fontFamily: 'Barlow Condensed', fontWeight: 900, fontSize: 'clamp(56px, 9vw, 112px)', textTransform: 'uppercase', color: 'var(--text)', lineHeight: 0.9, marginBottom: 24 }}>{title}</h1>
        <p style={{ fontSize: 18, color: 'var(--text-sub)', maxWidth: 480, lineHeight: 1.65, marginBottom: 48 }}>{desc}</p>
        <button onClick={() => navigate('home')} style={{
          background: 'var(--accent)', color: '#000', border: 'none', cursor: 'pointer',
          padding: '13px 28px', borderRadius: 4, fontFamily: 'DM Sans', fontWeight: 700, fontSize: 14,
        }}>← Back to Home</button>
      </section>
    </main>
  );
}

function ContactPage({ navigate }) {
  return (
    <main style={{ paddingTop: 72, minHeight: '100vh', background: 'var(--bg)' }}>
      <section style={{ maxWidth: 1200, margin: '0 auto', padding: '100px 48px' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 80 }}>
          <div>
            <div style={{ fontFamily: 'DM Sans', fontSize: 12, fontWeight: 600, letterSpacing: '0.14em', color: 'var(--accent)', textTransform: 'uppercase', marginBottom: 20 }}>Get In Touch</div>
            <h1 style={{ fontFamily: 'Barlow Condensed', fontWeight: 900, fontSize: 'clamp(48px, 6vw, 80px)', textTransform: 'uppercase', color: 'var(--text)', lineHeight: 0.92, marginBottom: 24 }}>
              Contact<br />Sales
            </h1>
            <p style={{ fontSize: 17, lineHeight: 1.7, color: 'var(--text-sub)', marginBottom: 40 }}>
              De-escalation is the goal. But when it fails, officers still need a way to act. Schedule a conversation to learn how the WRAP® NLR System can help your agency.
            </p>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
              {[
                { label: 'Schedule a Meeting', href: 'https://meetings.hubspot.com/wrap/connect', desc: 'Book directly with our team via HubSpot' },
                { label: 'Visit wrap.com', href: 'https://www.wrap.com', desc: 'Learn more at our main website' },
              ].map(({ label, href, desc }) => (
                <a key={label} href={href} target="_blank" rel="noopener noreferrer" style={{ textDecoration: 'none' }}>
                  <div style={{ background: 'var(--card-bg)', border: '1px solid var(--border)', borderRadius: 8, padding: '24px 28px', transition: 'border-color 0.2s' }}
                    onMouseEnter={e => e.currentTarget.style.borderColor = 'rgba(255,181,5,0.3)'}
                    onMouseLeave={e => e.currentTarget.style.borderColor = 'var(--border)'}
                  >
                    <div style={{ fontFamily: 'DM Sans', fontWeight: 600, fontSize: 16, color: 'var(--accent)', marginBottom: 6 }}>{label} →</div>
                    <div style={{ fontSize: 14, color: 'var(--text-sub)' }}>{desc}</div>
                  </div>
                </a>
              ))}
            </div>
          </div>
          <div style={{ background: 'var(--card-bg)', border: '1px solid var(--border)', borderRadius: 12, padding: '40px' }}>
            <div style={{ fontFamily: 'Barlow Condensed', fontWeight: 700, fontSize: 28, textTransform: 'uppercase', color: 'var(--text)', marginBottom: 8 }}>Send a Message</div>
            <p style={{ fontSize: 13, color: 'var(--text-muted)', marginBottom: 28 }}>Fill out the form below and our team will be in touch shortly.</p>
            <HubSpotForm />
          </div>
        </div>
      </section>
      <Footer navigate={navigate} />
    </main>
  );
}


// ─── THEME TOKENS ─────────────────────────────────────────────────────────────
const THEMES = {
  dark:  { '--bg': '#09090b', '--bg-2': '#111113', '--bg-3': '#1a1b21', '--text': '#f2ede4', '--text-sub': '#b0aa9e', '--text-muted': '#6a6a60', '--border': 'rgba(255,255,255,0.07)', '--border-strong': 'rgba(255,255,255,0.15)', '--card-bg': '#131418', '--accent-dim': 'rgba(255,181,5,0.1)' },
  navy:  { '--bg': '#060c1c', '--bg-2': '#0a1428', '--bg-3': '#0f1d35', '--text': '#e8edf8', '--text-sub': '#8899bb', '--text-muted': '#4a5a7a', '--border': 'rgba(255,255,255,0.07)', '--border-strong': 'rgba(255,255,255,0.15)', '--card-bg': '#0a1428', '--accent-dim': 'rgba(255,181,5,0.1)' },
  white: { '--bg': '#fafaf8', '--bg-2': '#f3f2ef', '--bg-3': '#e8e7e3', '--text': '#111110', '--text-sub': '#555550', '--text-muted': '#99998e', '--border': 'rgba(0,0,0,0.08)', '--border-strong': 'rgba(0,0,0,0.16)', '--card-bg': '#f0efec', '--accent-dim': 'rgba(255,181,5,0.12)' },
};

function applyTheme(name) {
  const tokens = THEMES[name] || THEMES.navy;
  Object.entries(tokens).forEach(([k, v]) => document.documentElement.style.setProperty(k, v));
}

// ─── APP ──────────────────────────────────────────────────────────────────────
function App() {
  const [page,      setPageState] = useState(() => sessionStorage.getItem('wrap-page') || 'home');
  const [productId, setProductId] = useState(() => sessionStorage.getItem('wrap-pid') || null);
  const [legalDoc, setLegalDoc] = useState(() => sessionStorage.getItem('wrap-legal') || 'privacy');
  const [ucId,     setUcId]     = useState(() => sessionStorage.getItem('wrap-uc') || null);
  const tweaks = TWEAKS;

  const navigate = (p, pid = null) => {
    setPageState(p);
    if (pid) {
      if (p === 'legal')     { setLegalDoc(pid); sessionStorage.setItem('wrap-legal', pid); }
      else if (p === 'use-case') { setUcId(pid); sessionStorage.setItem('wrap-uc', pid); }
      else { setProductId(pid); sessionStorage.setItem('wrap-pid', pid); }
    }
    sessionStorage.setItem('wrap-page', p);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  useEffect(() => { applyTheme('navy'); }, []);

  const stubs = {
    training:  { title: 'Training',   desc: 'WRAP® training programs, certifications, and resources for law enforcement agencies — coming soon.' },
    support:   { title: 'Support',    desc: 'Technical support, documentation, and resources for WRAP® system operators — coming soon.' },
    investors: { title: 'Investors',  desc: 'Investor relations, financial information, and corporate governance — coming soon.' },
  };

  return (
    <>
      <Nav page={page} setPage={p => navigate(p)} theme={tweaks.theme} />
      {page === 'home'      && <HomePage     navigate={navigate} tweaks={tweaks} />}
      {page === 'products'  && <ProductsPage navigate={navigate} productId={null} />}
      {page === 'product'   && <ProductsPage navigate={navigate} productId={productId} />}
      {page === 'contact'   && <ContactPage  navigate={navigate} />}
      {page === 'about'     && <AboutPage    navigate={navigate} />}
      {page === 'use-cases' && <UseCasesPage navigate={navigate} ucId={null} />}
      {page === 'use-case'  && <UseCasesPage navigate={navigate} ucId={ucId} />}
      {page === 'legal'     && <LegalPage    navigate={navigate} doc={legalDoc} />}
      {page === 'training'  && <StubPage title={stubs.training.title}  desc={stubs.training.desc}  navigate={navigate} />}
      {page === 'support'   && <StubPage title={stubs.support.title}   desc={stubs.support.desc}   navigate={navigate} />}
      {page === 'investors' && <StubPage title={stubs.investors.title} desc={stubs.investors.desc} navigate={navigate} />}
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
