/* Parent → "Where's my child now?" — a live timeline pulling every tracking signal. */
function TimelineScreen({ onNav, onBack }) {
  const child = jlChild();
  const [bus, setBus] = React.useState(null);
  const [roster, setRoster] = React.useState(null);
  const [pickup, setPickup] = React.useState(null);
  const [att, setAtt] = React.useState(null);
  React.useEffect(() => {
    const read = () => {
      try {
        setBus(JSON.parse(localStorage.getItem('jl_buspos') || 'null'));
        setRoster((JSON.parse(localStorage.getItem('jl_roster') || '{}'))[child.id] || null);
        setPickup(JSON.parse(localStorage.getItem('jl_pickup') || 'null'));
        setAtt((JSON.parse(localStorage.getItem('jl_attendance') || '{}'))[child.id] || null);
      } catch(e){}
    };
    read();
    const iv = setInterval(read, 1500);
    window.addEventListener('storage', read);
    return () => { clearInterval(iv); window.removeEventListener('storage', read); };
  }, [child.id]);

  // derive current status + step states
  const boarded = roster && roster.status === 'boarded';
  const atSchool = att && (att.status === 'present' || att.status === 'tardy') || boarded;
  const pickedUp = pickup && pickup.done;
  const cur = pickedUp ? 'Picked up' : atSchool ? 'At school' : boarded ? 'On the bus' : 'Getting ready';

  const steps = [
    { key:'home',   icon:'home',            title:'Left for school', sub: roster ? (boarded ? child.first + ' boarded ' + child.bus + (roster.stop?' at '+roster.stop:'') : 'Waiting at the stop') : 'Morning routine', done: !!boarded || atSchool || pickedUp, live:!boarded && !atSchool && !pickedUp },
    { key:'bus',    icon:'bus-front',       title:'On the bus', sub: bus ? ('Next: ' + bus.nextStop + ' · ETA ' + bus.eta + ' min') : (boarded ? 'On board '+child.bus : 'Not on route yet'), done: atSchool || pickedUp, live: boarded && !atSchool && !pickedUp },
    { key:'school', icon:'school',          title:'Arrived at school', sub: att ? (att.status==='tardy' ? 'Marked tardy · ' + (att.at||'') : 'Marked present' + (att.at?' · '+att.at:'')) : 'Homeroom check-in', done: pickedUp, live: atSchool && !pickedUp },
    { key:'day',    icon:'book-open',       title:'In class', sub:'Following the daily schedule', done: pickedUp, live: atSchool && !pickedUp },
    { key:'out',    icon:'car-front',       title:'Dismissal', sub: pickedUp ? (child.first + ' was picked up' + (pickup.at?' at '+pickup.at:'')) : 'Not dismissed yet', done: pickedUp, live: pickedUp },
  ];

  return (
    <div style={{ background:'var(--gray-50)', minHeight:'100%' }}>
      <PushBar title={"Where's " + child.first + '?'} onBack={onBack} />
      <div style={{ padding:'14px 18px 40px' }}>
        {/* current status hero */}
        <div style={{ background:'var(--color-grad-hero)', borderRadius:18, padding:'18px', color:'#fff', boxShadow:'var(--shadow-navy)' }}>
          <div style={{ display:'flex', alignItems:'center', gap:13 }}>
            <Avatar initials={child.initials} color={child.color} size={46} />
            <div style={{ flex:1 }}>
              <div style={{ fontSize:10, fontWeight:800, letterSpacing:'.1em', color:'rgba(255,255,255,.7)' }}>RIGHT NOW</div>
              <div style={{ fontSize:22, fontWeight:800 }}>{cur}</div>
            </div>
            <span className="jl-pulse" style={{ display:'inline-flex', alignItems:'center', gap:6, fontSize:11, fontWeight:700, color:'rgba(255,255,255,.85)' }}><span style={{ width:7, height:7, borderRadius:'999px', background:'var(--success-tint)' }} />Live</span>
          </div>
        </div>

        {/* timeline */}
        <SectionLabel>Today's Journey</SectionLabel>
        <div style={{ position:'relative', paddingLeft:6 }}>
          {steps.map((s,i) => {
            const color = s.done ? 'var(--success-500)' : s.live ? 'var(--blue-500)' : 'var(--gray-300)';
            return (
              <div key={s.key} style={{ display:'flex', gap:14, position:'relative' }}>
                {/* rail */}
                <div style={{ display:'flex', flexDirection:'column', alignItems:'center', flex:'0 0 auto' }}>
                  <span className={s.live?'jl-pulse':''} style={{ width:34, height:34, borderRadius:'999px', background: s.done||s.live?color:'#fff', border: s.done||s.live?'0':'2px solid var(--gray-200)', display:'flex', alignItems:'center', justifyContent:'center', zIndex:1 }}>
                    <Icon name={s.done?'check':s.icon} size={17} color={s.done||s.live?'#fff':'var(--gray-400)'} stroke={2.2} />
                  </span>
                  {i<steps.length-1 && <span style={{ width:2, flex:1, minHeight:26, background: s.done?'var(--success-500)':'var(--gray-200)' }} />}
                </div>
                {/* content */}
                <div style={{ flex:1, paddingBottom:18 }}>
                  <div style={{ fontSize:15, fontWeight:700, color: s.done||s.live?'var(--ink)':'var(--gray-400)' }}>{s.title}</div>
                  <div style={{ fontSize:12.5, color:'var(--gray-500)', marginTop:2 }}>{s.sub}</div>
                  {s.live && <Pill bg="var(--blue-100)" fg="var(--blue-600)" style={{ marginTop:7 }}>Now</Pill>}
                </div>
              </div>
            );
          })}
        </div>

        {/* jump links */}
        <SectionLabel>Details</SectionLabel>
        <div style={cardWrap}>
          <ScheduleRow icon="bus" tint="var(--gold-100)" ic="var(--gold-600)" title="Bus &amp; transport" sub="Live map &amp; ETA" onClick={()=>onNav('transport')} />
          <Divider />
          <ScheduleRow icon="calendar-check" tint="var(--blue-100)" ic="var(--blue-500)" title="Attendance" sub="Today's check-in" onClick={()=>onNav('attendance')} />
          <Divider />
          <ScheduleRow icon="car-front" tint="var(--success-100)" ic="var(--success-500)" title="Pickup" sub="Dismissal &amp; check-in" onClick={()=>onNav('pickup')} />
        </div>
      </div>
    </div>
  );
}
Object.assign(window, { TimelineScreen });
