// screens-b.jsx — Bestellen, Voortgang, Profiel (overhaul)

// ─────────── BESTELLEN ───────────
function ScreenBestellen({ state, setState }) {
  const [step, setStep] = React.useState('list'); // list | confirm | sent
  const [copied, setCopied] = React.useState(null);
  const [sending, setSending] = React.useState(false);

  const isLoading = state.suppletie == null;
  const supps = (state.suppletie || []).map(s => ({
    id: s.id, Ic: IconLeaf,
    name: s.naam, dose: s.dosering || '', stText: s.frequentie || '',
    tone: 'calm', prem: !!s.is_premium,
  }));
  const toneColor = { calm: '#82A898', attention: '#D9937A', urgent: '#C47A6A' };

  const chgQty = (id, delta) => setState(s => ({
    ...s, qty: { ...s.qty, [id]: Math.max(0, (s.qty[id] ?? 0) + delta) },
  }));

  const bestelItems = supps.filter(s => (state.qty[s.id] ?? 0) > 0);
  const totaalAantal = bestelItems.reduce((a, s) => a + state.qty[s.id], 0);

  const copyCode = (code) => {
    setCopied(code);
    setTimeout(() => setCopied(null), 1800);
  };

  const partners = state.aanbevolenProducten;

  const verstuurBestelling = async () => {
    console.log('[Bestellen] verstuurBestelling gestart');
    console.log('[Bestellen] supps:', supps);
    console.log('[Bestellen] qty:', state.qty);

    const tebestellen = supps.filter(s => (state.qty[s.id] ?? 0) > 0);
    console.log('[Bestellen] geselecteerde items:', tebestellen);

    if (tebestellen.length === 0) {
      console.warn('[Bestellen] Geen items geselecteerd — knop had disabled moeten zijn');
      return;
    }

    const gebruikerId = window.MintDB?.gebruikerId();
    console.log('[Bestellen] gebruikerId:', gebruikerId);

    if (!gebruikerId) {
      console.error('[Bestellen] Niet ingelogd — geen gebruikerId beschikbaar');
      return;
    }

    setSending(true);

    const rijen = tebestellen.map(s => ({
      gebruiker_id: gebruikerId,
      suppletie_id: s.id,
      status: 'nieuw',
    }));
    console.log('[Bestellen] insert payload:', rijen);

    const { data, error } = await window.MintDB._db
      .from('suppletie_bestellingen')
      .insert(rijen)
      .select();

    console.log('[Bestellen] insert resultaat:', { data, error });
    setSending(false);

    if (error) {
      console.error('[Bestellen] Insert mislukt:', error.message, error);
      return;
    }

    console.log('[Bestellen] Bestelling opgeslagen, qty resetten');
    setState(s => ({ ...s, qty: {} }));
    setStep('sent');
  };

  return (
    <div style={{ padding: '24px 20px 32px' }}>
      <H1>Bestellen</H1>
      <Sub>Voor jouw traject: {state.protocol
        ? `${state.protocol.actieve.naam}${state.protocol.actieve.fase_titel ? ` · ${state.protocol.actieve.fase_titel}` : ''}`
        : 'Jouw protocol'}</Sub>

      <ThirzaQuote>
        Laat me weten wat je nodig hebt en ik regel de bestelling voor je.
        Je ontvangt dan een factuur per e-mail.
      </ThirzaQuote>

      <SectionHead title="Jouw supplementen" sub="deze maand bestellen"/>
      <Card pad={4}>
        {isLoading ? (
          <div style={{ padding: '18px 14px', fontSize: 12.5, color: '#a59f95', textAlign: 'center' }}>
            Jouw suppletie wordt geladen…
          </div>
        ) : supps.length === 0 ? (
          <div style={{ padding: '18px 14px', fontSize: 12.5, color: '#a59f95', textAlign: 'center' }}>
            Geen supplementen gevonden voor jouw protocol.
          </div>
        ) : supps.map((s, i) => (
          <div key={s.id} style={{
            display: 'flex', alignItems: 'center', gap: 14, padding: '14px 14px',
            borderBottom: i < supps.length-1 ? '1px solid #F4F1EA' : 'none',
          }}>
            <div style={{
              width: 46, height: 46, borderRadius: 11, background: '#F4F1EA',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              flexShrink: 0,
            }}><s.Ic size={24} color="#6B8F84"/></div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 14, fontWeight: 500, color: '#2F4F4F', marginBottom: 2 }}>{s.name}</div>
              <div style={{ fontSize: 11.5, color: '#888', marginBottom: 4 }}>{s.dose}</div>
              <div style={{ fontSize: 11, color: toneColor[s.tone], lineHeight: 1.4 }}>{s.stText}</div>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexShrink: 0 }}>
              <div onClick={() => chgQty(s.id, -1)} style={qtyBtnStyle}>
                <IconMinus size={15} color="#2F4F4F"/>
              </div>
              <div style={{ fontSize: 14, fontWeight: 500, minWidth: 20, textAlign: 'center', color: '#2F4F4F' }}>
                {state.qty[s.id] ?? 0}
              </div>
              <div onClick={() => chgQty(s.id, 1)} style={qtyBtnStyle}>
                <IconPlus size={15} color="#2F4F4F"/>
              </div>
            </div>
          </div>
        ))}
      </Card>

      {/* Samenvatting + knop */}
      {step === 'list' && (
        <>
          {totaalAantal > 0 && (
            <div style={{
              background: '#eaf2ef', borderRadius: 10, padding: '12px 14px',
              fontSize: 13, color: '#6B8F84', lineHeight: 1.5, marginBottom: 12,
            }}>
              Je bestelt {totaalAantal} {totaalAantal === 1 ? 'product' : 'producten'}
              {': '}
              {bestelItems.map((s, i) => (
                <span key={s.id}>
                  {state.qty[s.id]}× {s.name}{i < bestelItems.length-1 ? ', ' : ''}
                </span>
              ))}
            </div>
          )}
          <div
            onClick={async () => { await verstuurBestelling(); }}
            style={{
              width: '100%', background: totaalAantal > 0 ? '#82A898' : '#d0d0d0',
              color: sending ? '#c0d4cc' : '#fff', borderRadius: 8, padding: 14, fontSize: 14, fontWeight: 500,
              textAlign: 'center', cursor: totaalAantal > 0 && !sending ? 'pointer' : 'not-allowed',
              marginBottom: 22, transition: 'background .2s',
            }}>
            {sending ? 'Versturen…' : 'Bestelverzoek sturen naar Thirza'}
          </div>
        </>
      )}

      {/* Confirm stap */}
      {step === 'confirm' && (
        <div style={{
          background: '#fff', border: '1.5px solid #82A898', borderRadius: 14, padding: 18, marginBottom: 22,
        }}>
          <H2 style={{ marginBottom: 10 }}>Kloppen je keuzes?</H2>
          <div style={{ marginBottom: 14 }}>
            {bestelItems.map(s => (
              <div key={s.id} style={{
                display: 'flex', justifyContent: 'space-between',
                padding: '8px 0', fontSize: 13.5, color: '#2F4F4F',
              }}>
                <span>{s.name}</span>
                <span style={{ color: '#82A898', fontWeight: 500 }}>{state.qty[s.id]}×</span>
              </div>
            ))}
          </div>
          <div style={{ fontSize: 12, color: '#888', lineHeight: 1.6, marginBottom: 14 }}>
            Thirza ontvangt je verzoek en bevestigt binnen 1 werkdag. Je krijgt
            een factuur per e-mail voor de verzending.
          </div>
          <div style={{ display: 'flex', gap: 10 }}>
            <div onClick={() => setStep('list')} style={{
              flex: 1, borderRadius: 8, padding: 12, fontSize: 13.5, fontWeight: 500,
              textAlign: 'center', cursor: 'pointer',
              background: '#F4F1EA', color: '#2F4F4F',
            }}>Terug</div>
            <div onClick={async () => {
              setSending(true);
              if (window.MintDB) {
                await window.MintDB.slaaBestelVerzoek(bestelItems.map(s => ({ suppletieId: s.id })));
              }
              setSending(false);
              setStep('sent');
            }} style={{
              flex: 1, borderRadius: 8, padding: 12, fontSize: 13.5, fontWeight: 500,
              textAlign: 'center', cursor: sending ? 'default' : 'pointer',
              background: sending ? '#c0d4cc' : '#82A898', color: '#fff',
            }}>{sending ? 'Versturen…' : 'Verzenden'}</div>
          </div>
        </div>
      )}

      {step === 'sent' && (
        <div style={{
          background: '#eaf2ef', borderRadius: 14, padding: 18, marginBottom: 22,
          display: 'flex', gap: 14, alignItems: 'flex-start',
        }}>
          <div style={{
            width: 36, height: 36, borderRadius: '50%', background: '#82A898',
            display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
          }}><IconCheck size={18} color="#fff" stroke={2.5}/></div>
          <div>
            <div style={{ fontFamily: serif(), fontSize: 17, color: '#2F4F4F', marginBottom: 4 }}>
              Verzonden
            </div>
            <div style={{ fontSize: 13, color: '#6B8F84', lineHeight: 1.6 }}>
              Thirza ontvangt je verzoek en bevestigt binnen 1 werkdag per e-mail.
            </div>
            <div onClick={() => setStep('list')} style={{
              fontSize: 12.5, color: '#D9937A', cursor: 'pointer', marginTop: 8,
            }}>Nieuwe bestelling</div>
          </div>
        </div>
      )}

      {/* Aanbevolen producten */}
      <SectionHead title="Aanbevolen door Thirza" sub="partnerproducten"/>
      <div style={{ fontSize: 12.5, color: '#a0a0a0', marginBottom: 14, lineHeight: 1.6 }}>
        Producten van partners die passen bij jouw fase. Je krijgt een kortingscode.
      </div>

      {partners === null ? (
        <div style={{ fontSize: 12.5, color: '#a59f95', textAlign: 'center', padding: '18px 0' }}>
          Producten worden geladen…
        </div>
      ) : partners.length === 0 ? (
        <div style={{ fontSize: 12.5, color: '#a59f95', textAlign: 'center', padding: '18px 0' }}>
          Momenteel geen aanbevolen producten.
        </div>
      ) : partners.map(p => (
        <div key={p.id} style={{
          background: '#fff', borderRadius: 14, padding: 18, marginBottom: 12,
          boxShadow: '0 2px 8px rgba(47,79,79,0.08)',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12 }}>
            <div style={{
              width: 44, height: 44, borderRadius: 11, background: '#F4F1EA',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}><IconLeaf size={24} color="#6B8F84"/></div>
            <div style={{ fontSize: 15, fontWeight: 500, color: '#2F4F4F' }}>{p.naam}</div>
          </div>
          {p.omschrijving && (
            <div style={{ fontSize: 13, color: '#666', lineHeight: 1.65, marginBottom: 14 }}>{p.omschrijving}</div>
          )}
          {p.kortingscode && (
            <div style={{
              background: '#F4F1EA', borderRadius: 8, padding: '12px 14px',
              display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            }}>
              <div>
                <div style={{ fontSize: 11, color: '#888', marginBottom: 2 }}>Jouw kortingscode</div>
                <div style={{ fontSize: 14, fontWeight: 500, color: '#2F4F4F', letterSpacing: '0.08em' }}>{p.kortingscode}</div>
              </div>
              <div onClick={() => copyCode(p.kortingscode)} style={{
                display: 'flex', alignItems: 'center', gap: 5,
                fontSize: 12, color: copied === p.kortingscode ? '#6B8F84' : '#D9937A',
                cursor: 'pointer', fontWeight: 500,
              }}>
                {copied === p.kortingscode
                  ? <><IconCheck size={13} color="#6B8F84" stroke={2.2}/> Gekopieerd</>
                  : <><IconCopy size={13} color="#D9937A"/> Kopieer</>}
              </div>
            </div>
          )}
          {p.website_url && (
            <a href={p.website_url} target="_blank" rel="noopener noreferrer" style={{
              display: 'block', marginTop: 10, textAlign: 'center',
              fontSize: 13, fontWeight: 500, color: '#6B8F84',
              border: '1.5px solid #6B8F84', borderRadius: 8, padding: '9px 0',
              textDecoration: 'none',
            }}>Bekijk website</a>
          )}
        </div>
      ))}
    </div>
  );
}

