// Mission/About, Founder preview, Newsletter, Contact sections

// ---------- FORM BACKEND (Supabase Edge Function) ----------
const SUBMIT_URL = "https://wzhkocpdydxzyvqdrogo.supabase.co/functions/v1/submit-form";
// Public anon key — safe to expose in the browser (read-only gate; the function
// uses a server-side service key the public never sees).
const SUPABASE_ANON_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Ind6aGtvY3BkeWR4enl2cWRyb2dvIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NDE4MDE0MTksImV4cCI6MjA1NzM3NzQxOX0.v1aUkhgffvNN9zT9VPxtzLUC7X7btrgQxelbdekjEIg";

async function submitForm(payload) {
  const res = await fetch(SUBMIT_URL, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Authorization": `Bearer ${SUPABASE_ANON_KEY}`,
      "apikey": SUPABASE_ANON_KEY,
    },
    body: JSON.stringify(payload),
  });
  const data = await res.json().catch(() => ({}));
  if (!res.ok) throw new Error(data.error || "Something went wrong. Please try again.");
  return data;
}

// ---------- MISSION / ABOUT ----------
const Mission = () => (
  <section id="about" style={{ padding: '120px 28px', background: '#fff', position: 'relative', overflow: 'hidden' }}>
    <div style={{ position: 'absolute', left: -80, top: 40, opacity: 0.08, color: 'var(--brand-ember)' }}>
      <DotPattern size={28} dotSize={1.5} opacity={0.3} />
    </div>
    <div style={{ maxWidth: 1100, margin: '0 auto', position: 'relative' }}>
      <Reveal>
        <Eyebrow>Our mission</Eyebrow>
        <h2 style={{
          fontFamily: 'var(--font-display)', fontWeight: 500,
          fontSize: 'clamp(36px, 5vw, 64px)', letterSpacing: '-0.03em',
          margin: '18px 0 28px', lineHeight: 1.05, maxWidth: 1000,
        }}>
          Remove every barrier between a driven person and a real,
          {' '}<span style={{ color: 'var(--brand-ember)' }}>functioning business.</span>
        </h2>
      </Reveal>
      <Reveal delay={100}>
        <div style={{
          display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 48,
          marginTop: 16, maxWidth: 1000,
        }} className="d2-mission-grid">
          <p style={{ fontSize: 17.5, lineHeight: 1.65, color: 'var(--fg-2)', margin: 0 }}>
            dub2.ai is built on a simple idea: the same AI tools that power Fortune 500 companies should power the entrepreneur running a business from their kitchen table.
          </p>
          <p style={{ fontSize: 17.5, lineHeight: 1.65, color: 'var(--fg-2)', margin: 0 }}>
            Headquartered in Houston and backed by engineering talent behind Diversified Robotic and SmartMode.ai, we design AI applications and ready-built white-label businesses — so anyone can own and operate a real AI-powered company.
          </p>
        </div>
      </Reveal>
    </div>
  </section>
);

