/* ─────────────────────────────────────────────
   Reading practice mode for Learn.html
   Exposes window.ReadingMode
   Receives LessonQ + LEVELS as props from Learn.html.
   ───────────────────────────────────────────── */

const READING_CSS = `
  .rd-note{display:flex;align-items:center;gap:10px;background:rgba(200,146,42,.08);border:1.5px solid rgba(200,146,42,.22);border-radius:10px;padding:12px 18px;font-size:13px;color:var(--navy);margin-bottom:24px;}
  .rd-note .dot{display:inline-block;padding:2px 10px;border-radius:6px;background:rgba(200,146,42,.16);color:var(--gold);font-weight:700;font-size:13px;}
  .rd-body p{font-size:17px;line-height:1.9;color:var(--navy);margin-bottom:20px;font-weight:300;max-width:720px;}
  .rd-body p em{font-style:italic;}
  .vw-wrap{position:relative;display:inline-block;}
  .vw{font-family:inherit;font-size:inherit;font-weight:600;color:var(--gold);background:transparent;border:none;border-bottom:2px dotted rgba(200,146,42,.55);cursor:pointer;padding:0;line-height:inherit;}
  .vw:hover,.vw.open{background:rgba(200,146,42,.12);border-bottom-style:solid;}
  .vw-pop{position:absolute;bottom:calc(100% + 8px);left:50%;transform:translateX(-50%);z-index:60;width:270px;background:var(--navy);color:#fff;border-radius:12px;padding:14px 16px;box-shadow:0 16px 40px rgba(13,31,60,.35);display:block;text-align:left;direction:ltr;cursor:default;}
  .vw-pop::after{content:'';position:absolute;top:100%;left:50%;transform:translateX(-50%);border:7px solid transparent;border-top-color:var(--navy);}
  .vw-pop-word{display:block;font-family:var(--font-d);font-size:17px;font-weight:700;margin-bottom:4px;}
  .vw-pop-word em{font-size:11px;font-weight:400;color:var(--gold-lt);font-style:normal;letter-spacing:1px;text-transform:uppercase;margin-left:8px;}
  .vw-pop-def{display:block;font-size:13px;line-height:1.55;color:rgba(255,255,255,.85);font-weight:300;}
  .vw-pop-ex{display:block;font-size:12px;font-style:italic;color:rgba(255,255,255,.55);margin-top:8px;padding-top:8px;border-top:1px solid rgba(255,255,255,.12);}
  .rd-fig{margin:0 0 28px;}
  .rd-fig-slot{width:100%;max-width:720px;height:280px;}
  .rd-fig-cap{font-size:12.5px;color:var(--text-lt);font-style:italic;margin-top:10px;max-width:720px;}
  .rd-meta-row{display:flex;gap:14px;align-items:center;flex-wrap:wrap;margin-top:8px;font-size:12.5px;color:var(--text-lt);}
  .rd-meta-row .sep{width:3px;height:3px;border-radius:50%;background:var(--text-lt);}
  .rd-gloss{display:grid;grid-template-columns:repeat(auto-fill,minmax(300px,1fr));gap:12px;}
  .rd-gloss-item{background:#fff;border:1px solid rgba(13,31,60,.08);border-radius:12px;padding:14px 16px;}
  .rd-gloss-item .w{font-family:var(--font-d);font-size:16px;font-weight:700;color:var(--navy);}
  .rd-gloss-item .w em{font-size:10px;font-weight:600;color:var(--gold);font-style:normal;letter-spacing:1px;text-transform:uppercase;margin-left:7px;}
  .rd-gloss-item .d{font-size:13px;color:var(--text-mid);line-height:1.55;margin-top:4px;font-weight:300;}
  .rd-gloss-item .e{font-size:12px;color:var(--text-lt);font-style:italic;margin-top:6px;}
  @media(max-width:640px){ .rd-body p{font-size:16px;} .vw-pop{width:230px;} }
`;