const qtyBtnStyle = {
  width: 30, height: 30, borderRadius: 8,
  border: '1px solid #cfe0db', background: '#fff', cursor: 'pointer',
  display: 'flex', alignItems: 'center', justifyContent: 'center',
};

// ─────────── REFLECTIE FORMULIER ───────────
// Steekwoord-chips per categorie. Eén of meer per categorie selecteerbaar.
const REFLECTIE_CATS = [
  {
    id: 'energie', label: 'Energie',
    options: ['fit', 'oké', 'moe', 'uitgeput'],
  },
  {
    id: 'slaap', label: 'Slaap',
    options: ['diep', 'voldoende', 'onrustig', 'kort'],
  },
  {
    id: 'spijsvertering', label: 'Spijsvertering',
    options: ['rustig', 'opgeblazen', 'krampen', 'goed'],
  },
  {
    id: 'stemming', label: 'Stemming',
    options: ['kalm', 'vrolijk', 'gespannen', 'somber', 'prikkelbaar'],
  },
  {
    id: 'lichaam', label: 'Lichaam',
    options: ['licht', 'pijn', 'hoofdpijn', 'gespannen schouders'],
  },
];

function todayKey() {
  const d = new Date();
  return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`;
}

function ReflectieForm({ state, setState, onClose, dateKey: dateKeyProp }) {
  const dateKey = dateKeyProp || todayKey();
  const isToday = dateKey === todayKey();
  const existing = state.reflecties?.[dateKey] || { mood: 0, tags: {}, note: '' };
  const [mood, setMood] = React.useState(existing.mood || 0);
  const [tags, setTags] = React.useState(existing.tags || {});
  const [note, setNote] = React.useState(existing.note || '');

  const toggleTag = (cat, opt) => {
    setTags(prev => {
      const cur = new Set(prev[cat] || []);
      if (cur.has(opt)) cur.delete(opt); else cur.add(opt);
      return { ...prev, [cat]: [...cur] };
    });
  };

  const save = () => {
    setState(s => ({
      ...s,
      reflecties: {
        ...(s.reflecties || {}),
        [dateKey]: { mood, tags, note, savedAt: Date.now() },
      },
      openReflectie: false,
    }));
    onClose();
  };

  const dStr = new Date(dateKey).toLocaleDateString('nl-NL', { weekday: 'long', day: 'numeric', month: 'long' });

  const moodLabels = ['heel zwaar', 'zwaar', 'gemiddeld', 'licht', 'heel licht'];

  return (
    <div style={{ padding: '24px 20px 120px' }}>
      <div onClick={onClose} style={{
        display: 'inline-flex', alignItems: 'center', gap: 6,
        fontSize: 12.5, color: '#6B8F84', cursor: 'pointer', marginBottom: 14,
      }}>
        <span style={{ transform: 'rotate(180deg)', display: 'inline-block' }}>
          <IconArrow size={13} color="#6B8F84"/>
        </span>
        Terug
      </div>

      <Eyebrow>Reflectie · {dStr}</Eyebrow>
      <H1>Hoe voel je je?</H1>
      <Sub>In steekwoorden — Thirza leest mee</Sub>

      <ThirzaQuote>
        Een paar woorden is genoeg. Dit helpt mij om patronen te zien tussen wat
        je eet, je suppletie en hoe je je voelt. Eerlijk is altijd beter dan compleet.
      </ThirzaQuote>

      {/* Mood scale */}
      <div style={{
        background: '#fff', borderRadius: 14, padding: 18, marginBottom: 14,
        boxShadow: '0 2px 8px rgba(47,79,79,0.08)',
      }}>
        <div style={{ fontSize: 13, color: '#2F4F4F', fontWeight: 500, marginBottom: 12 }}>
          Hoe was de dag in één ademteug?
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', gap: 8, marginBottom: 8 }}>
          {[1,2,3,4,5].map(n => {
            const on = mood === n;
            const size = 12 + n*4; // groeit van klein naar groot
            return (
              <div key={n} onClick={() => setMood(n)} style={{
                flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center',
                gap: 6, cursor: 'pointer', padding: '6px 0',
              }}>
                <div style={{
                  width: size, height: size, borderRadius: '50%',
                  background: on ? '#82A898' : '#eaf2ef',
                  border: on ? '2px solid #6B8F84' : '2px solid transparent',
                  transition: 'all .15s',
                }}/>
                <div style={{
                  fontSize: 9.5, color: on ? '#6B8F84' : '#a59f95',
                  fontWeight: on ? 500 : 400, textAlign: 'center', lineHeight: 1.2,
                }}>{moodLabels[n-1]}</div>
              </div>
            );
          })}
        </div>
      </div>

      {/* Categorieën met chips */}
      {REFLECTIE_CATS.map(cat => (
        <div key={cat.id} style={{
          background: '#fff', borderRadius: 14, padding: 18, marginBottom: 12,
          boxShadow: '0 2px 8px rgba(47,79,79,0.08)',
        }}>
          <div style={{ fontSize: 13, color: '#2F4F4F', fontWeight: 500, marginBottom: 11 }}>
            {cat.label}
          </div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7 }}>
            {cat.options.map(opt => {
              const on = (tags[cat.id] || []).includes(opt);
              return (
                <div key={opt} onClick={() => toggleTag(cat.id, opt)} style={{
                  fontSize: 12, padding: '7px 13px', borderRadius: 18,
                  background: on ? '#82A898' : '#F4F1EA',
                  color: on ? '#fff' : '#6B8F84',
                  cursor: 'pointer', fontWeight: on ? 500 : 400,
                  border: on ? '1px solid #6B8F84' : '1px solid transparent',
                }}>
                  {opt}
                </div>
              );
            })}
          </div>
        </div>
      ))}

      {/* Vrije notitie */}
      <div style={{
        background: '#fff', borderRadius: 14, padding: 18, marginBottom: 18,
        boxShadow: '0 2px 8px rgba(47,79,79,0.08)',
      }}>
        <div style={{ fontSize: 13, color: '#2F4F4F', fontWeight: 500, marginBottom: 8 }}>
          Iets toevoegen voor Thirza?
        </div>
        <div style={{ fontSize: 11.5, color: '#a59f95', marginBottom: 10, lineHeight: 1.5 }}>
          Optioneel — een zin over wat je opvalt, of een vraag.
        </div>
        <textarea
          className="mint-input"
          value={note}
          onChange={e => setNote(e.target.value)}
          placeholder="bv. vandaag minder energie na de lunch"
          rows={3}
          style={{
            width: '100%', resize: 'vertical', minHeight: 70,
            fontFamily: 'inherit', fontSize: 13, lineHeight: 1.55,
            padding: '10px 12px', borderRadius: 10,
            border: '1px solid #eaf2ef', background: '#FAFAF7',
            color: '#2F4F4F', outline: 'none', boxSizing: 'border-box',
          }}
        />
      </div>

      {/* Opslaan */}
      <div onClick={save} style={{
        background: mood > 0 ? '#6B8F84' : '#b9c9c2',
        color: '#fff', borderRadius: 12, padding: '15px 20px',
        textAlign: 'center', fontSize: 14, fontWeight: 500,
        cursor: mood > 0 ? 'pointer' : 'not-allowed',
        marginBottom: 10,
      }}>
        Opslaan en delen met Thirza
      </div>
      <div style={{ fontSize: 11, color: '#a59f95', textAlign: 'center', lineHeight: 1.5 }}>
        Je reflectie verschijnt in je voortgang en in Thirza's overzicht.
      </div>
    </div>
  );
}

// Modal-wrapper rond ReflectieForm — bottom-sheet stijl, vol-scherm op mobiel.
// Gebruikt door Vandaag (entrypoint) en Voortgang (klik op tijdlijn-rij).
function ReflectieModal({ state, setState, onClose, dateKey }) {
  // Sluit met Escape
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);

  // Render de modal binnen het telefoon-frame (portal), zodat hij niet over
  // het hele desktop-viewport gaat staan en correct schaalt op mobiel-formaat.
  const modal = (
    <div
      onClick={onClose}
      style={{
        position: 'absolute', inset: 0, zIndex: 9999,
        background: 'rgba(47,79,79,0.35)',
        display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
        animation: 'mintFadeIn .18s ease-out',
      }}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          background: '#FAFAF7', borderTopLeftRadius: 22, borderTopRightRadius: 22,
          width: '100%', maxHeight: '92%', overflowY: 'auto',
          boxShadow: '0 -10px 30px rgba(47,79,79,0.18)',
          animation: 'mintSlideUp .22s ease-out',
        }}
      >
        {/* Sleep-grip */}
        <div style={{ display: 'flex', justifyContent: 'center', paddingTop: 8 }}>
          <div style={{ width: 38, height: 4, borderRadius: 2, background: '#dcd7cd' }}/>
        </div>
        <ReflectieForm state={state} setState={setState} onClose={onClose} dateKey={dateKey}/>
      </div>
    </div>
  );

  return modal;
}

// ─────────── VOORTGANG ───────────
function BemoedigingsKaart({ bemoediging }) {
  if (!bemoediging || !bemoediging.tekst) return null;
  const dagLabel = bemoediging.dag != null ? `Dag ${bemoediging.dag}` : '';
  const datum = bemoediging.datum || '';
  const meta = [dagLabel, datum].filter(Boolean).join(' · ');
  return (
    <div style={{
      background: '#fff', borderRadius: 12, padding: '16px 18px 14px 18px',
      marginBottom: 22, boxShadow: '0 2px 8px rgba(47,79,79,0.08)',
      borderLeft: '4px solid #D9937A',
      animation: 'mintFadeIn .3s ease',
    }}>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 10, flexWrap: 'wrap' }}>
        <span style={{
          fontFamily: "'Montserrat', sans-serif", fontWeight: 500,
          fontSize: 10, color: '#D9937A', letterSpacing: '0.04em',
        }}>Van Thirza</span>
        {meta && (
          <span style={{ fontSize: 10, color: '#9BBAB3' }}>{meta}</span>
        )}
      </div>
      <div style={{
        fontFamily: serif(), fontSize: 14, color: '#2F4F4F',
        lineHeight: 1.6, marginBottom: 12,
      }}>
        {bemoediging.tekst}
      </div>
      <div style={{
        fontSize: 10, color: '#9BBAB3', fontStyle: 'italic', lineHeight: 1.5,
      }}>
        Samengesteld door Thirza Wondergem, natuurgeneeskundig therapeut bij Mint.
      </div>
    </div>
  );
}

function parseBullets(val) {
  if (!val) return [];
  if (Array.isArray(val)) return val;
  try { return JSON.parse(val); } catch(e) {}
  const s = String(val);
  if (s.includes('|')) return s.split('|').map(x => x.trim()).filter(Boolean);
  return s.split('\n').map(x => x.trim()).filter(Boolean);
}

function ScreenVoortgang({ state, setState }) {
  const alleProtocollen = state.protocol?.alle || [];
  const actieveFase = state.protocol?.actieveFase || 1;
  const phases = alleProtocollen.length > 0
    ? alleProtocollen.map(p => ({
        n: p.fase_nummer,
        t: p.fase_titel || `Fase ${p.fase_nummer}`,
        status: p.fase_nummer < actieveFase ? 'done' : p.fase_nummer === actieveFase ? 'active' : 'todo',
      }))
    : [{ n: actieveFase, t: state.protocol?.actieve?.fase_titel || 'Actiefase', status: 'active' }];
  const [cijfers, setCijfers] = React.useState(null);
  React.useEffect(() => {
    if (!window.MintDB) return;
    const _db  = window.MintDB._db;
    const uid  = window.MintDB.gebruikerId();
    if (!uid) return;
    (async () => {
      const [gRes, afvRes, waterRes, menuRes] = await Promise.all([
        _db.from('Gebruikers').select('created_at').eq('auth_id', uid).single(),
        _db.from('afvinklijst').select('datum, afgevinkt').eq('gebruiker_id', uid),
        _db.from('water_intake').select('hoeveelheid').eq('gebruiker_id', uid),
        _db.from('client_weekmenu').select('recept_id').eq('gebruiker_id', uid),
      ]);

      let dagenOnderweg = 0;
      let startDatum = null;
      if (gRes.data?.created_at) {
        const d = new Date(gRes.data.created_at);
        dagenOnderweg = Math.max(0, Math.floor((Date.now() - d.getTime()) / 86_400_000));
        startDatum = d.toLocaleDateString('nl-NL', { day: 'numeric', month: 'long', year: 'numeric' });
      }

      const afvRows = afvRes.data || [];
      const dagenMet    = new Set(afvRows.filter(r => r.afgevinkt).map(r => r.datum)).size;
      const totaalDagen = new Set(afvRows.map(r => r.datum)).size;
      const suppDagen   = totaalDagen > 0 ? `${dagenMet}/${totaalDagen}` : '—';

      const waterRows = waterRes.data || [];
      const waterGem  = waterRows.length > 0
        ? (waterRows.reduce((s, r) => s + (r.hoeveelheid || 0), 0) / waterRows.length)
            .toFixed(1).replace('.', ',') + ' l'
        : '—';

      const menuRows       = menuRes.data || [];
      const uniekeRecepten = new Set(menuRows.map(r => r.recept_id).filter(Boolean)).size;

      setCijfers({ dagenOnderweg, startDatum, suppDagen, waterGem, uniekeRecepten });
    })();
  }, []);

  const dayNum = cijfers?.dagenOnderweg ?? '…';

  // Reflectie-modal: open voor elke datum (vandaag of historisch)
  const [editDate, setEditDate] = React.useState(null);

  // Backwards-compat: als Vandaag ooit nog 'openReflectie' zet, openen we vandaag.
  React.useEffect(() => {
    if (state.openReflectie) {
      setEditDate(todayKey());
      setState(s => ({ ...s, openReflectie: false }));
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [state.openReflectie]);

  const todayK = todayKey();
  const reflEntries = Object.entries(state.reflecties || {})
    .sort((a,b) => b[0].localeCompare(a[0]))
    .slice(0, 7);

  return (
    <div style={{ padding: '24px 20px 32px' }}>
      <Eyebrow>Jouw traject</Eyebrow>
      <H1>{state.protocol ? state.protocol.actieve.naam : 'Jouw traject'}</H1>
      {state.protocol?.actieve?.omschrijving
        ? <Sub>{state.protocol.actieve.omschrijving}</Sub>
        : cijfers?.startDatum
          ? <Sub>Gestart op {cijfers.startDatum}</Sub>
          : null
      }

      {/* Bemoediging/mijlpaal van Thirza — geïntegreerd in de bestaande Thirza-quote
          zodat het bij de pagina hoort en niet als losse alert bovenop landt. */}
      {(() => {
        const b = state.bemoediging;
        if (b && b.tekst) {
          const dagLabel = b.dag != null ? `Dag ${b.dag}` : '';
          const datum = b.datum || '';
          const eyebrow = [dagLabel, datum].filter(Boolean).join(' · ');
          return <ThirzaQuote eyebrow={eyebrow}>{b.tekst}</ThirzaQuote>;
        }
        return (
          <ThirzaQuote>
            Je bent nu {dayNum} dagen onderweg. Dat is geen kleinigheid —
            consistentie in deze fase maakt het verschil. Mooie stappen tot nu toe.
          </ThirzaQuote>
        );
      })()}

      {/* Reflectie-CTA verplaatst naar Vandaag — Voortgang toont alleen resultaten. */}

      {/* Fase-tracker */}
      <Card>
        <Eyebrow>Fases</Eyebrow>
        <div style={{ display: 'flex', alignItems: 'flex-start', marginTop: 6 }}>
          {phases.map((p, i) => (
            <React.Fragment key={p.n}>
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 7, flex: '0 0 auto', width: 64 }}>
                <div style={{
                  width: 36, height: 36, borderRadius: '50%',
                  border: p.status === 'todo' ? '1.5px solid #ddd' : '1.5px solid #82A898',
                  background: p.status === 'done' ? '#82A898' : '#fff',
                  color: p.status === 'done' ? '#fff' : p.status === 'active' ? '#6B8F84' : '#bbb',
                  fontSize: 13.5, fontWeight: 500,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  boxShadow: p.status === 'active' ? '0 0 0 4px rgba(130,168,152,0.18)' : 'none',
                }}>
                  {p.status === 'done'
                    ? <IconCheck size={16} color="#fff" stroke={2.5}/>
                    : p.status === 'todo'
                      ? <IconLock size={14} color="#ccc" stroke={1.8}/>
                      : p.n}
                </div>
                <div style={{
                  fontSize: 10, textAlign: 'center', lineHeight: 1.4,
                  color: p.status === 'todo' ? '#bbb' : p.status === 'active' ? '#6B8F84' : '#82A898',
                  fontWeight: p.status === 'active' ? 500 : 400,
                }}>{p.t}</div>
              </div>
              {i < phases.length - 1 && (
                <div style={{
                  flex: 1, height: 2, background: phases[i].status === 'done' ? '#82A898' : '#e5e5e5',
                  marginTop: 18,
                }}/>
              )}
            </React.Fragment>
          ))}
        </div>
      </Card>

      {/* Jouw cijfers — nu bovenaan */}
      <SectionHead title="Jouw cijfers" sub="in een oogopslag"/>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 22 }}>
        {[
          [dayNum, 'Dagen onderweg'],
          [cijfers?.suppDagen ?? '…', 'Dagen afgevinkt'],
          [cijfers?.waterGem  ?? '—', 'Gem. water p/dag'],
          [cijfers?.uniekeRecepten ?? '—', 'Recepten in menu'],
        ].map(([n, l]) => (
          <div key={l} style={{
            background: '#fff', borderRadius: 14, padding: 16,
            boxShadow: '0 2px 8px rgba(47,79,79,0.08)',
          }}>
            <div style={{
              fontFamily: serif(), fontSize: 32, color: '#6B8F84',
              lineHeight: 1, marginBottom: 6, letterSpacing: '-0.01em',
            }}>{n}</div>
            <div style={{ fontSize: 11.5, color: '#888', lineHeight: 1.4 }}>{l}</div>
          </div>
        ))}
      </div>

      {/* Reflectie-tijdlijn */}
      {reflEntries.length > 0 && (
        <div style={{ marginBottom: 22 }}>
          <SectionHead title="Hoe je je voelde" sub="tik om bij te werken"/>
          <Card pad={0}>
            {reflEntries.map(([k, r], i) => {
              const d = new Date(k);
              const dStr = d.toLocaleDateString('nl-NL', { weekday: 'short', day: 'numeric', month: 'short' });
              const moodSize = 8 + (r.mood || 0) * 3;
              const allTags = Object.values(r.tags || {}).flat();
              const preview = allTags.slice(0, 4).join(' · ');
              return (
                <div key={k} onClick={() => setEditDate(k)} style={{
                  display: 'flex', alignItems: 'flex-start', gap: 13, padding: '14px 16px',
                  borderBottom: i < reflEntries.length - 1 ? '1px solid #F4F1EA' : 'none',
                  cursor: 'pointer',
                }}>
                  <div style={{
                    width: 36, display: 'flex', flexDirection: 'column', alignItems: 'center',
                    paddingTop: 3, flexShrink: 0,
                  }}>
                    <div style={{
                      width: moodSize, height: moodSize, borderRadius: '50%',
                      background: '#82A898',
                    }}/>
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 12, color: '#6B8F84', marginBottom: 3, textTransform: 'capitalize' }}>
                      {dStr}{k === todayK ? ' · vandaag' : ''}
                    </div>
                    {preview && (
                      <div style={{ fontSize: 13, color: '#2F4F4F', lineHeight: 1.5, marginBottom: r.note ? 4 : 0 }}>
                        {preview}{allTags.length > 4 ? ` +${allTags.length - 4}` : ''}
                      </div>
                    )}
                    {r.note && (
                      <div style={{ fontSize: 12, color: '#a59f95', fontStyle: 'italic', lineHeight: 1.5 }}>
                        "{r.note}"
                      </div>
                    )}
                  </div>
                </div>
              );
            })}
          </Card>
        </div>
      )}

      {/* Huidige fase */}
      <div style={{
        background: '#fff', borderRadius: 14, padding: 22,
        boxShadow: '0 2px 8px rgba(47,79,79,0.08)',
        borderLeft: '4px solid #82A898', marginBottom: 14,
      }}>
        <Eyebrow>Nu bezig{state.protocol?.actieve?.fase_titel ? ` · ${state.protocol.actieve.fase_titel}` : ''}</Eyebrow>
        <H2 style={{ marginBottom: 10 }}>{state.protocol?.actieve?.fase_titel || 'Actieve fase'}</H2>
        {phases.length > 1 && (() => {
          const pct = Math.round((actieveFase / phases.length) * 100);
          return (
            <div style={{ marginBottom: 16 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, color: '#a59f95', marginBottom: 5 }}>
                <span>Fase {actieveFase} van {phases.length}</span>
                <span>{pct}%</span>
              </div>
              <div style={{ height: 6, background: '#F4F1EA', borderRadius: 3, overflow: 'hidden' }}>
                <div style={{
                  height: '100%', width: `${pct}%`,
                  background: 'linear-gradient(90deg, #82A898, #6B8F84)',
                  borderRadius: 3, transition: 'width .6s ease',
                }}/>
              </div>
            </div>
          );
        })()}
        {state.protocol?.actieve?.fase_omschrijving && (
          <Body style={{ marginBottom: 16, color: '#555' }}>
            {state.protocol.actieve.fase_omschrijving}
          </Body>
        )}
        {parseBullets(state.protocol?.actieve?.fase_bulletpoints).map(x => (
          <div key={x} style={{ display: 'flex', alignItems: 'center', gap: 11, fontSize: 13, color: '#2F4F4F', marginBottom: 9 }}>
            <div style={{ width: 7, height: 7, borderRadius: '50%', background: '#82A898' }}/>
            {x}
          </div>
        ))}
        {(state.protocol?.vorige || state.protocol?.volgende) && (
          <div style={{ display: 'flex', gap: 8, marginTop: 14, flexWrap: 'wrap' }}>
            {state.protocol.vorige && (
              <div style={{ fontSize: 11, color: '#82A898', background: '#eaf2ef', borderRadius: 10, padding: '4px 10px', display: 'flex', alignItems: 'center', gap: 5 }}>
                <IconCheck size={11} color="#82A898" stroke={2.5}/> Afgerond: {state.protocol.vorige.fase_titel}
              </div>
            )}
            {state.protocol.volgende && (
              <div style={{ fontSize: 11, color: '#b0b0b0', background: '#f4f4f4', borderRadius: 10, padding: '4px 10px', display: 'flex', alignItems: 'center', gap: 5 }}>
                <IconLock size={10} color="#c0c0c0" stroke={2}/> Volgende: {state.protocol.volgende.fase_titel}
              </div>
            )}
          </div>
        )}
        {!state.protocol && (
          <div style={{ fontSize: 12.5, color: '#a59f95' }}>Protocol wordt geladen…</div>
        )}
      </div>

      {editDate && (
        <ReflectieModal
          state={state}
          setState={setState}
          dateKey={editDate}
          onClose={() => setEditDate(null)}
        />
      )}
    </div>
  );
}

// ─────────── PROFIEL ───────────
function NotificatiesSectie() {
  return (
    <>
      <div style={{
        fontFamily: serif(), fontSize: 16, color: '#2F4F4F',
        marginBottom: 10, marginTop: 4,
      }}>Meldingen</div>

      <div style={{
        background: '#fff', borderRadius: 12, padding: '16px 18px',
        marginBottom: 22, boxShadow: '0 2px 8px rgba(47,79,79,0.08)',
      }}>
        <div style={{ fontSize: 13, color: '#6B6B6B', lineHeight: 1.65 }}>
          Meldingen komen beschikbaar wanneer de app in de App Store verschijnt.
        </div>
      </div>
    </>
  );
}

function ScreenProfiel({ state, setState }) {
  const [view, setView] = React.useState('main'); // main | saved
  const [openArticle, setOpenArticle] = React.useState(null);
  const [behandelplan, setBehandelplan] = React.useState(undefined); // undefined=laden, null=geen plan

  React.useEffect(() => {
    if (window.MintDB) {
      window.MintDB.laadBehandelplan().then(plan => setBehandelplan(plan || null));
    }
  }, []);

  if (openArticle) {
    return <ArtikelDetail article={openArticle} onBack={() => setOpenArticle(null)} state={state} setState={setState}/>;
  }
  if (view === 'saved') {
    return <ScreenMijnArtikelen
      state={state} setState={setState}
      onBack={() => setView('main')}
      onOpen={(a) => setOpenArticle(a)}
    />;
  }

  const updGewicht = (v) => {
    const kg = Math.max(30, Math.min(200, parseFloat(v) || 70));
    const liters = (kg * 0.030).toFixed(1).replace('.', ',');
    setState(s => ({ ...s, gewicht: kg, waterDoel: liters }));
  };

  const fmtGeboortedatum = (iso) => {
    if (!iso) return '—';
    const d = new Date(iso + 'T00:00:00');
    if (isNaN(d)) return iso;
    return d.toLocaleDateString('nl-NL', { day: 'numeric', month: 'long', year: 'numeric' });
  };
  const toggleMeal = (m) => setState(s => ({
    ...s, meals: { ...s.meals, [m]: !s.meals[m] },
  }));

  const activeUitsluitingen = Object.keys(state.uitsluitingen || {}).filter(k => state.uitsluitingen[k]);

  return (
    <div style={{ padding: '24px 20px 32px' }}>
      <H1 style={{ textAlign: 'center', marginBottom: 4 }}>Mijn profiel</H1>
      <Sub><div style={{ textAlign: 'center' }}>Cliënt sinds 3 maart 2026</div></Sub>

      {/* Persoonskaart */}
      <div style={{
        background: '#fff', borderRadius: 14, padding: 22, textAlign: 'center',
        marginBottom: 18, boxShadow: '0 2px 8px rgba(47,79,79,0.08)',
      }}>
        <div style={{
          width: 84, height: 84, borderRadius: '50%', background: '#9BBAB3',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          margin: '0 auto 12px',
          fontFamily: serif(), fontSize: 34, color: '#fff',
        }}>T</div>
        <div style={{ fontFamily: serif(), fontSize: 22, color: '#2F4F4F', marginBottom: 4 }}>
          {state.naam || '—'}
        </div>
        <div style={{ fontSize: 12, color: '#82A898' }}>
          {state.protocol
            ? `${state.protocol.actieve.naam} · ${state.protocol.actieve.fase_titel}`
            : 'Jouw traject'}
        </div>
      </div>


      {/* Mail Thirza — prominente kaart */}
      <div style={{
        background: '#1a2e28', borderRadius: 14, padding: 20, marginBottom: 22,
        display: 'flex', gap: 14, alignItems: 'center',
      }}>
        <div style={{
          width: 48, height: 48, borderRadius: '50%', background: '#D9937A',
          display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
          fontFamily: serif(), fontSize: 20, color: '#fff',
        }}>T</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 13.5, color: '#fff', marginBottom: 2, fontWeight: 500 }}>
            Vraag aan Thirza
          </div>
          <div style={{ fontSize: 11.5, color: '#9BBAB3', lineHeight: 1.5 }}>
            Een vraag over je protocol? Ik lees mee en antwoord binnen enkele werkdagen.
          </div>
        </div>
        <a href="mailto:thirza@mint-natuurgeneeskunde.nl" style={{
          width: 40, height: 40, borderRadius: '50%', background: '#D9937A',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          cursor: 'pointer', flexShrink: 0, textDecoration: 'none',
        }}>
          <IconMail size={18} color="#fff"/>
        </a>
      </div>

      {/* Mijn artikelen — tappable rij */}
      <SectionHead title="Mijn artikelen"/>
      <div
        onClick={() => setView('saved')}
        style={{
          background: '#fff', borderRadius: 14, padding: '16px 18px',
          marginBottom: 22, boxShadow: '0 2px 8px rgba(47,79,79,0.08)',
          display: 'flex', alignItems: 'center', gap: 14, cursor: 'pointer',
        }}
      >
        <div style={{
          width: 40, height: 40, borderRadius: '50%', background: '#eaf2ef',
          display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
        }}>
          <IconBookmark size={18} color="#82A898" stroke={1.8} filled={true}/>
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 14, color: '#2F4F4F', marginBottom: 2 }}>Bewaarde artikelen</div>
          <div style={{ fontSize: 11.5, color: '#a59f95' }}>
            {(() => {
              const n = Object.keys(state.savedArticles || {}).length;
              if (n === 0) return 'Nog niets bewaard';
              return `${n} ${n === 1 ? 'artikel' : 'artikelen'} opgeslagen`;
            })()}
          </div>
        </div>
        <IconArrow size={16} color="#82A898" stroke={1.6}/>
      </div>

      {/* Mijn behandelplan */}
      <SectionHead title="Mijn behandelplan"/>
      <div style={{
        background: '#fff', borderRadius: 14, padding: 18, marginBottom: 22,
        boxShadow: '0 2px 8px rgba(47,79,79,0.08)',
      }}>
        {behandelplan === undefined ? (
          <div style={{ fontSize: 12.5, color: '#a59f95' }}>Laden…</div>
        ) : behandelplan === null ? (
          <div style={{ fontSize: 12.5, color: '#a59f95', fontStyle: 'italic', lineHeight: 1.6 }}>
            Nog geen behandelplan beschikbaar. Thirza uploadt dit voor je.
          </div>
        ) : (
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <div style={{
              width: 44, height: 44, borderRadius: 11, background: '#eaf2ef',
              display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
            }}>
              <svg width="22" height="22" fill="none" stroke="#6B8F84" strokeWidth="1.7"
                viewBox="0 0 24 24" strokeLinecap="round" strokeLinejoin="round">
                <path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/>
                <polyline points="14 2 14 8 20 8"/>
                <line x1="9" y1="13" x2="15" y2="13"/>
                <line x1="9" y1="17" x2="15" y2="17"/>
              </svg>
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13.5, fontWeight: 500, color: '#2F4F4F', marginBottom: 3 }}>
                {behandelplan.bestand_naam}
              </div>
              <div style={{ fontSize: 11, color: '#a59f95' }}>
                {'Geüpload op ' + new Date(behandelplan.upload_datum).toLocaleDateString('nl-NL', { day: 'numeric', month: 'long', year: 'numeric' })}
              </div>
            </div>
            {behandelplan.downloadUrl ? (
              <a
                href={behandelplan.downloadUrl}
                target="_blank"
                rel="noopener noreferrer"
                style={{
                  background: '#82A898', color: '#fff', borderRadius: 8,
                  padding: '9px 16px', fontSize: 12.5, fontWeight: 500,
                  textDecoration: 'none', flexShrink: 0,
                }}
              >
                Download
              </a>
            ) : (
              <div style={{ fontSize: 11.5, color: '#c0392b', flexShrink: 0 }}>Niet beschikbaar</div>
            )}
          </div>
        )}
      </div>

      {/* Mijn gegevens */}
      <SectionHead title="Mijn gegevens"/>
      {(() => {
        const [gewichtStr, setGewichtStr] = React.useState(String(state.gewicht ?? ''));
        return (
          <Card>
            <div style={rowStyle}>
              <span style={labelStyle}>Naam</span>
              <span style={{ fontSize: 13, color: '#2F4F4F' }}>{state.naam || '—'}</span>
            </div>
            <div style={rowStyle}>
              <span style={labelStyle}>Geboortedatum</span>
              <span style={{ fontSize: 13, color: '#2F4F4F' }}>{fmtGeboortedatum(state.geboortedatum)}</span>
            </div>
            <div style={{ ...rowStyle, borderBottom: 'none' }}>
              <span style={labelStyle}>Gewicht</span>
              <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
                <input
                  className="mint-input"
                  type="number"
                  step="0.1"
                  value={gewichtStr}
                  onChange={e => setGewichtStr(e.target.value)}
                  onBlur={() => {
                    const kg = Math.max(30, Math.min(200, parseFloat(gewichtStr) || state.gewicht));
                    const liters = (kg * 0.030).toFixed(1).replace('.', ',');
                    setGewichtStr(String(kg));
                    setState(s => ({ ...s, gewicht: kg, waterDoel: liters }));
                    if (window.MintDB) window.MintDB.slaaProfiel({ lichaamsgewicht_kg: kg });
                  }}
                  style={{ width: 72, textAlign: 'right' }}
                />
                <span style={{ fontSize: 12.5, color: '#82A898' }}>kg</span>
              </div>
            </div>
            <div style={{
              background: '#eaf2ef', borderRadius: 8, padding: '11px 14px',
              marginTop: 12, fontSize: 12.5, color: '#6B8F84', fontWeight: 500,
              display: 'flex', alignItems: 'center', gap: 9,
            }}>
              <IconDrop size={16} color="#6B8F84"/>
              Afgeleid: {state.waterDoel} liter water per dag
            </div>
          </Card>
        );
      })()}

      {/* Maaltijden — bewerkbaar */}
      <SectionHead title="Welke maaltijden wil je zien"/>
      <Card>
        {['Ontbijt', 'Lunch', 'Diner', 'Snack 1', 'Feest'].map((m, i, a) => (
          <div key={m} style={{
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            padding: '12px 0',
            borderBottom: i < a.length-1 ? '1px solid #F4F1EA' : 'none',
          }}>
            <span style={{ fontSize: 14, color: '#2F4F4F' }}>{m}</span>
            <Toggle on={!!state.meals[m]} onClick={() => toggleMeal(m)}/>
          </div>
        ))}
      </Card>

      {/* Voedingsaanpassingen — readonly, door therapeut */}
      <SectionHead title="Voedingsaanpassingen" sub="door Thirza ingesteld"/>
      <div style={{
        background: '#fff', borderRadius: 14, padding: 18, marginBottom: 8,
        boxShadow: '0 2px 8px rgba(47,79,79,0.08)',
      }}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 9, marginBottom: 12,
          fontSize: 11.5, color: '#a59f95',
        }}>
          <IconLock size={13} color="#a59f95"/>
          Ingesteld door Thirza · niet aanpasbaar
        </div>
        {activeUitsluitingen.length === 0 ? (
          <div style={{ fontSize: 12.5, color: '#a59f95', fontStyle: 'italic' }}>
            Geen voedingsaanpassingen ingesteld.
          </div>
        ) : (
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
            {activeUitsluitingen.map(d => (
              <div key={d} style={{
                background: '#eaf2ef', color: '#6B8F84',
                borderRadius: 20, padding: '6px 13px', fontSize: 12.5,
              }}>{d.charAt(0).toUpperCase() + d.slice(1)}</div>
            ))}
          </div>
        )}
        <div style={{ fontSize: 12, color: '#a0a0a0', lineHeight: 1.6, marginTop: 12 }}>
          Deze aanpassingen zijn bepaald op basis van je anamnese.
          Recepten worden hier automatisch op gefilterd. Neem contact op met
          Thirza als je hier vragen over hebt.
        </div>
      </div>

      <div style={{ textAlign: 'center', fontSize: 11, color: '#b5b5b5', marginTop: 22, lineHeight: 1.6 }}>
        Mint · versie 1.0<br/>
        Privacy · Voorwaarden ·{' '}
        <span
          onClick={() => window.MintDB?.uitloggen()}
          style={{ cursor: 'pointer', textDecoration: 'underline' }}
        >Uitloggen</span>
      </div>
    </div>
  );
}

const rowStyle = {
  display: 'flex', alignItems: 'center', justifyContent: 'space-between',
  padding: '12px 0', borderBottom: '1px solid #F4F1EA',
};
const labelStyle = { fontSize: 14, color: '#2F4F4F' };

// ─────────── MIJN ARTIKELEN ───────────
function ScreenMijnArtikelen({ state, setState, onBack, onOpen }) {
  const all = (state.blogs || []).map(b => window.mapBlog ? window.mapBlog(b) : b);
  const savedIds = state.savedArticles || {};
  const saved = all.filter(a => savedIds[a.id]);

  return (
    <div style={{ padding: '24px 20px 32px' }}>
      {/* Header met terug */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 14 }}>
        <div onClick={onBack} style={{
          width: 36, height: 36, borderRadius: '50%', background: '#fff',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          cursor: 'pointer', boxShadow: '0 2px 6px rgba(47,79,79,0.08)',
        }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#2F4F4F" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
            <path d="M19 12H5M11 18l-6-6 6-6"/>
          </svg>
        </div>
        <div>
          <Eyebrow style={{ marginBottom: 2 }}>Profiel</Eyebrow>
          <H1 style={{ marginBottom: 0 }}>Mijn artikelen</H1>
        </div>
      </div>

      <Sub style={{ marginBottom: 22 }}>Wat je hebt bewaard om later te lezen</Sub>

      {saved.length === 0 ? (
        <div style={{
          background: '#fff', borderRadius: 14, padding: '40px 24px',
          textAlign: 'center', boxShadow: '0 2px 8px rgba(47,79,79,0.08)',
        }}>
          <div style={{
            width: 72, height: 72, borderRadius: '50%', background: '#F4F1EA',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            margin: '0 auto 16px',
          }}>
            <IconBookmark size={28} color="#C9B79C" stroke={1.4}/>
          </div>
          <div style={{
            fontFamily: serif(), fontSize: 18, color: '#2F4F4F',
            lineHeight: 1.35, marginBottom: 8,
          }}>
            Je hebt nog geen artikelen bewaard.
          </div>
          <div style={{ fontSize: 12.5, color: '#a59f95', lineHeight: 1.6, maxWidth: 260, margin: '0 auto' }}>
            Tik op het bladwijzer-icoon rechtsboven in een artikel om het hier te verzamelen.
          </div>
        </div>
      ) : (
        saved.map(a => {
          const AIc = a.Ic;
          return (
            <div key={a.id} onClick={() => onOpen(a)} style={{
              background: '#fff', borderRadius: 14, padding: 14, marginBottom: 12,
              boxShadow: '0 2px 8px rgba(47,79,79,0.08)', cursor: 'pointer',
              display: 'flex', gap: 14,
            }}>
              <div style={{
                width: 70, height: 70, borderRadius: 10, background: a.bg,
                display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
              }}>
                <AIc size={28} color="#6B8F84" stroke={1.3}/>
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 10.5, color: '#D9937A', marginBottom: 4, letterSpacing: '0.04em' }}>
                  {a.cat.toUpperCase()}
                </div>
                <div style={{
                  fontFamily: serif(), fontSize: 15, color: '#2F4F4F',
                  lineHeight: 1.3, marginBottom: 6,
                }}>{a.title}</div>
                <div style={{ fontSize: 11, color: '#82A898' }}>{a.readMin} min lezen</div>
              </div>
            </div>
          );
        })
      )}
    </div>
  );
}

Object.assign(window, { ScreenBestellen, ScreenVoortgang, ScreenProfiel, ReflectieModal, ScreenMijnArtikelen });
