/* Help & Support — searchable help center covering every parent-app feature */
const JL_HELP = [
  { cat:'Getting Started', icon:'rocket', tint:'var(--blue-100)', ic:'var(--blue-500)', items:[
    { q:'How do I sign in?', a:[
      'Open JewelLink and enter the email and password your school provided.',
      'You can also tap Continue with Google or Apple if your school enabled it.',
      'Forgot your password? Tap “Forgot password?” on the login screen to reset it by email.',
    ]},
    { q:'How do I find my child?', a:[
      'Your children are linked automatically by the school when your account is created.',
      'Tap the child card at the top of the Home screen to switch between children.',
      'If a child is missing, contact your school office to confirm the link.',
    ]},
    { q:'How do I get around the app?', a:[
      'Use the bottom tabs: Home, Messages, Transport, Activities, and Profile.',
      'Home has Quick Actions (Pickup, Grades, Lunch, AI Tutor) and an Explore list for everything else.',
      'Every screen except Home has a back arrow in the top-left corner.',
    ]},
  ]},
  { cat:'Pickup & Dismissal', icon:'car-front', tint:'var(--gold-100)', ic:'var(--gold-600)', items:[
    { q:'How do I check in for pickup?', a:[
      'Open Pickup from Home and tap “I’m Here — Check In”.',
      'Hold the QR code up to the gate scanner, or tap “Check In with GPS Instead”.',
      'Once checked in, you’ll see your live position in the car-rider queue.',
    ]},
    { q:'What does the live queue show?', a:[
      'Your number in the car-rider line, updated in real time as cars are cleared.',
      'When it says “Next”, a staff member is walking your child to your car.',
      'Please stay in your vehicle until your child is brought out.',
    ]},
    { q:'How do I change the pickup method?', a:[
      'In Pickup, tap “Change Pickup Method” and choose Car, Bus, Walker, or Aftercare.',
      'You can set a different method for each day using the day picker at the top.',
    ]},
    { q:'How do I add an authorized pickup person?', a:[
      'In Pickup, scroll to Authorized Pickups and tap “Add Authorized Person”.',
      'Enter their name, relationship, and phone, then tap Add Person.',
      'They’ll appear as a verified pickup contact for your child.',
    ]},
  ]},
  { cat:'Transport', icon:'bus', tint:'var(--info-100)', ic:'var(--info-500)', items:[
    { q:'How do I track the bus?', a:[
      'Tap the bus status card on Home, or open the Transport tab.',
      'You’ll see the live map, the driver, the route, and the estimated arrival time.',
    ]},
    { q:'Will I be notified when the bus is near?', a:[
      'Yes. You’ll get a push notification as the bus approaches your stop.',
      'Make sure notifications are enabled in Profile → Notifications.',
    ]},
  ]},
  { cat:'Grades', icon:'graduation-cap', tint:'var(--blue-100)', ic:'var(--blue-500)', items:[
    { q:'Where do I see my child’s grades?', a:[
      'Tap Grades from the Home Quick Actions.',
      'You’ll see the overall GPA, a grade for each subject, and recently graded work.',
    ]},
    { q:'How often do grades update?', a:[
      'Grades sync live from the school’s grade book, usually within minutes of a teacher posting.',
      'The “Live sync” line shows when grades were last updated.',
    ]},
  ]},
  { cat:'Lunch & Fees', icon:'utensils', tint:'var(--success-100)', ic:'var(--success-500)', items:[
    { q:'How do I add money to the lunch account?', a:[
      'Open Lunch & Fees and tap Add Funds.',
      'Choose an amount, confirm your card, and tap Pay.',
      'The balance updates instantly and appears in Recent Activity.',
    ]},
    { q:'What is auto-reload?', a:[
      'Auto-reload adds a set amount automatically when the balance drops below $10.',
      'Toggle it on or off from the Lunch & Fees screen.',
    ]},
    { q:'How do I pay a school fee?', a:[
      'Outstanding fees (field trips, supplies) appear in Lunch & Fees.',
      'Tap the amount button on a fee to pay it securely.',
    ]},
  ]},
  { cat:'AI Tutor', icon:'bot', tint:'var(--info-100)', ic:'var(--info-500)', items:[
    { q:'What is the AI Tutor?', a:[
      'A friendly homework helper for your child, opened from Home or the Activities screen.',
      'It explains concepts in simple terms and guides step by step rather than just giving answers.',
    ]},
    { q:'What can my child ask it?', a:[
      'Anything school-related — math, science, reading, study help, or practice questions.',
      'Tap a suggestion chip to get started, or type a question.',
    ]},
    { q:'Is it safe for kids?', a:[
      'Yes. It’s designed for age-appropriate, schoolwork-focused answers and steers away from off-topic requests.',
      'A live internet connection is required for the tutor to respond.',
    ]},
  ]},
  { cat:'Safety & Wellbeing', icon:'heart-pulse', tint:'var(--success-100)', ic:'var(--success-500)', items:[
    { q:'What are mood check-ins?', a:[
      'Your child can log how they’re feeling during homeroom each day.',
      'You’ll see the week’s moods and today’s check-in on the Safety & Wellbeing screen.',
    ]},
    { q:'What is the AI Wellbeing Insight?', a:[
      'It gently highlights patterns — for example, mood dips on certain days — to help you support your child.',
      'Insights are suggestions, not diagnoses. Reach out to the school counselor with any concerns.',
    ]},
  ]},
  { cat:'Attendance', icon:'calendar-check', tint:'var(--gold-100)', ic:'var(--gold-600)', items:[
    { q:'How do I report an absence?', a:[
      'Open Attendance and tap “Report an Absence”.',
      'Pick the day, choose a reason, add an optional note, and tap Submit Report.',
      'The front office is notified right away.',
    ]},
    { q:'What is the attendance pattern alert?', a:[
      'If your child is often absent or late on the same weekday, you’ll see an early heads-up.',
      'Catching patterns early helps prevent chronic absence.',
    ]},
  ]},
  { cat:'Marketplace', icon:'store', tint:'var(--danger-100)', ic:'var(--danger-500)', items:[
    { q:'What is the Marketplace?', a:[
      'A directory of school-approved programs — tutoring, sports, after-school clubs, and enrichment.',
      'Filter by category and tap Enroll to send a request, or bookmark a listing for later.',
    ]},
    { q:'How do fundraisers work?', a:[
      'Active school fundraisers appear at the top of the Marketplace with a progress bar.',
      'Tap Donate to contribute securely through JewelLink.',
    ]},
    { q:'Are vendors trustworthy?', a:[
      'Every vendor is reviewed and approved by your school before it appears here.',
      'Payments are processed securely through JewelLink.',
    ]},
  ]},
  { cat:'Messages', icon:'message-circle', tint:'var(--info-100)', ic:'var(--info-500)', items:[
    { q:'How do I message a teacher?', a:[
      'Open the Messages tab and choose a conversation, or start a new one.',
      'There’s one thread per child to keep things organized.',
    ]},
    { q:'What is the AI Summary in a chat?', a:[
      'Tap the AI Summary toggle in a long thread to get a quick recap of what was discussed.',
    ]},
  ]},
  { cat:'Emergency Alerts', icon:'siren', tint:'var(--danger-100)', ic:'var(--danger-500)', items:[
    { q:'What are emergency alerts?', a:[
      'Urgent school-wide notices — early dismissals, weather closures, or safety updates.',
      'They appear as a red banner at the top of Home and as a push notification.',
    ]},
    { q:'Can I turn them off?', a:[
      'Emergency alerts can’t be disabled — they’re essential for your child’s safety.',
      'You can dismiss a banner once you’ve read it by tapping the X.',
    ]},
  ]},
  { cat:'Account & Privacy', icon:'shield-check', tint:'var(--gray-200)', ic:'var(--gray-600)', items:[
    { q:'How do I change my password?', a:[
      'Go to Profile → Security → Change Password.',
      'You can also enable Face ID / biometrics for faster, secure sign-in.',
    ]},
    { q:'Who can see my information?', a:[
      'Only you and authorized school staff can see your child’s information.',
      'Your engagement score is private to you and never shared with other parents.',
    ]},
  ]},
];