function ReadingWord({ display, info, wid, openWord, setOpenWord, onAddWord, hasWord, t }) {
  const open = openWord === wid;
  const added = info && hasWord && hasWord(info.key);
  return (
    <span className="vw-wrap">
      <button className={'vw' + (open ? ' open' : '')}
              onClick={(e) => { e.stopPropagation(); setOpenWord(open ? null : wid); }}>
        {display}
      </button>
      {open && info && (
        <span className="vw-pop" onClick={(e) => e.stopPropagation()}>
          <span className="vw-pop-word">{info.key} <em>{info.pos}</em></span>
          <span className="vw-pop-def">{info.def}</span>
          {info.ex && <span className="vw-pop-ex">“{info.ex}”</span>}
          {onAddWord && (added
            ? <span className="vw-pop-add added">✓ {t('In My Words','في كلماتي','Kelimelerimde')}</span>
            : <button className="vw-pop-add" onClick={(e) => { e.stopPropagation(); onAddWord(info.key, info); }}>＋ {t('Add to My Words','أضف إلى كلماتي','Kelimelerime ekle')}</button>)}
        </span>
      )}
    </span>
  );
}

/* Renders one paragraph, turning [[word]] / [[display|key]] into tappable vocab */
function ReadingParagraph({ text, vocab, pIdx, openWord, setOpenWord, onAddWord, hasWord, t }) {
  const parts = text.split(/\[\[(.+?)\]\]/g);
  return (
    <p>
      {parts.map((part, i) => {
        if (i % 2 === 0) {
          // plain text — support *italic*
          const sub = part.split(/\*([^*]+)\*/g);
          return sub.map((s, j) => (j % 2 === 1 ? <em key={`${i}-${j}`}>{s}</em> : <React.Fragment key={`${i}-${j}`}>{s}</React.Fragment>));
        }
        const [display, key] = part.includes('|') ? part.split('|') : [part, part];
        const entry = vocab[key] || vocab[display] || vocab[display.toLowerCase()];
        const info = entry ? { ...entry, key: key || display } : null;
        return <ReadingWord key={i} display={display} info={info} wid={`${pIdx}-${i}`} openWord={openWord} setOpenWord={setOpenWord} onAddWord={onAddWord} hasWord={hasWord} t={t} />;
      })}
    </p>
  );
}

