// WeWire applicant — Application form (stepped).

function Field({ label, children, hint }) {
  return (
    <label style={{ display: 'block', marginBottom: 16 }}>
      <div style={{ fontSize: 13, fontWeight: 600, color: WW.muted, marginBottom: 7 }}>{label}</div>
      {children}
      {hint && <div style={{ fontSize: 12, color: WW.subtle, marginTop: 6 }}>{hint}</div>}
    </label>
  );
}
const inputStyle = {
  width: '100%', height: 50, borderRadius: 13, border: `1px solid ${WW.line}`, background: WW.white,
  padding: '0 16px', fontFamily: FONT, fontSize: 15, color: WW.ink, outline: 'none', boxSizing: 'border-box',
};
function TextInput(props) {
  return <input {...props} style={{ ...inputStyle, ...(props.style || {}) }}
    onFocus={(e) => e.target.style.borderColor = WW.orange}
    onBlur={(e) => e.target.style.borderColor = WW.line} />;
}
function Select({ value, onChange, options, placeholder }) {
  return (
    <select value={value} onChange={onChange} style={{ ...inputStyle, appearance: 'none',
      backgroundImage: 'url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\' width=\'20\' height=\'20\' viewBox=\'0 0 24 24\' fill=\'none\' stroke=\'%236A645B\' stroke-width=\'2\' stroke-linecap=\'round\'><path d=\'M6 9l6 6 6-6\'/></svg>")',
      backgroundRepeat: 'no-repeat', backgroundPosition: 'right 14px center' }}>
      {placeholder && <option value="" disabled>{placeholder}</option>}
      {options.map(o => <option key={o} value={o}>{o}</option>)}
    </select>
  );
}

