/* Register interest — structured intake for early-access enquiries.
 *
 * Captures qualifying fields (role, use case, data scope, budget band) so
 * leads can be triaged for whitelisting and pricing-tier validation.
 *
 * Posts to the existing /api/contact endpoint to reuse its rate-limit /
 * honeypot / Resend forwarding. Structured fields are serialised into the
 * `message` body so the server contract is unchanged.
 */
const RI_LIMITS = {
  name:    { min: 1,  max: 200 },
  email:   { min: 5,  max: 254 },
  company: { min: 0,  max: 200 },
  role:    { min: 0,  max: 100 },
  notes:   { min: 0,  max: 4000 },
};

const RI_ROLES = [
  'Consultant / advisor',
  'Investor / asset manager',
  'NGO / civil society',
  'Regulator / standard-setter',
  'Researcher / academic',
  'Industry (mining or downstream)',
  'Journalist',
  'Other',
];

const RI_USE_CASES = [
  'Screening sustainability claims',
  'Investment due diligence',
  'Academic research',
  'Regulatory or compliance work',
  'Advising a client engagement',
  'Internal benchmarking',
  'Reporting / journalism',
  'Other',
];

const RI_DATA_SCOPES = [
  { k: 'specific',   label: 'A specific company or two' },
  { k: 'whole',      label: 'The whole dataset' },
  { k: 'historic',   label: 'Historical / multi-year trends' },
  { k: 'current',    label: 'Most recent reporting year' },
  { k: 'region',     label: 'Region-specific cuts' },
  { k: 'themes',     label: 'Specific CSV pillars or themes' },
];

const EMAIL_RE_RI = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;