function ReadingDetail({ article, lang, state, setState, t, onBack, LessonQ, LEVELS, addWord, myWords }) {
  const [openWord, setOpenWord] = React.useState(null);
  const [scoreCorrect, setScoreCorrect] = React.useState(0);
  const [scoreTotal, setScoreTotal] = React.useState(0);
  const isAr = lang === 'ar';
  const lvlObj = (LEVELS || []).find(l => l.id === article.level);
  const completed = (state.readingCompleted || []).includes(article.id);
  const wordCount = article.body.join(' ').replace(/\[\[|\]\]/g, '').split(/\s+/).length;

  const hasWord = (w) => (myWords || []).some(x => (x.word || '').trim().toLowerCase() === (w || '').trim().toLowerCase());
  const onAddWord = addWord ? (key, info) => addWord({
    word: key.charAt(0).toUpperCase() + key.slice(1),
    defEn: info.def || '',
    exEn: info.ex ? `“${info.ex}”` : '',
    level: article.level,
    cat: 'collected',
    ctxEn: 'From reading', ctxAr: 'من القراءة',
  }) : null;

  React.useEffect(() => {
    const close = () => setOpenWord(null);
    document.addEventListener('click', close);
    return () => document.removeEventListener('click', close);
  }, []);

  const onScore = (ok) => {
    setScoreTotal(x => x + 1);
    if (ok) setScoreCorrect(c => c + 1);
    setState(s => ({ ...s, practiceScore: { correct: s.practiceScore.correct + (ok ? 1 : 0), total: s.practiceScore.total + 1 } }));
  };

  React.useEffect(() => {
    if (scoreTotal === article.questions.length && scoreTotal > 0 && !completed) {
      setState(s => {
        const next = { ...s, readingCompleted: [...(s.readingCompleted || []), article.id] };
        return window.bumpHistory ? window.bumpHistory(next, 'reading') : next;
      });
    }
  }, [scoreTotal]);

  React.useEffect(() => { window.scrollTo({ top: 200, behavior: 'smooth' }); }, []);

  const title = isAr ? article.title.ar : (lang === 'tr' && article.title.tr ? article.title.tr : article.title.en);
  const summary = isAr ? article.summary.ar : (lang === 'tr' && article.summary.tr ? article.summary.tr : article.summary.en);
  const caption = article.figure ? (isAr ? article.figure.caption.ar : (lang === 'tr' && article.figure.caption.tr ? article.figure.caption.tr : article.figure.caption.en)) : null;

  return (
    <div className="lesson-detail">
      <button className="lesson-back" onClick={onBack}>← {t('Back to reading','الرجوع إلى القراءة','Okumaya geri dön')}</button>

      <div className="lesson-head">
        <div className="lesson-head-icon">{article.icon}</div>
        <div className="lesson-head-text">
          <span className="lvl-pill" style={{'--lvl-color': lvlObj?.color || 'var(--navy)'}}>{article.level} · {t(article.kind.en, article.kind.ar, article.kind.tr)}</span>
          <h2>{title}</h2>
          <p>{summary}</p>
          <div className="rd-meta-row" style={{direction:'ltr'}}>
            <span>⏱ {article.minutes} {t('min read','دقائق قراءة','dk okuma')}</span>
            <span className="sep"></span>
            <span>{wordCount} {t('words','كلمة','kelime')}</span>
            <span className="sep"></span>
            <span>{Object.keys(article.vocab).length} {t('new words','كلمات جديدة','yeni kelime')}</span>
            {completed && <><span className="sep"></span><span style={{color:'var(--teal)',fontWeight:600}}>✓ {t('Completed','أنهيته','Tamamlandı')}</span></>}
          </div>
        </div>
      </div>

      {article.figure && (
        <div className="rd-fig">
          <div className="rd-fig-slot">
            <image-slot id={'rdfig-' + article.id} shape="rounded" radius="14"
                        placeholder={t('Illustration coming soon — drop an image here','الرسم التوضيحي قريباً — أسقط صورة هنا','Görsel yakında — buraya bir resim bırakın')}></image-slot>
          </div>
          {caption && <div className="rd-fig-cap">{caption}</div>}
        </div>
      )}

      <div className="rd-note" style={{direction:'ltr'}}>
        <span className="dot">Aa</span>
        <span>{t('Tap the gold words to see their meaning in English.','اضغط على الكلمات الذهبية لترى معناها بالإنجليزية.','Anlamını İngilizce görmek için altın renkli kelimelere dokunun.')}</span>
      </div>

      <div className="rd-body" style={{direction:'ltr'}}>
        {article.body.map((para, i) => (
          <ReadingParagraph key={i} text={para} vocab={article.vocab} pIdx={i} openWord={openWord} setOpenWord={setOpenWord} onAddWord={onAddWord} hasWord={hasWord} t={t} />
        ))}
      </div>

      <div className="lesson-sec">
        <h3>📒 {t('New vocabulary from this text','مفردات جديدة من هذا النص','Bu metinden yeni kelimeler')}</h3>
        <div className="rd-gloss" style={{direction:'ltr'}}>
          {Object.entries(article.vocab).map(([w, v]) => (
            <div key={w} className="rd-gloss-item">
              <div className="w">{w} <em>{v.pos}</em></div>
              <div className="d">{v.def}</div>
              {v.ex && <div className="e">“{v.ex}”</div>}
              {onAddWord && (hasWord(w)
                ? <span className="gloss-add added">✓ {t('In My Words','في كلماتي','Kelimelerimde')}</span>
                : <button className="gloss-add" onClick={() => onAddWord(w, v)}>＋ {t('Add to My Words','أضف إلى كلماتي','Kelimelerime ekle')}</button>)}
            </div>
          ))}
        </div>
      </div>

      <div className="lesson-sec">
        <div className="lesson-practice">
          <div className="lp-head">
            <h3>🎯 {t('Check your understanding','اختبر فهمك','Anladığını kontrol et')}</h3>
            <div className="lp-progress">{scoreCorrect} / {article.questions.length} {t('correct','صحيح')}{completed && ' · ✓ ' + t('completed','أنهيته','tamamlandı')}</div>
          </div>
          {article.questions.map((q, i) => (
            <LessonQ key={`${article.id}-${i}`} q={q} lang={lang} onScore={onScore} t={t} />
          ))}
        </div>
      </div>
    </div>
  );
}

