// screens-learn.jsx — Knowledge base / Learn section

// ===========================================================
//  LEARN SCREEN — index / browse
// ===========================================================
function LearnScreen({ setRoute }) {
  const { t, lang } = useLang();
  const [category, setCategory] = useState('all');
  const [search, setSearch] = useState('');

  const filtered = useMemo(() => {
    let xs = LEARN_ARTICLES.slice();
    if (category !== 'all') xs = xs.filter(a => a.category === category);
    if (search.trim()) {
      const q = search.trim().toLowerCase();
      xs = xs.filter(a =>
        a.title.toLowerCase().includes(q) ||
        a.subtitle.toLowerCase().includes(q) ||
        a.intro.toLowerCase().includes(q) ||
        a.sections.some(s => s.heading.toLowerCase().includes(q))
      );
    }
    return xs;
  }, [category, search]);

  // Crisis article always goes last (unless searching for it)
  const sorted = [...filtered.filter(a => a.category !== 'crisis'), ...filtered.filter(a => a.category === 'crisis')];

  return (
    <div className="page">
      {/* Header */}
      <div style={{ marginBottom: 32 }}>
        <span className="eyebrow muted">{t('learn_eyebrow')}</span>
        <h1 className="display" style={{ fontSize: 48, marginTop: 10, textWrap: 'balance' }}>
          {t('learn_h1')}
        </h1>
        <p style={{ color: 'var(--fg2)', marginTop: 14, fontSize: 17, lineHeight: 1.55, maxWidth: 600 }}>
          {t('learn_eyebrow_sub')}
        </p>

        {/* Search */}
        <div className="search" style={{ marginTop: 24, maxWidth: 520 }}>
          <Icon name="search" />
          <input
            placeholder={t('learn_search')}
            value={search}
            onChange={e => setSearch(e.target.value)}
          />
        </div>
      </div>

      {/* Category tabs */}
      <div className="tabs" style={{ marginBottom: 28 }}>
        {LEARN_CATEGORIES.map(c => (
          <button
            key={c.id}
            className={`tab ${category === c.id ? 'active' : ''}`}
            onClick={() => { setCategory(c.id); setSearch(''); }}>
            {lang === 'el' && c.label_el ? c.label_el : c.label}
            {category !== 'all' && c.id !== 'all' && (
              <span style={{ marginLeft: 6, fontSize: 11, color: 'var(--fg3)' }}>
                {LEARN_ARTICLES.filter(a => a.category === c.id).length}
              </span>
            )}
          </button>
        ))}
      </div>

      {/* Featured crisis card — always visible, unobtrusive */}
      {(category === 'all' || category === 'crisis') && !search && (
        <div
          onClick={() => setRoute('article', 'crisis')}
          style={{
            background: 'var(--psy-ink)', color: 'white', borderRadius: 20,
            padding: '20px 24px', marginBottom: 24,
            display: 'flex', alignItems: 'center', gap: 14, cursor: 'pointer',
            transition: 'opacity 150ms',
          }}
          onMouseEnter={e => e.currentTarget.style.opacity = 0.9}
          onMouseLeave={e => e.currentTarget.style.opacity = 1}>
          <div style={{ width: 44, height: 44, borderRadius: 12, background: 'rgba(255,255,255,0.12)', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
            <Icon name="sos" style={{ color: 'white', fontSize: 22 }} />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: 600, fontSize: 15 }}>{t('learn_crisis_h')}</div>
            <div style={{ fontSize: 13, color: 'rgba(255,255,255,0.65)', marginTop: 2 }}>
              {t('learn_crisis_p')}
            </div>
          </div>
          <Icon name="arrow_forward" style={{ color: 'rgba(255,255,255,0.55)' }} />
        </div>
      )}

      {/* Article grid */}
      {sorted.filter(a => a.category !== 'crisis').length === 0 && !search ? null : (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(320px, 1fr))', gap: 16 }}>
          {sorted.filter(a => a.category !== 'crisis').map(article => (
            <ArticleCard key={article.id} article={article} onClick={() => setRoute('article', article.id)} />
          ))}
        </div>
      )}

      {filtered.length === 0 && (
        <div className="card" style={{ padding: 48, textAlign: 'center' }}>
          <Icon name="search_off" style={{ fontSize: 36, color: 'var(--fg3)' }} />
          <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 20, marginTop: 14, fontWeight: 600 }}>No articles found</h3>
          <p style={{ color: 'var(--fg2)', marginTop: 8 }}>Try a different search term or browse all categories.</p>
          <button className="btn ghost" style={{ marginTop: 16 }} onClick={() => { setSearch(''); setCategory('all'); }}>Clear search</button>
        </div>
      )}
    </div>
  );
}

