/* Pickup / Dismissal plan */
function PickupScreen({ onBack }) {
  const days = ['Mon','Tue','Wed','Thu','Fri'];
  const [day, setDay] = React.useState('Wed');
  const [person, setPerson] = React.useState(null);
  const METHODS = [
    { id:'car', label:'Car Rider', icon:'car-front', time:'3:30 PM' },
    { id:'bus', label:'Bus Rider', icon:'bus-front', time:'3:25 PM' },
    { id:'walk', label:'Walker', icon:'footprints', time:'3:35 PM' },
    { id:'after', label:'Aftercare', icon:'clock', time:'5:30 PM' },
  ];
  const [method, setMethod] = React.useState('car');
  const [sheet, setSheet] = React.useState(false);
  const [people, setPeople] = React.useState([
    { initials:'JH', color:'navy', name:'Jermaine Hatten', rel:'Parent', phone:'(281) 555-0142' },
    { initials:'AH', color:'cyan', name:'Ashley Hatten', rel:'Parent', phone:'(281) 555-0177' },
  ]);
  const [addOpen, setAddOpen] = React.useState(false);
  const [qr, setQr] = React.useState(false);
  const [checkedIn, setCheckedIn] = React.useState(false);
  const [pos, setPos] = React.useState(4);
  React.useEffect(() => {
    if (!checkedIn || pos <= 1) return;
    const t = setTimeout(() => setPos(p => Math.max(1, p - 1)), 3200);
    return () => clearTimeout(t);
  }, [checkedIn, pos]);
  const doCheckIn = () => {
    setQr(false); setCheckedIn(true); setPos(4);
    jlToast('Checked in · the school knows you\u2019re here', { icon:'check-check' });
  };
  const [fName, setFName] = React.useState('');
  const [fRel, setFRel] = React.useState('');
  const [fPhone, setFPhone] = React.useState('');
  const ADD_COLORS = ['gold','green','red','blue','navy','cyan'];
  const initialsOf = (n) => n.trim().split(/\s+/).map(w=>w[0]).slice(0,2).join('').toUpperCase() || '?';
  const canSave = fName.trim() && fRel.trim();
  const savePerson = () => {
    if (!canSave) return;
    const p = { initials: initialsOf(fName), color: ADD_COLORS[people.length % ADD_COLORS.length], name: fName.trim(), rel: fRel.trim(), phone: fPhone.trim() || 'No phone added' };
    setPeople(ps => [...ps, p]);
    setAddOpen(false); setFName(''); setFRel(''); setFPhone('');
    jlToast(p.name + ' added as authorized', { icon:'user-check' });
  };
  const cur = METHODS.find(m => m.id===method);
  return (
    <div style={{ background:'var(--gray-50)', minHeight:'100%' }}>
      <PushBar title="Pickup Plan" onBack={onBack} />
      <div style={{ padding:'14px 18px 40px' }}>
        {/* day picker */}
        <div style={{ display:'flex', gap:8, marginBottom:16 }}>
          {days.map(d => (
            <button key={d} onClick={()=>setDay(d)} style={{
              flex:1, padding:'10px 0', borderRadius:12, border:0, cursor:'pointer',
              fontWeight:700, fontSize:13, fontFamily:'var(--font-sans)',
              background: day===d ? 'var(--navy-600)' : '#fff',
              color: day===d ? '#fff' : 'var(--gray-600)',
              boxShadow: day===d ? 'none' : 'inset 0 0 0 1px var(--gray-200)',
            }}>{d}</button>
          ))}
        </div>

        {/* today's pickup */}
        <div style={{ background:'#fff', border:'1px solid var(--gray-200)', borderRadius:16, padding:'18px', boxShadow:'var(--shadow-sm)' }}>
          <div style={{ fontSize:11, fontWeight:800, letterSpacing:'.09em', color:'var(--gray-500)' }}>TODAY'S PICKUP</div>
          <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', margin:'8px 0 2px' }}>
            <div style={{ fontSize:26, fontWeight:800, color:'var(--ink)', letterSpacing:'-.01em' }}>{cur.label}</div>
            <span style={{ width:48, height:48, borderRadius:14, background:'var(--gold-100)', display:'flex', alignItems:'center', justifyContent:'center' }}>
              <Icon name={cur.icon} size={26} color="var(--gold-600)" />
            </span>
          </div>
          <div style={{ fontSize:16, fontWeight:700, color:'var(--blue-500)' }}>{cur.time}</div>
          <div style={{ fontSize:13, color:'var(--gray-500)', marginTop:6 }}>You · Katy Middle School</div>
          {!checkedIn ? (
            <button onClick={()=>setQr(true)} style={{ width:'100%', marginTop:16, display:'flex', alignItems:'center', justifyContent:'center', gap:9, background:'var(--gold-400)', color:'var(--on-gold)', border:0, borderRadius:12, padding:'14px', fontWeight:800, fontSize:15, cursor:'pointer', fontFamily:'var(--font-sans)', boxShadow:'var(--shadow-gold)' }}>
              <Icon name="qr-code" size={19} color="var(--on-gold)" />I'm Here — Check In
            </button>
          ) : (
            <div style={{ display:'flex', alignItems:'center', gap:9, marginTop:16, background:'var(--success-100)', borderRadius:12, padding:'12px 14px' }}>
              <Icon name="circle-check-big" size={20} color="var(--success-500)" />
              <span style={{ fontSize:14, fontWeight:700, color:'var(--success-600)' }}>Checked in at {new Date().toLocaleTimeString([], {hour:'numeric', minute:'2-digit'})}</span>
            </div>
          )}
          <button onClick={()=>setSheet(true)} style={{ width:'100%', marginTop:9, background:'#fff', color:'var(--navy-600)', border:'1px solid var(--gray-200)', borderRadius:12, padding:'12px', fontWeight:700, fontSize:14, cursor:'pointer', fontFamily:'var(--font-sans)' }}>Change Pickup Method</button>
        </div>

        {/* live queue (after check-in) */}
        {checkedIn && (
          <div style={{ marginTop:14, background:'var(--grad-hero)', borderRadius:16, padding:'17px 18px', color:'#fff', boxShadow:'var(--shadow-navy)' }}>
            <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between' }}>
              <div style={{ fontSize:10, fontWeight:800, letterSpacing:'.1em', color:'rgba(255,255,255,.7)' }}>LIVE PICKUP QUEUE</div>
              <span style={{ display:'inline-flex', alignItems:'center', gap:6, fontSize:11, fontWeight:700, color:'rgba(255,255,255,.85)' }}>
                <span className="jl-pulse" style={{ width:7, height:7, borderRadius:'999px', background:'var(--gold-400)' }} />Live
              </span>
            </div>
            <div style={{ display:'flex', alignItems:'flex-end', gap:10, margin:'8px 0 4px' }}>
              <div style={{ fontSize:46, fontWeight:800, lineHeight:.9, fontFamily:'var(--font-mono)' }}>{pos>1 ? '#'+pos : 'Next'}</div>
              <div style={{ fontSize:14, fontWeight:600, color:'rgba(255,255,255,.82)', paddingBottom:6 }}>
                {pos>1 ? 'in the car-rider line' : 'EJ is heading out now'}
              </div>
            </div>
            <div style={{ display:'flex', gap:6, marginTop:12 }}>
              {[1,2,3,4,5].map(n => (
                <div key={n} style={{ flex:1, height:6, borderRadius:'999px', background: n >= pos ? 'var(--gold-400)' : 'rgba(255,255,255,.22)' }} />
              ))}
            </div>
            <div style={{ fontSize:12, color:'rgba(255,255,255,.72)', marginTop:10 }}>
              {pos>1 ? 'Staff are calling students as cars arrive. Please stay in your vehicle.' : 'A staff member is walking EJ to your car.'}
            </div>
          </div>
        )}

        {/* authorized pickups */}
        <SectionLabel>Authorized Pickups</SectionLabel>
        <div style={cardWrap}>
          {people.map((p, i) => (
            <React.Fragment key={p.name + i}>
              {i > 0 && <Divider />}
              <PersonRow initials={p.initials} color={p.color} name={p.name} rel={p.rel} onClick={()=>setPerson(p)} />
            </React.Fragment>
          ))}
        </div>
        <button onClick={()=>setAddOpen(true)} style={{ width:'100%', marginTop:12, display:'flex', alignItems:'center', justifyContent:'center', gap:8, background:'#fff', color:'var(--navy-600)', border:'1.5px dashed var(--gray-300)', borderRadius:12, padding:'13px', fontWeight:700, fontSize:14, cursor:'pointer', fontFamily:'var(--font-sans)' }}>
          <Icon name="plus" size={18} color="var(--navy-600)" />Add Authorized Person
        </button>

        {/* proximity banner */}
        <div style={{ display:'flex', alignItems:'center', gap:11, marginTop:16, background:'var(--success-100)', borderRadius:14, padding:'14px 16px' }}>
          <span style={{ width:36, height:36, borderRadius:'999px', background:'var(--success-500)', display:'flex', alignItems:'center', justifyContent:'center', flex:'0 0 auto' }}><Icon name="map-pin" size={18} color="#fff" /></span>
          <div style={{ flex:1 }}>
            <div style={{ display:'flex', alignItems:'center', gap:7 }}>
              <span style={{ width:7, height:7, borderRadius:'999px', background:'var(--success-500)', flex:'0 0 auto' }} />
              <div style={{ fontSize:14, fontWeight:700, color:'var(--success-600)' }}>You are 2 mins away</div>
            </div>
            <div style={{ fontSize:12.5, color:'var(--success-600)', opacity:.85, marginTop:2 }}>Live from your location · we'll tell the school you're on the way.</div>
          </div>
        </div>
      </div>

      {/* bottom sheet: choose method */}
      {sheet && (
        <div onClick={()=>setSheet(false)} style={{ position:'absolute', inset:0, zIndex:60, 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 34px' }}>
            <div style={{ width:40, height:4, borderRadius:'999px', background:'var(--gray-300)', margin:'0 auto 14px' }} />
            <div style={{ fontSize:17, fontWeight:800, color:'var(--ink)', marginBottom:12 }}>Change Pickup Method</div>
            {METHODS.map(m => {
              const on = m.id===method;
              return (
                <button key={m.id} onClick={()=>{ setMethod(m.id); setSheet(false); }} style={{
                  width:'100%', display:'flex', alignItems:'center', gap:13, padding:'13px 14px', marginBottom:9,
                  border: on?'1.5px solid var(--blue-500)':'1px solid var(--gray-200)', borderRadius:14,
                  background: on?'var(--blue-100)':'#fff', cursor:'pointer', fontFamily:'var(--font-sans)', textAlign:'left',
                }}>
                  <span style={{ width:40, height:40, borderRadius:11, background: on?'#fff':'var(--gray-100)', display:'flex', alignItems:'center', justifyContent:'center', flex:'0 0 auto' }}>
                    <Icon name={m.icon} size={20} color={on?'var(--blue-600)':'var(--gray-600)'} />
                  </span>
                  <div style={{ flex:1 }}>
                    <div style={{ fontSize:15, fontWeight:700, color:'var(--ink)' }}>{m.label}</div>
                    <div style={{ fontSize:12.5, color:'var(--gray-500)' }}>Dismissal {m.time}</div>
                  </div>
                  {on && <Icon name="check" size={20} color="var(--blue-600)" />}
                </button>
              );
            })}
          </div>
        </div>
      )}
      {/* bottom sheet: QR check-in */}
      {qr && (
        <div onClick={()=>setQr(false)} style={{ position:'absolute', inset:0, zIndex:60, 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 32px' }}>
            <div style={{ width:40, height:4, borderRadius:'999px', background:'var(--gray-300)', margin:'0 auto 16px' }} />
            <div style={{ textAlign:'center' }}>
              <div style={{ fontSize:19, fontWeight:800, color:'var(--ink)' }}>Check In for Pickup</div>
              <div style={{ fontSize:13, color:'var(--gray-500)', marginTop:3 }}>Hold this code up at the gate scanner</div>
            </div>
            <div style={{ display:'flex', justifyContent:'center', margin:'18px 0 14px' }}>
              <div style={{ padding:16, background:'#fff', borderRadius:18, boxShadow:'var(--shadow-md)', border:'1px solid var(--gray-200)' }}>
                <FakeQR size={176} />
                <div style={{ display:'flex', alignItems:'center', justifyContent:'center', gap:7, marginTop:12 }}>
                  <Avatar initials="EJ" color="green" size={26} />
                  <span style={{ fontSize:13.5, fontWeight:700, color:'var(--ink)' }}>EJ Hatten · Car Rider</span>
                </div>
              </div>
            </div>
            <div style={{ display:'flex', alignItems:'center', gap:8, justifyContent:'center', color:'var(--gray-400)', margin:'4px 0 14px' }}>
              <div style={{ flex:1, height:1, background:'var(--gray-200)' }} />
              <span style={{ fontSize:12, fontWeight:700 }}>or</span>
              <div style={{ flex:1, height:1, background:'var(--gray-200)' }} />
            </div>
            <button onClick={doCheckIn} style={{ width:'100%', display:'flex', alignItems:'center', justifyContent:'center', gap:9, background:'var(--navy-600)', color:'#fff', border:0, borderRadius:12, padding:'14px', fontWeight:700, fontSize:14.5, cursor:'pointer', fontFamily:'var(--font-sans)' }}>
              <Icon name="map-pin" size={18} color="#fff" />Check In with GPS Instead
            </button>
            <button onClick={()=>setQr(false)} style={{ width:'100%', marginTop:9, background:'transparent', color:'var(--gray-500)', border:0, padding:'10px', fontWeight:700, fontSize:14, cursor:'pointer', fontFamily:'var(--font-sans)' }}>Cancel</button>
          </div>
        </div>
      )}

      {/* bottom sheet: authorized person detail */}
      {person && (
        <div onClick={()=>setPerson(null)} style={{ position:'absolute', inset:0, zIndex:60, 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 34px' }}>
            <div style={{ width:40, height:4, borderRadius:'999px', background:'var(--gray-300)', margin:'0 auto 16px' }} />
            <div style={{ display:'flex', alignItems:'center', gap:13, marginBottom:18 }}>
              <Avatar initials={person.initials} color={person.color} size={52} />
              <div style={{ flex:1 }}>
                <div style={{ fontSize:18, fontWeight:800, color:'var(--ink)' }}>{person.name}</div>
                <div style={{ fontSize:13, color:'var(--gray-500)' }}>{person.rel} · Authorized</div>
              </div>
              <Pill bg="var(--success-100)" fg="var(--success-600)"><Icon name="shield-check" size={13} color="var(--success-600)" />Verified</Pill>
            </div>
            <div style={{ display:'flex', alignItems:'center', gap:11, padding:'13px 0', borderTop:'1px solid var(--gray-100)' }}>
              <Icon name="phone" size={18} color="var(--gray-500)" />
              <span style={{ flex:1, fontSize:14.5, color:'var(--ink)', fontWeight:600 }}>{person.phone}</span>
            </div>
            <div style={{ display:'flex', alignItems:'center', gap:11, padding:'13px 0', borderTop:'1px solid var(--gray-100)' }}>
              <Icon name="badge-check" size={18} color="var(--gray-500)" />
              <span style={{ flex:1, fontSize:14.5, color:'var(--ink)', fontWeight:600 }}>Can pick up EJ Hatten</span>
            </div>
            <div style={{ display:'flex', gap:10, marginTop:16 }}>
              <button onClick={()=>{ jlToast('Calling '+person.name+'…', { icon:'phone' }); setPerson(null); }} style={{ flex:1, display:'flex', alignItems:'center', justifyContent:'center', gap:8, background:'var(--navy-600)', color:'#fff', border:0, borderRadius:12, padding:'14px', fontWeight:700, fontSize:14.5, cursor:'pointer', fontFamily:'var(--font-sans)' }}><Icon name="phone" size={17} color="#fff" />Call</button>
              <button onClick={()=>{ setPeople(ps => ps.filter(x => x.name !== person.name)); jlToast(person.name+' removed', { icon:'user-minus', color:'#E5484D' }); setPerson(null); }} style={{ flex:'0 0 auto', display:'flex', alignItems:'center', justifyContent:'center', gap:8, background:'#fff', color:'var(--danger-500)', border:'1px solid var(--gray-200)', borderRadius:12, padding:'14px 18px', fontWeight:700, fontSize:14.5, cursor:'pointer', fontFamily:'var(--font-sans)' }}><Icon name="trash-2" size={17} color="var(--danger-500)" />Remove</button>
            </div>
          </div>
        </div>
      )}

      {/* bottom sheet: add authorized person */}
      {addOpen && (
        <div onClick={()=>setAddOpen(false)} style={{ position:'absolute', inset:0, zIndex:60, 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={{ display:'flex', alignItems:'center', gap:11, marginBottom:16 }}>
              <span style={{ width:42, height:42, borderRadius:12, background:'var(--blue-100)', display:'flex', alignItems:'center', justifyContent:'center', flex:'0 0 auto' }}><Icon name="user-plus" size={21} color="var(--blue-600)" /></span>
              <div>
                <div style={{ fontSize:18, fontWeight:800, color:'var(--ink)' }}>Add Authorized Person</div>
                <div style={{ fontSize:13, color:'var(--gray-500)' }}>Who can pick up EJ Hatten?</div>
              </div>
            </div>

            <AddField label="Full name" value={fName} onChange={setFName} placeholder="e.g. Grandma Rose" icon="user" />
            <AddField label="Relationship" value={fRel} onChange={setFRel} placeholder="e.g. Grandparent" icon="users" />
            <AddField label="Phone (optional)" value={fPhone} onChange={setFPhone} placeholder="(281) 555-0000" icon="phone" />

            <button onClick={savePerson} disabled={!canSave} style={{ width:'100%', marginTop:6, display:'flex', alignItems:'center', justifyContent:'center', gap:8, background: canSave?'var(--gold-400)':'var(--gray-200)', color: canSave?'var(--on-gold)':'var(--gray-500)', border:0, borderRadius:12, padding:'15px', fontWeight:800, fontSize:15, cursor: canSave?'pointer':'not-allowed', fontFamily:'var(--font-sans)', boxShadow: canSave?'var(--shadow-gold)':'none' }}>
              <Icon name="check" size={17} color={canSave?'var(--on-gold)':'var(--gray-500)'} />Add Person
            </button>
            <button onClick={()=>setAddOpen(false)} style={{ width:'100%', marginTop:9, background:'transparent', color:'var(--gray-500)', border:0, padding:'10px', fontWeight:700, fontSize:14, cursor:'pointer', fontFamily:'var(--font-sans)' }}>Cancel</button>
          </div>
        </div>
      )}
    </div>
  );
}
function AddField({ label, value, onChange, placeholder, icon }) {
  return (
    <div style={{ marginBottom:12 }}>
      <div style={{ fontSize:12, fontWeight:700, color:'var(--gray-500)', marginBottom:6 }}>{label}</div>
      <div style={{ display:'flex', alignItems:'center', gap:10, background:'var(--gray-100)', border:'1.5px solid var(--gray-200)', borderRadius:12, padding:'12px 13px' }}>
        <Icon name={icon} size={17} color="var(--gray-500)" />
        <input value={value} onChange={e=>onChange(e.target.value)} placeholder={placeholder} style={{ flex:1, border:0, background:'transparent', outline:'none', fontSize:14.5, fontFamily:'var(--font-sans)', color:'var(--ink)' }} />
      </div>
    </div>
  );
}
function PersonRow({ initials, color, name, rel, onClick }) {
  return (
    <button onClick={onClick} style={{ width:'100%', textAlign:'left', background:'transparent', border:0, cursor:'pointer', fontFamily:'var(--font-sans)', display:'flex', alignItems:'center', gap:12, padding:'12px 14px' }}>
      <Avatar initials={initials} color={color} size={38} />
      <div style={{ flex:1 }}>
        <div style={{ fontSize:14.5, fontWeight:700, color:'var(--ink)' }}>{name}</div>
        <div style={{ fontSize:12.5, color:'var(--gray-500)' }}>{rel}</div>
      </div>
      <Icon name="chevron-right" size={18} color="var(--gray-400)" />
    </button>
  );
}

/* Stylized QR — deterministic module grid (a visual mock, not a real code). */
function FakeQR({ size = 176 }) {
  const N = 21;
  const finderCell = (r, c) => {
    // relative position within whichever 7x7 finder this cell is in
    let rr = r, cc = c;
    if (r >= N - 7) rr = r - (N - 7);
    if (c >= N - 7) cc = c - (N - 7);
    rr = rr % 7; cc = cc % 7;
    const ring = rr === 0 || rr === 6 || cc === 0 || cc === 6;
    const core = rr >= 2 && rr <= 4 && cc >= 2 && cc <= 4;
    return ring || core;
  };
  const cells = [];
  for (let r = 0; r < N; r++) {
    for (let c = 0; c < N; c++) {
      const inFinder = (r < 7 && c < 7) || (r < 7 && c >= N - 7) || (r >= N - 7 && c < 7);
      let on;
      if (inFinder) on = finderCell(r, c);
      else on = ((r * 13 + c * 7 + r * c * 3 + 5) % 5) < 2;
      cells.push(on);
    }
  }
  return (
    <div style={{ width:size, height:size, display:'grid', gridTemplateColumns:`repeat(${N}, 1fr)`, gridTemplateRows:`repeat(${N}, 1fr)`, gap:0 }}>
      {cells.map((on, i) => (
        <div key={i} style={{ background: on ? 'var(--ink)' : 'transparent' }} />
      ))}
    </div>
  );
}

Object.assign(window, { PickupScreen });
