// Useful.jsx — вкладка «Полезное»: статьи по неделям и категориям
(function () {
  const { useState } = React;
  const { t, getTrimester, fetusAsset } = window.AliaData;
  const { CATEGORIES, ARTICLES, weeklyArticle, getCategory, articlesByCat, getArticle } = window.AliaArticles;

  function coverFor(article, lang) {
    if (article.week) return fetusAsset(article.week);
    const cat = getCategory(article.cat);
    return 'assets/cover-' + (cat ? cat.cover : 'default') + '.svg';
  }

  /* ── Article reader ──────────────────────────────────────────── */
  function ArticleReader({ article, lang, onBack }) {
    const ru = lang === 'ru';
    const s = {
      wrap:{ height:'100%', overflowY:'auto', WebkitOverflowScrolling:'touch', paddingBottom:'24px' },
      hero:{ position:'relative', height:200, backgroundSize:'cover', backgroundPosition:'center',
             backgroundImage:`url(${coverFor(article, lang)})`, display:'flex', alignItems:'flex-end' },
      back:{ position:'absolute', top:14, left:14, width:38, height:38, borderRadius:'50%', border:'none',
             background:'rgba(0,0,0,0.35)', color:'#fff', fontSize:20, cursor:'pointer', backdropFilter:'blur(4px)' },
      heroPad:{ padding:'16px', width:'100%', background:'linear-gradient(transparent, rgba(0,0,0,0.45))' },
      heroTitle:{ color:'#fff', fontSize:24, fontWeight:900, lineHeight:1.15, textShadow:'0 1px 6px rgba(0,0,0,0.4)' },
      body:{ padding:'18px 18px 0', maxWidth:560, margin:'0 auto' },
      meta:{ fontSize:12, color:'var(--text-2)', fontWeight:700, marginBottom:14, textTransform:'uppercase', letterSpacing:'0.4px' },
      h:{ fontSize:17, fontWeight:800, color:'var(--text)', margin:'18px 0 7px' },
      p:{ fontSize:15.5, lineHeight:1.6, color:'var(--text)', opacity:0.92 },
      li:{ fontSize:15, lineHeight:1.55, color:'var(--text)', opacity:0.92, marginBottom:7, paddingLeft:18, position:'relative' },
      bullet:{ position:'absolute', left:0, top:0, color:'var(--primary)', fontWeight:900 },
      disc:{ marginTop:22, padding:'12px 14px', background:'var(--primary-light)', borderRadius:12, fontSize:13, color:'var(--text-2)', lineHeight:1.5 },
    };
    const cat = getCategory(article.cat);
    return (
      <div style={s.wrap}>
        <div style={s.hero}>
          <button style={s.back} onClick={onBack}>←</button>
          <div style={s.heroPad}><div style={s.heroTitle}>{article.title}</div></div>
        </div>
        <div style={s.body}>
          <div style={s.meta}>{cat ? (ru ? cat.ru : cat.en) : ''} · {article.minutes} {t('readMin', lang)}</div>
          {article.sections.map((sec, i) => (
            <div key={i}>
              {sec.h && <div style={s.h}>{sec.h}</div>}
              {sec.p && <div style={s.p}>{sec.p}</div>}
              {sec.list && sec.list.map((li, j) => (
                <div key={j} style={s.li}><span style={s.bullet}>•</span>{li}</div>
              ))}
            </div>
          ))}
          <div style={s.disc}>{ru
            ? 'Материал носит информационный характер и не заменяет консультацию врача.'
            : 'This content is informational and does not replace medical advice.'}</div>
        </div>
      </div>
    );
  }

  /* ── Card ────────────────────────────────────────────────────── */
  function ArticleCard({ article, lang, onOpen, wide }) {
    const s = {
      card:{ flexShrink:0, width: wide ? 240 : 170, cursor:'pointer' },
      img:{ width:'100%', height: wide ? 150 : 120, borderRadius:16, backgroundSize:'cover', backgroundPosition:'center',
            backgroundImage:`url(${coverFor(article, lang)})`, boxShadow:'0 3px 14px var(--shadow)',
            position:'relative', display:'flex', alignItems:'flex-start', padding:10 },
      tag:{ background:'rgba(0,0,0,0.4)', color:'#fff', fontSize:10, fontWeight:700, padding:'3px 8px', borderRadius:8, backdropFilter:'blur(3px)' },
      title:{ fontSize:14, fontWeight:800, color:'var(--text)', marginTop:8, lineHeight:1.25 },
      sum:{ fontSize:12, color:'var(--text-2)', marginTop:3, lineHeight:1.35, display:'-webkit-box',
            WebkitLineClamp:2, WebkitBoxOrient:'vertical', overflow:'hidden' },
    };
    return (
      <div style={s.card} onClick={() => onOpen(article)}>
        <div style={s.img}><span style={s.tag}>{lang === 'ru' ? 'Статья' : 'Article'}</span></div>
        <div style={s.title}>{article.title}</div>
        <div style={s.sum}>{article.summary}</div>
      </div>
    );
  }

  /* ── Main screen ─────────────────────────────────────────────── */
  function UsefulScreen({ lang, currentWeek, appMode }) {
    const [open, setOpen] = useState(null);
    const ru = lang === 'ru';

    if (open) return <ArticleReader article={open} lang={lang} onBack={() => setOpen(null)} />;

    const week = Math.max(4, Math.min(40, currentWeek || 12));
    const weekArticles = appMode === 'pregnancy'
      ? [0, 1, 2].map(d => weeklyArticle(Math.min(40, week + d), lang)).filter(Boolean)
      : [];

    // Категории, релевантные режиму: в режиме цикла/ttc показываем фертильность первой
    const cats = appMode === 'pregnancy'
      ? CATEGORIES.filter(c => c.id !== 'fertility')
      : [CATEGORIES.find(c => c.id === 'fertility'),
         CATEGORIES.find(c => c.id === 'body'),
         CATEGORIES.find(c => c.id === 'nutrition'),
         CATEGORIES.find(c => c.id === 'psychology'),
         CATEGORIES.find(c => c.id === 'lifestyle')].filter(Boolean);

    const s = {
      wrap:{ height:'100%', overflowY:'auto', WebkitOverflowScrolling:'touch', paddingBottom:'24px' },
      inner:{ padding:'18px 0 0', maxWidth:600, margin:'0 auto' },
      h1:{ fontSize:26, fontWeight:900, color:'var(--text)', padding:'0 16px 6px' },
      secTitle:{ fontSize:18, fontWeight:800, color:'var(--text)', padding:'18px 16px 10px' },
      rail:{ display:'flex', gap:14, overflowX:'auto', padding:'0 16px 6px', scrollbarWidth:'none' },
    };

    return (
      <div style={s.wrap}>
        <div style={s.inner}>
          <div style={s.h1}>{t('usefulTitle', lang)}</div>

          {weekArticles.length > 0 && (
            <>
              <div style={s.secTitle}>{t('byWeeks', lang)}</div>
              <div style={s.rail}>
                {weekArticles.map(a => <ArticleCard key={a.id} article={a} lang={lang} onOpen={setOpen} wide />)}
              </div>
            </>
          )}

          {cats.map(cat => {
            const list = articlesByCat(cat.id);
            if (!list.length) return null;
            return (
              <div key={cat.id}>
                <div style={s.secTitle}>{ru ? cat.ru : cat.en}</div>
                <div style={s.rail}>
                  {list.map(a => <ArticleCard key={a.id} article={a} lang={lang} onOpen={setOpen} />)}
                </div>
              </div>
            );
          })}
        </div>
      </div>
    );
  }

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