// ── Article card ──────────────────────────────────────────
const CATEGORY_STYLE = {
  therapy: { bg: 'var(--psy-accent-soft)', color: 'var(--psy-accent-deep)', label: 'Therapy guide',  label_el: 'Οδηγός θεραπείας' },
  topic:   { bg: 'var(--psy-leaf-soft)',   color: 'var(--psy-leaf)',         label: 'Mental health',  label_el: 'Ψυχική υγεία'      },
  faq:     { bg: 'var(--psy-surface)',      color: 'var(--fg2)',              label: 'Practical FAQ',  label_el: 'Πρακτικές ερωτήσεις' },
  crisis:  { bg: '#FEE2E2',                color: '#DC2626',                 label: 'Crisis support', label_el: 'Υποστήριξη κρίσης'  },
};

function ArticleCard({ article, onClick }) {
  const { t, lang } = useLang();
  const cs = CATEGORY_STYLE[article.category] || CATEGORY_STYLE.faq;
  const displayTitle    = lang === 'el' && article.title_el    ? article.title_el    : article.title;
  const displaySubtitle = lang === 'el' && article.subtitle_el ? article.subtitle_el : article.subtitle;
  const displayIntro    = lang === 'el' && article.intro_el    ? article.intro_el    : article.intro;
  const displayCatLabel = lang === 'el' && cs.label_el         ? cs.label_el         : cs.label;
  // readTime may be '6 min' — strip the English 'min' and append translated unit
  const readNum = parseInt(article.readTime, 10) || article.readTime;

  return (
    <div
      className="card hoverable"
      onClick={onClick}
      style={{ padding: 24, cursor: 'pointer', display: 'flex', flexDirection: 'column', gap: 0 }}>
      {/* Icon + category */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
        <div style={{ width: 44, height: 44, borderRadius: 12, background: cs.bg, display: 'grid', placeItems: 'center' }}>
          <Icon name={article.icon} style={{ color: cs.color, fontSize: 22 }} />
        </div>
        <span style={{ background: cs.bg, color: cs.color, borderRadius: 999, padding: '3px 10px', fontSize: 11, fontWeight: 600 }}>
          {displayCatLabel}
        </span>
      </div>

      <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 19, fontWeight: 600, letterSpacing: '-0.018em', margin: '0 0 6px', lineHeight: 1.25 }}>
        {displayTitle}
      </h3>
      <p style={{ margin: '0 0 16px', fontSize: 13, color: 'var(--fg2)', lineHeight: 1.5 }}>
        {displaySubtitle}
      </p>
      <p style={{ margin: '0 0 auto', fontSize: 13.5, color: 'var(--fg2)', lineHeight: 1.55,
        display: '-webkit-box', WebkitLineClamp: 3, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>
        {displayIntro}
      </p>

      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 18, paddingTop: 14, borderTop: '1px solid var(--psy-rule)' }}>
        <span style={{ fontSize: 12, color: 'var(--fg3)' }}>
          <Icon name="schedule" className="sm" style={{ verticalAlign: -3, marginRight: 4 }} />{readNum} {t('learn_mins')}
        </span>
        <Icon name="arrow_forward" style={{ color: 'var(--fg3)', fontSize: 18 }} />
      </div>
    </div>
  );
}