// ---------- FOUNDER PREVIEW (links to /ceo) ----------
const FounderPreview = () => (
  <section style={{ padding: '80px 28px 112px', background: '#fff' }}>
    <div style={{ maxWidth: 1240, margin: '0 auto' }}>
      <Reveal>
        <div style={{
          background: 'var(--bg-canvas)',
          border: '1px solid var(--border-1)',
          borderRadius: 'var(--radius-2xl)',
          padding: 'clamp(32px, 4vw, 56px)',
          display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 48, alignItems: 'center',
          position: 'relative', overflow: 'hidden',
        }} className="d2-founder-card">
          <div style={{ position: 'absolute', right: -60, top: -60, opacity: 0.1, pointerEvents: 'none' }}>
            <DotGrid w={280} h={280} />
          </div>
          <div style={{ position: 'relative' }}>
            <Eyebrow>Founder</Eyebrow>
            <h2 style={{
              fontFamily: 'var(--font-display)', fontWeight: 500,
              fontSize: 'clamp(32px, 3.8vw, 48px)', letterSpacing: '-0.025em',
              margin: '14px 0 18px', lineHeight: 1.05,
            }}>
              From the basketball court to the Army to AI pioneer.
            </h2>
            <p style={{ fontSize: 17, lineHeight: 1.6, color: 'var(--fg-2)', margin: '0 0 24px', maxWidth: 560 }}>
              Wilton White spent 23 years as a wireless engineer — RF engineering for Lucent, technology design for AT&amp;T — before founding dub2.ai to put enterprise AI in the hands of small teams.
            </p>
            <Button variant="primary" href="ceo.html">Read the founder's story <Icon name="arrow" size={15} /></Button>
          </div>

          {/* Credentials card */}
          <div style={{
            background: '#fff', border: '1px solid var(--border-1)',
            borderRadius: 'var(--radius-xl)', padding: 24, position: 'relative',
            boxShadow: 'var(--shadow-sm)',
          }} className="d2-founder-creds">
            <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 18 }}>
              <div style={{
                width: 52, height: 52, borderRadius: 999,
                background: 'var(--brand-gradient)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                color: '#fff', fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 22,
              }}>WW</div>
              <div>
                <div style={{ fontFamily: 'var(--font-display)', fontSize: 20, fontWeight: 500, letterSpacing: '-0.01em' }}>Wilton White</div>
                <div style={{ fontSize: 13, color: 'var(--fg-3)' }}>Founder · CTO · Board Chair</div>
              </div>
            </div>
            <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 12 }}>
              {[
                ['23y', 'Wireless engineering career'],
                ['6', 'International countries worked'],
                ['3', 'Companies founded'],
              ].map(([num, label]) => (
                <li key={label} style={{ display: 'flex', alignItems: 'baseline', gap: 14, paddingBottom: 12, borderBottom: '1px solid var(--border-1)' }}>
                  <span style={{ fontFamily: 'var(--font-display)', fontSize: 30, fontWeight: 500, color: 'var(--brand-ember)', letterSpacing: '-0.02em', minWidth: 60 }}>{num}</span>
                  <span style={{ fontSize: 14, color: 'var(--fg-2)' }}>{label}</span>
                </li>
              ))}
            </ul>
          </div>
        </div>
      </Reveal>
    </div>
  </section>
);

