// DemoRequestContent.jsx — Book a demo landing
const DemoRequestContent = () => {
  const [status, setStatus] = React.useState('idle'); // 'idle' | 'submitting' | 'submitted' | 'error'
  const [errorMessage, setErrorMessage] = React.useState('');
  const [form, setForm] = React.useState({
    name: '',
    email: '',
    company: '',
    role: '',
    team_size: '',
    use_case: '',
    timeline: '',
  });

  const onChange = (k) => (e) => setForm({ ...form, [k]: e.target.value });

  const onSubmit = async (e) => {
    e.preventDefault();
    if (!form.email || !form.name) return;
    setStatus('submitting');
    setErrorMessage('');
    try {
      const res = await fetch('/api/demo-request', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
        body: JSON.stringify({ ...form, source: 'book-a-demo' }),
      });
      if (!res.ok) {
        const payload = await res.json().catch(() => ({}));
        throw new Error(payload.error || `Submission failed (HTTP ${res.status})`);
      }
      setStatus('submitted');
      // Tracked after the API responds so analytics can never delay or
      // interfere with the submission itself.
      window.skardiIdentify?.(form.email, {
        name: form.name, company: form.company, role: form.role,
      });
      window.skardiTrack?.('demo_request_submitted', { timeline: form.timeline || 'unspecified' });
    } catch (err) {
      console.error(err);
      setErrorMessage(err.message || 'Something went wrong.');
      setStatus('error');
      window.skardiTrack?.('demo_request_failed', {
        error: String(err && err.message || 'unknown').slice(0, 100),
      });
    }
  };

  const agenda = [
    {
      h: '15 min · your stack',
      d: 'Walk us through the data sources, agent runtime, and the gnarly bit you keep running into. We listen first.',
    },
    {
      h: '20 min · live federation',
      d: 'A working Skardi workspace wired to a sample of your stack — Postgres + Lance + S3 joined in one query, served as a REST endpoint and a Claude skill.',
    },
    {
      h: '10 min · your next steps',
      d: 'Concrete pipeline shapes for your use case, what the design-partner program looks like, and how cloud onboarding works if you want it.',
    },
  ];

  const inputStyle = {
    width: '100%',
    padding: '12px 14px',
    background: '#060b14',
    border: '1px solid rgba(125,211,252,0.15)',
    borderRadius: 8,
    color: '#e6eef9',
    fontFamily: 'Inter, sans-serif', fontSize: 14,
    outline: 'none',
    transition: 'border-color 150ms ease-out',
  };
  const labelStyle = {
    display: 'block', marginBottom: 6,
    fontFamily: 'JetBrains Mono, monospace', fontSize: 11,
    letterSpacing: '0.08em', textTransform: 'uppercase',
    color: '#8ea3c0', fontWeight: 500,
  };
  const selectStyle = {
    ...inputStyle,
    appearance: 'none',
    WebkitAppearance: 'none',
    backgroundImage: "url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='12' height='8' viewBox='0 0 12 8' fill='none'><path d='M1 1L6 6L11 1' stroke='%238ea3c0' stroke-width='1.5'/></svg>\")",
    backgroundRepeat: 'no-repeat',
    backgroundPosition: 'right 14px center',
    paddingRight: 36,
  };

  return (
    <>
      {/* Hero + form */}
      <section style={{ position: 'relative', padding: '120px 32px 100px', overflow: 'hidden' }}>
        <div style={{
          position: 'absolute', inset: 0,
          backgroundImage: 'linear-gradient(rgba(125,211,252,0.06) 1px, transparent 1px), linear-gradient(90deg, rgba(125,211,252,0.06) 1px, transparent 1px)',
          backgroundSize: '32px 32px',
          maskImage: 'radial-gradient(ellipse 70% 80% at 50% 30%, #000 25%, transparent 80%)',
          WebkitMaskImage: 'radial-gradient(ellipse 70% 80% at 50% 30%, #000 25%, transparent 80%)',
          pointerEvents: 'none',
        }} />
        <div style={{
          position: 'absolute', top: 0, left: '50%', transform: 'translateX(-50%)',
          width: 900, height: 600,
          background: 'radial-gradient(ellipse at top, rgba(29,168,105,0.22) 0%, rgba(26,143,224,0.10) 40%, transparent 70%)',
          pointerEvents: 'none', filter: 'blur(30px)',
        }} />

        <div style={{
          position: 'relative', maxWidth: 1160, margin: '0 auto',
          display: 'grid', gridTemplateColumns: '1.1fr 1fr', gap: 56, alignItems: 'start',
        }}>
          <div style={{ paddingTop: 20 }}>
            <div style={{
              display: 'inline-flex', alignItems: 'center', gap: 8,
              padding: '5px 12px', borderRadius: 9999, marginBottom: 24,
              fontFamily: 'JetBrains Mono, monospace', fontSize: 11,
              letterSpacing: '0.06em',
              border: '1px solid rgba(46,232,154,0.22)',
              color: '#2ee89a',
              background: 'rgba(10,18,32,0.6)',
            }}>
              <span style={{ width: 6, height: 6, borderRadius: '50%', background: '#2ee89a', boxShadow: '0 0 0 3px rgba(46,232,154,0.2)' }} />
              45 minutes · live with the core team
            </div>
            <h1 style={{
              fontFamily: 'Inter, sans-serif', fontWeight: 700,
              fontSize: 'clamp(44px, 5.6vw, 72px)', lineHeight: 1.02,
              letterSpacing: '-0.03em', margin: 0, marginBottom: 24,
              color: '#e6eef9', textWrap: 'balance',
            }}>
              See Skardi running on{' '}
              <span style={{
                background: 'linear-gradient(90deg, #2ec47a 0%, #7ef3c4 40%, #1a8fe0 100%)',
                WebkitBackgroundClip: 'text', backgroundClip: 'text',
                WebkitTextFillColor: 'transparent', color: 'transparent',
                fontStyle: 'italic',
              }}>your stack.</span>
            </h1>
            <p style={{
              fontFamily: 'Inter, sans-serif', fontSize: 19, lineHeight: 1.55,
              color: '#8ea3c0', margin: 0, marginBottom: 20, maxWidth: 560,
            }}>
              Tell us a bit about what you're building and we'll set up a working
              workspace wired to a sample of your sources before the call. No slides —
              you'll see real federated queries against real data.
            </p>
            <p style={{
              fontFamily: 'Inter, sans-serif', fontSize: 15, lineHeight: 1.65,
              color: '#6b7e9a', margin: 0, maxWidth: 540,
            }}>
              We reply within one business day. If you'd rather skip the call and just
              get cloud access, <a href="/cloud"
                onClick={() => window.skardiTrack?.('cta_clicked', { cta: 'waitlist', location: 'demo_page' })}
                style={{color:'#2ee89a', textDecoration:'none'}}>early access</a> is open too.
            </p>
          </div>

          {/* Form card */}
          <div style={{
            background: '#0a1220',
            border: '1px solid rgba(125,211,252,0.12)',
            borderRadius: 16,
            padding: 28,
            boxShadow: '0 20px 60px rgba(0,0,0,0.45), 0 0 0 1px rgba(46,232,154,0.06)',
          }}>
            {status === 'submitted' ? (
              <div style={{ textAlign: 'center', padding: '36px 8px' }}>
                <div style={{
                  width: 56, height: 56, borderRadius: '50%',
                  margin: '0 auto 20px',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  background: 'rgba(46,232,154,0.1)',
                  border: '1px solid rgba(46,232,154,0.35)',
                  color: '#2ee89a', fontSize: 24,
                }}>✓</div>
                <h3 style={{
                  fontFamily: 'Inter, sans-serif', fontSize: 22, fontWeight: 600,
                  color: '#e6eef9', margin: 0, marginBottom: 10, letterSpacing: '-0.015em',
                }}>Request received.</h3>
                <p style={{
                  fontFamily: 'Inter, sans-serif', fontSize: 14, lineHeight: 1.6,
                  color: '#8ea3c0', margin: 0, maxWidth: 340, marginLeft: 'auto', marginRight: 'auto',
                }}>
                  We'll email <span style={{color:'#c4d2e2'}}>{form.email}</span> within one
                  business day with a few time slots and a short questionnaire about your stack.
                </p>
              </div>
            ) : (
              <form onSubmit={onSubmit}>
                <div style={{
                  fontFamily: 'JetBrains Mono, monospace', fontSize: 11,
                  letterSpacing: '0.12em', textTransform: 'uppercase', fontWeight: 500,
                  color: '#2ee89a', marginBottom: 8,
                }}>// request a demo</div>
                <h3 style={{
                  fontFamily: 'Inter, sans-serif', fontSize: 22, fontWeight: 600,
                  color: '#e6eef9', margin: 0, marginBottom: 22, letterSpacing: '-0.015em',
                }}>Tell us about your team</h3>

                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginBottom: 14 }}>
                  <div>
                    <label style={labelStyle} htmlFor="dr-name">Name <span style={{color:'#e04141'}}>*</span></label>
                    <input id="dr-name" type="text" required value={form.name} onChange={onChange('name')}
                      style={inputStyle} placeholder="Ada Lovelace" autoComplete="name" />
                  </div>
                  <div>
                    <label style={labelStyle} htmlFor="dr-role">Role</label>
                    <input id="dr-role" type="text" value={form.role} onChange={onChange('role')}
                      style={inputStyle} placeholder="Head of Data Platform" autoComplete="organization-title" />
                  </div>
                </div>
                <div style={{ marginBottom: 14 }}>
                  <label style={labelStyle} htmlFor="dr-email">Work email <span style={{color:'#e04141'}}>*</span></label>
                  <input id="dr-email" type="email" required value={form.email} onChange={onChange('email')}
                    style={inputStyle} placeholder="ada@engines.com" autoComplete="email" />
                </div>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginBottom: 14 }}>
                  <div>
                    <label style={labelStyle} htmlFor="dr-company">Company</label>
                    <input id="dr-company" type="text" value={form.company} onChange={onChange('company')}
                      style={inputStyle} placeholder="Analytical Engines Inc." autoComplete="organization" />
                  </div>
                  <div>
                    <label style={labelStyle} htmlFor="dr-team">Team size</label>
                    <select id="dr-team" value={form.team_size} onChange={onChange('team_size')} style={selectStyle}>
                      <option value="">Select…</option>
                      <option value="1-10">1 – 10</option>
                      <option value="11-50">11 – 50</option>
                      <option value="51-200">51 – 200</option>
                      <option value="201-1000">201 – 1,000</option>
                      <option value="1000+">1,000+</option>
                    </select>
                  </div>
                </div>
                <div style={{ marginBottom: 14 }}>
                  <label style={labelStyle} htmlFor="dr-timeline">Timeline</label>
                  <select id="dr-timeline" value={form.timeline} onChange={onChange('timeline')} style={selectStyle}>
                    <option value="">Select…</option>
                    <option value="evaluating">Just evaluating</option>
                    <option value="0-30">In production within 30 days</option>
                    <option value="30-90">Pilot in 30 – 90 days</option>
                    <option value="90+">Researching for next quarter+</option>
                  </select>
                </div>
                <div style={{ marginBottom: 20 }}>
                  <label style={labelStyle} htmlFor="dr-use-case">What would you use Skardi for?</label>
                  <textarea id="dr-use-case" value={form.use_case} onChange={onChange('use_case')}
                    style={{ ...inputStyle, minHeight: 84, resize: 'vertical', fontFamily: 'Inter, sans-serif' }}
                    placeholder="RAG over our product docs + Postgres, with batch jobs nightly into Lance…" />
                </div>

                <button type="submit" disabled={status === 'submitting' || !form.email || !form.name}
                  style={{
                    width: '100%',
                    background: (status === 'submitting' || !form.email || !form.name)
                      ? 'rgba(46,232,154,0.35)'
                      : 'linear-gradient(90deg, #2ec47a, #1a8fe0)',
                    border: 'none', color: '#fff',
                    padding: '14px 22px', borderRadius: '2rem',
                    fontFamily: 'Inter, sans-serif', fontSize: 15, fontWeight: 600,
                    cursor: (status === 'submitting' || !form.email || !form.name) ? 'not-allowed' : 'pointer',
                    transition: 'opacity 150ms ease-out',
                  }}>
                  {status === 'submitting' ? 'Sending…' : 'Request a demo →'}
                </button>

                {status === 'error' && (
                  <p style={{
                    fontFamily: 'Inter, sans-serif', fontSize: 13, color: '#e04141',
                    margin: '12px 0 0', textAlign: 'center',
                  }}>{errorMessage || 'Something went wrong. Please try again or email info@skardi.ai directly.'}</p>
                )}

                <p style={{
                  fontFamily: 'Inter, sans-serif', fontSize: 12, lineHeight: 1.55,
                  color: '#6b7e9a', margin: '16px 0 0', textAlign: 'center',
                }}>
                  We'll only use your details to schedule the demo. No marketing blasts.
                </p>
              </form>
            )}
          </div>
        </div>
      </section>

      {/* What you get */}
      <section style={{ padding: '60px 32px 100px', borderTop: '1px solid rgba(125,211,252,0.06)' }}>
        <div style={{ maxWidth: 1100, margin: '0 auto' }}>
          <div style={{ maxWidth: 720, marginBottom: 48 }}>
            <div style={{
              fontFamily: 'JetBrains Mono, monospace', fontSize: 12,
              letterSpacing: '0.12em', textTransform: 'uppercase', fontWeight: 500,
              color: '#2ee89a', marginBottom: 16,
            }}>// the 45 minutes</div>
            <h2 style={{
              fontFamily: 'Inter, sans-serif', fontSize: 'clamp(32px, 4.2vw, 44px)', fontWeight: 700,
              letterSpacing: '-0.025em', lineHeight: 1.1, margin: 0, color: '#e6eef9', textWrap: 'balance',
            }}>What the call looks like.</h2>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 20 }}>
            {agenda.map((p, i) => (
              <div key={p.h} style={{
                padding: '24px 26px', borderRadius: 12,
                background: '#0a1220',
                border: '1px solid rgba(125,211,252,0.08)',
              }}>
                <div style={{
                  fontFamily: 'JetBrains Mono, monospace', fontSize: 11,
                  letterSpacing: '0.12em', textTransform: 'uppercase', fontWeight: 500,
                  color: '#2ee89a', marginBottom: 12,
                }}>// 0{i + 1}</div>
                <h4 style={{
                  fontFamily: 'Inter, sans-serif', fontSize: 17, fontWeight: 600,
                  margin: 0, marginBottom: 10, color: '#e6eef9', letterSpacing: '-0.01em',
                }}>{p.h}</h4>
                <p style={{
                  fontFamily: 'Inter, sans-serif', fontSize: 14, lineHeight: 1.6,
                  margin: 0, color: '#8ea3c0',
                }}>{p.d}</p>
              </div>
            ))}
          </div>
        </div>
      </section>
    </>
  );
};

window.DemoRequestContent = DemoRequestContent;