function ApplicationForm({ onComplete, onName, onBack, initialForm, initialStep, authEmail, onFormChange, onFormStepChange, applicationsOpen }) {
  const { TRACKS, CITIES, UNIVERSITIES } = window.WWData;

  const normalizeUni = (uni) => {
    const aliases = {
      KNUST: 'Kwame Nkrumah University of Science and Technology (KNUST)',
      UCC: 'University of Cape Coast (UCC)',
      GIMPA: 'Ghana Institute of Management and Public Administration (GIMPA)',
    };
    return aliases[uni] || uni;
  };

  const defaultForm = {
    name: '', email: authEmail || '', phone: '', city: 'Accra',
    uni: '', degree: '', gradYear: '2026', classOf: 'Pending',
    track: 'Engineering & Product', cv: '', motive: '',
  };
  const [step, setStep] = React.useState(initialStep || 0);
  const [f, setF] = React.useState(() => {
    const merged = {
      ...defaultForm,
      ...(initialForm || {}),
      email: authEmail || initialForm?.email || '',
    };
    if (merged.uni) merged.uni = normalizeUni(merged.uni);
    return merged;
  });

  const cityOptions = React.useMemo(() => (
    f.city && !CITIES.includes(f.city) ? [f.city, ...CITIES] : CITIES
  ), [f.city, CITIES]);

  const uniOptions = React.useMemo(() => (
    f.uni && !UNIVERSITIES.includes(f.uni) ? [f.uni, ...UNIVERSITIES] : UNIVERSITIES
  ), [f.uni, UNIVERSITIES]);
  const [cvFile, setCvFile] = React.useState(null);
  const [consent, setConsent] = React.useState(!!initialForm?.consent);
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState('');

  React.useEffect(() => {
    if (authEmail) setF((prev) => ({ ...prev, email: authEmail }));
  }, [authEmail]);

  const updateForm = (next) => {
    setF(next);
    onFormChange && onFormChange(next);
  };

  const setStepAndSave = (s) => {
    setStep(s);
    onFormStepChange && onFormStepChange(s);
  };

  const set = (k) => (e) => updateForm({ ...f, [k]: e.target.value });
  const steps = ['About you', 'Education', 'Your track', 'Materials', 'Review'];

  const submitApplication = async () => {
    if (!applicationsOpen) {
      setError('Applications are closed.');
      return;
    }
    if (!consent) {
      setError('Please accept the privacy notice to continue.');
      return;
    }
    setError('');
    setSubmitting(true);
    try {
      if (WWAuth.useSupabase && WWAuth.useSupabase()) {
        if (cvFile) await window.WWApplicant.uploadCv(cvFile);
        await window.WWApplicant.submitApplication({ ...f, consent: true }, true);
        await WWAuth.flushSession();
      } else {
        await WWAuth.saveSession({ form: { ...f, consent: true } });
        await WWAuth.flushSession();
      }
      onName && onName(f.name.split(' ')[0]);
      onComplete();
    } catch (err) {
      setError(err.message || 'Could not submit. Try again.');
    } finally {
      setSubmitting(false);
    }
  };

  const next = () => {
    if (step === 0) onName && onName(f.name.split(' ')[0]);
    if (step < steps.length - 1) setStepAndSave(step + 1);
    else submitApplication();
  };
  const back = () => (step === 0 ? onBack() : setStepAndSave(step - 1));

  const fileRef = React.useRef();

  const motiveCharCount = f.motive.length;
  const motiveOverLimit = motiveCharCount > 120;
  const canContinue = step === 3 ? (f.cv && consent && f.motive.trim() && !motiveOverLimit) : step === 4 ? consent : true;

  return (
    <Screen footer={
      <Btn variant="primary" full onClick={next} disabled={!canContinue || submitting}
        icon={step === steps.length - 1 ? 'check' : 'arrow'}>
        {submitting ? 'Submitting…' : step === steps.length - 1 ? 'Submit application' : 'Continue'}
      </Btn>
    }>
      <TopBar title="Application" onBack={back} right={<span style={{ fontSize: 13, color: WW.subtle, fontWeight: 600 }}>{step + 1}/5</span>} />

      <div style={{ display: 'flex', gap: 6, margin: '6px 0 22px' }}>
        {steps.map((s, i) => (
          <div key={s} style={{ flex: 1, height: 4, borderRadius: 999, background: i <= step ? WW.orange : WW.sand,
            transition: 'background 300ms' }} />
        ))}
      </div>

      <h1 style={{ fontFamily: DISP, fontWeight: 600, fontSize: 26, letterSpacing: '-0.02em', marginBottom: 6 }}>{steps[step]}</h1>
      <p style={{ fontSize: 14, color: WW.muted, marginBottom: 22, lineHeight: 1.5 }}>
        {['Let\'s start with the basics.', 'Tell us where you studied.', 'Where are you drawn? You can change this later.',
          'Add your CV — and one line on why WeWire.', 'Check everything looks right, then submit.'][step]}
      </p>

      {error && (
        <Card pad={14} style={{ background: WW.redSoft, border: 'none', marginBottom: 14 }}>
          <div style={{ fontSize: 13, color: WW.red, lineHeight: 1.45 }}>{error}</div>
        </Card>
      )}

      {step === 0 && <div>
        <Field label="Full name"><TextInput value={f.name} onChange={set('name')} /></Field>
        <Field label="Email" hint="This is the email you signed in with — progress is saved here.">
          <TextInput value={f.email} readOnly style={{ background: WW.sand, color: WW.muted, cursor: 'default' }} />
        </Field>
        <Field label="Phone"><TextInput value={f.phone} onChange={set('phone')} /></Field>
        <Field label="City"><Select value={f.city} onChange={set('city')} options={cityOptions} /></Field>
      </div>}

      {step === 1 && <div>
        <Field label="University"><Select value={f.uni} onChange={set('uni')} options={uniOptions} placeholder="Choose university" /></Field>
        <Field label="Degree / programme"><TextInput value={f.degree} onChange={set('degree')} /></Field>
        <Field label="Graduation year"><Select value={f.gradYear} onChange={set('gradYear')} options={['2026']} /></Field>
        <Field label="Class of degree"><Select value={f.classOf} onChange={set('classOf')} options={['First Class','Second Class Upper','Second Class Lower','Pending']} /></Field>
      </div>}

      {step === 2 && <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {TRACKS.map(t => {
          const sel = f.track === t;
          return (
            <div key={t} onClick={() => updateForm({ ...f, track: t })} style={{
              display: 'flex', alignItems: 'center', gap: 12, padding: '16px', borderRadius: 16, cursor: 'pointer',
              background: sel ? WW.orangeSoft : WW.white, border: `1px solid ${sel ? 'transparent' : WW.line}`,
              boxShadow: sel ? `inset 0 0 0 1.5px ${WW.orange}` : 'none' }}>
              <div style={{ width: 22, height: 22, borderRadius: '50%', border: `2px solid ${sel ? WW.orange : WW.lineStrong}`,
                display: 'grid', placeItems: 'center', flex: 'none' }}>
                {sel && <div style={{ width: 11, height: 11, borderRadius: '50%', background: WW.orange }} />}
              </div>
              <span style={{ fontWeight: 600, fontSize: 15, color: sel ? WW.orangeDeep : WW.ink }}>{t}</span>
            </div>
          );
        })}
      </div>}

      {step === 3 && <div>
        <input ref={fileRef} type="file" accept=".pdf,.doc,.docx" style={{ display: 'none' }}
          onChange={(e) => {
            const file = e.target.files[0];
            if (file) {
              setCvFile(file);
              updateForm({ ...f, cv: file.name });
            }
          }} />
        <Field label="Your CV">
          <div onClick={() => fileRef.current?.click()} style={{
            border: `1.5px dashed ${f.cv ? WW.green : WW.lineStrong}`, borderRadius: 16, padding: '22px 18px',
            display: 'flex', alignItems: 'center', gap: 14, cursor: 'pointer', background: f.cv ? WW.greenSoft : WW.white }}>
            <div style={{ width: 44, height: 44, borderRadius: 12, background: f.cv ? WW.green : WW.sand,
              color: f.cv ? '#fff' : WW.muted, display: 'grid', placeItems: 'center', flex: 'none' }}>
              <Icon name={f.cv ? 'check' : 'upload'} size={20} />
            </div>
            <div style={{ minWidth: 0 }}>
              <div style={{ fontWeight: 600, fontSize: 15, color: WW.ink, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                {f.cv || 'Upload your CV'}</div>
              <div style={{ fontSize: 12, color: WW.muted }}>{f.cv ? 'Tap to replace' : 'PDF or Word · up to 5 MB'}</div>
            </div>
          </div>
        </Field>
        <Field label="What draws you to WeWire?" hint="Required.">
          <textarea value={f.motive} onChange={set('motive')} placeholder="I want to build the rails that move money across Africa…"
            rows={3} maxLength={120} style={{ ...inputStyle, height: 'auto', padding: 14, resize: 'none', lineHeight: 1.5, overflowWrap: 'break-word', overflowX: 'hidden' }} />
          <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 6 }}>
            <span style={{ fontSize: 12, fontWeight: 600, color: motiveOverLimit ? WW.red : WW.orange }}>
              {motiveCharCount} / 120
            </span>
          </div>
        </Field>
        <label style={{ display: 'flex', gap: 12, alignItems: 'flex-start', marginTop: 8, cursor: 'pointer' }}>
          <input type="checkbox" checked={consent} onChange={(e) => setConsent(e.target.checked)}
            style={{ width: 18, height: 18, marginTop: 2, accentColor: WW.orange }} />
          <span style={{ fontSize: 13, color: WW.muted, lineHeight: 1.5 }}>
            I agree to WeWire processing my personal data and assessment responses for recruitment purposes, as described in our{' '}
            <a href={WWPaths.privacy()} target="_blank" rel="noopener noreferrer" style={{ color: WW.orange, fontWeight: 600 }}>Privacy Notice</a>.
          </span>
        </label>
      </div>}

      {step === 4 && <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {[['Name', f.name], ['Email', f.email], ['City', f.city], ['University', f.uni],
          ['Degree', f.degree], ['Graduation', f.gradYear + ' · ' + f.classOf], ['Track', f.track],
          ['CV', f.cv || '—']].map(([k, v]) => (
          <div key={k} style={{ display: 'flex', justifyContent: 'space-between', gap: 16, padding: '12px 4px',
            borderBottom: `1px solid ${WW.line}` }}>
            <span style={{ fontSize: 13, color: WW.muted, fontWeight: 600 }}>{k}</span>
            <span style={{ fontSize: 14, fontWeight: 600, textAlign: 'right' }}>{v}</span>
          </div>
        ))}
        <Card pad={16} style={{ background: WW.orangeSoft, border: 'none', marginTop: 8 }}>
          <div style={{ fontSize: 13, color: WW.orangeDeep, lineHeight: 1.5 }}>
            Submitting unlocks your assessments. You can take them whenever you're ready — your place is always saved.
          </div>
        </Card>
      </div>}
    </Screen>
  );
}

Object.assign(window, { ApplicationForm, Field, TextInput, Select, inputStyle });