function HelpRow({ q, a, open, onToggle }) {
  return (
    <div style={{ borderBottom:'1px solid var(--gray-100)' }}>
      <button onClick={onToggle} style={{ width:'100%', display:'flex', alignItems:'center', gap:10, padding:'13px 14px', background:'transparent', border:0, cursor:'pointer', fontFamily:'var(--font-sans)', textAlign:'left' }}>
        <div style={{ flex:1, fontSize:14, fontWeight:700, color:'var(--ink)' }}>{q}</div>
        <Icon name={open?'chevron-up':'chevron-down'} size={18} color="var(--gray-400)" />
      </button>
      {open && (
        <div style={{ padding:'0 14px 14px 14px' }}>
          {a.map((step,i) => (
            <div key={i} style={{ display:'flex', gap:9, marginTop: i?9:2 }}>
              {a.length > 1 && (
                <span style={{ width:20, height:20, borderRadius:'999px', background:'var(--blue-100)', color:'var(--blue-600)', fontSize:11, fontWeight:800, display:'flex', alignItems:'center', justifyContent:'center', flex:'0 0 auto', marginTop:1, fontFamily:'var(--font-mono)' }}>{i+1}</span>
              )}
              <div style={{ flex:1, fontSize:13.5, color:'var(--gray-600)', lineHeight:1.5 }}>{step}</div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

function HelpScreen({ onNav, onBack }) {
  const [query, setQuery] = React.useState('');
  const [open, setOpen] = React.useState(null);
  const q = query.trim().toLowerCase();
  const groups = JL_HELP
    .map(g => ({ ...g, items: g.items.filter(it => !q || it.q.toLowerCase().includes(q) || it.a.join(' ').toLowerCase().includes(q)) }))
    .filter(g => g.items.length);
  const total = groups.reduce((n,g)=>n+g.items.length, 0);

  return (
    <div style={{ background:'var(--gray-50)', minHeight:'100%' }}>
      <PushBar title="Help & Support" onBack={onBack} bell={false} />
      <div style={{ padding:'14px 18px 40px' }}>

        {/* search */}
        <div style={{ display:'flex', alignItems:'center', gap:10, background:'#fff', border:'1.5px solid var(--gray-200)', borderRadius:12, padding:'12px 14px', boxShadow:'var(--shadow-sm)' }}>
          <Icon name="search" size={18} color="var(--gray-400)" />
          <input value={query} onChange={e=>{ setQuery(e.target.value); setOpen(null); }} placeholder="Search help topics…" style={{ flex:1, border:0, background:'transparent', outline:'none', fontSize:14.5, fontFamily:'var(--font-sans)', color:'var(--ink)' }} />
          {query && <button onClick={()=>setQuery('')} style={{ border:0, background:'transparent', cursor:'pointer', display:'flex', padding:0 }}><Icon name="x" size={17} color="var(--gray-400)" /></button>}
        </div>

        {/* quick contact hero */}
        {!q && (
          <div style={{ background:'var(--grad-hero)', borderRadius:18, padding:'18px', color:'#fff', boxShadow:'var(--shadow-navy)', marginTop:14 }}>
            <div style={{ fontSize:10, fontWeight:800, letterSpacing:'.1em', color:'rgba(255,255,255,.7)' }}>NEED A HAND?</div>
            <div style={{ fontSize:18, fontWeight:800, margin:'6px 0 3px' }}>We're here to help</div>
            <div style={{ fontSize:12.5, color:'rgba(255,255,255,.8)', lineHeight:1.45 }}>Browse topics below, or reach the JewelLink support team and your school office directly.</div>
            <div style={{ display:'flex', gap:9, marginTop:14 }}>
              <button onClick={()=>onNav('messages')} style={{ flex:1, display:'flex', alignItems:'center', justifyContent:'center', gap:7, background:'#fff', color:'var(--navy-700)', border:0, borderRadius:11, padding:'11px', fontWeight:700, fontSize:13, cursor:'pointer', fontFamily:'var(--font-sans)' }}><Icon name="message-circle" size={16} color="var(--navy-700)" />Message</button>
              <button onClick={()=>jlToast('Calling school office…', { icon:'phone' })} style={{ flex:1, display:'flex', alignItems:'center', justifyContent:'center', gap:7, background:'rgba(255,255,255,.16)', color:'#fff', border:0, borderRadius:11, padding:'11px', fontWeight:700, fontSize:13, cursor:'pointer', fontFamily:'var(--font-sans)' }}><Icon name="phone" size={16} color="#fff" />Call Office</button>
            </div>
          </div>
        )}

        {/* results count when searching */}
        {q && (
          <div style={{ fontSize:13, color:'var(--gray-500)', margin:'14px 2px 0', fontWeight:600 }}>
            {total} {total===1?'result':'results'} for “{query}”
          </div>
        )}

        {/* topic groups */}
        {groups.length === 0 ? (
          <div style={{ textAlign:'center', padding:'40px 20px', color:'var(--gray-500)' }}>
            <Icon name="search-x" size={36} color="var(--gray-300)" />
            <div style={{ fontSize:15, fontWeight:700, color:'var(--ink)', marginTop:12 }}>No topics found</div>
            <div style={{ fontSize:13, marginTop:4 }}>Try different words, or message your school office.</div>
          </div>
        ) : groups.map(g => (
          <React.Fragment key={g.cat}>
            <div style={{ display:'flex', alignItems:'center', gap:10, margin:'20px 2px 10px' }}>
              <span style={{ width:30, height:30, borderRadius:8, background:g.tint, display:'flex', alignItems:'center', justifyContent:'center', flex:'0 0 auto' }}>
                <Icon name={g.icon} size={16} color={g.ic} />
              </span>
              <span style={{ fontSize:14.5, fontWeight:800, color:'var(--ink)', whiteSpace:'nowrap' }}>{g.cat}</span>
            </div>
            <div style={{ ...cardWrap }}>
              {g.items.map((it,i) => {
                const id = g.cat + '::' + it.q;
                return (
                  <HelpRow key={id} q={it.q} a={it.a} open={open===id} onToggle={()=>setOpen(open===id?null:id)} />
                );
              })}
            </div>
          </React.Fragment>
        ))}

        {/* footer */}
        <div style={{ textAlign:'center', marginTop:24, fontSize:12, color:'var(--gray-400)', lineHeight:1.6 }}>
          JewelLink EDU · Parent App<br/>Still stuck? Email support@jewellink.edu
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { HelpScreen });
