// CloudWaitlistContent.jsx — Skardi Cloud waitlist landing
const CloudWaitlistContent = () => {
  const [status, setStatus] = React.useState('idle'); // 'idle' | 'submitting' | 'submitted' | 'error'
  const [form, setForm] = React.useState({ name: '', email: '', company: '', use_case: '' });

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

  const [errorMessage, setErrorMessage] = React.useState('');
  const onSubmit = async (e) => {
    e.preventDefault();
    if (!form.email) return;
    setStatus('submitting');
    setErrorMessage('');
    try {
      const res = await fetch('/api/waitlist', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
        body: JSON.stringify({ ...form, source: 'cloud-waitlist' }),
      });
      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 });
      window.skardiTrack?.('waitlist_submitted');
    } catch (err) {
      console.error(err);
      setErrorMessage(err.message || 'Something went wrong.');
      setStatus('error');
      window.skardiTrack?.('waitlist_failed', {
        error: String(err && err.message || 'unknown').slice(0, 100),
      });
    }
  };

  const props = [
    {
      h: 'ReBAC authorization',
      d: 'Agents reach exactly the rows the asking user could read in the source. No more, no less, enforced on every path: SQL, MCP, pipelines, jobs.',
    },
    {
      h: 'Semantic catalog',
      d: 'Plain-English definitions on every table and column, mapped once and corrected everywhere, with lineage and agent-facing context built in.',
    },
    {
      h: 'Governance and audit',
      d: 'Access requests, approvals and a full audit stream that can answer why an agent returned or refused a row after the fact. Support reads audit, not data.',
    },
    {
      h: 'The loop, managed',
      d: 'The query ledger, promotion and review are wired in, so the questions your agents keep asking become governed tools without extra plumbing.',
    },
    {
      h: 'Managed federated engine',
      d: 'One query across Postgres, MySQL, Mongo, Redis, object stores and your SaaS tools. You bring credentials; we run the engine.',
    },
    {
      h: 'Observability built in',
      d: 'Per-workspace identity, metering and OpenTelemetry traces, metrics and logs on a pre-configured stack. No extra wiring.',
    },
  ];

  const faqs = [
    {
      q: 'When does Skardi Cloud launch?',
      a: 'Invites are going out in waves. Design partners get earliest access; we prioritise teams that can give us tight feedback on the governance layer and pipeline ergonomics.',
    },
    {
      q: 'How is this different from self-hosting?',
      a: 'Self-hosting stays fully supported: same engine, same YAML, no lock-in. Skardi Cloud adds what the engine alone does not carry: ReBAC authorization, the semantic catalog, approvals and audit, plus provisioning, upgrades and multi-tenant isolation handled for you.',
    },
    {
      q: 'Will my data leave my region?',
      a: 'Cloud workspaces are pinned to a region you choose at provisioning time. For sources you already operate, Skardi connects via outbound credentials: your Postgres, your bucket, your policy.',
    },
    {
      q: 'How does pricing work?',
      a: 'Early access admits get an introductory tier covering a single production workspace. Usage-based pricing for compute, storage, and egress ships before GA.',
    },
  ];

  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,
  };

  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)' }} />
              early access · rolling invites
            </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',
            }}>
              Skardi{' '}
              <span style={{
                background: 'linear-gradient(90deg, #2ec47a 0%, #7ef3c4 40%, #1a8fe0 100%)',
                WebkitBackgroundClip: 'text', backgroundClip: 'text',
                WebkitTextFillColor: 'transparent', color: 'transparent',
              }}>Cloud</span>
            </h1>
            <p style={{
              fontFamily: 'Inter, sans-serif', fontSize: 19, lineHeight: 1.55,
              color: '#8ea3c0', margin: 0, marginBottom: 20, maxWidth: 560,
            }}>
              Enterprise Context, fully managed. The same self-improving engine with
              identity, authorization, a semantic catalog and observability wrapped
              around it, provisioned in minutes.
            </p>
            <p style={{
              fontFamily: 'Inter, sans-serif', fontSize: 15, lineHeight: 1.65,
              color: '#6b7e9a', margin: 0, maxWidth: 540,
            }}>
              We're rolling out access in batches. Drop us your details and we'll reach
              out as slots open. Design partners get first dibs.
            </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: 320, marginLeft: 'auto', marginRight: 'auto',
                }}>
                  We'll reach out to <span style={{color:'#c4d2e2'}}>{form.email}</span> as soon as a
                  slot opens.
                </p>
              </div>
            ) : (
              <form onSubmit={onSubmit}>
                <div style={{
                  fontFamily: 'JetBrains Mono, monospace', fontSize: 11,
                  letterSpacing: '0.12em', textTransform: 'uppercase', fontWeight: 500,
                  color: '#2ee89a', marginBottom: 8,
                }}>Early access</div>
                <h3 style={{
                  fontFamily: 'Inter, sans-serif', fontSize: 22, fontWeight: 600,
                  color: '#e6eef9', margin: 0, marginBottom: 22, letterSpacing: '-0.015em',
                }}>Request access</h3>

                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginBottom: 14 }}>
                  <div>
                    <label style={labelStyle} htmlFor="wl-name">Name</label>
                    <input id="wl-name" type="text" value={form.name} onChange={onChange('name')}
                      style={inputStyle} placeholder="Ada Lovelace" autoComplete="name" />
                  </div>
                  <div>
                    <label style={labelStyle} htmlFor="wl-company">Company</label>
                    <input id="wl-company" type="text" value={form.company} onChange={onChange('company')}
                      style={inputStyle} placeholder="Analytical Engines Inc." autoComplete="organization" />
                  </div>
                </div>
                <div style={{ marginBottom: 14 }}>
                  <label style={labelStyle} htmlFor="wl-email">Work email <span style={{color:'#e04141'}}>*</span></label>
                  <input id="wl-email" type="email" required value={form.email} onChange={onChange('email')}
                    style={inputStyle} placeholder="ada@engines.com" autoComplete="email" />
                </div>
                <div style={{ marginBottom: 20 }}>
                  <label style={labelStyle} htmlFor="wl-use-case">What would you build on Skardi?</label>
                  <textarea id="wl-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}
                  style={{
                    width: '100%',
                    background: (status === 'submitting' || !form.email)
                      ? '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) ? 'not-allowed' : 'pointer',
                    transition: 'opacity 150ms ease-out',
                  }}>
                  {status === 'submitting' ? 'Submitting…' : 'Request access →'}
                </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 us 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 email to send cloud access info. 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: 1200, margin: '0 auto' }}>
          <div style={{ maxWidth: 780, marginBottom: 48 }}>
            <div style={{
              fontFamily: 'JetBrains Mono, monospace', fontSize: 12,
              letterSpacing: '0.12em', textTransform: 'uppercase', fontWeight: 500,
              color: '#2ee89a', marginBottom: 16,
            }}>What you get</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',
            }}>Everything that makes an engine safe to point an agent at</h2>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 20 }}>
            {props.map((p) => (
              <div key={p.h} style={{
                padding: '22px 24px', borderRadius: 12,
                background: '#0a1220',
                border: '1px solid rgba(125,211,252,0.08)',
              }}>
                <h4 style={{
                  fontFamily: 'Inter, sans-serif', fontSize: 16, 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>

      {/* FAQ */}
      <section style={{ padding: '80px 32px 120px', background: '#060b14', borderTop: '1px solid rgba(125,211,252,0.06)' }}>
        <div style={{ maxWidth: 880, margin: '0 auto' }}>
          <div style={{ marginBottom: 40 }}>
            <div style={{
              fontFamily: 'JetBrains Mono, monospace', fontSize: 12,
              letterSpacing: '0.12em', textTransform: 'uppercase', fontWeight: 500,
              color: '#2ee89a', marginBottom: 16,
            }}>FAQ</div>
            <h2 style={{
              fontFamily: 'Inter, sans-serif', fontSize: 'clamp(30px, 4vw, 40px)', fontWeight: 700,
              letterSpacing: '-0.025em', lineHeight: 1.1, margin: 0, color: '#e6eef9',
            }}>Questions before you sign up</h2>
          </div>
          <div style={{
            border: '1px solid rgba(125,211,252,0.08)',
            borderRadius: 12, overflow: 'hidden',
          }}>
            {faqs.map((f, i) => (
              <div key={f.q} style={{
                padding: '22px 24px',
                background: i % 2 === 0 ? '#0a1220' : '#0e1a2e',
                borderBottom: i < faqs.length - 1 ? '1px solid rgba(125,211,252,0.06)' : 'none',
              }}>
                <h4 style={{
                  fontFamily: 'Inter, sans-serif', fontSize: 16, fontWeight: 600,
                  margin: 0, marginBottom: 8, color: '#e6eef9', letterSpacing: '-0.01em',
                }}>{f.q}</h4>
                <p style={{
                  fontFamily: 'Inter, sans-serif', fontSize: 14.5, lineHeight: 1.6,
                  margin: 0, color: '#8ea3c0',
                }}>{f.a}</p>
              </div>
            ))}
          </div>
        </div>
      </section>
    </>
  );
};

window.CloudWaitlistContent = CloudWaitlistContent;
