/* Home dashboard */
function SectionLabel({ children, action }) {
  return (
    <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', margin:'18px 2px 9px' }}>
      <span style={{ fontSize:11, fontWeight:800, letterSpacing:'.09em', textTransform:'uppercase', color:'var(--gray-500)' }}>{children}</span>
      {action}
    </div>
  );
}

function HomeScreen({ onNav, onBack, child, childList, onSwitchChild }) {
  const [busOpen, setBusOpen] = React.useState(true);
  const [emOpen, setEmOpen] = React.useState(true);
  const [emExp, setEmExp] = React.useState(false);
  const [childSheet, setChildSheet] = React.useState(false);
  const [roster, setRoster] = React.useState({});
  React.useEffect(() => {
    const read = () => { try { setRoster(JSON.parse(localStorage.getItem('jl_roster') || '{}')); } catch(e){} };
    read();
    const onStore = (e) => { if (e.key === 'jl_roster') read(); };
    window.addEventListener('storage', onStore);
    const iv = setInterval(read, 1500);
    return () => { window.removeEventListener('storage', onStore); clearInterval(iv); };
  }, []);
  const boarding = roster[child.id];
  const [att, setAtt] = React.useState(null);
  React.useEffect(() => {
    const read = () => { try { const all = JSON.parse(localStorage.getItem('jl_attendance') || '{}'); setAtt(all[child.id] || null); } catch(e){} };
    read();
    const onStore = (e) => { if (e.key === 'jl_attendance') read(); };
    window.addEventListener('storage', onStore);
    const iv = setInterval(read, 1500);
    return () => { window.removeEventListener('storage', onStore); clearInterval(iv); };
  }, [child.id]);
  const [hw, setHw] = React.useState(null);
  React.useEffect(() => {
    const read = () => { try { const all = JSON.parse(localStorage.getItem('jl_homework') || '{}'); setHw(all[child.id] || null); } catch(e){} };
    read();
    const onStore = (e) => { if (e.key === 'jl_homework') read(); };
    window.addEventListener('storage', onStore);
    const iv = setInterval(read, 1500);
    return () => { window.removeEventListener('storage', onStore); clearInterval(iv); };
  }, [child.id]);
  const [bus, setBus] = React.useState(null);
  React.useEffect(() => {
    const read = () => { try { setBus(JSON.parse(localStorage.getItem('jl_buspos') || 'null')); } catch(e){} };
    read();
    const onStore = (e) => { if (e.key === 'jl_buspos') read(); };
    window.addEventListener('storage', onStore);
    const iv = setInterval(read, 1500);
    return () => { window.removeEventListener('storage', onStore); clearInterval(iv); };
  }, []);
  const [busAlert, setBusAlert] = React.useState(null);
  React.useEffect(() => {
    const read = () => { try { const a = JSON.parse(localStorage.getItem('jl_alerts') || '[]'); setBusAlert(a.find(x => (x.kind==='delay'||x.kind==='incident') && x.status!=='resolved' && (!child.bus || x.bus===child.bus)) || null); } catch(e){} };
    read();
    const onStore = (e) => { if (e.key === 'jl_alerts') read(); };
    window.addEventListener('storage', onStore);
    const iv = setInterval(read, 1500);
    return () => { window.removeEventListener('storage', onStore); clearInterval(iv); };
  }, [child.bus]);
  return (
    <div style={{ background:'var(--gray-50)', minHeight:'100%' }}>
      <GreetingBar onBell={()=>onNav('notifications')} onBack={onBack} />
      {childSheet && (
        <div onClick={()=>setChildSheet(false)} style={{ position:'absolute', inset:0, zIndex:70, background:'rgba(10,20,40,.4)', display:'flex', alignItems:'flex-end' }}>
          <div onClick={e=>e.stopPropagation()} style={{ width:'100%', background:'#fff', borderRadius:'22px 22px 0 0', padding:'10px 18px 30px' }}>
            <div style={{ width:40, height:4, borderRadius:'999px', background:'var(--gray-300)', margin:'0 auto 16px' }} />
            <div style={{ fontSize:18, fontWeight:800, color:'var(--ink)', marginBottom:4 }}>Your Children</div>
            <div style={{ fontSize:13, color:'var(--gray-500)', marginBottom:14 }}>Switch to see each child’s info</div>
            <div style={{ display:'flex', flexDirection:'column', gap:9 }}>
              {childList.map(c => {
                const on = c.id === child.id;
                return (
                  <button key={c.id} onClick={()=>{ onSwitchChild(c.id); setChildSheet(false); jlToast('Now viewing ' + c.name, { icon:'user-round-check' }); }} style={{ display:'flex', alignItems:'center', gap:12, padding:'13px 14px', borderRadius:13, cursor:'pointer', fontFamily:'var(--font-sans)', textAlign:'left', border: on?'1.5px solid var(--navy-600)':'1px solid var(--gray-200)', background: on?'var(--blue-100)':'#fff' }}>
                    <Avatar initials={c.initials} color={c.color} size={40} />
                    <div style={{ flex:1 }}>
                      <div style={{ fontSize:15, fontWeight:700, color:'var(--ink)' }}>{c.name}</div>
                      <div style={{ fontSize:12.5, color:'var(--gray-500)' }}>{c.gradeLabel} · {c.school}</div>
                    </div>
                    {on && <Icon name="check" size={20} color="var(--navy-600)" />}
                  </button>
                );
              })}
            </div>
          </div>
        </div>
      )}
      <div style={{ padding:'0 18px 110px' }}>

        {busAlert && (
          <div style={{ display:'flex', alignItems:'center', gap:11, background: busAlert.kind==='incident'?'var(--danger-100)':'var(--warning-100)', borderRadius:14, padding:'13px 15px', marginBottom:14 }}>
            <span style={{ width:34, height:34, borderRadius:10, background: busAlert.kind==='incident'?'var(--danger-500)':'var(--warning-500)', display:'flex', alignItems:'center', justifyContent:'center', flex:'0 0 auto' }}><Icon name={busAlert.kind==='incident'?'triangle-alert':'clock'} size={17} color="#fff" /></span>
            <div style={{ flex:1, minWidth:0 }}>
              <div style={{ fontSize:14, fontWeight:700, color: busAlert.kind==='incident'?'var(--danger-600)':'var(--warning-600)' }}>Bus {busAlert.bus} {busAlert.kind==='incident'?'incident reported':'is running late'}</div>
              <div style={{ fontSize:12, color: busAlert.kind==='incident'?'var(--danger-600)':'var(--warning-600)', opacity:.85 }}>{busAlert.kind==='incident'?'The school is responding — we’ll update you shortly.':(child.first + '’s ride may arrive later than usual.')}</div>
            </div>
            <button onClick={()=>onNav('transport')} style={{ background:'#fff', border:0, borderRadius:9, padding:'8px 12px', fontWeight:700, fontSize:12.5, color: busAlert.kind==='incident'?'var(--danger-600)':'var(--warning-600)', cursor:'pointer', fontFamily:'var(--font-sans)' }}>Track</button>
          </div>
        )}

        {/* emergency alert */}
        {emOpen && (
          <div style={{ background:'var(--danger-500)', borderRadius:14, padding:'13px 15px', color:'#fff', boxShadow:'0 8px 20px rgba(229,72,77,.32)', marginBottom:14 }}>
            <div style={{ display:'flex', alignItems:'center', gap:10 }}>
              <span style={{ width:34, height:34, borderRadius:10, background:'rgba(255,255,255,.2)', display:'flex', alignItems:'center', justifyContent:'center', flex:'0 0 auto' }}>
                <Icon name="siren" size={18} color="#fff" />
              </span>
              <div style={{ flex:1, minWidth:0 }}>
                <div style={{ fontSize:9.5, fontWeight:800, letterSpacing:'.1em', color:'rgba(255,255,255,.8)' }}>EMERGENCY ALERT · KATY MIDDLE</div>
                <div style={{ fontSize:14.5, fontWeight:700 }}>Early dismissal today at 1:00 PM</div>
              </div>
              <button onClick={()=>setEmOpen(false)} style={{ border:0, background:'rgba(255,255,255,.18)', width:26, height:26, borderRadius:'999px', display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer', flex:'0 0 auto' }}>
                <Icon name="x" size={14} color="#fff" />
              </button>
            </div>
            {emExp && (
              <div style={{ fontSize:13, color:'rgba(255,255,255,.92)', lineHeight:1.5, margin:'10px 0 2px', paddingLeft:44 }}>
                Due to a forecasted storm, all students will be dismissed at 1:00 PM. Buses will run on the early schedule. Please confirm your pickup plan.
              </div>
            )}
            <div style={{ display:'flex', gap:8, marginTop:11, paddingLeft:44 }}>
              <button onClick={()=>setEmExp(v=>!v)} style={{ flex:1, background:'#fff', color:'var(--danger-600)', border:0, borderRadius:9, padding:'9px', fontWeight:700, fontSize:12.5, cursor:'pointer', fontFamily:'var(--font-sans)' }}>{emExp?'Show Less':'Read More'}</button>
              <button onClick={()=>onNav('pickup')} style={{ flex:1, background:'rgba(255,255,255,.18)', color:'#fff', border:0, borderRadius:9, padding:'9px', fontWeight:700, fontSize:12.5, cursor:'pointer', fontFamily:'var(--font-sans)' }}>Update Pickup</button>
            </div>
          </div>
        )}

        {/* child selector */}
        <button onClick={()=>setChildSheet(true)} style={{
          width:'100%', display:'flex', alignItems:'center', gap:12,
          background:'#fff', border:'1px solid var(--gray-200)', borderRadius:14,
          padding:'13px 15px', boxShadow:'var(--shadow-sm)', cursor:'pointer',
          fontFamily:'var(--font-sans)', textAlign:'left',
        }}>
          <Avatar initials={child.initials} color={child.color} size={40} />
          <div style={{ flex:1 }}>
            <div style={{ fontSize:15, fontWeight:700, color:'var(--ink)', display:'flex', alignItems:'center', gap:7 }}>{child.name}{childList.length>1 && <span style={{ fontSize:11, fontWeight:700, color:'var(--blue-600)', background:'var(--blue-100)', borderRadius:'999px', padding:'2px 8px' }}>{jlT('switch')}</span>}</div>
            <div style={{ fontSize:12.5, color:'var(--gray-500)' }}>{child.gradeLabel} · {child.school}</div>
          </div>
          <Icon name="chevron-down" size={20} color="var(--gray-400)" />
        </button>

        {/* bus status hero */}
        {att && att.status && att.status!=='present' && (
          <div style={{ display:'flex', alignItems:'center', gap:11, background: att.status==='absent'?'var(--danger-100)':'var(--warning-100)', borderRadius:14, padding:'13px 15px', marginBottom:14 }}>
            <span style={{ width:34, height:34, borderRadius:10, background: att.status==='absent'?'var(--danger-500)':'var(--warning-500)', display:'flex', alignItems:'center', justifyContent:'center', flex:'0 0 auto' }}><Icon name={att.status==='absent'?'user-x':'clock'} size={17} color="#fff" /></span>
            <div style={{ flex:1, minWidth:0 }}>
              <div style={{ fontSize:14, fontWeight:700, color: att.status==='absent'?'var(--danger-600)':'var(--warning-600)' }}>{child.first} marked {att.status} in {att.period}</div>
              <div style={{ fontSize:12, color: att.status==='absent'?'var(--danger-600)':'var(--warning-600)', opacity:.85 }}>{att.cls} · {att.at} · by teacher</div>
            </div>
            <button onClick={()=>onNav('attendance')} style={{ background:'#fff', border:0, borderRadius:9, padding:'8px 12px', fontWeight:700, fontSize:12.5, color: att.status==='absent'?'var(--danger-600)':'var(--warning-600)', cursor:'pointer', fontFamily:'var(--font-sans)' }}>View</button>
          </div>
        )}

        {/* bus status hero */}
        {busOpen && (
          <div style={{
            marginTop:14, background:'var(--color-grad-hero)', borderRadius:18,
            padding:'17px 18px', color:'#fff', boxShadow:'var(--shadow-navy)', position:'relative', overflow:'hidden',
          }}>
            <button onClick={()=>setBusOpen(false)} style={{ position:'absolute', top:13, right:13, border:0, background:'rgba(255,255,255,.15)', width:26, height:26, borderRadius:'999px', display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer' }}>
              <Icon name="x" size={15} color="#fff" />
            </button>
            <div style={{ fontSize:10, fontWeight:800, letterSpacing:'.1em', color:'rgba(255,255,255,.7)' }}>BUS STATUS</div>
            <div style={{ display:'flex', alignItems:'center', gap:14, margin:'10px 0 4px' }}>
              <div>
                <div style={{ fontSize:20, fontWeight:800 }}>{child.bus==='Walker' ? 'Walker' : (bus ? 'On the way' : 'Not on route yet')}</div>
                <Pill bg="rgba(255,255,255,.18)" fg="#fff" style={{ marginTop:6 }}>{child.bus==='Walker' ? 'Walks home' : 'Bus '+child.bus}</Pill>
              </div>
              <div style={{ marginLeft:'auto', textAlign:'right' }}>
                <Icon name="bus-front" size={54} color="var(--gold-400)" />
              </div>
            </div>
            <div style={{ display:'flex', alignItems:'flex-end', justifyContent:'space-between', marginTop:6 }}>
              <div>
                <div style={{ fontSize:10, fontWeight:800, letterSpacing:'.1em', color:'rgba(255,255,255,.7)' }}>ETA</div>
                <div style={{ fontSize:30, fontWeight:800, letterSpacing:'-.02em', lineHeight:1 }}>{child.bus==='Walker' ? '—' : (bus ? bus.eta : 5)}<span style={{ fontSize:16, fontWeight:600, color:'rgba(255,255,255,.8)' }}> min</span></div>
                <div style={{ fontSize:11.5, color:'rgba(255,255,255,.7)', marginTop:4 }}>{bus ? 'Next: ' + bus.nextStop + ' · live' : 'Last updated 3:19 PM'}</div>
              </div>
              <button onClick={()=>onNav('transport')} style={{ background:'rgba(255,255,255,.16)', color:'#fff', border:0, borderRadius:10, padding:'9px 14px', fontWeight:700, fontSize:13, cursor:'pointer', fontFamily:'var(--font-sans)', display:'flex', alignItems:'center', gap:6 }}>
                <Icon name="map-pin" size={15} color="#fff" />View on map
              </button>
            </div>
            {boarding && (
              <div style={{ display:'flex', alignItems:'center', gap:9, marginTop:13, padding:'10px 12px', borderRadius:11, background: boarding.status==='boarded' ? 'rgba(31,157,87,.22)' : 'rgba(229,72,77,.22)' }}>
                <Icon name={boarding.status==='boarded' ? 'circle-check-big' : 'user-x'} size={17} color="#fff" />
                <span style={{ fontSize:12.5, fontWeight:700, color:'#fff' }}>
                  {boarding.status==='boarded'
                    ? child.first + ' boarded at ' + boarding.stop + ' · ' + boarding.time
                    : child.first + ' marked absent by the driver'}
                </span>
              </div>
            )}
          </div>
        )}

        {/* quick actions */}
        <SectionLabel>{jlT('quick_actions')}</SectionLabel>
        <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:10 }}>
          {[
            { id:'pickup', label:'Pickup', icon:'car-front', tint:'var(--gold-100)', ic:'var(--gold-600)' },
            { id:'grades', label:'Grades', icon:'graduation-cap', tint:'var(--blue-100)', ic:'var(--blue-500)' },
            { id:'wallet', label:'Lunch', icon:'utensils', tint:'var(--success-100)', ic:'var(--success-500)' },
            { id:'tutor', label:'AI Tutor', icon:'bot', tint:'var(--info-100)', ic:'var(--info-500)' },
          ].map(q => (
            <button key={q.id} onClick={()=>onNav(q.id)} style={{ display:'flex', flexDirection:'column', alignItems:'center', gap:7, background:'#fff', border:'1px solid var(--gray-200)', borderRadius:14, padding:'13px 4px', cursor:'pointer', fontFamily:'var(--font-sans)', boxShadow:'var(--shadow-sm)' }}>
              <span style={{ width:40, height:40, borderRadius:11, background:q.tint, display:'flex', alignItems:'center', justifyContent:'center' }}><Icon name={q.icon} size={20} color={q.ic} /></span>
              <span style={{ fontSize:11.5, fontWeight:700, color:'var(--ink)' }}>{jlT('qa_'+q.id)}</span>
            </button>
          ))}
        </div>

        {/* where's my child */}
        <button onClick={()=>onNav('timeline')} style={{ width:'100%', marginTop:14, display:'flex', alignItems:'center', gap:13, background:'#fff', border:'1px solid var(--gray-200)', borderRadius:16, padding:'15px 16px', boxShadow:'var(--shadow-sm)', cursor:'pointer', fontFamily:'var(--font-sans)', textAlign:'left' }}>
          <span style={{ width:44, height:44, borderRadius:12, background:'var(--blue-100)', display:'flex', alignItems:'center', justifyContent:'center', flex:'0 0 auto' }}><Icon name="map-pinned" size={22} color="var(--blue-500)" /></span>
          <div style={{ flex:1, minWidth:0 }}>
            <div style={{ fontSize:15.5, fontWeight:800, color:'var(--ink)' }}>Where's {child.first}?</div>
            <div style={{ fontSize:12.5, color:'var(--gray-500)' }}>Live journey · bus, school &amp; pickup</div>
          </div>
          <span className="jl-pulse" style={{ width:9, height:9, borderRadius:'999px', background:'var(--success-500)', flex:'0 0 auto' }} />
        </button>

        {/* explore */}
        <SectionLabel>{jlT('explore')}</SectionLabel>
        <div style={cardWrap}>
          <ScheduleRow icon="heart-pulse" tint="var(--success-100)" ic="var(--success-500)" title={jlT('ex_safety')} sub="Mood check-ins · teacher feedback" onClick={()=>onNav('safety')} />
          <Divider />
          <ScheduleRow icon="calendar-check" tint="var(--gold-100)" ic="var(--gold-600)" title={jlT('ex_attendance')} sub={child.attendancePct + '% this year · report an absence'} onClick={()=>onNav('attendance')} />
          <Divider />
          <ScheduleRow icon="store" tint="var(--danger-100)" ic="var(--danger-500)" title={jlT('ex_marketplace')} sub="Tutoring, sports & programs" onClick={()=>onNav('marketplace')} />
          <Divider />
          <ScheduleRow icon="calendar-days" tint="var(--gold-100)" ic="var(--gold-600)" title={jlT('ex_calendar')} sub="Science Fair Jun 12 · RSVP" onClick={()=>onNav('calendar')} />
          <Divider />
          <ScheduleRow icon="file-signature" tint="var(--info-100)" ic="var(--info-500)" title={jlT('ex_forms')} sub="3 forms need signing" onClick={()=>onNav('forms')} />
          <Divider />
          <ScheduleRow icon="heart-pulse" tint="var(--success-100)" ic="var(--success-500)" title={jlT('ex_health')} sub="Allergies · meds · visits" onClick={()=>onNav('health')} />
          <Divider />
          <ScheduleRow icon="folder" tint="var(--blue-100)" ic="var(--blue-500)" title="Documents" sub="Handbooks, newsletters & forms" onClick={()=>onNav('docs')} />
          <Divider />
          <ScheduleRow icon="user-plus" tint="var(--gold-100)" ic="var(--gold-600)" title="Application Status" sub="Enrollment & waitlist" onClick={()=>onNav('waitlist')} />
          <Divider />
          <ScheduleRow icon="nfc" tint="var(--blue-100)" ic="var(--blue-500)" title="Wristband" sub="Pair &amp; manage tap-to-board band" onClick={()=>onNav('wristband')} />
          <Divider />
          <ScheduleRow icon="watch" tint="var(--danger-100)" ic="var(--danger-500)" title="GPS Watch" sub="Live location · battery · SOS" onClick={()=>onNav('watch')} />
          <Divider />
          <ScheduleRow icon="award" tint="var(--info-100)" ic="var(--info-500)" title={jlT('ex_involvement')} sub={'Engagement score · ' + child.engagementScore} onClick={()=>onNav('engagement')} />
        </div>

        {/* today's schedule */}
        {hw && (() => { const next = (hw.items||[]).find(h=>!h.done); return (
          <React.Fragment>
            <SectionLabel>Homework</SectionLabel>
            <div style={cardWrap}>
              <div style={{ display:'flex', alignItems:'center', gap:12, padding:'13px 14px' }}>
                <span style={{ width:38, height:38, borderRadius:10, background: hw.done>=hw.total?'var(--success-100)':'var(--blue-100)', display:'flex', alignItems:'center', justifyContent:'center', flex:'0 0 auto' }}><Icon name={hw.done>=hw.total?'circle-check-big':'clipboard-list'} size={19} color={hw.done>=hw.total?'var(--success-500)':'var(--blue-500)'} /></span>
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ fontSize:14.5, fontWeight:700, color:'var(--ink)' }}>{hw.done} of {hw.total} done{next?' · '+next.title:''}</div>
                  <div style={{ fontSize:12.5, color:'var(--gray-500)' }}>{hw.done>=hw.total?child.first+' is all caught up':'Updated from '+child.first+'’s app'}</div>
                </div>
                <Pill bg={hw.done>=hw.total?'var(--success-100)':'var(--blue-100)'} fg={hw.done>=hw.total?'var(--success-600)':'var(--blue-600)'}>{Math.round((hw.done/hw.total)*100)}%</Pill>
              </div>
            </div>
          </React.Fragment>
        ); })()}

        {/* today's schedule */}
        <SectionLabel>{jlT('todays_schedule')}</SectionLabel>
        <div style={cardWrap}>
          <ScheduleRow icon="book-open" tint="var(--blue-100)" ic="var(--blue-500)" title="Math Homework" sub="Due today · 11:59 PM" />
          <Divider />
          <ScheduleRow icon="flask-conical" tint="var(--gold-100)" ic="var(--gold-600)" title="Science Quiz" sub="Tomorrow · 9:00 AM" />
        </div>

        {/* recent alerts */}
        <SectionLabel action={<span style={{ fontSize:12, fontWeight:700, color:'var(--blue-500)' }}>{jlT('view_all')}</span>}>{jlT('recent_alerts')}</SectionLabel>
        <div style={cardWrap}>
          <ScheduleRow icon="alert-triangle" tint="var(--danger-100)" ic="var(--danger-500)" title="Missing Assignment" sub="ELA · Due Apr 26" right={<Pill bg="var(--danger-100)" fg="var(--danger-600)">High</Pill>} onClick={()=>onNav('activities')} />
          <Divider />
          <ScheduleRow icon="message-circle" tint="var(--blue-100)" ic="var(--blue-500)" title="New message" sub="From Mrs. Johnson" onClick={()=>onNav('messages')} />
        </div>
      </div>
      <BottomNav active="home" onNav={onNav} />
    </div>
  );
}

