/* ============================================================
   MUIY — Help Center (rebuilt)
   A modern, patient-friendly help experience generated from the
   CURRENT app: onboarding · medical profile · transfusions +
   forecast · monitoring + lab OCR · ferritin + chelation · donors
   + eligibility · reminders · data & privacy · account.

   Search · categories · popular · recently updated · expandable
   answers · contact / feedback / privacy shortcuts.

   Loads AFTER me.jsx (so it overrides the old HelpSheet export),
   BEFORE shell.jsx. Uses globals: Sheet, Icon, Pearl, TC.
   ============================================================ */

/* ---- content model: one source of truth, grouped by category ----
   q  · the question, as a patient would ask it
   a  · array of paragraphs (string). **bold** marks a navigation path
        or term; rendered with light emphasis.
   pop· surfaced under "Popular questions"
   new· surfaced under "Recently updated" (recent feature work)        */
const HELP_CATEGORIES = [
  {
    key: 'start', title: 'Getting started', icon: 'sparkle', color: 'var(--orange)', wash: 'var(--orange-wash)',
    qs: [
      { q: 'What is MUIY?', a: [
        'MUIY is a calm self-management companion for people living with transfusion-dependent thalassaemia. It keeps your donors, transfusions, iron levels and lab results together in one gentle place.',
        'It’s a companion — not a medical device. Its forecasts, dose targets and insights are helpful estimates, never a replacement for your care team.' ] },
      { q: 'Who is MUIY for?', a: [
        'It’s built with and for the thalassaemia community in the Maldives (ThalFrndz). It suits anyone living with thalassaemia — transfusion-dependent (TDT) or not (NTDT) — and the family or caregivers who help manage their care.' ] },
      { q: 'How do I set up my medical profile?', a: [
        'When you first open MUIY, a friendly welcome flow walks you through it one question at a time — your name, date of birth, thalassaemia type, blood group, weight and a few optional details.',
        'You can change anything later under **Me → Medical Profile**. The little ring there shows how complete your profile is — the more you add, the more personal your reminders and forecasts become.' ], pop: true },
      { q: 'How do I add or change my blood group?', a: [
        'Go to **Me → Medical Profile → Blood group** and pick yours. MUIY uses it to match compatible donors and to measure your donor pool’s readiness for your exact group.' ] },
      { q: 'Do I have to fill everything in at once?', a: [
        'No. Only a few essentials are needed to start. Optional details — your transfusion centre, usual interval and chelation medication — can be skipped and added whenever you like. You can also pause onboarding and resume it later.' ] },
    ],
  },
  {
    key: 'trans', title: 'Transfusions', icon: 'drop', color: 'var(--sky-deep)', wash: 'var(--sky-wash)',
    qs: [
      { q: 'How do I log a transfusion?', a: [
        'Tap the **+** button in the bottom bar → **Transfusion log**, or go to **Health → Transfusion → + Log**.',
        'Record the date, number of units, where the blood came from (a direct donor or a camp), the volume, and your Hb-before value if you have it. You can also note any reaction.' ], pop: true },
      { q: 'How does the next-transfusion forecast work?', a: [
        'Once you’ve logged a couple of transfusions, MUIY learns the rhythm of your own history and estimates a likely window for your next one — shown as a range of days, never a single hard date.',
        'As you add more detail — Hb-before, transfused volume and donor Hb — it sharpens the estimate using your fitted Hb-decline rate, and recent transfusions count for more.' ], new: true },
      { q: 'Why is the forecast only an estimate?', a: [
        'Your Hb can change for reasons MUIY can’t see — an infection, your diet, or simply how each unit settles. The window is a gentle guide to help you plan ahead and line up donors early.',
        'Always follow your healthcare team’s advice on the actual timing of your transfusions.' ] },
      { q: 'Why does pre-transfusion Hb matter?', a: [
        'Your pre-transfusion Hb is your level at its lowest point, just before a transfusion. MUIY saves it each time you log one.',
        'Keeping it within your target band (around 9.5–10.5 g/dL) calms the bone marrow’s overactivity, which means fewer complications and better growth.' ] },
      { q: 'How can I view previous transfusions?', a: [
        'In **Health → Transfusion** you’ll see your most recent transfusions. Tap **View all** for your full history, and tap any entry to edit it.' ] },
    ],
  },
  {
    key: 'mon', title: 'Monitoring & lab results', icon: 'clipboard', color: 'var(--success)', wash: 'var(--green-wash)',
    qs: [
      { q: 'What is the Monitoring section?', a: [
        '**Health → Monitoring** keeps track of the wider set of check-ups recommended for thalassaemia — iron, liver, heart, hormones, bones and more — following TIF guidelines, personalised to your age, sex and profile.',
        'It shows at a glance what’s up to date, due soon, or overdue, with a coverage ring and a general timeline.' ] },
      { q: 'How do I manually add a test result?', a: [
        'In **Monitoring**, find the test (search or browse the categories) and tap **Add result**. Enter the value and the date it was taken — that’s it.' ] },
      { q: 'How do I upload a lab report?', a: [
        'Open **Monitoring → Visits** and start a scan, then add your reports — photos, screenshots, scans or PDFs. You can add several files at once, and even paste the report text instead.' ], pop: true },
      { q: 'How does the automatic reading (OCR) work?', a: [
        'Everything happens on your device. MUIY gently enhances each image (or reads a PDF’s text layer), pulls out only the values actually printed on your report, and matches each one to the right test in your panel.',
        'Every value gets a confidence score. Nothing is invented, and nothing is saved until you confirm it.' ], new: true },
      { q: 'What should I do if it reads something incorrectly?', a: [
        'You always review before saving. You can edit any value, unit or date, re-match a result to the correct test, remove ones you don’t want, or add a result it missed by hand.',
        'Low-confidence reads and unusual values are highlighted so they’re easy to spot and double-check.' ] },
      { q: 'How can I see my historical results?', a: [
        'Results are grouped by visit (the date they were collected) — the way you think about hospital trips. Open any test in **Monitoring** to see its full history. Your Hb and ferritin also flow into the Today snapshot and your trends automatically.' ] },
    ],
  },
  {
    key: 'iron', title: 'Ferritin & chelation', icon: 'pill', color: 'var(--waiting)', wash: 'var(--yellow-wash)',
    qs: [
      { q: 'How do I track ferritin?', a: [
        'Log a ferritin reading from the **+** menu or your ferritin history, or let a lab-report upload fill it in. MUIY colour-codes each reading against target bands and shows your trend over time.' ] },
      { q: 'Why do ferritin results vary between laboratories?', a: [
        'Different labs use different machines and reference ranges, so the same blood can read a little differently from place to place. It’s usually best to follow the trend over several readings rather than read too much into one number.' ] },
      { q: 'Can illness or infection affect ferritin levels?', a: [
        'Yes. Ferritin naturally rises during infection or inflammation, so a single high reading while you’re unwell may not reflect your true iron load. Your care team reads ferritin alongside other markers for the full picture.' ] },
      { q: 'How do chelation dose targets work?', a: [
        'In **Health → Chelation**, MUIY works out weight-based target ranges from TIF guidelines for each of your medications. Keep your weight current under **Medical Profile** and the targets refresh.',
        'These are guideline ranges only — your haematologist always sets your actual dose.' ] },
      { q: 'What is the daily dose check-in?', a: [
        'If you’re on chelation, your **Today** screen shows the doses scheduled for the day so you can tap “taken” in seconds. It builds a gentle streak — encouraging, never shaming — and an insights view you can share with your care team.',
        'Reminders can nudge you at each dose time (see Reminders below).' ], new: true },
    ],
  },
  {
    key: 'donors', title: 'Donors', icon: 'users', color: 'var(--orange)', wash: 'var(--orange-wash)',
    qs: [
      { q: 'How do I add a donor?', a: [
        'Tap **+ → Add a donor**, or the **+** on the Pool screen. Add their name, mobile number, blood group and last donation.',
        'Please only add someone’s contact details with their agreement — and remove them if they ask.' ] },
      { q: 'How does donor eligibility work?', a: [
        'After a normal whole-blood donation, a donor rests for 90 days. After an apheresis donation it’s 120 days, because more is collected and the body needs longer to recover.',
        'MUIY counts down from each donor’s last donation and marks them **Eligible**, **Due soon** or **Waiting** for you.' ], pop: true },
      { q: 'What’s the difference between “Your donors” and “Other groups”?', a: [
        'Your own readiness is measured against donors who share your exact blood group — these are **Your donors**.',
        'You can still keep donors of other groups (for friends or family who need them) — they appear under **Other groups**, kept strictly separate so your own readiness stays clear.' ] },
      { q: 'Can I track donation and contact history?', a: [
        'Yes. Each donor card keeps their full donation history and a contact log — your calls and messages, and how they went. You can temporarily **defer** a donor, or **archive** one while keeping all their history.' ] },
      { q: 'How do I message a donor?', a: [
        'From a donor’s card (or the quick actions on Today and Pool) you can call directly, or send a **WhatsApp** or **SMS** using your saved message template. **[Donor Name]** and **[Patient Name]** fill in automatically — edit the template under **Me → Message templates**.' ] },
    ],
  },
  {
    key: 'remind', title: 'Reminders & notifications', icon: 'bell', color: 'var(--waiting)', wash: 'var(--yellow-wash)',
    qs: [
      { q: 'How do I install MUIY and turn on reminders?', a: [
        'Open **Me → Get the app & reminders**. There you can add MUIY to your home screen so it opens like a normal app, and turn on notifications for this device.',
        'Reminders work best once MUIY is installed to your home screen. Background delivery while the app is fully closed is still rolling out.' ], new: true },
      { q: 'What reminders can MUIY send?', a: [
        'Gentle nudges for your chelation doses, an approaching transfusion, and when a donor in your pool can give again. Choose which ones you’d like during setup or under **Me → Notifications**, and set per-dose times under **Health → Chelation → Reminders**.' ] },
      { q: 'Does it work during Ramadan?', a: [
        'Dose-reminder timing is built to adjust around fasting hours, so your dose times can shift around suhoor and iftar rather than landing mid-fast.' ] },
      { q: 'Why didn’t I get a notification?', a: [
        'Notifications depend on your device granting permission, and some browsers limit them. Whatever happens with notifications, your data and check-ins are always saved safely on your device.' ] },
    ],
  },
  {
    key: 'share', title: 'Sharing & caregivers', icon: 'users', color: 'var(--orange)', wash: 'var(--orange-wash)',
    qs: [
      { q: 'Can someone help me manage MUIY?', a: [
        'Yes. Under **Me → Sharing & access → Caregivers & doctors** you can invite someone you trust — a parent who helps with doses and donors, or your haematologist who follows your trends.',
        'You choose exactly what each person can see, and you can change or remove their access at any time.' ], pop: true, new: true },
      { q: 'What can a caregiver or doctor see?', a: [
        'You set one access level per person: **Full access** — view and add records, manage donors and reminders; **Health only** — transfusions, iron, labs and chelation, with no donor pool; or **View only** — a read-only summary and your doctor report.' ] },
      { q: 'How do I invite someone?', a: [
        'Tap **Invite someone**, add their name, choose the relationship (parent, family, caregiver or doctor) and what they can see, then create the invite. MUIY makes a join code you can send by **WhatsApp**, copy, or your phone’s share sheet.' ] },
      { q: 'Is shared access live yet?', a: [
        'Caregiver sharing is in **preview**. Invites create a real, shareable join code, but live shared viewing isn’t switched on yet.',
        'For now, the best way to give your doctor a complete snapshot is the doctor report in **Health → Monitoring → Report**.' ] },
      { q: 'How do I remove someone’s access?', a: [
        'In **Caregivers & doctors**, tap the ✕ beside anyone who has access — they’ll no longer be able to see or help with your records. You stay in control the whole time.' ] },
    ],
  },
  {
    key: 'data', title: 'Data & privacy', icon: 'shield', color: 'var(--sky-deep)', wash: 'var(--slate-wash)',
    qs: [
      { q: 'Where is my data stored?', a: [
        'On your device only. MUIY is local-first — your records aren’t uploaded to a MUIY account. This version has no cloud sync, so keep a backup (see below) in case you change or lose your phone.' ], pop: true },
      { q: 'Who can access my information?', a: [
        'By default, only you — on this device. No MUIY staff can ever see your health records, donors or labs; we hold no copy of them.',
        'If you’d like help, you can choose to invite a caregiver or doctor (see **Sharing & caregivers**). You decide what they see and can remove access at any time. The only things that leave your device are an invite or feedback you choose to send.' ] },
      { q: 'Is my data encrypted?', a: [
        'Your records are kept in this device’s own storage, so keep your phone protected with its screen lock and passcode. Any feedback you submit is sent over a secure (HTTPS) connection and never includes your health records.' ] },
      { q: 'How do I export or back up my data?', a: [
        '**Me → Data → Export a copy** saves a complete file you can keep, move to another phone, or hand to your clinic — it’s also your portable backup. **Me → Backup & restore** brings a saved file back in.' ] },
      { q: 'How do I delete my data?', a: [
        '**Me → Data → Clear all data** permanently erases everything on this device (your profile and settings are kept). This can’t be undone — export a copy first if you’d like a backup somewhere safe.' ] },
    ],
  },
  {
    key: 'account', title: 'Account & settings', icon: 'user', color: 'var(--ink-2)', wash: 'var(--surface-2)',
    qs: [
      { q: 'How do I edit my medical profile?', a: [
        'Open **Me → Medical Profile** and tap any row — thalassaemia type, blood group, splenectomy, weight, transfusion centre or usual interval — to update it. Your chelation medication is managed under **Health → Chelation**.' ] },
      { q: 'How do I change how the app looks?', a: [
        'Under **Me → Preferences** you can turn on **Dark mode** and choose your **Home illustration** (the scene behind your greeting).' ] },
      { q: 'How do I send feedback?', a: [
        'Tap **Send feedback** at the bottom of this Help Center, or go to **Me → Send feedback**. Rate your experience, tap what you liked, and add a comment. It sends when you’re online, and saves to send later if you’re not.' ] },
      { q: 'How do I rate MUIY?', a: [
        'Go to **Me → About MUIY → Rate MUIY**. On a published app it opens your app-store listing; otherwise it records an in-app rating that helps us improve.' ] },
    ],
  },
];

