// Tools.jsx — вкладка «Инструменты»: сетка + экраны функций
(function () {
  const { useState, useEffect, useRef } = React;
  const D = window.AliaData;
  const { t, getWeekData, getTrimester, fetusAsset, getSize, NAMES, CHECKLISTS, TIMELINE, weightGainRange } = D;
  const API = window.AliaAPI;

  const loggedIn = () => API.isLoggedIn() && !localStorage.getItem('alia_guest');

  /* ── Хук: синхронизируемый список (localStorage + бэкенд) ──────── */
  function useSyncedList(kind, seedTitles) {
    const [items, setItems] = useState([]);
    const lsKey = 'alia_items_' + kind;

    function saveLocal(list) { localStorage.setItem(lsKey, JSON.stringify(list)); }
    function loadLocal() {
      const raw = localStorage.getItem(lsKey);
      if (raw) { try { return JSON.parse(raw); } catch (e) {} }
      if (seedTitles && seedTitles.length) {
        return seedTitles.map((title, i) => ({ id: 'l' + i + '_' + Date.now(), title, done: false, sort_order: i, payload: {} }));
      }
      return [];
    }

    useEffect(() => {
      let alive = true;
      if (loggedIn()) {
        API.getItems(kind).then(r => {
          if (!alive) return;
          let list = r.items || [];
          if (list.length === 0 && seedTitles && seedTitles.length) {
            Promise.all(seedTitles.map((title, i) => API.createItem({ kind, title, sort_order: i })))
              .then(() => API.getItems(kind)).then(r2 => { if (alive) setItems(normalize(r2.items || [])); })
              .catch(() => { const l = loadLocal(); setItems(l); saveLocal(l); });
          } else setItems(normalize(list));
        }).catch(() => { const l = loadLocal(); setItems(l); saveLocal(l); });
      } else {
        const l = loadLocal(); setItems(l); saveLocal(l);
      }
      return () => { alive = false; };
    }, []); // eslint-disable-line

    function normalize(list) {
      return list.map(it => ({ ...it, payload: typeof it.payload === 'string' ? safeParse(it.payload) : (it.payload || {}) }));
    }
    function safeParse(s) { try { return JSON.parse(s); } catch (e) { return {}; } }

    function add(title, payload) {
      const tmpId = 'l_' + Date.now();
      const next = [...items, { id: tmpId, title, done: false, sort_order: items.length, payload: payload || {} }];
      setItems(next); if (!loggedIn()) saveLocal(next);
      if (loggedIn()) API.createItem({ kind, title, payload: payload || {}, sort_order: items.length })
        .then(r => setItems(cur => cur.map(x => x.id === tmpId ? { ...x, id: r.id } : x)))
        .catch(() => { saveLocal(next); });
    }
    function update(id, fields) {
      const next = items.map(x => x.id === id ? { ...x, ...fields } : x);
      setItems(next); if (!loggedIn()) saveLocal(next);
      if (loggedIn() && typeof id === 'number') API.updateItem(id, fields).catch(() => {});
    }
    function toggle(id) {
      const it = items.find(x => x.id === id); if (!it) return;
      update(id, { done: !it.done });
    }
    function remove(id) {
      const next = items.filter(x => x.id !== id);
      setItems(next); if (!loggedIn()) saveLocal(next);
      if (loggedIn() && typeof id === 'number') API.deleteItem(id).catch(() => {});
    }
    return { items, add, update, toggle, remove };
  }

  /* ── Общие стили ──────────────────────────────────────────────── */
  function screenStyles() {
    return {
      wrap:{ height:'100%', overflowY:'auto', WebkitOverflowScrolling:'touch', paddingBottom:'24px' },
      inner:{ padding:'16px', maxWidth:600, margin:'0 auto' },
      head:{ display:'flex', alignItems:'center', gap:12, padding:'4px 0 14px' },
      back:{ width:38, height:38, borderRadius:'50%', border:'none', background:'var(--bg-card)', color:'var(--text)',
             fontSize:20, cursor:'pointer', boxShadow:'0 2px 8px var(--shadow)', flexShrink:0 },
      title:{ fontSize:22, fontWeight:900, color:'var(--text)' },
      card:{ background:'var(--bg-card)', borderRadius:16, padding:'14px 16px', boxShadow:'0 2px 12px var(--shadow)', marginBottom:12 },
      row:{ display:'flex', alignItems:'center', gap:12, padding:'12px 0', borderBottom:'1px solid var(--border)' },
      check:(d)=>({ width:24, height:24, borderRadius:7, border:'2px solid', flexShrink:0, cursor:'pointer',
        borderColor: d ? 'var(--primary)' : 'var(--border)', background: d ? 'var(--primary)' : 'transparent',
        color:'#fff', display:'flex', alignItems:'center', justifyContent:'center', fontSize:14 }),
      itemText:(d)=>({ flex:1, fontSize:15.5, color:'var(--text)', textDecoration: d ? 'line-through' : 'none', opacity: d ? 0.5 : 1 }),
      del:{ background:'none', border:'none', color:'var(--text-2)', fontSize:18, cursor:'pointer', padding:'2px 4px' },
      addRow:{ display:'flex', gap:8, marginTop:14 },
      input:{ flex:1, padding:'13px 14px', borderRadius:12, border:'2px solid var(--border)', background:'var(--bg-card)',
              color:'var(--text)', fontSize:15, fontFamily:'Nunito,sans-serif', outline:'none' },
      addBtn:{ padding:'0 18px', borderRadius:12, border:'none', background:'var(--primary)', color:'#fff',
               fontSize:15, fontWeight:800, cursor:'pointer', fontFamily:'Nunito,sans-serif' },
      progress:{ height:8, borderRadius:4, background:'var(--primary-light)', overflow:'hidden', margin:'2px 0 14px' },
      progressFill:(p)=>({ height:'100%', width:p+'%', background:'var(--primary)', transition:'width .3s' }),
      muted:{ fontSize:13, color:'var(--text-2)' },
    };
  }

  /* ── Чек-лист (сумка, дела, покупки) ──────────────────────────── */
  function ChecklistScreen({ lang, title, kind, seed, onBack, placeholder }) {
    const { items, add, toggle, remove } = useSyncedList(kind, seed);
    const [val, setVal] = useState('');
    const s = screenStyles();
    const doneCount = items.filter(i => i.done).length;
    const pct = items.length ? Math.round(doneCount / items.length * 100) : 0;
    return (
      <div style={s.wrap}><div style={s.inner}>
        <div style={s.head}><button style={s.back} onClick={onBack}>←</button><span style={s.title}>{title}</span></div>
        <div style={s.muted}>{t('completed', lang)}: {doneCount} / {items.length}</div>
        <div style={s.progress}><div style={s.progressFill(pct)}></div></div>
        <div style={s.card}>
          {items.length === 0 && <div style={s.muted}>{t('noData', lang)}</div>}
          {items.map((it, i) => (
            <div key={it.id} style={{ ...s.row, borderBottom: i === items.length - 1 ? 'none' : '1px solid var(--border)' }}>
              <div style={s.check(it.done)} onClick={() => toggle(it.id)}>{it.done ? '✓' : ''}</div>
              <span style={s.itemText(it.done)}>{it.title}</span>
              <button style={s.del} onClick={() => remove(it.id)}>✕</button>
            </div>
          ))}
        </div>
        <div style={s.addRow}>
          <input style={s.input} value={val} placeholder={placeholder || (lang==='ru'?'Новый пункт':'New item')}
            onChange={e => setVal(e.target.value)} onKeyDown={e => { if (e.key === 'Enter' && val.trim()) { add(val.trim()); setVal(''); } }} />
          <button style={s.addBtn} onClick={() => { if (val.trim()) { add(val.trim()); setVal(''); } }}>+</button>
        </div>
      </div></div>
    );
  }

  /* ── Вопросы врачу ────────────────────────────────────────────── */
  function QuestionsScreen({ lang, onBack }) {
    return <ChecklistScreen lang={lang} title={t('toolQuestions', lang)} kind="question"
      seed={CHECKLISTS.question} onBack={onBack} placeholder={lang==='ru'?'Ваш вопрос':'Your question'} />;
  }

  /* ── Визиты к врачу ───────────────────────────────────────────── */
  function VisitsScreen({ lang, onBack }) {
    const { items, add, remove } = useSyncedList('appointment', null);
    const [title, setTitle] = useState('');
    const [date, setDate] = useState('');
    const s = screenStyles();
    const sorted = [...items].sort((a, b) => (a.payload.date || '').localeCompare(b.payload.date || ''));
    return (
      <div style={s.wrap}><div style={s.inner}>
        <div style={s.head}><button style={s.back} onClick={onBack}>←</button><span style={s.title}>{t('toolVisits', lang)}</span></div>
        <div style={s.card}>
          {sorted.length === 0 && <div style={s.muted}>{t('noData', lang)}</div>}
          {sorted.map((it, i) => (
            <div key={it.id} style={{ ...s.row, borderBottom: i === sorted.length - 1 ? 'none' : '1px solid var(--border)' }}>
              <span style={{ fontSize:13, fontWeight:800, color:'var(--primary)', minWidth:92 }}>{it.payload.date || '—'}</span>
              <span style={{ flex:1, fontSize:15, color:'var(--text)' }}>{it.title}</span>
              <button style={s.del} onClick={() => remove(it.id)}>✕</button>
            </div>
          ))}
        </div>
        <div style={s.card}>
          <input type="date" style={{ ...s.input, width:'100%', marginBottom:10 }} value={date} onChange={e => setDate(e.target.value)} />
          <div style={s.addRow}>
            <input style={s.input} value={title} placeholder={lang==='ru'?'Напр. УЗИ, приём':'e.g. ultrasound'}
              onChange={e => setTitle(e.target.value)} />
            <button style={s.addBtn} onClick={() => { if (title.trim()) { add(title.trim(), { date }); setTitle(''); setDate(''); } }}>+</button>
          </div>
        </div>
      </div></div>
    );
  }

  /* ── Имена ────────────────────────────────────────────────────── */
  function NamesScreen({ lang, babyGender, onBack }) {
    const { items, add, remove } = useSyncedList('name_fav', null);
    const [gender, setGender] = useState(babyGender === 'boy' ? 'boy' : 'girl');
    const s = screenStyles();
    const ru = lang === 'ru';
    const favSet = new Set(items.map(i => i.title));
    const list = NAMES[gender] || [];
    function toggleFav(name) {
      const ex = items.find(i => i.title === name);
      if (ex) remove(ex.id); else add(name, { gender });
    }
    const tab = (a) => ({ flex:1, padding:'10px', borderRadius:12, border:'2px solid',
      borderColor:a?'var(--primary)':'var(--border)', background:a?'var(--primary-light)':'var(--bg-card)',
      color:a?'var(--primary)':'var(--text-2)', fontSize:14, fontWeight:700, cursor:'pointer', fontFamily:'Nunito,sans-serif' });
    return (
      <div style={s.wrap}><div style={s.inner}>
        <div style={s.head}><button style={s.back} onClick={onBack}>←</button><span style={s.title}>{t('toolNames', lang)}</span></div>
        {items.length > 0 && (
          <div style={s.card}>
            <div style={{ fontSize:13, fontWeight:800, color:'var(--text-2)', marginBottom:8 }}>{ru?'Избранное':'Favorites'} ⭐</div>
            <div style={{ display:'flex', flexWrap:'wrap', gap:8 }}>
              {items.map(it => (
                <span key={it.id} onClick={() => remove(it.id)}
                  style={{ background:'var(--primary-light)', color:'var(--primary)', padding:'6px 12px', borderRadius:20, fontSize:14, fontWeight:700, cursor:'pointer' }}>
                  {it.title} ✕
                </span>
              ))}
            </div>
          </div>
        )}
        <div style={{ display:'flex', gap:8, marginBottom:12 }}>
          <button style={tab(gender==='girl')} onClick={() => setGender('girl')}>💗 {ru?'Девочки':'Girls'}</button>
          <button style={tab(gender==='boy')} onClick={() => setGender('boy')}>💙 {ru?'Мальчики':'Boys'}</button>
        </div>
        <div style={s.card}>
          {list.map((it, i) => (
            <div key={it.n} style={{ ...s.row, borderBottom: i === list.length - 1 ? 'none' : '1px solid var(--border)' }}>
              <div style={{ flex:1 }}>
                <div style={{ fontSize:16, fontWeight:700, color:'var(--text)' }}>{it.n}</div>
                <div style={{ fontSize:12.5, color:'var(--text-2)' }}>{it.m}</div>
              </div>
              <button onClick={() => toggleFav(it.n)} style={{ background:'none', border:'none', fontSize:22, cursor:'pointer' }}>
                {favSet.has(it.n) ? '⭐' : '☆'}
              </button>
            </div>
          ))}
        </div>
      </div></div>
    );
  }

  /* ── Мой вес ──────────────────────────────────────────────────── */
  function WeightScreen({ lang, onBack }) {
    const [entries, setEntries] = useState([]);
    const [date, setDate] = useState((D.todayISO || (() => new Date().toISOString().split('T')[0]))());
    const [kg, setKg] = useState('');
    const s = screenStyles();
    const lsKey = 'alia_weights';

    useEffect(() => {
      if (loggedIn()) API.getWeights().then(r => setEntries(r.weights || [])).catch(loadLocal);
      else loadLocal();
      function loadLocal() { const raw = localStorage.getItem(lsKey); if (raw) { try { setEntries(JSON.parse(raw)); } catch(e){} } }
    }, []); // eslint-disable-line

    function addEntry() {
      if (!kg) return;
      const w = parseFloat(kg);
      const tmpId = Date.now();
      const next = [...entries.filter(e => e.date !== date), { id: tmpId, date, weight_kg: w }].sort((a,b)=>a.date.localeCompare(b.date));
      setEntries(next); localStorage.setItem(lsKey, JSON.stringify(next));
      if (loggedIn()) API.saveWeight({ date, weight_kg: w })
        .then(r => { if (r && r.id) setEntries(cur => { const upd = cur.map(e => e.id === tmpId ? { ...e, id: r.id } : e); localStorage.setItem(lsKey, JSON.stringify(upd)); return upd; }); })
        .catch(() => {});
      setKg('');
    }
    function delEntry(e) {
      const next = entries.filter(x => x !== e);
      setEntries(next); localStorage.setItem(lsKey, JSON.stringify(next));
      if (loggedIn() && typeof e.id === 'number' && e.id < 1e12) API.deleteWeight(e.id).catch(() => {});
    }

    const ru = lang === 'ru';
    const vals = entries.map(e => +e.weight_kg);
    const min = Math.min(...vals, 40), max = Math.max(...vals, 100);
    const W = 320, Hh = 90;
    const pts = entries.map((e, i) => {
      const x = entries.length > 1 ? (i / (entries.length - 1)) * W : W / 2;
      const y = Hh - ((+e.weight_kg - min) / (max - min || 1)) * Hh;
      return [x, y];
    });
    const path = pts.map((p, i) => (i === 0 ? 'M' : 'L') + p[0].toFixed(1) + ' ' + p[1].toFixed(1)).join(' ');
    const diff = entries.length ? (vals[vals.length-1] - vals[0]).toFixed(1) : null;

    return (
      <div style={s.wrap}><div style={s.inner}>
        <div style={s.head}><button style={s.back} onClick={onBack}>←</button><span style={s.title}>{t('toolWeight', lang)}</span></div>
        {entries.length > 0 && (
          <div style={s.card}>
            <div style={{ display:'flex', justifyContent:'space-between', marginBottom:10 }}>
              <span style={s.muted}>{ru?'Прибавка':'Total gain'}</span>
              <b style={{ color:'var(--primary)' }}>{diff > 0 ? '+' : ''}{diff} {ru?'кг':'kg'}</b>
            </div>
            <svg width="100%" viewBox={`0 0 ${W} ${Hh}`} preserveAspectRatio="none" style={{ display:'block' }}>
              <path d={path} fill="none" stroke="var(--primary)" strokeWidth="2.5" strokeLinejoin="round" strokeLinecap="round" />
              {pts.map((p, i) => <circle key={i} cx={p[0]} cy={p[1]} r="3.5" fill="var(--primary)" />)}
            </svg>
          </div>
        )}
        <div style={s.card}>
          <div style={s.addRow}>
            <input type="date" style={s.input} value={date} max={(D.todayISO || (() => new Date().toISOString().split('T')[0]))()} onChange={e => setDate(e.target.value)} />
            <input type="number" style={{ ...s.input, maxWidth:90 }} value={kg} placeholder={ru?'кг':'kg'} onChange={e => setKg(e.target.value)} />
            <button style={s.addBtn} onClick={addEntry}>+</button>
          </div>
        </div>
        <div style={{ ...s.card, background:'var(--primary-light)' }}>
          <div style={{ fontSize:13.5, color:'var(--text)', lineHeight:1.5 }}>
            {ru ? '💡 Рекомендованная прибавка за беременность (IOM/ВОЗ): при нормальном ИМТ — 11,5–16 кг, при дефиците — 12,5–18 кг, при избытке — 7–11,5 кг, при ожирении — 5–9 кг.'
                : '💡 Recommended total gain (IOM/WHO): normal BMI 11.5–16 kg, underweight 12.5–18 kg, overweight 7–11.5 kg, obese 5–9 kg.'}
          </div>
        </div>
        {entries.length > 0 && (
          <div style={s.card}>
            {[...entries].reverse().map((e, i) => (
              <div key={i} style={{ ...s.row, borderBottom: i === entries.length-1 ? 'none' : '1px solid var(--border)' }}>
                <span style={{ flex:1, fontSize:14, color:'var(--text-2)' }}>{e.date}</span>
                <b style={{ color:'var(--text)' }}>{(+e.weight_kg).toFixed(1)} {ru?'кг':'kg'}</b>
                <button style={s.del} onClick={() => delEntry(e)}>✕</button>
              </div>
            ))}
          </div>
        )}
      </div></div>
    );
  }

  /* ── Размер малыша ────────────────────────────────────────────── */
  function SizeScreen({ lang, currentWeek, onBack }) {
    const [week, setWeek] = useState(Math.max(4, Math.min(40, currentWeek || 20)));
    const s = screenStyles();
    const ru = lang === 'ru';
    const sz = getSize(week);
    return (
      <div style={s.wrap}><div style={s.inner}>
        <div style={s.head}><button style={s.back} onClick={onBack}>←</button><span style={s.title}>{t('toolSize', lang)}</span></div>
        <div style={{ ...s.card, textAlign:'center', padding:'28px 16px' }}>
          <div style={{ fontSize:96, lineHeight:1 }}>{sz.emoji}</div>
          <div style={{ fontSize:22, fontWeight:900, color:'var(--text)', marginTop:14 }}>{ru ? sz.sizeRu : sz.sizeEn}</div>
          <div style={{ display:'flex', justifyContent:'center', gap:24, marginTop:18 }}>
            <div><div style={s.muted}>{t('labelLength', lang)}</div><b style={{ fontSize:18 }}>{D.formatLength(sz.lengthMm, lang)}</b></div>
            <div><div style={s.muted}>{t('labelWeight', lang)}</div><b style={{ fontSize:18 }}>{D.formatWeight(sz.weightG, lang)}</b></div>
          </div>
        </div>
        <div style={s.card}>
          <div style={{ display:'flex', justifyContent:'space-between', marginBottom:8 }}>
            <span style={s.muted}>{t('week', lang)}</span><b>{week}</b>
          </div>
          <input type="range" min={4} max={40} value={week} onChange={e => setWeek(+e.target.value)}
            style={{ width:'100%', accentColor:'var(--primary)' }} />
        </div>
      </div></div>
    );
  }

  /* ── 3D Модель (иллюстрация по неделям) ───────────────────────── */
  function ModelScreen({ lang, currentWeek, onBack }) {
    const [week, setWeek] = useState(Math.max(4, Math.min(40, currentWeek || 20)));
    const s = screenStyles();
    const ru = lang === 'ru';
    const wd = getWeekData(week);
    return (
      <div style={s.wrap}><div style={s.inner}>
        <div style={s.head}><button style={s.back} onClick={onBack}>←</button><span style={s.title}>{t('tool3d', lang)}</span></div>
        <div style={{ borderRadius:20, overflow:'hidden', boxShadow:'0 4px 20px var(--shadow)', marginBottom:12 }}>
          <img src={fetusAsset(week)} alt="" style={{ width:'100%', display:'block' }} />
        </div>
        <div style={{ ...s.card, textAlign:'center' }}>
          <div style={{ fontSize:20, fontWeight:900, color:'var(--primary)' }}>{t('week', lang)} {week}</div>
          <div style={{ fontSize:14.5, color:'var(--text)', marginTop:8, lineHeight:1.5 }}>{ru ? wd.babyRu : wd.babyEn}</div>
        </div>
        <div style={s.card}>
          <input type="range" min={4} max={40} value={week} onChange={e => setWeek(+e.target.value)}
            style={{ width:'100%', accentColor:'var(--primary)' }} />
          <div style={{ display:'flex', justifyContent:'space-between' }}><span style={s.muted}>4</span><span style={s.muted}>40</span></div>
        </div>
        <div style={{ ...s.card, background:'var(--primary-light)' }}>
          <div style={{ fontSize:12.5, color:'var(--text-2)', lineHeight:1.5 }}>
            {ru ? 'Иллюстрация схематична и помогает представить развитие малыша по неделям.'
                : 'Illustration is schematic and helps visualize weekly development.'}
          </div>
        </div>
      </div></div>
    );
  }

  /* ── Хронология ───────────────────────────────────────────────── */
  function TimelineScreen({ lang, currentWeek, onBack }) {
    const s = screenStyles();
    const ru = lang === 'ru';
    return (
      <div style={s.wrap}><div style={s.inner}>
        <div style={s.head}><button style={s.back} onClick={onBack}>←</button><span style={s.title}>{t('toolTimeline', lang)}</span></div>
        <div style={{ position:'relative', paddingLeft:8 }}>
          {TIMELINE.map((m, i) => {
            const passed = currentWeek && currentWeek >= m.week;
            const isNow = currentWeek && currentWeek >= m.week && (i === TIMELINE.length-1 || currentWeek < TIMELINE[i+1].week);
            return (
              <div key={i} style={{ display:'flex', gap:14, alignItems:'flex-start', position:'relative', paddingBottom:18 }}>
                {i < TIMELINE.length-1 && <div style={{ position:'absolute', left:21, top:34, bottom:0, width:2, background:'var(--border)' }}></div>}
                <div style={{ width:44, height:44, borderRadius:'50%', flexShrink:0, display:'flex', alignItems:'center', justifyContent:'center',
                  fontSize:20, zIndex:1, background: passed ? 'var(--primary)' : 'var(--bg-card)',
                  border:'2px solid', borderColor: passed ? 'var(--primary)' : 'var(--border)',
                  boxShadow: isNow ? '0 0 0 4px var(--primary-light)' : 'none' }}>{m.emoji}</div>
                <div style={{ flex:1, background:'var(--bg-card)', borderRadius:14, padding:'12px 14px', boxShadow:'0 2px 10px var(--shadow)' }}>
                  <div style={{ fontSize:12, fontWeight:800, color:'var(--primary)' }}>{t('week', lang)} {m.week}{isNow ? (ru?' · сейчас':' · now') : ''}</div>
                  <div style={{ fontSize:15, fontWeight:700, color:'var(--text)', marginTop:2 }}>{ru ? m.ru : m.en}</div>
                </div>
              </div>
            );
          })}
        </div>
      </div></div>
    );
  }

  /* ── УЗИ (пример по неделям + заметки) ────────────────────────── */
  function UltrasoundScreen({ lang, currentWeek, onBack }) {
    const [week, setWeek] = useState(Math.max(8, Math.min(40, currentWeek || 20)));
    const s = screenStyles();
    const ru = lang === 'ru';
    return (
      <div style={s.wrap}><div style={s.inner}>
        <div style={s.head}><button style={s.back} onClick={onBack}>←</button><span style={s.title}>{t('toolUltrasound', lang)}</span></div>
        <div style={{ borderRadius:20, overflow:'hidden', marginBottom:12, background:'#1a1a1a', position:'relative' }}>
          <img src={fetusAsset(week)} alt="" style={{ width:'100%', display:'block', filter:'grayscale(1) contrast(1.3) brightness(0.85) sepia(0.25)' }} />
          <div style={{ position:'absolute', top:10, left:12, color:'#fff', fontSize:12, fontWeight:700, opacity:0.85 }}>
            ALIA · {t('week', lang)} {week}
          </div>
        </div>
        <div style={{ ...s.card, background:'var(--primary-light)' }}>
          <div style={{ fontSize:12.5, color:'var(--text-2)', lineHeight:1.5 }}>
            {ru ? 'Это иллюстративный пример. Сюда вы сможете загрузить собственные снимки УЗИ (в следующих обновлениях).'
                : 'This is an illustrative sample. You will be able to upload your own ultrasound scans in upcoming updates.'}
          </div>
        </div>
        <div style={s.card}>
          <input type="range" min={8} max={40} value={week} onChange={e => setWeek(+e.target.value)}
            style={{ width:'100%', accentColor:'var(--primary)' }} />
        </div>
      </div></div>
    );
  }

  /* ── План родов ───────────────────────────────────────────────── */
  function BirthPlanScreen({ lang, onBack }) {
    const lsKey = 'alia_birth_plan';
    const [sel, setSel] = useState(() => { try { return JSON.parse(localStorage.getItem(lsKey)) || {}; } catch(e){ return {}; } });
    const s = screenStyles();
    const ru = lang === 'ru';
    const GROUPS = [
      { id:'place', q: ru?'Место родов':'Place of birth', opts: ru?['Роддом','Перинатальный центр','Дом']:['Hospital','Perinatal center','Home'] },
      { id:'pain',  q: ru?'Обезболивание':'Pain relief', opts: ru?['Естественно, без анестезии','Эпидуральная анестезия','По ситуации']:['Natural','Epidural','Decide later'] },
      { id:'partner', q: ru?'Партнёрские роды':'Birth partner', opts: ru?['Да, с партнёром','Нет']:['Yes','No'] },
      { id:'feeding', q: ru?'Первое прикладывание':'First feeding', opts: ru?['Сразу к груди','Позже']:['Skin-to-skin asap','Later'] },
      { id:'cord', q: ru?'Пуповина':'Umbilical cord', opts: ru?['Отсроченное пересечение','По решению врача']:['Delayed clamping','Doctor decides'] },
    ];
    function pick(g, o) {
      const next = { ...sel, [g]: o };
      setSel(next); localStorage.setItem(lsKey, JSON.stringify(next));
      if (loggedIn()) API.updateProfile({ birth_plan: next }).catch(() => {});
    }
    const opt = (a) => ({ padding:'11px 14px', borderRadius:12, border:'2px solid', marginBottom:8, cursor:'pointer',
      borderColor:a?'var(--primary)':'var(--border)', background:a?'var(--primary-light)':'var(--bg-card)',
      color:a?'var(--primary)':'var(--text)', fontSize:14.5, fontWeight:a?700:600 });
    return (
      <div style={s.wrap}><div style={s.inner}>
        <div style={s.head}><button style={s.back} onClick={onBack}>←</button><span style={s.title}>{t('toolBirthPlan', lang)}</span></div>
        {GROUPS.map(g => (
          <div key={g.id} style={s.card}>
            <div style={{ fontSize:15, fontWeight:800, color:'var(--text)', marginBottom:10 }}>{g.q}</div>
            {g.opts.map(o => <div key={o} style={opt(sel[g.id] === o)} onClick={() => pick(g.id, o)}>{sel[g.id] === o ? '✓ ' : ''}{o}</div>)}
          </div>
        ))}
      </div></div>
    );
  }

  /* ── Иконки инструментов (адаптируются под тему) ──────────────── */
  const ic = (paths) => ({ size = 30 }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="var(--primary)" strokeWidth="1.9"
      strokeLinecap="round" strokeLinejoin="round">{paths}</svg>
  );
  const ICONS = {
    size: ic(<><path d="M12 3a4 4 0 0 1 4 4c0 3-4 5-4 5s-4-2-4-5a4 4 0 0 1 4-4z"/><path d="M9 16h6M10 20h4"/></>),
    model: ic(<><circle cx="12" cy="8" r="4"/><path d="M6 21c0-4 2-6 6-6s6 2 6 6"/></>),
    timeline: ic(<><circle cx="6" cy="6" r="2"/><circle cx="6" cy="18" r="2"/><path d="M6 8v8M11 6h7M11 18h7"/></>),
    names: ic(<><path d="M12 21s-7-4.5-7-10a4 4 0 0 1 7-2.5A4 4 0 0 1 19 11c0 5.5-7 10-7 10z"/></>),
    ultrasound: ic(<><rect x="3" y="4" width="18" height="14" rx="2"/><path d="M7 14c2-4 8-4 10 0"/><circle cx="12" cy="9" r="1.5"/></>),
    birthplan: ic(<><rect x="5" y="3" width="14" height="18" rx="2"/><path d="M9 8h6M9 12h6M9 16h4"/></>),
    bag: ic(<><rect x="4" y="7" width="16" height="13" rx="2"/><path d="M9 7V5a3 3 0 0 1 6 0v2"/></>),
    weight: ic(<><circle cx="12" cy="13" r="8"/><path d="M12 13l3-4M8 4h8"/></>),
    todo: ic(<><path d="M4 6h16M4 12h16M4 18h10"/><path d="M19 16l2 2 3-3" transform="translate(-4 0)"/></>),
    shopping: ic(<><path d="M6 6h15l-1.5 9h-12z"/><circle cx="9" cy="20" r="1.5"/><circle cx="18" cy="20" r="1.5"/><path d="M6 6L5 3H3"/></>),
    visits: ic(<><rect x="3" y="5" width="18" height="16" rx="2"/><path d="M3 9h18M8 3v4M16 3v4"/></>),
    questions: ic(<><circle cx="12" cy="12" r="9"/><path d="M9.5 9a2.5 2.5 0 1 1 3.5 2.3c-.8.4-1 .9-1 1.7M12 17h.01"/></>),
    kicks: ic(<><path d="M12 21s-7-4.5-7-10a4 4 0 0 1 7-2.5A4 4 0 0 1 19 11c0 5.5-7 10-7 10z"/></>),
    contractions: ic(<><circle cx="12" cy="13" r="8"/><path d="M12 13V8M12 2h0M9 2h6"/></>),
  };

  /* ── Каталог инструментов ─────────────────────────────────────── */
  const TOOLS = [
    { id:'size',         icon:'size',         titleK:'toolSize',         subK:'toolSizeSub',         modes:['pregnancy'] },
    { id:'model',        icon:'model',        titleK:'tool3d',           subK:'tool3dSub',           modes:['pregnancy'] },
    { id:'timeline',     icon:'timeline',     titleK:'toolTimeline',     subK:'toolTimelineSub',     modes:['pregnancy'] },
    { id:'names',        icon:'names',        titleK:'toolNames',        subK:'toolNamesSub',        modes:['pregnancy','ttc'] },
    { id:'ultrasound',   icon:'ultrasound',   titleK:'toolUltrasound',   subK:'toolUltrasoundSub',   modes:['pregnancy'] },
    { id:'birthplan',    icon:'birthplan',    titleK:'toolBirthPlan',    subK:'toolBirthPlanSub',    modes:['pregnancy'] },
    { id:'bag',          icon:'bag',          titleK:'toolBag',          subK:'toolBagSub',          modes:['pregnancy'] },
    { id:'weight',       icon:'weight',       titleK:'toolWeight',       subK:'toolWeightSub',       modes:['pregnancy','cycle','ttc'] },
    { id:'kicks',        icon:'kicks',        titleK:'toolKicks',        subK:'toolKicksSub',        modes:['pregnancy'] },
    { id:'contractions', icon:'contractions', titleK:'toolContr',        subK:'toolContrSub',        modes:['pregnancy'] },
    { id:'todo',         icon:'todo',         titleK:'toolTodo',         subK:'toolTodoSub',         modes:['pregnancy','ttc'] },
    { id:'shopping',     icon:'shopping',     titleK:'toolShopping',     subK:'toolShoppingSub',     modes:['pregnancy'] },
    { id:'visits',       icon:'visits',       titleK:'toolVisits',       subK:'toolVisitsSub',       modes:['pregnancy','cycle','ttc'] },
    { id:'questions',    icon:'questions',    titleK:'toolQuestions',    subK:'toolQuestionsSub',    modes:['pregnancy','ttc'] },
  ];

  /* ── Main screen ─────────────────────────────────────────────── */
  function ToolsScreen({ lang, currentWeek, dueDate, appMode, babyGender, initialView, onViewConsumed, refreshTick = 0 }) {
    const [view, setView] = useState(initialView || 'grid');
    const back = () => setView('grid');
    // быстрый переход с главного экрана (kicks/contractions) — один раз при монтировании
    useEffect(() => { if (initialView && onViewConsumed) onViewConsumed(); }, []); // eslint-disable-line

    // refreshTick меняется при «обновить» / pull-to-refresh — перемонтируем активный
    // экран (через key), чтобы его useEffect заново подтянул данные из БД, сохранив view.
    const rk = 'r' + refreshTick;
    let screen;
    if (view === 'size')              screen = <SizeScreen lang={lang} currentWeek={currentWeek} onBack={back} />;
    else if (view === 'model')        screen = <ModelScreen lang={lang} currentWeek={currentWeek} onBack={back} />;
    else if (view === 'timeline')     screen = <TimelineScreen lang={lang} currentWeek={currentWeek} onBack={back} />;
    else if (view === 'names')        screen = <NamesScreen lang={lang} babyGender={babyGender} onBack={back} />;
    else if (view === 'ultrasound')   screen = <UltrasoundScreen lang={lang} currentWeek={currentWeek} onBack={back} />;
    else if (view === 'birthplan')    screen = <BirthPlanScreen lang={lang} onBack={back} />;
    else if (view === 'weight')       screen = <WeightScreen lang={lang} onBack={back} />;
    else if (view === 'questions')    screen = <QuestionsScreen lang={lang} onBack={back} />;
    else if (view === 'visits')       screen = <VisitsScreen lang={lang} onBack={back} />;
    else if (view === 'bag')          screen = <ChecklistScreen lang={lang} title={t('toolBag', lang)} kind="bag" seed={CHECKLISTS.bag} onBack={back} />;
    else if (view === 'todo')         screen = <ChecklistScreen lang={lang} title={t('toolTodo', lang)} kind="todo" seed={CHECKLISTS.todo} onBack={back} />;
    else if (view === 'shopping')     screen = <ChecklistScreen lang={lang} title={t('toolShopping', lang)} kind="shopping" seed={CHECKLISTS.shopping} onBack={back} />;
    else if (view === 'kicks')        screen = <BackWrap onBack={back}><window.KicksScreen lang={lang} /></BackWrap>;
    else if (view === 'contractions') screen = <BackWrap onBack={back}><window.ContractionsScreen lang={lang} /></BackWrap>;
    if (screen) return <React.Fragment key={rk}>{screen}</React.Fragment>;

    const tools = TOOLS.filter(tt => tt.modes.includes(appMode));
    const s = {
      wrap:{ height:'100%', overflowY:'auto', WebkitOverflowScrolling:'touch', paddingBottom:'24px' },
      inner:{ padding:'18px 16px', maxWidth:600, margin:'0 auto' },
      h1:{ fontSize:26, fontWeight:900, color:'var(--text)', marginBottom:16 },
      grid:{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12 },
      card:{ background:'var(--bg-card)', borderRadius:18, padding:'16px', boxShadow:'0 2px 12px var(--shadow)', cursor:'pointer', border:'1px solid var(--border)' },
      iconBg:{ width:54, height:54, borderRadius:'50%', background:'var(--primary-light)', display:'flex', alignItems:'center', justifyContent:'center', marginBottom:12 },
      tTitle:{ fontSize:15.5, fontWeight:800, color:'var(--text)' },
      tSub:{ fontSize:12.5, color:'var(--text-2)', marginTop:3, lineHeight:1.3 },
    };
    return (
      <div style={s.wrap}><div style={s.inner}>
        <div style={s.h1}>{t('toolsTitle', lang)}</div>
        <div style={s.grid}>
          {tools.map(tt => {
            const Icon = ICONS[tt.icon];
            return (
              <div key={tt.id} style={s.card} onClick={() => setView(tt.id)}>
                <div style={s.iconBg}><Icon size={28} /></div>
                <div style={s.tTitle}>{t(tt.titleK, lang)}</div>
                <div style={s.tSub}>{t(tt.subK, lang)}</div>
              </div>
            );
          })}
        </div>
      </div></div>
    );
  }

  function BackWrap({ onBack, children }) {
    return (
      <div style={{ height:'100%', display:'flex', flexDirection:'column' }}>
        <div style={{ padding:'10px 16px 0' }}>
          <button onClick={onBack} style={{ width:38, height:38, borderRadius:'50%', border:'none',
            background:'var(--bg-card)', color:'var(--text)', fontSize:20, cursor:'pointer', boxShadow:'0 2px 8px var(--shadow)' }}>←</button>
        </div>
        <div style={{ flex:1, overflow:'hidden' }}>{children}</div>
      </div>
    );
  }

  Object.assign(window, { ToolsScreen });
})();