function ScheduleRow({ icon, tint, ic, title, sub, right, onClick }) {
  return (
    <button onClick={onClick} style={{ width:'100%', display:'flex', alignItems:'center', gap:12, padding:'13px 14px', border:0, background:'transparent', cursor: onClick?'pointer':'default', fontFamily:'var(--font-sans)', textAlign:'left' }}>
      <span style={{ width:38, height:38, borderRadius:10, background:tint, display:'flex', alignItems:'center', justifyContent:'center', flex:'0 0 auto' }}>
        <Icon name={icon} size={19} color={ic} />
      </span>
      <div style={{ flex:1, minWidth:0 }}>
        <div style={{ fontSize:14.5, fontWeight:700, color:'var(--ink)' }}>{title}</div>
        <div style={{ fontSize:12.5, color:'var(--gray-500)' }}>{sub}</div>
      </div>
      {right || <Icon name="chevron-right" size={18} color="var(--gray-400)" />}
    </button>
  );
}
const cardWrap = { background:'#fff', border:'1px solid var(--gray-200)', borderRadius:14, boxShadow:'var(--shadow-sm)', overflow:'hidden' };
function Divider(){ return <div style={{ height:1, background:'var(--gray-200)', marginLeft:64 }} />; }

Object.assign(window, { HomeScreen, SectionLabel, ScheduleRow, Divider, cardWrap });