/* light **bold** renderer for navigation crumbs inside answers */
function HelpText({ text }) {
  const parts = String(text).split(/\*\*(.+?)\*\*/g);
  return (
    <span>
      {parts.map((p, i) => i % 2 === 1
        ? <b key={i} style={{ fontWeight: 800, color: 'var(--ink)' }}>{p}</b>
        : <React.Fragment key={i}>{p}</React.Fragment>)}
    </span>
  );
}

/* a single expandable Q&A row */
function HelpQA({ id, q, a, open, onToggle, badge }) {
  return (
    <div className="card-flat" style={{ padding: 0, overflow: 'hidden' }}>
      <button className="between" onClick={onToggle}
        style={{ width: '100%', background: 'none', border: 'none', cursor: 'pointer', textAlign: 'left', padding: '13px 15px', gap: 10, fontFamily: 'inherit', alignItems: 'flex-start' }}>
        <span style={{ flex: 1, minWidth: 0 }}>
          <span style={{ display: 'block', fontWeight: 700, fontSize: 13.5, color: 'var(--ink)', lineHeight: 1.4 }}>{q}</span>
          {badge && !open && <span className="chip-status" style={{ background: 'var(--green-wash)', color: 'var(--success)', marginTop: 6, fontSize: 10 }}>{badge}</span>}
        </span>
        <Icon name="chevD" size={17} color="var(--ink-3)" style={{ flex: 'none', marginTop: 2, transform: open ? 'rotate(180deg)' : 'none', transition: 'transform .2s' }} />
      </button>
      {open && (
        <div style={{ padding: '0 15px 14px' }}>
          {a.map((para, i) => (
            <div key={i} className="body" style={{ fontSize: 13, lineHeight: 1.55, marginTop: i === 0 ? 0 : 9 }}>
              <HelpText text={para} />
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

/* category header that expands to reveal its questions */
function HelpCategory({ cat, open, onToggle, openKey, setOpenKey }) {
  return (
    <div style={{ marginBottom: 10 }}>
      <button className="me-row" onClick={onToggle}
        style={{ width: '100%', padding: '12px 14px', borderBottom: 'none', borderRadius: 16, background: open ? 'var(--surface-2)' : 'var(--surface)', border: '1.5px solid var(--hairline)' }}>
        <div className="me-ic" style={{ background: cat.wash, color: cat.color }}><Icon name={cat.icon} size={18} color={cat.color} fill={cat.icon === 'sparkle' || cat.icon === 'drop' || cat.icon === 'heart' ? cat.color : 'none'} /></div>
        <div style={{ flex: 1, textAlign: 'left', minWidth: 0 }}>
          <span style={{ fontWeight: 800, fontSize: 14.5 }}>{cat.title}</span>
          <div className="body" style={{ fontSize: 12 }}>{cat.qs.length} {cat.qs.length === 1 ? 'question' : 'questions'}</div>
        </div>
        <Icon name="chevD" size={17} color="var(--ink-3)" style={{ flex: 'none', transform: open ? 'rotate(180deg)' : 'none', transition: 'transform .2s' }} />
      </button>
      {open && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 8, paddingLeft: 4 }}>
          {cat.qs.map((item, i) => {
            const id = cat.key + ':' + i;
            return <HelpQA key={id} id={id} q={item.q} a={item.a} open={openKey === id} onToggle={() => setOpenKey(openKey === id ? null : id)} badge={item.new ? 'Updated' : null} />;
          })}
        </div>
      )}
    </div>
  );
}

/* ---------- Help Center (replaces the old 5-item HelpSheet) ---------- */
function HelpSheet({ store, close }) {
  const [query, setQuery] = React.useState('');
  const [openCat, setOpenCat] = React.useState(null);
  const [openKey, setOpenKey] = React.useState(null);

  // flatten every Q&A once, tagged with its category, for search + the
  // popular / recently-updated rails
  const all = React.useMemo(() => {
    const out = [];
    HELP_CATEGORIES.forEach((c) => c.qs.forEach((item, i) => out.push({ ...item, id: c.key + ':' + i, cat: c })));
    return out;
  }, []);

  const q = query.trim().toLowerCase();
  const results = q
    ? all.filter((x) => x.q.toLowerCase().includes(q) || x.a.join(' ').toLowerCase().includes(q) || x.cat.title.toLowerCase().includes(q))
    : [];
  const popular = all.filter((x) => x.pop);

  const Crumb = ({ cat }) => (
    <span className="row" style={{ gap: 6, marginBottom: 7 }}>
      <span style={{ width: 16, height: 16, borderRadius: 6, background: cat.wash, display: 'grid', placeItems: 'center', flex: 'none' }}><Icon name={cat.icon} size={10} color={cat.color} /></span>
      <span style={{ fontSize: 10.5, fontWeight: 900, letterSpacing: '.05em', textTransform: 'uppercase', color: 'var(--ink-3)' }}>{cat.title}</span>
    </span>
  );

  const Rail = ({ icon, color, label, items, badge }) => (
    <div style={{ marginBottom: 18 }}>
      <div className="row" style={{ gap: 8, margin: '2px 2px 9px' }}>
        <Icon name={icon} size={15} color={color} fill={icon === 'sparkle' || icon === 'heart' ? color : 'none'} />
        <span style={{ fontWeight: 900, fontSize: 11.5, letterSpacing: '.05em', textTransform: 'uppercase', color: 'var(--ink-3)' }}>{label}</span>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {items.map((x) => (
          <HelpQA key={'r' + x.id} id={x.id} q={x.q} a={x.a} open={openKey === x.id} onToggle={() => setOpenKey(openKey === x.id ? null : x.id)} badge={badge && openKey !== x.id ? badge : null} />
        ))}
      </div>
    </div>
  );

  return (
    <Sheet title="Help & FAQ" onClose={close}>
      <div className="body" style={{ fontSize: 13, lineHeight: 1.5, marginTop: -4, marginBottom: 14 }}>
        Find your way around MUIY and get clear answers — written for you, in plain language.
      </div>

      {/* search */}
      <div className="card-flat row" style={{ gap: 9, padding: '10px 13px', marginBottom: 16 }}>
        <Icon name="search" size={18} color="var(--ink-3)" />
        <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search help…"
          style={{ flex: 1, minWidth: 0, border: 'none', background: 'none', outline: 'none', fontFamily: 'inherit', fontSize: 14.5, fontWeight: 600, color: 'var(--ink)' }} />
        {query && <button className="icon-btn" style={{ width: 26, height: 26, flex: 'none', background: 'var(--surface-2)' }} onClick={() => setQuery('')} aria-label="Clear search"><Icon name="x" size={14} /></button>}
      </div>

      {q ? (
        /* ---- search results ---- */
        <div>
          <div className="dmeta muted" style={{ marginBottom: 10, fontWeight: 700 }}>{results.length} {results.length === 1 ? 'result' : 'results'} for “{query}”</div>
          {results.length === 0 ? (
            <div className="card-flat" style={{ padding: '16px 15px' }}>
              <div className="body" style={{ fontSize: 13, lineHeight: 1.5 }}>No answers matched that. Try a simpler word, or reach us below — we’re happy to help.</div>
            </div>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {results.map((x) => (
                <div key={x.id}>
                  <Crumb cat={x.cat} />
                  <HelpQA id={x.id} q={x.q} a={x.a} open={openKey === x.id} onToggle={() => setOpenKey(openKey === x.id ? null : x.id)} />
                </div>
              ))}
            </div>
          )}
        </div>
      ) : (
        /* ---- browse ---- */
        <div>
          {popular.length > 0 && <Rail icon="sparkle" color="var(--orange)" label="Popular questions" items={popular} />}

          <div className="row" style={{ gap: 8, margin: '2px 2px 10px' }}>
            <Icon name="grid" size={15} color="var(--ink-2)" />
            <span style={{ fontWeight: 900, fontSize: 11.5, letterSpacing: '.05em', textTransform: 'uppercase', color: 'var(--ink-3)' }}>Browse by topic</span>
          </div>
          {HELP_CATEGORIES.map((cat) => (
            <HelpCategory key={cat.key} cat={cat}
              open={openCat === cat.key}
              onToggle={() => { setOpenCat(openCat === cat.key ? null : cat.key); setOpenKey(null); }}
              openKey={openKey} setOpenKey={setOpenKey} />
          ))}
        </div>
      )}

      {/* contact / feedback / privacy shortcuts */}
      <div style={{ marginTop: 18, paddingTop: 16, borderTop: '1.5px solid var(--hairline)' }}>
        <div className="row" style={{ gap: 12, alignItems: 'center', marginBottom: 12 }}>
          <Pearl size={34} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontWeight: 800, fontSize: 14 }}>Still need a hand?</div>
            <div className="body" style={{ fontSize: 12.5, lineHeight: 1.45 }}>We’re a small community team and we read everything you send.</div>
          </div>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
          <button className="btn btn-primary" style={{ width: '100%', gap: 8 }} onClick={() => { close(); store.openModal('contactUs', {}); }}><Icon name="chat" size={17} color="#fff" /> Send feedback</button>
          <button className="btn btn-ghost" style={{ width: '100%', gap: 8 }} onClick={() => { close(); store.openModal('privacyData', {}); }}><Icon name="shield" size={17} color="var(--sky-deep)" /> Privacy &amp; data</button>
        </div>
        <div className="body" style={{ fontSize: 11.5, textAlign: 'center', marginTop: 14, color: 'var(--ink-3)' }}>MUIY v{TC.APP_VERSION} · Help Center updated June 2026</div>
      </div>
    </Sheet>
  );
}

Object.assign(window, { HelpSheet, HELP_CATEGORIES });