// ---------- NEWSLETTER (dark full-bleed + dot matrix pattern) ----------
const Newsletter = () => {
  const [email, setEmail] = React.useState('');
  const [status, setStatus] = React.useState('idle'); // idle | error | loading | success
  const [error, setError] = React.useState('');
  const [hp, setHp] = React.useState(''); // honeypot

  const submit = async (e) => {
    e.preventDefault();
    const valid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim());
    if (!valid) {
      setError('Please enter a valid email address.');
      setStatus('error');
      return;
    }
    setStatus('loading');
    setError('');
    try {
      await submitForm({ form: 'newsletter', email: email.trim(), company_website: hp });
      setStatus('success');
    } catch (err) {
      setError(err.message);
      setStatus('error');
    }
  };

  return (
    <section id="newsletter" style={{
      padding: 'clamp(72px, 10vw, 120px) 28px',
      background: 'var(--neutral-900)', color: '#fff', position: 'relative', overflow: 'hidden',
    }}>
      <div style={{ position: 'absolute', inset: 0, color: '#fff' }}>
        <DotPattern size={30} dotSize={1.4} opacity={0.08} />
      </div>
      <div style={{ position: 'absolute', right: '-8%', top: '50%', transform: 'translateY(-50%)', opacity: 0.6, pointerEvents: 'none' }}>
        <AnimatedMark size={380} speed={0.7} />
      </div>

      <div style={{ maxWidth: 1240, margin: '0 auto', position: 'relative', zIndex: 1 }}>
        <div style={{ maxWidth: 620 }}>
          <Eyebrow light>Newsletter</Eyebrow>
          <h2 style={{
            fontFamily: 'var(--font-display)', fontWeight: 500,
            fontSize: 'clamp(36px, 4.8vw, 60px)', letterSpacing: '-0.03em',
            margin: '16px 0 18px', lineHeight: 1.05,
          }}>
            Get early access to new white-label opportunities.
          </h2>
          <p style={{ fontSize: 18, lineHeight: 1.55, color: 'rgba(255,255,255,0.7)', margin: '0 0 32px' }}>
            Join the list. We'll email you when new ready-built AI businesses drop.
          </p>

          {status === 'success' ? (
            <div style={{
              display: 'flex', alignItems: 'center', gap: 14, padding: '18px 20px',
              background: 'rgba(255,255,255,0.06)', border: '1px solid rgba(255,255,255,0.18)',
              borderRadius: 'var(--radius-lg)',
            }}>
              <div style={{ width: 36, height: 36, borderRadius: 999, background: 'var(--success)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                <Icon name="check" size={18} color="#fff" />
              </div>
              <div>
                <div style={{ fontSize: 15, fontWeight: 600 }}>You're on the list.</div>
                <div style={{ fontSize: 13.5, color: 'rgba(255,255,255,0.65)', marginTop: 2 }}>We'll reach out when the next drop is ready.</div>
              </div>
            </div>
          ) : (
            <form onSubmit={submit} noValidate style={{ maxWidth: 520 }}>
              <input
                type="text" tabIndex={-1} autoComplete="off"
                value={hp} onChange={(e) => setHp(e.target.value)}
                name="company_website" aria-hidden="true"
                style={{ position: 'absolute', left: '-9999px', width: 1, height: 1, opacity: 0 }}
              />
              <div style={{
                display: 'flex', gap: 8, padding: 6,
                background: 'rgba(255,255,255,0.06)',
                border: `1.5px solid ${status === 'error' ? '#FF604C' : 'rgba(255,255,255,0.14)'}`,
                borderRadius: 'var(--radius-lg)',
                transition: 'border-color .14s',
              }}>
                <input
                  type="email"
                  value={email}
                  onChange={(e) => { setEmail(e.target.value); if (status === 'error') setStatus('idle'); }}
                  placeholder="you@company.com"
                  aria-label="Email address"
                  style={{
                    flex: 1, background: 'transparent', border: 'none', outline: 'none',
                    color: '#fff', padding: '12px 14px', fontSize: 15, fontFamily: 'var(--font-body)',
                  }}
                />
                <Button type="submit" variant="onDark" size="md" style={{ minWidth: 120 }}>
                  {status === 'loading' ? 'Joining…' : 'Notify me'}
                </Button>
              </div>
              <div style={{ marginTop: 12, fontSize: 13, color: status === 'error' ? '#FF604C' : 'rgba(255,255,255,0.5)', minHeight: 20 }}>
                {status === 'error' ? error : 'No spam. Unsubscribe any time.'}
              </div>
            </form>
          )}
        </div>
      </div>
    </section>
  );
};

// ---------- CONTACT ----------
const Contact = () => {
  const [form, setForm] = React.useState({ name: '', email: '', company: '', interest: 'AI Applications', message: '' });
  const [status, setStatus] = React.useState('idle');
  const [errors, setErrors] = React.useState({});
  const [hp, setHp] = React.useState(''); // honeypot
  const [submitError, setSubmitError] = React.useState('');

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

  const submit = async (e) => {
    e.preventDefault();
    const errs = {};
    if (!form.name.trim()) errs.name = 'Required';
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email.trim())) errs.email = 'Valid email required';
    if (!form.message.trim()) errs.message = 'Tell us a bit about what you need';
    setErrors(errs);
    if (Object.keys(errs).length) return;
    setStatus('loading');
    setSubmitError('');
    try {
      await submitForm({
        form: 'contact',
        name: form.name.trim(),
        email: form.email.trim(),
        company: form.company.trim(),
        interest: form.interest,
        message: form.message.trim(),
        company_website: hp,
      });
      setStatus('success');
    } catch (err) {
      setSubmitError(err.message);
      setStatus('idle');
    }
  };

  if (status === 'success') {
    return (
      <section id="contact" style={{ padding: '112px 28px', background: 'var(--bg-canvas)' }}>
        <div style={{ maxWidth: 720, margin: '0 auto', textAlign: 'center' }}>
          <div style={{
            width: 64, height: 64, borderRadius: 999, margin: '0 auto 20px',
            background: 'var(--success-bg)', color: 'var(--success)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <Icon name="check" size={30} strokeWidth={2} />
          </div>
          <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 44, letterSpacing: '-0.025em', margin: '0 0 14px', lineHeight: 1.1 }}>
            Thanks, {form.name.split(' ')[0]}.
          </h2>
          <p style={{ fontSize: 18, color: 'var(--fg-2)', lineHeight: 1.55, margin: 0 }}>
            We got your message. Expect a reply within one business day — Houston hours.
          </p>
        </div>
      </section>
    );
  }

  return (
    <section id="contact" style={{ padding: '112px 28px', background: 'var(--bg-canvas)' }}>
      <div style={{ maxWidth: 1240, margin: '0 auto' }}>
        <div className="d2-contact-grid" style={{ display: 'grid', gridTemplateColumns: '1fr 1.2fr', gap: 64 }}>
          {/* Left: copy + info */}
          <Reveal>
            <Eyebrow>Contact</Eyebrow>
            <h2 style={{
              fontFamily: 'var(--font-display)', fontWeight: 500,
              fontSize: 'clamp(36px, 4.4vw, 54px)', letterSpacing: '-0.025em',
              margin: '14px 0 18px', lineHeight: 1.05,
            }}>
              Tell us the hardest problem you're trying to solve.
            </h2>
            <p style={{ fontSize: 17.5, lineHeight: 1.6, color: 'var(--fg-2)', margin: '0 0 32px', maxWidth: 480 }}>
              No slides, no pitch deck. A real conversation with the engineers who'll build it.
            </p>
          </Reveal>

          {/* Right: form */}
          <Reveal delay={120}>
            <form onSubmit={submit} noValidate style={{
              background: '#fff', border: '1px solid var(--border-1)', borderRadius: 'var(--radius-2xl)',
              padding: 'clamp(24px, 3vw, 36px)', display: 'flex', flexDirection: 'column', gap: 18,
              boxShadow: 'var(--shadow-sm)',
            }}>
              <input
                type="text" tabIndex={-1} autoComplete="off"
                value={hp} onChange={(e) => setHp(e.target.value)}
                name="company_website" aria-hidden="true"
                style={{ position: 'absolute', left: '-9999px', width: 1, height: 1, opacity: 0 }}
              />
              <div className="d2-form-row" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                <Field label="Your name" value={form.name} onChange={v => update('name', v)} error={errors.name} placeholder="Wilton White" />
                <Field label="Email" type="email" value={form.email} onChange={v => update('email', v)} error={errors.email} placeholder="you@company.com" />
              </div>
              <Field label="Company" value={form.company} onChange={v => update('company', v)} placeholder="Optional" />
              <div>
                <label style={{ fontSize: 13, fontWeight: 600, color: 'var(--fg-2)', marginBottom: 8, display: 'block' }}>I'm interested in</label>
                <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                  {['AI Applications', 'White-Label Solutions', 'Something else'].map(opt => (
                    <button key={opt} type="button" onClick={() => update('interest', opt)} style={{
                      padding: '9px 14px', fontSize: 13.5, fontWeight: 500, fontFamily: 'var(--font-body)',
                      borderRadius: 999, cursor: 'pointer',
                      background: form.interest === opt ? 'var(--brand-ember)' : '#fff',
                      color: form.interest === opt ? '#fff' : 'var(--fg-1)',
                      border: `1.5px solid ${form.interest === opt ? 'var(--brand-ember)' : 'var(--border-2)'}`,
                      transition: 'all .14s',
                    }}>{opt}</button>
                  ))}
                </div>
              </div>
              <Field label="Tell us a bit" textarea value={form.message} onChange={v => update('message', v)} error={errors.message} placeholder="What are you trying to build, automate, or launch?" />
              <Button type="submit" variant="primary" size="lg" style={{ alignSelf: 'flex-start' }} disabled={status === 'loading'}>
                {status === 'loading' ? 'Sending…' : 'Send message'} <Icon name="arrow" size={16} />
              </Button>
              {submitError && (
                <div style={{ fontSize: 13.5, color: 'var(--brand-ember)' }}>{submitError}</div>
              )}
            </form>
          </Reveal>
        </div>
      </div>
    </section>
  );
};

