// ─────────────────────────────────────────────────────────────
// screens-leave.jsx — leave / pickup / attendance dispute / homework submit
// All four are P0 flows previously stubbed as buttons.
// ─────────────────────────────────────────────────────────────
const { useState: useStateL, useEffect: useEffectL, useMemo: useMemoL, useRef: useRefL } = React;

const inrL = (n) => '₹' + Number(n).toLocaleString('en-IN');
const ymd = (d) => d.toISOString().slice(0, 10);
const today = () => ymd(new Date());

// ─────────────────────────────────────────────────────────────
// ApplyLeaveScreen — parent submits leave for a child
// ─────────────────────────────────────────────────────────────
function ApplyLeaveScreen({ nav, params }) {
  const childName = params?.child || 'Aarav Mehra';
  const childCls = params?.cls || '8-B';

  const [draft, setDraft, hyd] = useDraft('leave-draft', {
    type: 'sick',
    from: today(),
    to: today(),
    reason: '',
    notifyTeachers: true,
    requestMakeup: true,
    attachment: null
  });
  const [submitted, setSubmitted] = useStateL(false);
  const fileRef = useRefL();

  const days = useMemoL(() => {
    const a = new Date(draft.from), b = new Date(draft.to);
    if (isNaN(a) || isNaN(b)) return 0;
    return Math.max(1, Math.round((b - a) / 86400000) + 1);
  }, [draft.from, draft.to]);

  if (!hyd) return <div className="screen-bg" style={{ padding: 20 }}><SkeletonList n={3}/></div>;

  if (submitted) {
    return (
      <div className="screen-bg" style={{ minHeight: '100%' }} data-screen-label="LeaveSubmitted">
        <PageHeader title="Leave applied" onBack={() => nav.replace('home')}/>
        <div style={{ padding: '40px 24px', textAlign: 'center', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 14 }}>
          <div style={{ width: 84, height: 84, borderRadius: '50%', background: 'var(--success-50)', color: '#065F46', display: 'grid', placeItems: 'center', boxShadow: '0 0 0 12px rgba(16,185,129,.06)' }}><Icon name="check" size={38}/></div>
          <div>
            <div style={{ fontSize: 22, fontWeight: 800, color: 'var(--n900)' }}>Leave request sent</div>
            <div style={{ fontSize: 13, color: 'var(--n500)', marginTop: 6, maxWidth: 280 }}>Class teacher will review and approve · usually within 2 hours</div>
          </div>
          <div className="card" style={{ padding: 14, width: '100%', textAlign: 'left', display: 'flex', flexDirection: 'column', gap: 8 }}>
            <div style={{ fontSize: 11, color: 'var(--n400)', textTransform: 'uppercase', letterSpacing: '.08em' }}>Submitted</div>
            <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--n900)' }}>{childName} · {childCls}</div>
            <div style={{ fontSize: 12, color: 'var(--n600)' }}>{LEAVE_TYPES[draft.type].label} · {days} day{days !== 1 ? 's' : ''}</div>
            <div style={{ fontSize: 11, color: 'var(--n500)' }}>{draft.from} → {draft.to}</div>
          </div>
          <div className="card" style={{ padding: 12, background: 'var(--p50)', borderColor: 'var(--p100)', textAlign: 'left', display: 'flex', alignItems: 'center', gap: 10, width: '100%' }}>
            <Icon name="info" size={14} color="var(--p600)"/>
            <div style={{ fontSize: 11, color: 'var(--p700)' }}>You'll get a push when {childName.split(' ')[0]}'s teacher approves.</div>
          </div>
          <div style={{ display: 'flex', gap: 8, width: '100%', marginTop: 4 }}>
            <button onClick={() => { setDraft({ type: 'sick', from: today(), to: today(), reason: '', notifyTeachers: true, requestMakeup: true, attachment: null }); setSubmitted(false); }} className="btn btn-outline" style={{ flex: 1 }}>Apply another</button>
            <button onClick={() => nav.replace('home')} className="btn" style={{ flex: 1.4 }}>Done</button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="screen-bg" style={{ minHeight: '100%' }} data-screen-label="ApplyLeave">
      <PageHeader title="Apply for leave" subtitle={`${childName} · ${childCls}`} onBack={() => nav.pop()}/>
      <OfflineBanner message="You're offline — request will queue and submit when you reconnect"/>

      <div style={{ padding: '14px 16px 100px', display: 'flex', flexDirection: 'column', gap: 14 }}>
        <FormField label="Type of leave" required>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
            {Object.entries(LEAVE_TYPES).map(([k, v]) => {
              const active = draft.type === k;
              return (
                <button key={k} onClick={() => setDraft((d) => ({ ...d, type: k }))} className="card" style={{ padding: 12, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6, textAlign: 'center', borderColor: active ? 'var(--p400)' : 'var(--n100)', background: active ? 'var(--p50)' : '#fff' }}>
                  <div style={{ width: 32, height: 32, borderRadius: 10, background: active ? 'var(--p500)' : 'var(--n50)', color: active ? '#fff' : 'var(--n500)', display: 'grid', placeItems: 'center' }}><Icon name={v.ic} size={15}/></div>
                  <div style={{ fontSize: 11.5, fontWeight: 700, color: 'var(--n900)' }}>{v.label}</div>
                </button>
              );
            })}
          </div>
        </FormField>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          <FormField label="From" required>
            <input type="date" value={draft.from} onChange={(e) => setDraft((d) => ({ ...d, from: e.target.value, to: e.target.value > d.to ? e.target.value : d.to }))} style={fldS}/>
          </FormField>
          <FormField label="To" required>
            <input type="date" min={draft.from} value={draft.to} onChange={(e) => setDraft((d) => ({ ...d, to: e.target.value }))} style={fldS}/>
          </FormField>
        </div>
        {days > 0 && (
          <div className="card" style={{ padding: 12, display: 'flex', alignItems: 'center', gap: 10, background: 'var(--n50)', borderColor: 'var(--n100)' }}>
            <Icon name="calendar" size={16} color="var(--n500)"/>
            <div style={{ flex: 1, fontSize: 12, color: 'var(--n700)' }}>
              <strong>{days} school day{days !== 1 ? 's' : ''}</strong> · {childName.split(' ')[0]} will miss <strong>{days * 7}</strong> periods
            </div>
          </div>
        )}

        <FormField label="Reason" required hint={`${draft.reason.length}/300`}>
          <textarea
            value={draft.reason}
            onChange={(e) => setDraft((d) => ({ ...d, reason: e.target.value.slice(0, 300) }))}
            rows={3}
            placeholder={LEAVE_TYPES[draft.type].placeholder}
            style={{ ...fldS, padding: 12, resize: 'vertical', minHeight: 84 }}/>
        </FormField>

        {/* Attachment — medical certificate, etc */}
        <FormField label={draft.type === 'sick' ? 'Doctor\'s note (recommended for >2 days)' : 'Attachment (optional)'} hint="JPG, PNG, PDF · max 8 MB">
          {draft.attachment ? (
            <div className="card" style={{ padding: 10, display: 'flex', alignItems: 'center', gap: 10, background: 'var(--success-50)', borderColor: 'var(--success-200)' }}>
              <div style={{ width: 36, height: 36, borderRadius: 10, background: '#fff', color: '#065F46', display: 'grid', placeItems: 'center' }}><Icon name="document" size={16}/></div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--n900)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{draft.attachment.name}</div>
                <div style={{ fontSize: 10.5, color: 'var(--n500)' }}>{(draft.attachment.size / 1024).toFixed(0)} KB</div>
              </div>
              <button onClick={() => setDraft((d) => ({ ...d, attachment: null }))} aria-label="Remove" style={{ width: 28, height: 28, borderRadius: 8, background: 'rgba(255,255,255,.6)', display: 'grid', placeItems: 'center' }}><Icon name="x" size={14}/></button>
            </div>
          ) : (
            <button onClick={() => fileRef.current?.click()} className="card" style={{ padding: 16, display: 'flex', alignItems: 'center', gap: 12, textAlign: 'left', borderStyle: 'dashed', borderColor: 'var(--n200)' }}>
              <div style={{ width: 36, height: 36, borderRadius: 11, background: 'var(--n50)', color: 'var(--n500)', display: 'grid', placeItems: 'center' }}><Icon name="paperclip" size={16}/></div>
              <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--n600)' }}>Attach document or photo</div>
            </button>
          )}
          <input ref={fileRef} type="file" accept="image/*,application/pdf" hidden
            onChange={(e) => { const f = e.target.files?.[0]; if (f) setDraft((d) => ({ ...d, attachment: { name: f.name, size: f.size, type: f.type } })); }}/>
        </FormField>

        <SectionLabelL label="Options"/>
        <ToggleRow ic="bell" t="Notify subject teachers" s="They'll see absence in roll-call" on={draft.notifyTeachers} onChange={(v) => setDraft((d) => ({ ...d, notifyTeachers: v }))}/>
        <ToggleRow ic="book-open" t="Request makeup material" s="Class notes & homework auto-shared" on={draft.requestMakeup} onChange={(v) => setDraft((d) => ({ ...d, requestMakeup: v }))} last/>

        <div style={{ fontSize: 10.5, color: 'var(--n400)', display: 'flex', gap: 6, padding: '8px 4px' }}>
          <Icon name="info" size={11}/>
          <span>School policy: leaves &gt; 5 days need principal approval. Medical leaves carry over to attendance shortfall calc.</span>
        </div>
      </div>

      <div style={{ position: 'sticky', bottom: 0, background: 'rgba(255,255,255,.96)', backdropFilter: 'blur(10px)', borderTop: '1px solid var(--n100)', padding: '12px 16px 22px' }}>
        <button disabled={!draft.reason.trim() || days < 1} onClick={() => { setSubmitted(true); idbDel('leave-draft'); }} className="btn" style={{ height: 50, opacity: !draft.reason.trim() || days < 1 ? .5 : 1 }}>
          <Icon name="check" size={16}/> Submit leave request
        </button>
      </div>
    </div>
  );
}