function ReadingMode({ lang, level, state, setState, t, LessonQ, LEVELS, member, onMember, addWord, myWords }) {
  const [openId, setOpenId] = React.useState(null);
  const [gateOpen, setGateOpen] = React.useState(false);
  const articles = window.READING_DATA || [];
  const filtered = level === 'all' ? articles : articles.filter(a => a.level === level);
  const open = articles.find(a => a.id === openId);
  const completedSet = new Set(state.readingCompleted || []);

  /* Free preview: one text from each of the first levels — the rest needs a free account */
  const freeIds = React.useMemo(() => {
    const ids = new Set();
    ['A1','A2','B1'].forEach(lv => { const f = articles.find(a => a.level === lv); if (f) ids.add(f.id); });
    if (!ids.size) articles.slice(0, 3).forEach(a => ids.add(a.id));
    return ids;
  }, [articles.length]);
  const isLocked = (a) => !member && !freeIds.has(a.id);

  if (gateOpen && !member) {
    return (
      <>
        <style>{READING_CSS}</style>
        <button className="lesson-back" onClick={() => setGateOpen(false)}>← {t('Back to reading','الرجوع إلى القراءة','Okumaya geri dön')}</button>
        <window.SignupCard t={t}
          context={{
            emoji: '📕',
            title: t('Unlock every reading text','افتح كل نصوص القراءة','Tüm okuma metinlerini aç'),
            sub: t(`You\u2019ve got ${freeIds.size} free texts. Join free to read all ${articles.length} — with tap-to-translate vocabulary and comprehension questions.`,
                   `لديك ${freeIds.size} نصوص مجانية. انضم مجاناً لقراءة كل الـ ${articles.length} نصاً — مع مفردات تفاعلية وأسئلة فهم.`,
                   `${freeIds.size} ücretsiz metnin var. ${articles.length} metnin tamamını okumak için ücretsiz katıl.`),
          }}
          onDone={(m) => { if (onMember) onMember(m); setGateOpen(false); }} />
      </>
    );
  }

  if (open) {
    return (
      <>
        <style>{READING_CSS}</style>
        <ReadingDetail article={open} lang={lang} state={state} setState={setState} t={t}
                       onBack={() => setOpenId(null)} LessonQ={LessonQ} LEVELS={LEVELS}
                       addWord={addWord} myWords={myWords} />
      </>
    );
  }

  if (filtered.length === 0) {
    return <div className="lesson-detail" style={{textAlign:'center',padding:'48px 24px'}}>
      <div style={{fontSize:48,marginBottom:12}}>📭</div>
      <div style={{fontFamily:'var(--font-d)',fontSize:22,fontWeight:700,color:'var(--navy)',marginBottom:6}}>{t('No reading at this level yet','لا توجد قراءة في هذا المستوى بعد','Bu seviyede henüz okuma yok')}</div>
      <div style={{fontSize:14,color:'var(--text-mid)'}}>{t('Try another level — more texts are coming.','جرّب مستوى آخر — المزيد من النصوص قادم.','Başka bir seviye deneyin — daha fazla metin geliyor.')}</div>
    </div>;
  }

  const groups = [
    { id: 'A1', emoji: '🌱', en: 'A1 — First Steps', ar: 'A1 — الخطوات الأولى', tr: 'A1 — İlk Adımlar' },
    { id: 'A2', emoji: '🌿', en: 'A2 — Building Up', ar: 'A2 — البناء التدريجي', tr: 'A2 — Gelişme' },
    { id: 'B1', emoji: '🌳', en: 'B1 — Going Deeper', ar: 'B1 — التعمق', tr: 'B1 — Derinleşme' },
    { id: 'B2', emoji: '🏔️', en: 'B2 — Upper-Intermediate', ar: 'B2 — فوق المتوسط', tr: 'B2 — Orta-Üstü' },
    { id: 'C1', emoji: '🦅', en: 'C1 — Advanced', ar: 'C1 — متقدم', tr: 'C1 — İleri' },
    { id: 'C2', emoji: '🌌', en: 'C2 — Mastery', ar: 'C2 — إتقان', tr: 'C2 — Ustalık' },
  ];

  return (
    <div>
      <style>{READING_CSS}</style>
      {!member && (
        <div className="su-banner">
          <span>🎁 {t('Free preview','جولة مجانية','Ücretsiz önizleme')} — {freeIds.size} {t('texts unlocked out of','نصوص مفتوحة من أصل','metin açık /')} {articles.length}</span>
          <button className="quiz-btn" style={{padding:'8px 16px',fontSize:12}} onClick={() => setGateOpen(true)}>✨ {t('Join free to unlock all','انضم مجاناً لفتح الكل','Hepsini açmak için katıl')}</button>
        </div>
      )}
      {groups.map(g => {
        const items = filtered.filter(a => a.level === g.id);
        if (items.length === 0) return null;
        return (
          <div key={g.id} className="lesson-group">
            <div className="lg-head">
              <span className="lg-emoji">{g.emoji}</span>
              <h3 className="lg-title">{t(g.en, g.ar, g.tr)}</h3>
              <span className="lg-line"></span>
              <span className="lg-count">{items.length} {t('texts','نصوص','metin')}</span>
            </div>
            <div className="lesson-list">
              {items.map(a => {
                const lvlObj = (LEVELS || []).find(x => x.id === a.level);
                const done = completedSet.has(a.id);
                const locked = isLocked(a);
                return (
                  <button key={a.id} className={'lesson-tile' + (locked ? ' locked' : '')} onClick={() => locked ? setGateOpen(true) : setOpenId(a.id)}>
                    <div className="lesson-tile-top">
                      <span className="lesson-tile-icon">{a.icon}</span>
                      <span style={{display:'flex',gap:6,alignItems:'center'}}>
                        {!member && freeIds.has(a.id) && <span className="tile-freepill">{t('FREE','مجاني','ÜCRETSİZ')}</span>}
                        <span className="lesson-tile-lvl" style={{'--lvl-color': lvlObj?.color || 'var(--navy)'}}>{a.level}</span>
                      </span>
                    </div>
                    <h4>{locked ? '🔒 ' : ''}{lang === 'ar' ? a.title.ar : (lang === 'tr' && a.title.tr ? a.title.tr : a.title.en)}</h4>
                    <p>{lang === 'ar' ? a.summary.ar : (lang === 'tr' && a.summary.tr ? a.summary.tr : a.summary.en)}</p>
                    <div className="lesson-tile-meta">
                      <span>{t(a.kind.en, a.kind.ar, a.kind.tr)} · ⏱ {a.minutes} {t('min','دقائق','dk')} · {a.questions.length} {t('questions','أسئلة','soru')}</span>
                      {locked ? <span className="gate-note">{t('Join free','انضم مجاناً','Ücretsiz katıl')}</span> : done && <span className="done">✓ {t('Completed','أنهيته','Tamamlandı')}</span>}
                    </div>
                  </button>
                );
              })}
            </div>
          </div>
        );
      })}
    </div>
  );
}

Object.assign(window, { ReadingMode });