const Field = ({ label, value, onChange, error, placeholder, type = 'text', textarea }) => {
  const [focused, setFocused] = React.useState(false);
  const Tag = textarea ? 'textarea' : 'input';
  return (
    <div>
      <label style={{ fontSize: 13, fontWeight: 600, color: 'var(--fg-2)', marginBottom: 8, display: 'block' }}>
        {label} {error && <span style={{ color: 'var(--brand-ember)', fontWeight: 500 }}>· {error}</span>}
      </label>
      <Tag
        type={textarea ? undefined : type}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        placeholder={placeholder}
        rows={textarea ? 4 : undefined}
        onFocus={() => setFocused(true)}
        onBlur={() => setFocused(false)}
        style={{
          width: '100%', background: '#fff',
          border: `1.5px solid ${error ? 'var(--brand-ember)' : focused ? 'var(--brand-ember)' : 'var(--border-2)'}`,
          borderRadius: 'var(--radius-md)',
          padding: '11px 14px', fontSize: 14.5, fontFamily: 'var(--font-body)',
          color: 'var(--fg-1)', outline: 'none',
          boxShadow: focused ? 'var(--ring-focus)' : 'none',
          transition: 'all .14s',
          resize: textarea ? 'vertical' : 'none',
          minHeight: textarea ? 110 : undefined,
          boxSizing: 'border-box',
        }}
      />
    </div>
  );
};

Object.assign(window, { Mission, FounderPreview, Newsletter, Contact });
