const { SectionHeader, Field, Button, Card } = window.ECPSDesignSystem_a74b4a;

// Supabase edge function that saves the briefing lead and sends the confirmation
// email. It handles auth server-side, so no anon key is needed in the client.
const SUPABASE_URL = 'https://uhaeirzrdimhmaupcmjs.supabase.co';

const SPECS = [['Scope', 'One dive zone, trail, or safari concession'], ['Reporting', 'Rangers & licensed guides only'], ['Tech', 'Tag-scan + rule-based tiering'], ['Consequences', 'Tiers 1–2 only, logged appeal from day one'], ['Ownership', 'Platform built and operated by ecps. Deployed in partnership with the destination authority.']];

// What we deliver: five deliverables rendered as mono field notes (tidal prefix,
// muted body), matching the field-note treatment used in the Problem section.
const DELIVERABLES = [
  ['SOFTWARE', 'Custom-built enforcement platform: ranger app, rule engine, evidence store, command dashboard'],
  ['HARDWARE', 'Procurement specification for commercial off-the-shelf cameras, tag readers, and network infrastructure'],
  ['DEPLOYMENT', 'On-site installation, integration, and 6 to 12 months of supported operation'],
  ['DATA', 'Detection accuracy reports, false-positive analysis, enforcement metrics, go/no-go recommendation for Phase 2'],
  ['OWNERSHIP', 'You own the enforcement authority and the operational data. We own the platform and the IP.'],
];

// Site-level fix for the Role <select>. Native selects ignore most control CSS,
// so we strip the OS appearance and draw a custom chevron. Scoped to the pilot
// form's select; the Field component in the bundle is left untouched. !important
// is required to beat Field's inline styles on the <select>. The chevron fill
// #0F2A2E is --ecps-text-on-light (the input text color); a data-URI SVG cannot
// reference a CSS var, so the token value is inlined here.
const BRIEFING_CSS = `
#pilot select {
  -webkit-appearance: none !important;
  appearance: none !important;
  background-image: url("data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20width='10'%20height='6'%3E%3Cpath%20d='M0%200%205%206%2010%200z'%20fill='%230F2A2E'/%3E%3C/svg%3E") !important;
  background-repeat: no-repeat !important;
  background-position: right 12px center !important;
  padding-right: 34px !important;
}
`;