const LEAVE_TYPES = {
  sick:    { ic: 'flask',     label: 'Sick',     placeholder: 'Brief description — doctor\'s note recommended for >2 days' },
  family:  { ic: 'users',     label: 'Family',   placeholder: 'Family event, travel, ceremony…' },
  emerg:   { ic: 'alert',     label: 'Emergency',placeholder: 'Tell the teacher only what you need to' },
  other:   { ic: 'info',      label: 'Other',    placeholder: 'Add a clear reason' }
};

// ─────────────────────────────────────────────────────────────
// EarlyPickupScreen — request early pickup with custody-aware validation
// ─────────────────────────────────────────────────────────────
function EarlyPickupScreen({ nav, params }) {
  const childName = params?.child || 'Aarav Mehra';
  const childCls = params?.cls || '8-B';
  const [draft, setDraft, hyd] = useDraft('pickup-draft', {
    when: today(),
    time: '13:00',
    reason: 'doctor',
    pickupBy: 'self',
    other: '',
    photoAck: false
  });
  const [submitted, setSubmitted] = useStateL(false);

  if (!hyd) return <div className="screen-bg" style={{ padding: 20 }}><SkeletonList n={2}/></div>;

  if (submitted) {
    return (
      <div className="screen-bg" style={{ minHeight: '100%' }} data-screen-label="PickupSubmitted">
        <PageHeader title="Pickup approved" onBack={() => nav.replace('home')}/>
        <div style={{ padding: '40px 24px', textAlign: 'center', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 14 }}>
          <div style={{ width: 84, height: 84, borderRadius: '50%', background: 'var(--success-50)', color: '#065F46', display: 'grid', placeItems: 'center' }}><Icon name="check" size={38}/></div>
          <div>
            <div style={{ fontSize: 22, fontWeight: 800, color: 'var(--n900)' }}>You're set</div>
            <div style={{ fontSize: 13, color: 'var(--n500)', marginTop: 6, maxWidth: 300, lineHeight: 1.6 }}>
              Show this gate-pass at the school entrance. {childName.split(' ')[0]}'s class teacher has been notified.
            </div>
          </div>
          <div className="card" style={{ padding: 18, width: '100%', textAlign: 'center', background: 'linear-gradient(135deg, #0F172A 0%, #1E293B 100%)', color: '#fff', border: 'none' }}>
            <div style={{ fontSize: 10.5, color: 'rgba(255,255,255,.6)', textTransform: 'uppercase', letterSpacing: '.08em' }}>Gate pass</div>
            <div style={{ fontSize: 22, fontWeight: 800, marginTop: 6, fontFamily: 'JetBrains Mono, monospace', letterSpacing: '.04em' }}>GP-7-3284</div>
            <div style={{ width: 120, height: 120, margin: '14px auto', background: '#fff', borderRadius: 14, display: 'grid', placeItems: 'center' }}>
              <Icon name="qr" size={92} color="#0F172A"/>
            </div>
            <div style={{ fontSize: 12, fontWeight: 700 }}>{childName} · {childCls}</div>
            <div style={{ fontSize: 11, color: 'rgba(255,255,255,.7)', marginTop: 4 }}>{draft.when} · {draft.time}</div>
          </div>
          <button onClick={() => nav.replace('home')} className="btn" style={{ width: '100%', marginTop: 8 }}>Done</button>
        </div>
      </div>
    );
  }

  const REASONS = [
    { k: 'doctor', ic: 'flask', label: 'Doctor visit' },
    { k: 'family', ic: 'users', label: 'Family event' },
    { k: 'unwell', ic: 'alert', label: 'Feeling unwell' },
    { k: 'other', ic: 'info', label: 'Other' }
  ];
  const PICKUPS = [
    { k: 'self', label: 'I will pick up', ic: 'user' },
    { k: 'spouse', label: 'My spouse', ic: 'user' },
    { k: 'gp', label: 'Grandparent', ic: 'users' },
    { k: 'other', label: 'Someone else', ic: 'plus' }
  ];

  return (
    <div className="screen-bg" style={{ minHeight: '100%' }} data-screen-label="EarlyPickup">
      <PageHeader title="Early pickup" subtitle={`${childName} · ${childCls}`} onBack={() => nav.pop()}/>

      <div style={{ padding: '14px 16px 100px', display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 10 }}>
          <FormField label="Date" required>
            <input type="date" min={today()} value={draft.when} onChange={(e) => setDraft((d) => ({ ...d, when: e.target.value }))} style={fldS}/>
          </FormField>
          <FormField label="Pickup time" required>
            <input type="time" min="08:30" max="15:30" value={draft.time} onChange={(e) => setDraft((d) => ({ ...d, time: e.target.value }))} style={fldS}/>
          </FormField>
        </div>

        <FormField label="Reason" required>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 8 }}>
            {REASONS.map((r) => {
              const a = draft.reason === r.k;
              return (
                <button key={r.k} onClick={() => setDraft((d) => ({ ...d, reason: r.k }))} className="card" style={{ padding: 12, display: 'flex', alignItems: 'center', gap: 10, textAlign: 'left', borderColor: a ? 'var(--p400)' : 'var(--n100)', background: a ? 'var(--p50)' : '#fff' }}>
                  <div style={{ width: 32, height: 32, borderRadius: 10, background: a ? 'var(--p500)' : 'var(--n50)', color: a ? '#fff' : 'var(--n500)', display: 'grid', placeItems: 'center' }}><Icon name={r.ic} size={15}/></div>
                  <div style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--n900)' }}>{r.label}</div>
                </button>
              );
            })}
          </div>
        </FormField>

        {draft.reason === 'other' && (
          <FormField label="Tell the school why" required>
            <textarea value={draft.other} onChange={(e) => setDraft((d) => ({ ...d, other: e.target.value }))} rows={2} style={{ ...fldS, padding: 12, resize: 'vertical' }} placeholder="One line is enough"/>
          </FormField>
        )}

        <FormField label="Who's picking up?" required>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 8 }}>
            {PICKUPS.map((p) => {
              const a = draft.pickupBy === p.k;
              return (
                <button key={p.k} onClick={() => setDraft((d) => ({ ...d, pickupBy: p.k }))} className="card" style={{ padding: 12, display: 'flex', alignItems: 'center', gap: 10, textAlign: 'left', borderColor: a ? 'var(--p400)' : 'var(--n100)', background: a ? 'var(--p50)' : '#fff' }}>
                  <div style={{ width: 32, height: 32, borderRadius: 10, background: a ? 'var(--p500)' : 'var(--n50)', color: a ? '#fff' : 'var(--n500)', display: 'grid', placeItems: 'center' }}><Icon name={p.ic} size={15}/></div>
                  <div style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--n900)' }}>{p.label}</div>
                </button>
              );
            })}
          </div>
        </FormField>

        {draft.pickupBy === 'other' && (
          <div className="card" style={{ padding: 14, background: 'var(--warn-50)', borderColor: 'var(--warn-200)' }}>
            <div className="row" style={{ gap: 10 }}>
              <Icon name="info" size={16} color="#92400E"/>
              <div style={{ fontSize: 11.5, color: '#92400E', lineHeight: 1.5 }}>
                <strong>Custody check:</strong> only people on your approved list can pick up. Add their photo + ID under <a href="#" onClick={(e) => e.preventDefault()} style={{ color: '#92400E', textDecoration: 'underline' }}>Trusted contacts</a> first.
              </div>
            </div>
            <button onClick={() => setDraft((d) => ({ ...d, photoAck: !d.photoAck }))} className="row" style={{ marginTop: 10, gap: 8, padding: '8px 0', textAlign: 'left' }}>
              <div style={{ width: 20, height: 20, borderRadius: 6, border: draft.photoAck ? '2px solid var(--p500)' : '2px solid var(--n200)', background: draft.photoAck ? 'var(--p500)' : '#fff', display: 'grid', placeItems: 'center' }}>
                {draft.photoAck && <Icon name="check" size={11} color="#fff"/>}
              </div>
              <div style={{ fontSize: 11, color: 'var(--n700)' }}>I confirm the pickup person is on my approved list and I'll share their photo</div>
            </button>
          </div>
        )}

        <div className="card" style={{ padding: 14, background: 'var(--p50)', borderColor: 'var(--p100)', display: 'flex', gap: 10, alignItems: 'flex-start' }}>
          <Icon name="info" size={16} color="var(--p600)"/>
          <div style={{ fontSize: 11, color: 'var(--p700)', lineHeight: 1.55 }}>
            On approval you'll get a <strong>QR gate-pass</strong>. Security scans it at the gate to verify identity.
          </div>
        </div>
      </div>

      <div style={{ position: 'sticky', bottom: 0, background: 'rgba(255,255,255,.96)', backdropFilter: 'blur(10px)', borderTop: '1px solid var(--n100)', padding: '12px 16px 22px' }}>
        <button
          disabled={(draft.reason === 'other' && !draft.other.trim()) || (draft.pickupBy === 'other' && !draft.photoAck)}
          onClick={() => { setSubmitted(true); idbDel('pickup-draft'); }}
          className="btn"
          style={{ height: 50, opacity: ((draft.reason === 'other' && !draft.other.trim()) || (draft.pickupBy === 'other' && !draft.photoAck)) ? .5 : 1 }}
        >
          <Icon name="qr" size={16}/> Generate gate pass
        </button>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// AttendanceDisputeScreen — dispute a wrongly-marked absent day
