// ContactView — contact details + a PhD / Postdoc application form for WiNTEL.
// No backend: submitting composes a pre-filled email to the PI and shows a
// confirmation, so the form works as a standalone artifact.
const CV = window.WINTELAcademicDesignSystem_045d4f;
const CONTACT_EMAIL = 'a.celik@soton.ac.uk';

const inputBase = {
  width: '100%', boxSizing: 'border-box', padding: '0.6rem 0.75rem',
  fontFamily: 'var(--font-sans)', fontSize: 'var(--text-base)', color: 'var(--text-primary)',
  background: 'var(--surface-card)', border: '1px solid var(--border-default)',
  borderRadius: 'var(--radius-md)', outline: 'none',
};

function Field({ label, required, children, hint }) {
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: '0.35rem' }}>
      <span style={{ fontSize: 'var(--text-sm)', fontWeight: 'var(--weight-medium)', color: 'var(--text-primary)' }}>
        {label}{required ? <span style={{ color: 'var(--accent)' }}> *</span> : null}
      </span>
      {children}
      {hint ? <span style={{ fontSize: 'var(--text-xs)', color: 'var(--text-muted)' }}>{hint}</span> : null}
    </label>
  );
}

function ContactView({ data }) {
  const p = data.person;
  const POSITIONS = ['PhD Student', 'Postdoctoral Fellow', 'Visiting Researcher'];
  const AREAS = data.research || [];
  const [f, setF] = React.useState({
    position: 'PhD Student', name: '', email: '', institution: '', country: '',
    degree: '', start: '', links: '', message: '', areas: [],
  });
  const [submitted, setSubmitted] = React.useState(false);
  const [error, setError] = React.useState('');
  const set = (k, v) => setF((s) => ({ ...s, [k]: v }));
  const toggleArea = (a) => setF((s) => ({ ...s, areas: s.areas.includes(a) ? s.areas.filter((x) => x !== a) : [...s.areas, a] }));

  const submit = (e) => {
    e.preventDefault();
    if (!f.name.trim() || !f.email.trim() || !f.message.trim()) {
      setError('Please complete the required fields (name, email, and message).');
      return;
    }
    setError('');
    const body = [
      'WiNTEL Application',
      '',
      'Position: ' + f.position,
      'Name: ' + f.name,
      'Email: ' + f.email,
      'Current institution: ' + f.institution,
      'Country: ' + f.country,
      'Highest qualification: ' + f.degree,
      'Earliest availability: ' + f.start,
      'Research areas of interest: ' + (f.areas.length ? f.areas.join(', ') : '—'),
      'Links (Scholar / CV / site): ' + f.links,
      '',
      'Message:',
      f.message,
    ].join('\n');
    const subject = 'WiNTEL Application — ' + f.position + ' — ' + f.name;
    window.location.href = 'mailto:' + CONTACT_EMAIL + '?subject=' + encodeURIComponent(subject) + '&body=' + encodeURIComponent(body);
    setSubmitted(true);
  };

  return (
    <main style={{ display: 'flex', flexDirection: 'column', gap: '2.5rem' }}>
      <CV.SectionHeading title="Apply" />

      {/* ---- Application form ---- */}
      <section style={{ display: 'flex', flexDirection: 'column', gap: '1.25rem' }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: '0.4rem', borderBottom: '1px solid var(--border-default)', paddingBottom: '0.6rem' }}>
          <h2 style={{ margin: 0, fontSize: 'var(--text-xl)', fontWeight: 'var(--weight-semibold)', letterSpacing: 'var(--tracking-tight)', color: 'var(--text-primary)' }}>Join WiNTEL</h2>
          <p style={{ margin: 0, fontSize: 'var(--text-base)', color: 'var(--text-body)', fontWeight: 'var(--weight-light)', textWrap: 'pretty' }}>
            We welcome motivated PhD students, postdoctoral fellows, and visiting researchers working on AI-native networks, ISAC, RIS, non-terrestrial networks, and the Internet of Bodies. Tell us about yourself below.
          </p>
        </div>

        {submitted ? (
          <div style={{ display: 'flex', flexDirection: 'column', gap: '0.6rem', alignItems: 'flex-start', padding: '1.5rem', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-xl)', background: 'var(--surface-muted)' }}>
            <i className="ri-checkbox-circle-line" style={{ fontSize: 28, color: 'var(--accent)' }} />
            <h3 style={{ margin: 0, fontSize: 'var(--text-lg)', fontWeight: 'var(--weight-semibold)', color: 'var(--text-primary)' }}>Your email is ready to send</h3>
            <p style={{ margin: 0, fontSize: 'var(--text-base)', color: 'var(--text-body)', fontWeight: 'var(--weight-light)' }}>
              A pre-filled message should have opened in your mail app. If it didn’t, email <a href={'mailto:' + CONTACT_EMAIL} style={{ color: 'var(--accent)' }}>{CONTACT_EMAIL}</a> directly with your CV attached.
            </p>
            <CV.Button variant="outline" size="sm" onClick={() => setSubmitted(false)}>Edit the form</CV.Button>
          </div>
        ) : (
          <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: '1.1rem' }}>
            <Field label="Position" required>
              <div style={{ display: 'flex', gap: '0.5rem', flexWrap: 'wrap' }}>
                {POSITIONS.map((pos) => (
                  <CV.Button key={pos} type="button" size="sm" variant={f.position === pos ? 'default' : 'outline'} onClick={() => set('position', pos)}>{pos}</CV.Button>
                ))}
              </div>
            </Field>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: '1.1rem' }}>
              <Field label="Full name" required>
                <input style={inputBase} value={f.name} onChange={(e) => set('name', e.target.value)} placeholder="Jane Doe" />
              </Field>
              <Field label="Email" required>
                <input style={inputBase} type="email" value={f.email} onChange={(e) => set('email', e.target.value)} placeholder="jane@university.edu" />
              </Field>
              <Field label="Current institution">
                <input style={inputBase} value={f.institution} onChange={(e) => set('institution', e.target.value)} placeholder="University / company" />
              </Field>
              <Field label="Country">
                <input style={inputBase} value={f.country} onChange={(e) => set('country', e.target.value)} placeholder="Country of residence" />
              </Field>
              <Field label="Highest qualification">
                <input style={inputBase} value={f.degree} onChange={(e) => set('degree', e.target.value)} placeholder="e.g. MSc in Electrical Engineering" />
              </Field>
              <Field label="Earliest availability">
                <input style={inputBase} value={f.start} onChange={(e) => set('start', e.target.value)} placeholder="e.g. Sept 2026" />
              </Field>
            </div>
            <Field label="Research areas of interest" hint="Select all that apply.">
              <div style={{ display: 'flex', gap: '0.5rem', flexWrap: 'wrap' }}>
                {AREAS.map((a) => {
                  const on = f.areas.includes(a);
                  return (
                    <button key={a} type="button" onClick={() => toggleArea(a)} style={{
                      cursor: 'pointer', padding: '0.4rem 0.7rem', fontSize: 'var(--text-sm)', fontFamily: 'var(--font-sans)',
                      borderRadius: 'var(--radius-full)', border: '1px solid ' + (on ? 'var(--accent)' : 'var(--border-default)'),
                      background: on ? 'var(--accent)' : 'var(--surface-card)', color: on ? 'var(--text-inverse, #fff)' : 'var(--text-body)',
                      transition: 'all var(--duration-fast) var(--ease-standard)',
                    }}>{a}</button>
                  );
                })}
              </div>
            </Field>
            <Field label="Links" hint="Google Scholar, personal site, or a link to your CV.">
              <input style={inputBase} value={f.links} onChange={(e) => set('links', e.target.value)} placeholder="https://scholar.google.com/… , https://… (CV)" />
            </Field>
            <Field label="Message / research statement" required>
              <textarea style={{ ...inputBase, minHeight: '7rem', resize: 'vertical', lineHeight: 'var(--leading-normal)' }}
                value={f.message} onChange={(e) => set('message', e.target.value)}
                placeholder="Briefly describe your background, research interests, and why you'd like to join WiNTEL." />
            </Field>
            {error ? <p style={{ margin: 0, color: '#dc2626', fontSize: 'var(--text-sm)' }}>{error}</p> : null}
            <div style={{ display: 'flex', alignItems: 'center', gap: '1rem', flexWrap: 'wrap' }}>
              <CV.Button type="submit" variant="default" size="default">
                <i className="ri-send-plane-line" style={{ fontSize: 16 }} /> Send application
              </CV.Button>
              <span style={{ fontSize: 'var(--text-xs)', color: 'var(--text-muted)' }}>Opens a pre-filled email — attach your CV before sending.</span>
            </div>
          </form>
        )}
      </section>
    </main>
  );
}

Object.assign(window, { ContactView });
