/* ============================================================
   Student — Registration form (digital)
   Mirrors the paper RPA registration form, auto-saves as you type.
   ============================================================ */

function StudentRegistration({ ctx, rec }) {
  const { setToast } = ctx;
  const p = rec.profile;
  const reg = rec.registration;

  const set = (path, v) => {
    window.Store.patchStudent(rec.id, (r) => {
      const segs = path.split('.');
      let o = r;
      for (let i = 0; i < segs.length - 1; i++) o = o[segs[i]];
      o[segs[segs.length - 1]] = v;
      return r;
    });
  };

  // Every student-fillable field is mandatory except `organisation`
  // and `passport`. `batch` and `rollNo` are set by the instructor
  // on the Enrolment card and don't appear in this form at all.
  // Profile fields validated on submit + counted in the chip:
  const requiredProfile = [
    'fullName', 'fathersName', 'dob', 'qualification',
    'email', 'phone', 'address', 'pincode',
    'aadhaar', 'govtId',
    'course', 'startDate',
    'height', 'weight', 'chest',
  ];
  const requiredRegistration = ['place', 'date'];
  const labels = {
    fullName:'Full name', fathersName:"Father's name", dob:'Date of birth',
    qualification:'Educational qualification',
    email:'Email', phone:'Phone', address:'Address', pincode:'Pincode',
    aadhaar:'Aadhaar number', govtId:'Other Govt. ID',
    course:'Course', startDate:'Start date',
    height:'Height', weight:'Weight', chest:'Chest',
    place:'Place', date:'Date',
  };

  const missing = [
    ...requiredProfile.filter(f => !String(p[f] || '').trim()),
    ...requiredRegistration.filter(f => !String(reg[f] || '').trim()),
  ];
  const filledCount = requiredProfile.length + requiredRegistration.length - missing.length;
  const totalCount  = requiredProfile.length + requiredRegistration.length;

  const submit = () => {
    if (missing.length) {
      return setToast(`Fill the ${missing.length} remaining field${missing.length===1?'':'s'} first (${labels[missing[0]] || missing[0]}…)`);
    }
    if (!reg.declarationAccepted) return setToast('Please tick the declaration first');
    if (!reg.signature) return setToast('Sign the form before submitting');
    window.Store.patchStudent(rec.id, (r) => {
      r.registration.submitted = true;
      r.registration.submittedAt = new Date().toISOString();
      return r;
    });
    window.Store.logAudit('Registration submitted', p.fullName || 'Student', '');
    setToast('Registration submitted — awaiting officer verification');
  };

  const durDays = window.courseDurationDays(p.course);

  return (
    <div className="module">
      <ModuleHeader
        crumbs={`MODULE 1 OF 8 · REGISTRATION`}
        title={tr("Registration form")}
        sub={tr("The digitised version of the IDA registration form. Saves automatically as you go.")}
        right={
          <div className="row" style={{gap:8}}>
            {reg.submitted ? <StatusPill status={reg.verifiedByOfficer ? 'verified' : 'submitted'}/> : <StatusPill status="draft"/>}
            <div className={cls('pill', missing.length ? 'pill-warn' : 'pill-good')}>
              <i className="dotty"/>{filledCount}/{totalCount} fields
            </div>
          </div>
        }
      />

      {reg.submitted && reg.verifiedByOfficer && (
        <div className="banner good">
          <div className="body"><b>Verified.</b> Submitted {UI.fmtDateTime(reg.submittedAt)} · verified by office. You can still update fields but they need re-verification.</div>
        </div>
      )}
      {reg.submitted && !reg.verifiedByOfficer && (
        <div className="banner warn">
          <div className="body"><b>Submitted.</b> Awaiting officer verification — usually within a working day.</div>
        </div>
      )}

      <div className="grid g-side">
        <div className="stack">
          {/* Section 1 — personal */}
          <FormSection title="1. Personal details" sub="As per government ID — make sure spellings match Aadhaar.">
            <FormRow>
              <Field upper label="Full name" req v={p.fullName} on={v=>set('profile.fullName', v)}/>
              <Field upper label="Father's name" req v={p.fathersName} on={v=>set('profile.fathersName', v)}/>
            </FormRow>
            <FormRow>
              <Field label="Date of birth" type="date" req v={p.dob} on={v=>set('profile.dob', v)}/>
              <Field upper label="Educational qualification" req v={p.qualification} on={v=>set('profile.qualification', v)}/>
            </FormRow>
            <FormRow>
              <Field upper label="Organisation (if any)" v={p.organisation} on={v=>set('profile.organisation', v)}/>
              <div className="field">
                <label>Batch</label>
                <input className="input" type="text" readOnly
                  value={p.batch || ''}
                  placeholder="Assigned by your instructor"/>
                <div className="input-help">Set by your instructor after enrolment.</div>
              </div>
            </FormRow>
          </FormSection>

          {/* Section 2 — contact */}
          <FormSection title="2. Contact">
            <FormRow>
              <Field label="Email" req type="email" v={p.email} on={v=>set('profile.email', v)}/>
              <Field label="Phone" req v={p.phone} on={v=>set('profile.phone', v)}/>
            </FormRow>
            <Field upper label="Address" req v={p.address} on={v=>set('profile.address', v)} as="textarea"/>
            <FormRow>
              <Field label="Pincode" req v={p.pincode} on={v=>set('profile.pincode', v)}/>
              <span style={{flex:1}}/>
            </FormRow>
          </FormSection>

          {/* Section 3 — IDs */}
          <FormSection title="3. Identification">
            <FormRow>
              <Field label="Aadhaar number" req v={p.aadhaar} on={v=>set('profile.aadhaar', v)} hint="12 digits, separated by spaces"/>
              <Field upper label="Passport (if any)" v={p.passport} on={v=>set('profile.passport', v)}/>
            </FormRow>
            <Field upper label="Other Govt. ID (DL / Voter / Ration)" req v={p.govtId} on={v=>set('profile.govtId', v)}/>
          </FormSection>

          {/* Section 4 — course. Roll / Student No. is assigned by
              the instructor on the Enrolment card, not here. */}
          <FormSection title="4. Course">
            <FormRow>
              <Field label="Course" req as="select" v={p.course} on={v=>set('profile.course', v)}
                opts={window.COURSES}/>
              <Field label="Start date" type="date" req v={p.startDate} on={v=>set('profile.startDate', v)}
                hint={durDays ? `${durDays}-day course` : 'Select a course to set duration'}/>
            </FormRow>
          </FormSection>

          {/* Section 5 — biometric */}
          <FormSection title="5. Biometric particulars" sub="As entered on the medical fitness certificate.">
            <FormRow>
              <Field label="Height" req v={p.height} on={v=>set('profile.height', v)} hint="e.g. 172 cm"/>
              <Field label="Weight" req v={p.weight} on={v=>set('profile.weight', v)} hint="e.g. 68 kg"/>
              <Field label="Chest"  req v={p.chest}  on={v=>set('profile.chest', v)}  hint="e.g. 92 cm"/>
            </FormRow>
          </FormSection>

          {/* Section 6 — declaration */}
          <FormSection title="6. Declaration & signature">
            <div className="paper" style={{marginBottom:14}}>
              <p style={{margin:0,fontSize:11.5,color:'var(--ink-2)'}}>
                I, <b>{p.fullName || '__________'}</b>, hereby declare that the information furnished above is true to the
                best of my knowledge. I shall abide by the rules and regulations of the Remote Pilot Training
                Organisation and the Directorate General of Civil Aviation (DGCA), India. I understand that any
                misrepresentation may lead to cancellation of my enrolment.
              </p>
            </div>
            <label className="checkbox">
              <input type="checkbox" checked={reg.declarationAccepted}
                     onChange={(e)=>set('registration.declarationAccepted', e.target.checked)}/>
              I accept the declaration above
            </label>
            <FormRow>
              <Field upper label="Place" req v={reg.place} on={v=>set('registration.place', v)}/>
              <Field label="Date" type="date" req v={reg.date} on={v=>set('registration.date', v)}/>
            </FormRow>
            <div style={{maxWidth:340}}>
              <SignaturePad label="Student signature" role={p.fullName || 'Student'}
                value={reg.signature} onChange={v=>set('registration.signature', v)}
                disabled={reg.verifiedByOfficer}/>
            </div>
            <div className="row" style={{marginTop:14, gap:10}}>
              <button className="btn btn-primary" onClick={submit}
                disabled={reg.submitted && reg.verifiedByOfficer}>
                {reg.submitted ? 'Re-submit for verification' : 'Submit registration'}
              </button>
              {reg.submitted && <span className="tiny muted">Last submitted {UI.fmtDateTime(reg.submittedAt)}</span>}
            </div>
          </FormSection>
        </div>

        {/* Side — verification status */}
        <div className="stack">
          <div className="card">
            <div className="card-hd"><h3>Verification status</h3></div>
            <div className="card-body">
              <ChecklistRow done={!!p.fullName && !!p.dob} text="Personal details filled"/>
              <ChecklistRow done={!!p.email && !!p.phone && !!p.address} text="Contact information"/>
              <ChecklistRow done={!!p.aadhaar} text="Aadhaar provided"/>
              <ChecklistRow done={!!p.course && !!p.startDate} text="Course & start date"/>
              <ChecklistRow done={reg.declarationAccepted && !!reg.signature} text="Declaration signed"/>
              <ChecklistRow done={reg.submitted} text="Submitted to office"/>
              <ChecklistRow done={reg.verifiedByOfficer} text="Officer verified"/>
            </div>
          </div>
          <div className="card">
            <div className="card-hd"><h3>Quick links</h3></div>
            <div className="card-body" style={{padding:'8px 0'}}>
              <button className="list-row" onClick={()=>ctx.setRoute('documents')}>
                <div className="ix">D</div>
                <div className="nm"><div className="ttl">Master document checklist</div><div className="desc">Upload remaining 12 documents</div></div>
              </button>
              <button className="list-row" onClick={()=>ctx.setRoute('medical')}>
                <div className="ix">M</div>
                <div className="nm"><div className="ttl">Medical fitness</div><div className="desc">Download · endorse · upload</div></div>
              </button>
            </div>
          </div>
          <div className="card">
            <div className="card-hd"><h3>Need the paper form?</h3></div>
            <div className="card-body">
              <p className="small muted" style={{margin:'0 0 10px'}}>You can also download the printable version of this registration form for offline use.</p>
              <a className="btn btn-sm" href="assets/Registration-Form.docx" download>
                {window.NavIcons.download} Download .docx
              </a>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ---------- form helpers ---------- */
/* Registration is student-only, so FormSection / Field translate their
   own labels via tr() — saves wrapping every call site. */
function FormSection({ title, sub, children }) {
  return (
    <div className="card">
      <div className="card-hd">
        <div>
          <h3>{tr(title)}</h3>
          {sub && <div className="sub">{tr(sub)}</div>}
        </div>
      </div>
      <div className="card-body stack-sm" style={{gap:12}}>{children}</div>
    </div>
  );
}
function FormRow({ children }) {
  // row-wrap so two-up fields collapse to single column on phones
  // instead of squeezing each `<Field>` into < 160px.
  return <div className="row-wrap" style={{gap:12, alignItems:'flex-start'}}>{
    React.Children.map(children, (c,i) => (
      <div key={i} style={{flex:'1 1 200px', minWidth:0}}>{c}</div>
    ))
  }</div>;
}
function Field({ label, v, on, type='text', req, hint, as, opts, upper }) {
  // Per IDA / DGCA forms most candidate text is filled IN BLOCK LETTERS;
  // setting upper=true uppercases the value as the student types and
  // styles the visible input in caps. Email/phone/numeric stay as-is.
  const handle = (val) => on(upper ? String(val || '').toUpperCase() : val);
  const upStyle = upper ? { textTransform: 'uppercase' } : undefined;
  return (
    <div className="field">
      <label>{tr(label)}{req && <span className="req">*</span>}</label>
      {as === 'textarea' ?
        <textarea className="textarea" style={upStyle} value={v||''} onChange={e=>handle(e.target.value)}/> :
       as === 'select' ?
        <select className="select" value={v||''} onChange={e=>on(e.target.value)}>
          <option value="">— {tr('select')} —</option>
          {opts.map(o => <option key={o} value={o}>{o}</option>)}
        </select> :
        <input className="input" style={upStyle} type={type} value={v||''} onChange={e=>handle(e.target.value)}/>
      }
      {hint && <div className="input-help">{tr(hint)}</div>}
    </div>
  );
}
function ChecklistRow({ done, text }) {
  return (
    <div className="row" style={{gap:10, padding:'6px 0'}}>
      <span style={{
        width:16,height:16,borderRadius:50,
        background: done ? 'var(--good)' : 'transparent',
        border: done ? 'none' : '1.5px solid var(--line-strong)',
        display:'grid',placeItems:'center', flexShrink:0,
      }}>
        {done && <svg width="9" height="9" viewBox="0 0 12 12" fill="none"><path d="M2.5 6L5 8.5 9.5 3.5" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>}
      </span>
      <span className="small" style={{color: done ? 'var(--ink-2)' : 'var(--muted)'}}>{text}</span>
    </div>
  );
}
window.ChecklistRow = ChecklistRow;
window.FormSection = FormSection;
window.FormRow = FormRow;
window.Field = Field;
window.StudentRegistration = StudentRegistration;