// ─────────────────────────────────────────────────────────────
function AttendanceDisputeScreen({ nav, params }) {
  const date = params?.date || 'Mar 12, 2026';
  const subject = params?.subject || 'Maths · Period 4';
  const [draft, setDraft, hyd] = useDraft('dispute-draft', {
    claim: 'present',
    note: '',
    evidence: 'classmate'
  });
  const [submitted, setSubmitted] = useStateL(false);

  if (!hyd) return <div className="screen-bg" style={{ padding: 20 }}><SkeletonList n={2}/></div>;

  if (submitted) {
    return (
      <div className="screen-bg" style={{ minHeight: '100%' }} data-screen-label="DisputeSubmitted">
        <PageHeader title="Dispute submitted" onBack={() => nav.replace('attendance')}/>
        <div style={{ padding: '40px 24px', textAlign: 'center', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 14 }}>
          <div style={{ width: 84, height: 84, borderRadius: '50%', background: 'var(--p50)', color: 'var(--p600)', display: 'grid', placeItems: 'center' }}><Icon name="flag" size={38}/></div>
          <div>
            <div style={{ fontSize: 22, fontWeight: 800, color: 'var(--n900)' }}>We'll investigate</div>
            <div style={{ fontSize: 13, color: 'var(--n500)', marginTop: 6, maxWidth: 280, lineHeight: 1.6 }}>The class teacher will check the period register and respond within 48 hours.</div>
          </div>
          <div className="card" style={{ padding: 14, width: '100%', textAlign: 'left' }}>
            <div className="spread">
              <div style={{ fontSize: 11, color: 'var(--n400)', textTransform: 'uppercase', letterSpacing: '.08em' }}>Reference</div>
              <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--n900)', fontFamily: 'JetBrains Mono, monospace' }}>DSP-{Math.floor(Math.random() * 9000 + 1000)}</div>
            </div>
            <div style={{ fontSize: 12.5, color: 'var(--n700)', marginTop: 8 }}>{date} · {subject}</div>
          </div>
          <button onClick={() => nav.replace('attendance')} className="btn" style={{ width: '100%', marginTop: 8 }}>Back to attendance</button>
        </div>
      </div>
    );
  }

  return (
    <div className="screen-bg" style={{ minHeight: '100%' }} data-screen-label="AttendanceDispute">
      <PageHeader title="Dispute attendance" subtitle={`${date} · ${subject}`} onBack={() => nav.pop()}/>
      <div style={{ padding: '14px 16px 100px', display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div className="card" style={{ padding: 14, background: 'var(--n50)', borderColor: 'var(--n100)', display: 'flex', gap: 10, alignItems: 'flex-start' }}>
          <Icon name="info" size={16} color="var(--n500)"/>
          <div style={{ fontSize: 11.5, color: 'var(--n700)', lineHeight: 1.55 }}>
            False disputes can affect your standing. Only flag this if you genuinely believe attendance was marked incorrectly.
          </div>
        </div>

        <FormField label="What actually happened?" required>
          {[
            { k: 'present', t: 'I was present', s: 'In the classroom for the full period' },
            { k: 'late', t: 'I was late, not absent', s: 'Arrived after roll call' },
            { k: 'authorised', t: 'I had a sanctioned reason', s: 'Inter-school event, sick bay, lab' }
          ].map((opt) => {
            const a = draft.claim === opt.k;
            return (
              <button key={opt.k} onClick={() => setDraft((d) => ({ ...d, claim: opt.k }))} className="card" style={{ padding: 14, display: 'flex', alignItems: 'flex-start', gap: 12, textAlign: 'left', borderColor: a ? 'var(--p400)' : 'var(--n100)', background: a ? 'var(--p50)' : '#fff', marginTop: 8 }}>
                <div style={{ width: 22, height: 22, borderRadius: '50%', border: a ? '6px solid var(--p500)' : '2px solid var(--n200)', flexShrink: 0, marginTop: 2 }}/>
                <div>
                  <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--n900)' }}>{opt.t}</div>
                  <div style={{ fontSize: 11, color: 'var(--n500)', marginTop: 2 }}>{opt.s}</div>
                </div>
              </button>
            );
          })}
        </FormField>

        <FormField label="Add context" required hint={`${draft.note.length}/300`}>
          <textarea value={draft.note} onChange={(e) => setDraft((d) => ({ ...d, note: e.target.value.slice(0, 300) }))} rows={3} placeholder="What seat were you in? Did anyone speak to you?" style={{ ...fldS, padding: 12, resize: 'vertical' }}/>
        </FormField>

        <FormField label="Who can vouch (optional)">
          <Segmented value={draft.evidence} onChange={(v) => setDraft((d) => ({ ...d, evidence: v }))} options={[
            { value: 'classmate', label: 'Classmate' },
            { value: 'teacher', label: 'Subject teacher' },
            { value: 'none', label: 'None' }
          ]}/>
        </FormField>
      </div>

      <div style={{ position: 'sticky', bottom: 0, background: 'rgba(255,255,255,.96)', backdropFilter: 'blur(10px)', borderTop: '1px solid var(--n100)', padding: '12px 16px 22px' }}>
        <button disabled={!draft.note.trim()} onClick={() => { setSubmitted(true); idbDel('dispute-draft'); }} className="btn" style={{ height: 50, opacity: !draft.note.trim() ? .5 : 1 }}>
          <Icon name="flag" size={16}/> Submit dispute
        </button>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// HomeworkSubmitScreen — real submit flow with autosave + offline queue
// ─────────────────────────────────────────────────────────────
function HomeworkSubmitScreen({ nav, params }) {
  const hwid = params?.hwid || 'hw-1';
  const subject = params?.subject || 'Maths';
  const task = params?.task || 'Quadratic equations · Ex 4.3';
  const due = params?.due || 'Today · 11:59 PM';

  const draftKey = `hw-submit-${hwid}`;
  const [draft, setDraft, hyd] = useDraft(draftKey, {
    note: '',
    files: [],
    text: '',
    asText: false
  });
  const [stage, setStage] = useStateL('compose'); // compose | uploading | submitted
  const [progress, setProgress] = useStateL(0);
  const [restored, setRestored] = useStateL(false);
  const fileRef = useRefL();
  const cameraRef = useRefL();

  useEffectL(() => {
    if (hyd && (draft.note || draft.files.length > 0 || draft.text)) {
      setRestored(true);
      const t = setTimeout(() => setRestored(false), 4000);
      return () => clearTimeout(t);
    }
  }, [hyd]);

  const handleFiles = (fl) => {
    const arr = Array.from(fl).map((f) => ({
      id: 'f-' + Math.random().toString(36).slice(2),
      name: f.name,
      size: f.size,
      type: f.type,
      preview: f.type.startsWith('image/') ? URL.createObjectURL(f) : null
    }));
    setDraft((d) => ({ ...d, files: [...d.files, ...arr] }));
  };

  const removeFile = (id) => setDraft((d) => ({ ...d, files: d.files.filter((f) => f.id !== id) }));

  const totalSize = draft.files.reduce((s, f) => s + f.size, 0);
  const canSubmit = (draft.files.length > 0 || (draft.asText && draft.text.trim().length > 0)) && totalSize < 25 * 1024 * 1024;

  const submit = () => {
    setStage('uploading');
    setProgress(0);
    const start = Date.now();
    const tick = setInterval(() => {
      const t = (Date.now() - start) / 1500;
      const p = Math.min(100, t * 100);
      setProgress(p);
      if (p >= 100) {
        clearInterval(tick);
        setStage('submitted');
        idbDel(draftKey);
      }
    }, 80);
  };

  if (!hyd) return <div className="screen-bg" style={{ padding: 20 }}><SkeletonList n={3}/></div>;

  if (stage === 'submitted') {
    return (
      <div className="screen-bg" style={{ minHeight: '100%' }} data-screen-label="HomeworkSubmitted">
        <PageHeader title="Submitted" onBack={() => nav.replace('homework')}/>
        <div style={{ padding: '40px 24px', textAlign: 'center', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 14 }}>
          <div style={{ width: 84, height: 84, borderRadius: '50%', background: 'var(--success-50)', color: '#065F46', display: 'grid', placeItems: 'center' }}><Icon name="check" size={38}/></div>
          <div>
            <div style={{ fontSize: 22, fontWeight: 800, color: 'var(--n900)' }}>Homework submitted</div>
            <div style={{ fontSize: 13, color: 'var(--n500)', marginTop: 6, maxWidth: 280, lineHeight: 1.6 }}>Your teacher will see it on their grading queue. You'll be notified when it's marked.</div>
          </div>
          <div className="card" style={{ padding: 14, width: '100%', textAlign: 'left' }}>
            <div style={{ fontSize: 11, color: 'var(--n400)', textTransform: 'uppercase', letterSpacing: '.08em' }}>{subject}</div>
            <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--n900)', marginTop: 4 }}>{task}</div>
            <div style={{ fontSize: 11, color: 'var(--n500)', marginTop: 6 }}>
              {draft.files.length > 0 && `${draft.files.length} file${draft.files.length !== 1 ? 's' : ''}`}
              {draft.files.length > 0 && draft.asText && ' · '}
              {draft.asText && draft.text.length + ' chars typed'}
            </div>
          </div>
          <button onClick={() => nav.replace('homework')} className="btn" style={{ width: '100%', marginTop: 8 }}>Back to homework</button>
        </div>
      </div>
    );
  }

  return (
    <div className="screen-bg" style={{ minHeight: '100%' }} data-screen-label="HomeworkSubmit">
      <PageHeader title="Submit homework" subtitle={`${subject} · ${task}`} onBack={() => nav.pop()}/>
      <OfflineBanner message="You're offline — submission will queue and upload automatically when you reconnect"/>

      {restored && (
        <div role="status" style={{ margin: '8px 16px', padding: '10px 14px', borderRadius: 12, background: 'var(--p50)', border: '1px solid var(--p200)', fontSize: 11.5, color: 'var(--p700)', display: 'flex', alignItems: 'center', gap: 8, animation: 'sp-up .25s' }}>
          <Icon name="history" size={14}/> Restored your draft from {new Date().toLocaleString('en-IN', { weekday: 'short', hour: 'numeric', minute: '2-digit' })}
        </div>
      )}

      <div style={{ padding: '8px 16px 100px', display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div className="card" style={{ padding: 12, background: 'var(--warn-50)', borderColor: 'var(--warn-200)', display: 'flex', alignItems: 'center', gap: 10 }}>
          <Icon name="history" size={14} color="#92400E"/>
          <div style={{ flex: 1, fontSize: 11.5, color: '#92400E' }}>Due <strong>{due}</strong> · late submissions get a 10% penalty</div>
        </div>

        {/* File chooser CTAs */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
          <button onClick={() => cameraRef.current?.click()} className="card" style={{ padding: 16, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8, textAlign: 'center' }}>
            <div style={{ width: 38, height: 38, borderRadius: 11, background: 'var(--p50)', color: 'var(--p600)', display: 'grid', placeItems: 'center' }}><Icon name="camera" size={18}/></div>
            <div style={{ fontSize: 11.5, fontWeight: 700, color: 'var(--n900)' }}>Take photo</div>
          </button>
          <button onClick={() => fileRef.current?.click()} className="card" style={{ padding: 16, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8, textAlign: 'center' }}>
            <div style={{ width: 38, height: 38, borderRadius: 11, background: 'var(--n50)', color: 'var(--n600)', display: 'grid', placeItems: 'center' }}><Icon name="paperclip" size={18}/></div>
            <div style={{ fontSize: 11.5, fontWeight: 700, color: 'var(--n900)' }}>Files</div>
          </button>
          <button onClick={() => setDraft((d) => ({ ...d, asText: !d.asText }))} className="card" style={{ padding: 16, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8, textAlign: 'center', borderColor: draft.asText ? 'var(--p400)' : 'var(--n100)', background: draft.asText ? 'var(--p50)' : '#fff' }}>
            <div style={{ width: 38, height: 38, borderRadius: 11, background: draft.asText ? 'var(--p500)' : 'var(--n50)', color: draft.asText ? '#fff' : 'var(--n600)', display: 'grid', placeItems: 'center' }}><Icon name="edit" size={18}/></div>
            <div style={{ fontSize: 11.5, fontWeight: 700, color: 'var(--n900)' }}>Type answer</div>
          </button>
        </div>
        <input ref={cameraRef} type="file" accept="image/*" capture="environment" hidden multiple onChange={(e) => handleFiles(e.target.files)}/>
        <input ref={fileRef} type="file" hidden multiple accept="image/*,application/pdf,.doc,.docx" onChange={(e) => handleFiles(e.target.files)}/>

        {/* File list */}
        {draft.files.length > 0 && (
          <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
            <div style={{ padding: '10px 14px', borderBottom: '1px solid var(--n100)', background: 'var(--n50)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--n600)', textTransform: 'uppercase', letterSpacing: '.06em' }}>{draft.files.length} attachment{draft.files.length !== 1 ? 's' : ''}</div>
              <div style={{ fontSize: 11, color: 'var(--n500)' }}>{(totalSize / 1024 / 1024).toFixed(1)} MB / 25 MB</div>
            </div>
            {draft.files.map((f) => (
              <div key={f.id} style={{ padding: '10px 14px', display: 'flex', alignItems: 'center', gap: 10, borderTop: '1px solid var(--n50)' }}>
                {f.preview
                  ? <img alt="" src={f.preview} style={{ width: 44, height: 44, borderRadius: 9, objectFit: 'cover', flexShrink: 0 }}/>
                  : <div style={{ width: 44, height: 44, borderRadius: 9, background: 'var(--n50)', color: 'var(--n500)', display: 'grid', placeItems: 'center', flexShrink: 0 }}><Icon name="document" size={16}/></div>
                }
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--n900)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{f.name}</div>
                  <div style={{ fontSize: 10.5, color: 'var(--n500)' }}>{(f.size / 1024).toFixed(0)} KB · {f.type.split('/')[1]?.toUpperCase() || 'FILE'}</div>
                </div>
                <button onClick={() => removeFile(f.id)} aria-label="Remove" style={{ width: 28, height: 28, borderRadius: 8, background: 'var(--n50)', display: 'grid', placeItems: 'center' }}><Icon name="x" size={13}/></button>
              </div>
            ))}
          </div>
        )}

        {totalSize >= 25 * 1024 * 1024 && (
          <ErrorBanner title="Files too large" sub="Total under 25 MB please. Try compressing or splitting submission."/>
        )}

        {/* Inline text editor */}
        {draft.asText && (
          <FormField label="Type your answer" hint={draft.text.length + ' chars'}>
            <textarea
              value={draft.text}
              onChange={(e) => setDraft((d) => ({ ...d, text: e.target.value }))}
              rows={6}
              placeholder="Show your working — your teacher likes seeing how you got there."
              style={{ ...fldS, padding: 12, resize: 'vertical', minHeight: 140, fontSize: 13.5, lineHeight: 1.6 }}
            />
          </FormField>
        )}

        <FormField label="Note for teacher (optional)" hint={`${draft.note.length}/200`}>
          <textarea
            value={draft.note}
            onChange={(e) => setDraft((d) => ({ ...d, note: e.target.value.slice(0, 200) }))}
            rows={2}
            placeholder="Stuck on Q4 — explanation request, anything else"
            style={{ ...fldS, padding: 12, resize: 'vertical' }}
          />
        </FormField>

        {stage === 'uploading' && (
          <div className="card" style={{ padding: 14 }}>
            <div className="spread" style={{ marginBottom: 10 }}>
              <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--n900)' }}>Uploading…</div>
              <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--p600)', fontFamily: 'JetBrains Mono, monospace' }}>{Math.floor(progress)}%</div>
            </div>
            <div style={{ height: 8, borderRadius: 999, background: 'var(--n100)', overflow: 'hidden' }}>
              <div style={{ height: '100%', width: progress + '%', background: 'linear-gradient(90deg, var(--p400), var(--p600))', transition: 'width .12s' }}/>
            </div>
          </div>
        )}

        <div style={{ fontSize: 10.5, color: 'var(--n400)', display: 'flex', gap: 6, padding: '4px 4px' }}>
          <Icon name="info" size={11}/>
          <span>Your draft saves automatically every few seconds. Lose connection? Pick up where you left off.</span>
        </div>
      </div>

      <div style={{ position: 'sticky', bottom: 0, background: 'rgba(255,255,255,.96)', backdropFilter: 'blur(10px)', borderTop: '1px solid var(--n100)', padding: '12px 16px 22px', display: 'flex', gap: 10 }}>
        <button onClick={() => { idbDel(draftKey); setDraft({ note: '', files: [], text: '', asText: false }); }} className="btn btn-outline" style={{ flex: 1 }}>Clear draft</button>
        <button onClick={submit} disabled={!canSubmit || stage === 'uploading'} className="btn" style={{ flex: 2, opacity: !canSubmit || stage === 'uploading' ? .5 : 1 }}>
          {stage === 'uploading' ? 'Uploading…' : <>Submit homework <Icon name="arrow-right" size={16}/></>}
        </button>
      </div>
    </div>
  );
}

// Small helpers
const fldS = { padding: '12px 14px', borderRadius: 12, border: '1.5px solid var(--n200)', fontSize: 14, fontFamily: 'inherit', width: '100%' };

function ToggleRow({ ic, t, s, on, onChange, last }) {
  return (
    <div className="card" style={{ padding: 14, display: 'flex', alignItems: 'center', gap: 12 }}>
      <div style={{ width: 36, height: 36, borderRadius: 11, background: on ? 'var(--p50)' : 'var(--n50)', color: on ? 'var(--p600)' : 'var(--n400)', display: 'grid', placeItems: 'center' }}><Icon name={ic} size={16}/></div>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--n900)' }}>{t}</div>
        <div style={{ fontSize: 11, color: 'var(--n500)', marginTop: 2 }}>{s}</div>
      </div>
      <button onClick={() => onChange(!on)} role="switch" aria-checked={on} aria-label={t} style={{ width: 38, height: 22, borderRadius: 999, background: on ? 'var(--p500)' : 'var(--n200)', border: 'none', position: 'relative' }}>
        <span aria-hidden="true" style={{ position: 'absolute', top: 2, left: on ? 18 : 2, width: 18, height: 18, borderRadius: '50%', background: '#fff', boxShadow: '0 1px 3px rgba(15,23,42,.18)', transition: 'left .2s' }}/>
      </button>
    </div>
  );
}

function SectionLabelL({ label }) {
  return <div style={{ fontSize: 10.5, fontWeight: 800, color: 'var(--n400)', textTransform: 'uppercase', letterSpacing: '.08em', padding: '4px 4px' }}>{label}</div>;
}

Object.assign(window, {
  ApplyLeaveScreen, EarlyPickupScreen, AttendanceDisputeScreen, HomeworkSubmitScreen
});