const RegisterInterest = ({ setRoute }) => {
  const [form, setForm] = React.useState({
    name: '', email: '', company: '', role: '',
    persona: RI_ROLES[0],
    useCase: RI_USE_CASES[0],
    scope: {},
    notes: '',
    website: '',
  });
  const [touched, setTouched] = React.useState({});
  const [status, setStatus] = React.useState('idle');
  const [errorMsg, setErrorMsg] = React.useState('');

  const set = (k) => (e) => setForm(f => ({ ...f, [k]: e.target.value }));
  const blur = (k) => () => setTouched(t => ({ ...t, [k]: true }));
  const toggleScope = (k) => () => setForm(f => ({ ...f, scope: { ...f.scope, [k]: !f.scope[k] } }));

  const errors = React.useMemo(() => {
    const e = {};
    const n = form.name.trim();
    if (n.length < RI_LIMITS.name.min) e.name = 'Name is required';
    else if (n.length > RI_LIMITS.name.max) e.name = 'Name is too long';

    const em = form.email.trim();
    if (em.length < RI_LIMITS.email.min) e.email = 'Email is required';
    else if (em.length > RI_LIMITS.email.max) e.email = 'Email is too long';
    else if (!EMAIL_RE_RI.test(em)) e.email = 'Enter a valid email';

    if (form.company.length > RI_LIMITS.company.max) e.company = 'Company is too long';
    if (form.role.length    > RI_LIMITS.role.max)    e.role    = 'Role is too long';
    if (form.notes.length   > RI_LIMITS.notes.max)   e.notes   = 'Notes are too long';

    const anyScope = Object.values(form.scope).some(Boolean);
    if (!anyScope) e.scope = 'Pick at least one';
    return e;
  }, [form]);

  const showErr = (k) => touched[k] && errors[k];
  const isInvalid = Object.keys(errors).length > 0;

  const submit = async (e) => {
    e.preventDefault();
    setTouched({ name:true, email:true, company:true, role:true, scope:true, notes:true });
    if (isInvalid) return;
    if (form.website) { setStatus('sent'); return; } // honeypot
    setStatus('sending');
    setErrorMsg('');

    // Compose the human-readable email body once, but also send the
    // structured fields as their own keys so the API can write them as
    // distinct columns in the RegisterInterest sheet tab. Persona is
    // no longer folded into the role string — it travels in its own field.
    const scopeText = RI_DATA_SCOPES
      .filter(s => form.scope[s.k]).map(s => s.label).join(', ');
    const message = [
      `Persona: ${form.persona}`,
      `Use case: ${form.useCase}`,
      `Data scope: ${scopeText || '—'}`,
      '',
      'Notes:',
      form.notes.trim() || '(none provided)',
    ].join('\n');

    try {
      const r = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name:       form.name.trim(),
          email:      form.email.trim(),
          company:    form.company.trim(),
          role:       form.role.trim(),
          subject:    'Register interest',
          message,
          persona:    form.persona,
          use_case:   form.useCase,
          data_scope: scopeText,
          notes:      form.notes.trim(),
          website:    form.website,
        }),
      });
      if (r.ok) {
        setStatus('sent');
      } else if (r.status === 429) {
        setStatus('error');
        setErrorMsg('Too many requests — please wait a moment and try again.');
      } else if (r.status === 400) {
        setStatus('error');
        setErrorMsg('We couldn\u2019t accept that submission. Please review the fields and try again.');
      } else {
        setStatus('error');
        setErrorMsg('Something went wrong on our end. Please try again shortly.');
      }
    } catch (_) {
      setStatus('error');
      setErrorMsg('Network error — check your connection and try again.');
    }
  };

  const reset = () => {
    setForm({
      name:'', email:'', company:'', role:'',
      persona: RI_ROLES[0], useCase: RI_USE_CASES[0],
      scope: {}, notes: '', website: '',
    });
    setTouched({});
    setStatus('idle');
    setErrorMsg('');
  };

  if (status === 'sent') {
    return (
      <section className="section first contact-section">
        <div className="site-wrap">
          <EyebrowRow label="Register interest"/>
          <Reveal>
            <h1 style={{fontSize:56,lineHeight:'62px',fontWeight:600,letterSpacing:'-0.025em',maxWidth:780}}>
              Thank you. <span className="serif-moment" style={{fontSize:56,lineHeight:'62px'}}>We&rsquo;ll be in touch.</span>
            </h1>
            <p className="lede" style={{marginTop:24,maxWidth:560}}>
              Early access is granted in waves. We&rsquo;ll write back within a few working days with what we can share now and how to get the rest.
            </p>
            <div style={{marginTop:40,display:'flex',gap:12,flexWrap:'wrap'}}>
              <button className="btn btn-primary btn-lg" onClick={()=>setRoute({page:'home'})}>
                Back to overview
              </button>
              <button className="btn btn-ghost btn-lg" onClick={reset}>
                Submit another
              </button>
            </div>
          </Reveal>
        </div>
      </section>
    );
  }

  return (
    <section className="section first contact-section">
      <div className="site-wrap">
        <EyebrowRow label="Register interest"/>
        <h1 style={{fontSize:56,lineHeight:'62px',fontWeight:600,letterSpacing:'-0.025em',maxWidth:820}}>
          Tell us how you&rsquo;d use Kestrel.<br/>
          <span className="serif-moment" style={{fontSize:56,lineHeight:'62px'}}>We&rsquo;ll match access to the brief.</span>
        </h1>
        <p className="lede" style={{marginTop:24,maxWidth:640}}>
          Verbatim passages, written justifications, and four-criteria grading are released selectively while we onboard early users.
        </p>
        <p style={{marginTop:12,maxWidth:580,fontSize:14,lineHeight:'22px',color:'var(--ink-2)'}}>
          A few details on who you are, what you&rsquo;re working on, and the slice of data you need helps us route enquiries quickly and keep the early cohort focused.
        </p>

        <Reveal delay={60}>
          <form className="contact-form" onSubmit={submit} noValidate style={{
            marginTop:48, display:'grid', gridTemplateColumns:'1fr 1fr', gap:20,
            maxWidth:820,
          }}>
            <RIField label="Name" required error={showErr('name') && errors.name}>
              <input type="text" value={form.name} onChange={set('name')} onBlur={blur('name')}
                maxLength={RI_LIMITS.name.max} autoComplete="name" required
                aria-invalid={!!showErr('name')} className="contact-input"/>
            </RIField>

            <RIField label="Email" required error={showErr('email') && errors.email}>
              <input type="email" value={form.email} onChange={set('email')} onBlur={blur('email')}
                maxLength={RI_LIMITS.email.max} autoComplete="email" inputMode="email" required
                aria-invalid={!!showErr('email')} className="contact-input"/>
            </RIField>

            <RIField label="Company / organisation" error={showErr('company') && errors.company}>
              <input type="text" value={form.company} onChange={set('company')} onBlur={blur('company')}
                maxLength={RI_LIMITS.company.max} autoComplete="organization" className="contact-input"/>
            </RIField>

            <RIField label="Job title" error={showErr('role') && errors.role}>
              <input type="text" value={form.role} onChange={set('role')} onBlur={blur('role')}
                maxLength={RI_LIMITS.role.max} autoComplete="organization-title" className="contact-input"/>
            </RIField>

            <RIField label="Which best describes you?" required>
              <select value={form.persona} onChange={set('persona')} className="contact-input">
                {RI_ROLES.map(r => <option key={r} value={r}>{r}</option>)}
              </select>
            </RIField>

            <RIField label="Primary use case" required>
              <select value={form.useCase} onChange={set('useCase')} className="contact-input">
                {RI_USE_CASES.map(u => <option key={u} value={u}>{u}</option>)}
              </select>
            </RIField>

            <RIField label="Data scope" required full
                     help="Pick all that apply"
                     error={showErr('scope') && errors.scope}>
              <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fit,minmax(240px,1fr))',gap:10,marginTop:4}}>
                {RI_DATA_SCOPES.map(s => {
                  const on = !!form.scope[s.k];
                  return (
                    <label key={s.k} onClick={blur('scope')}
                      style={{
                        display:'flex',alignItems:'center',gap:10,
                        padding:'12px 14px',
                        border:`1px solid ${on ? 'var(--moss)' : 'var(--line)'}`,
                        background: on ? 'var(--sage-tint, #EDF1E6)' : 'var(--canvas)',
                        borderRadius:10,cursor:'pointer',
                        transition:'border-color 160ms var(--ease-quiet), background 160ms var(--ease-quiet)',
                      }}>
                      <input type="checkbox" checked={on} onChange={toggleScope(s.k)}
                        style={{accentColor:'var(--moss-deep)',width:16,height:16,margin:0}}/>
                      <span style={{fontSize:13,color:on ? 'var(--moss-deep)' : 'var(--ink)',fontWeight: on ? 500 : 400}}>{s.label}</span>
                    </label>
                  );
                })}
              </div>
            </RIField>

            <RIField label="Anything else we should know?" full
                     help={`${form.notes.length} / ${RI_LIMITS.notes.max}`}
                     error={showErr('notes') && errors.notes}>
              <textarea value={form.notes} onChange={set('notes')} onBlur={blur('notes')}
                maxLength={RI_LIMITS.notes.max} rows={5}
                aria-invalid={!!showErr('notes')}
                className="contact-input contact-textarea"
                placeholder="What would you use Kestrel for?"/>
            </RIField>

            <div aria-hidden="true" className="contact-honeypot">
              <label>Website (leave blank)
                <input type="text" tabIndex={-1} autoComplete="off"
                  value={form.website} onChange={set('website')}/>
              </label>
            </div>

            <div className="contact-actions" style={{gridColumn:'1 / -1', display:'flex', flexDirection:'column', gap:14, marginTop:8}}>
              {status === 'error' && (
                <div role="alert" style={{
                  padding:'12px 16px', borderRadius:10,
                  border:'1px solid #C97070', background:'#FBEDED',
                  color:'#7A2E2E', fontSize:13, lineHeight:'20px',
                }}>
                  {errorMsg || 'Could not submit. Please try again.'}
                </div>
              )}
              <div style={{display:'flex', gap:14, alignItems:'center', flexWrap:'wrap'}}>
                <button type="submit" className="btn btn-primary btn-lg" disabled={status === 'sending'}>
                  {status === 'sending' ? 'Submitting…' : <>Register interest <Icon name="arrow-right" size={16} style={{marginLeft:4}} className="arrow"/></>}
                </button>
                <span style={{fontSize:12, color:'var(--ink-3)', maxWidth:420, lineHeight:'18px'}}>
                  We use these details only to route your enquiry. Never shared, never resold.
                </span>
              </div>
            </div>
          </form>
        </Reveal>
      </div>
    </section>
  );
};

const RIField = ({ label, required, full, help, error, children }) => (
  <div className={`contact-field ${full ? 'is-full' : ''}`} style={full ? {gridColumn:'1 / -1'} : undefined}>
    <div className="contact-field-head">
      <label className="contact-label">
        {label}{required && <span aria-hidden="true" style={{color:'var(--moss-deep)',marginLeft:4}}>*</span>}
      </label>
      {help && <span className="contact-help">{help}</span>}
    </div>
    {children}
    {error && <div className="contact-error" role="alert">{error}</div>}
  </div>
);

window.RegisterInterest = RegisterInterest;