// ===========================================================
//  ARTICLE SCREEN — individual article reader
// ===========================================================
function ArticleScreen({ articleId, setRoute }) {
  const { t, lang } = useLang();
  const article = LEARN_ARTICLES.find(a => a.id === articleId);
  const related = LEARN_ARTICLES.filter(a => article?.relatedIds?.includes(a.id));

  if (!article) {
    return (
      <div className="page narrow" style={{ textAlign: 'center', paddingTop: 80 }}>
        <h2 className="display" style={{ fontSize: 28 }}>Article not found</h2>
        <button className="btn ghost" style={{ marginTop: 20 }} onClick={() => setRoute('learn')}>
          <Icon name="arrow_back" className="sm" /> Back to Learn
        </button>
      </div>
    );
  }

  const cs = CATEGORY_STYLE[article.category] || CATEGORY_STYLE.faq;
  const displayCatLabel = lang === 'el' && cs.label_el ? cs.label_el : cs.label;
  const readNum = parseInt(article.readTime, 10) || article.readTime;

  return (
    <div className="page narrow" style={{ maxWidth: 760 }}>
      {/* Breadcrumb */}
      <button className="btn link" style={{ fontSize: 13, marginBottom: 24 }} onClick={() => setRoute('learn')}>
        <Icon name="arrow_back" className="sm" /> {t('learn_back')}
      </button>

      {/* Article header */}
      <div style={{ marginBottom: 36 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 16 }}>
          <span style={{ background: cs.bg, color: cs.color, borderRadius: 999, padding: '4px 12px', fontSize: 12, fontWeight: 600 }}>
            {displayCatLabel}
          </span>
          <span style={{ fontSize: 12, color: 'var(--fg3)' }}>
            <Icon name="schedule" className="sm" style={{ verticalAlign: -3, marginRight: 4 }} />{readNum} {t('learn_mins')}
          </span>
        </div>
        <h1 className="display" style={{ fontSize: 44, fontWeight: 600, letterSpacing: '-0.028em', lineHeight: 1.08, textWrap: 'balance', margin: '0 0 12px' }}>
          {lang === 'el' && article.title_el ? article.title_el : article.title}
        </h1>
        <p style={{ fontSize: 20, color: 'var(--fg2)', margin: '0 0 14px', lineHeight: 1.4 }}>
          {lang === 'el' && article.subtitle_el ? article.subtitle_el : article.subtitle}
        </p>
        {/* Byline */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13, color: 'var(--fg3)' }}>
          <Icon name="person" style={{ fontSize: 15, verticalAlign: -2 }} />
          <span>{lang === 'el' ? 'από' : 'by'} The Psyche Team</span>
          <span style={{ opacity: 0.5 }}>·</span>
          <span>{article.date || 'June 2025'}</span>
        </div>
      </div>

      {/* Intro */}
      <p style={{ fontSize: 18, lineHeight: 1.65, color: 'var(--psy-ink)', marginBottom: 40, borderLeft: '3px solid var(--psy-accent)', paddingLeft: 20 }}>
        {lang === 'el' && article.intro_el ? article.intro_el : article.intro}
      </p>

      {/* Sections */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 36 }}>
        {article.sections.map((s, i) => {
          const sHeading = lang === 'el' && s.heading_el ? s.heading_el : s.heading;
          const sParas   = lang === 'el' && s.paragraphs_el ? s.paragraphs_el : s.paragraphs;
          return (
          <section key={i}>
            <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 24, fontWeight: 600, letterSpacing: '-0.02em', margin: '0 0 14px', color: 'var(--psy-ink)' }}>
              {sHeading}
            </h2>
            {sParas.map((p, j) => (
              <p key={j} style={{ fontSize: 16, lineHeight: 1.7, color: 'var(--psy-ink)', margin: j < sParas.length - 1 ? '0 0 14px' : 0 }}>
                {p}
              </p>
            ))}
          </section>
          );
        })}
      </div>

      {/* CTA — directory link */}
      {(article.approachId || article.specializationId) && (
        <div className="card" style={{ marginTop: 48, padding: 28, background: 'var(--psy-ink)', borderColor: 'transparent', color: 'white' }}>
          <span className="eyebrow" style={{ color: 'color-mix(in oklab, var(--psy-accent) 55%, white)' }}>Find a psychologist</span>
          <h3 className="display" style={{ color: 'white', fontSize: 22, marginTop: 8, marginBottom: 14 }}>
            {article.approachId
              ? `Looking for a ${article.title.split('(')[0].trim()} practitioner in Cyprus?`
              : `Looking for a psychologist specialising in ${article.title.replace('Understanding ', '')}?`}
          </h3>
          <button
            className="btn accent"
            onClick={() => setRoute('directory')}>
            Browse the directory <Icon name="arrow_forward" className="sm" />
          </button>
        </div>
      )}

      {/* Crisis resources — always present */}
      {article.category !== 'crisis' && (
        <div style={{ marginTop: 24, padding: '14px 20px', background: 'var(--psy-surface)', borderRadius: 14, display: 'flex', gap: 12, alignItems: 'center' }}>
          <Icon name="sos" style={{ color: 'var(--fg2)', fontSize: 20, flexShrink: 0 }} />
          <span style={{ fontSize: 13, color: 'var(--fg2)', lineHeight: 1.5 }}>
            If you need support right now, call the Cyprus Mental Health Helpline{' '}
            <a href="tel:1410" style={{ fontWeight: 600, color: 'var(--psy-ink)' }}>1410</a>{' '}
            (free, 24/7) or emergency services{' '}
            <a href="tel:112" style={{ fontWeight: 600, color: 'var(--psy-ink)' }}>112</a>.
          </span>
        </div>
      )}

      {/* Related articles */}
      {related.length > 0 && (
        <div style={{ marginTop: 56 }}>
          <h2 className="display" style={{ fontSize: 26, fontWeight: 600, marginBottom: 20 }}>{t('learn_related')}</h2>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))', gap: 14 }}>
            {related.map(r => (
              <ArticleCard key={r.id} article={r} onClick={() => { setRoute('article', r.id); window.scrollTo({ top: 0, behavior: 'smooth' }); }} />
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { LearnScreen, ArticleScreen, ArticleCard });