function Briefing() {
  const { compact, narrow } = window.useViewport();
  const [v, setV] = React.useState({ name: '', email: '', org: '', role: 'Destination authority', region: '', message: '' });
  const [errors, setErrors] = React.useState({});
  const [status, setStatus] = React.useState('idle');
  const set = (k) => (e) => setV({ ...v, [k]: e.target.value });
  const validate = (k) => () => setErrors(prev => ({ ...prev, [k]: v[k].trim() ? undefined : 'This field is required.' }));

  const submit = async (e) => {
    e.preventDefault();
    const next = {};
    ['name', 'email', 'org', 'region'].forEach(k => { if (!v[k].trim()) next[k] = 'This field is required.'; });
    setErrors(next);
    if (Object.keys(next).length) return;

    setStatus('submitting');
    try {
      const res = await fetch(`${SUPABASE_URL}/functions/v1/briefing-request`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: v.name.trim(),
          email: v.email.trim(),
          organization: v.org.trim(),
          role: v.role,
          site_type: v.region.trim(),
          message: v.message.trim(),
        }),
      });
      const body = await res.json().catch(() => ({}));
      // A saved lead counts as success even if the confirmation email failed
      // (email_sent: false); only a failed save (success: false) is an error.
      setStatus(res.ok && body.success ? 'success' : 'error');
    } catch (err) {
      setStatus('error');
    }
  };

  return (
    <section id="pilot" style={{ padding: 'var(--ecps-section-y) 0', background: 'var(--ecps-deep-tide)', scrollMarginTop: 76 }}>
      <style>{BRIEFING_CSS}</style>
      <div style={{ maxWidth: 'var(--ecps-max-width)', margin: '0 auto', padding: '0 var(--ecps-gutter)', display: 'grid', gridTemplateColumns: compact ? '1fr' : '1fr 1fr', gap: compact ? 32 : 56, alignItems: 'start' }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 32 }}>
          <SectionHeader onDark eyebrow="The pilot" title="A single site. 6–12 months. Real data before we scale." lede="We're looking for a destination authority or conservation partner ready to close the coverage gap, without cutting corners on legal defensibility." />
          <div style={{ borderTop: '1px solid var(--ecps-rule-on-dark)', borderBottom: '1px solid var(--ecps-rule-on-dark)', display: 'grid', gridTemplateColumns: '1fr 1fr' }}>
            {SPECS.map(([k, val], i) => (
              <div key={k} style={{ padding: '18px 20px 18px 0', borderRight: i % 2 === 0 ? '1px solid var(--ecps-rule-on-dark)' : 'none', paddingLeft: i % 2 === 1 ? 20 : 0, display: 'flex', flexDirection: 'column', gap: 6 }}>
                <div style={{ fontFamily: 'var(--ecps-font-label)', fontSize: 'var(--ecps-fs-label)', fontWeight: 700, letterSpacing: 'var(--ecps-ls-label)', textTransform: 'uppercase', color: 'var(--ecps-tidal)' }}>{k}</div>
                <div style={{ fontFamily: 'var(--ecps-font-display)', fontSize: 13, lineHeight: 1.6, color: 'var(--ecps-text-on-dark-muted)' }}>{val}</div>
              </div>
            ))}
          </div>

          {/* What we deliver: dark partnership block above the form. Mono field
              notes for the deliverables. No CTA here; the form is the call to action. */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              <div style={{ fontFamily: 'var(--ecps-font-label)', fontSize: 'var(--ecps-fs-label)', fontWeight: 700, letterSpacing: 'var(--ecps-ls-label)', textTransform: 'uppercase', color: 'var(--ecps-tidal)' }}>The partnership</div>
              <div style={{ fontFamily: 'var(--ecps-font-display)', fontSize: 'var(--ecps-fs-h2)', fontWeight: 300, letterSpacing: 'var(--ecps-ls-h2)', lineHeight: 'var(--ecps-lh-h2)', color: 'var(--ecps-shell)' }}>We build it. We deploy it. You operate it.</div>
              <div style={{ fontFamily: 'var(--ecps-font-display)', fontSize: 'var(--ecps-fs-body)', lineHeight: 'var(--ecps-lh-body)', color: 'var(--ecps-text-on-dark-muted)' }}>ecps is a platform company. We build the detection and enforcement software, specify the hardware, and deploy the system at your site. You provide the site, the regulatory authority, and the rangers. The platform remains ours. The enforcement authority remains yours.</div>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {DELIVERABLES.map(([k, b]) => (
                <div key={k} style={{ fontFamily: 'var(--ecps-font-mono)', fontSize: 11.5, lineHeight: 1.7, color: 'var(--ecps-text-on-dark-muted)' }}>
                  <span style={{ color: 'var(--ecps-tidal)' }}>{k} · </span>{b}
                </div>
              ))}
            </div>
          </div>
        </div>

        {status === 'success' ? (
          <div style={{ background: 'var(--ecps-shell)', padding: '32px 34px', display: 'flex', flexDirection: 'column', gap: 12 }}>
            <div style={{ fontFamily: 'var(--ecps-font-mono)', fontSize: 'var(--ecps-fs-eyebrow)', fontWeight: 600, letterSpacing: 'var(--ecps-ls-eyebrow)', textTransform: 'uppercase', color: 'var(--ecps-kelp)' }}>Request logged</div>
            <div style={{ fontFamily: 'var(--ecps-font-display)', fontSize: 'var(--ecps-fs-h2)', fontWeight: 300, letterSpacing: 'var(--ecps-ls-h2)', lineHeight: 'var(--ecps-lh-h2)', color: 'var(--ecps-deep-tide)' }}>Request received.</div>
            <div style={{ fontFamily: 'var(--ecps-font-display)', fontSize: 'var(--ecps-fs-body)', lineHeight: 'var(--ecps-lh-body)', color: 'var(--ecps-text-on-light-body)' }}>Thank you for your interest. The executive summary is available to download below.</div>
            <div>
              <a href="assets/ecps_pilot_briefing.pdf" target="_blank" style={{ display: 'inline-block', padding: '12px 24px', background: 'var(--ecps-tidal)', color: 'var(--ecps-deep-tide)', textDecoration: 'none', fontFamily: 'var(--ecps-font-label)', fontSize: 13, fontWeight: 700, letterSpacing: '2px', textTransform: 'uppercase', marginTop: 16 }}>Download pilot briefing</a>
            </div>
          </div>
        ) : (
          <form onSubmit={submit} style={{ background: 'var(--ecps-shell)', padding: '32px 34px', display: 'flex', flexDirection: 'column', gap: 18 }}>
            <div>
              <div style={{ fontFamily: 'var(--ecps-font-display)', fontWeight: 500, fontSize: 18, color: 'var(--ecps-deep-tide)' }}>Request the pilot briefing</div>
              <div style={{ fontFamily: 'var(--ecps-font-display)', fontWeight: 400, fontSize: 14, lineHeight: 'var(--ecps-lh-body)', color: 'var(--ecps-text-on-light-muted)', marginTop: 4, marginBottom: 24 }}>Sign up below to receive the briefing.</div>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: narrow ? '1fr' : '1fr 1fr', gap: 18 }}>
              <Field label="Name" name="name" value={v.name} onChange={set('name')} onBlur={validate('name')} error={errors.name} />
              <Field label="Organization" name="org" value={v.org} onChange={set('org')} onBlur={validate('org')} error={errors.org} />
            </div>
            <Field label="Email" name="email" type="email" value={v.email} onChange={set('email')} onBlur={validate('email')} error={errors.email} placeholder="you@organization.org" />
            <Field label="Role" name="role" type="select" value={v.role} onChange={set('role')} options={['Destination authority', 'Conservation partner', 'Institutional investor', 'Government agency']} />
            <Field label="Site / region of interest" name="region" value={v.region} onChange={set('region')} onBlur={validate('region')} error={errors.region} placeholder="Which coastline, trail, or heritage site?" />
            <Field label="Message" name="message" type="textarea" rows={4} value={v.message} onChange={set('message')} />
            <div style={{ display: 'flex', gap: 14, alignItems: 'center' }}>
              <Button variant="primary" type="submit" disabled={status === 'submitting'}>{status === 'submitting' ? 'Sending…' : 'Request a briefing'}</Button>
              <span style={{ fontFamily: 'var(--ecps-font-display)', fontSize: 'var(--ecps-fs-small)', color: 'var(--ecps-text-on-light-muted)' }}>Your information is confidential and will not be shared.</span>
            </div>
            {status === 'error' && (
              <div role="alert" style={{ fontFamily: 'var(--ecps-font-display)', fontSize: 'var(--ecps-fs-small)', lineHeight: 'var(--ecps-lh-small)', color: 'var(--ecps-flag)' }}>Something went wrong. Please try again or email briefings@ecps.org directly.</div>
            )}
          </form>
        )}
      </div>
    </section>
  );
}
Object.assign(window, { Briefing });
