/* ─────────────────────────────────────────────
   LEARNING HOME — general dashboard
   · Level test (members only)
   · Daily learning plan + today's checklist
   · Learning history: streak, totals, last 14 days
   Exposes: window.HomeMode, window.LEARN_PLANS,
            window.todayKey, window.bumpHistory, window.computeStreak
   ───────────────────────────────────────────── */

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

/* Add +n to today's counter for `kind` inside a state object (immutably). */
function bumpHistory(s, kind, n) {
  const k = todayKey();
  const h = { ...(s.history || {}) };
  const day = { ...(h[k] || {}) };
  day[kind] = (day[kind] || 0) + (n || 1);
  h[k] = day;
  return { ...s, history: h };
}

function dayHasActivity(history, dt) {
  const day = history[todayKey(dt)];
  return !!day && Object.values(day).some(v => v > 0);
}

function computeStreak(history) {
  if (!history) return 0;
  const DAY = 86400000;
  let d = new Date();
  if (!dayHasActivity(history, d)) d = new Date(d.getTime() - DAY); // today can still be empty
  let streak = 0;
  while (dayHasActivity(history, d)) { streak++; d = new Date(d.getTime() - DAY); }
  return streak;
}

const HOME_TASKS = [
  { key:'words',    emoji:'📖', en:'Learn new words',        ar:'تعلّم كلمات جديدة',   tr:'Yeni kelimeler öğren', mode:'vocab' },
  { key:'lessons',  emoji:'📚', en:'Complete a lesson',      ar:'أكمل درساً',           tr:'Bir ders tamamla',     mode:'lessons' },
  { key:'reading',  emoji:'📕', en:'Read a text',            ar:'اقرأ نصاً',            tr:'Bir metin oku',        mode:'reading' },
  { key:'practice', emoji:'🎯', en:'Practice answers',       ar:'إجابات تمرين',         tr:'Alıştırma cevapları',  mode:'practice' },
  { key:'speaking', emoji:'🎤', en:'Speaking session',       ar:'جلسة محادثة',          tr:'Konuşma oturumu',      mode:'speaking' },
];

const LEARN_PLANS = [
  { id:'spark', emoji:'🌱', minutes:10,
    en:'Daily Spark', ar:'الشرارة اليومية', tr:'Günlük Kıvılcım',
    descEn:'A light habit that survives busy weeks. Words plus one short text a day.',
    descAr:'عادة خفيفة تصمد في الأسابيع المزدحمة. كلمات ونص قصير واحد يومياً.',
    descTr:'Yoğun haftalara dayanan hafif bir alışkanlık. Her gün kelimeler ve kısa bir metin.',
    targets:{ words:5, reading:1 } },
  { id:'builder', emoji:'🔧', minutes:20,
    en:'Steady Builder', ar:'البنّاء المنتظم', tr:'İstikrarlı İnşacı',
    descEn:'One lesson, one text and real practice — solid progress, every single day.',
    descAr:'درس واحد ونص واحد وتمرين حقيقي — تقدّم متين كل يوم.',
    descTr:'Bir ders, bir metin ve gerçek alıştırma — her gün sağlam ilerleme.',
    targets:{ words:5, lessons:1, reading:1, practice:8 } },
  { id:'throttle', emoji:'🚀', minutes:40,
    en:'Full Throttle', ar:'أقصى سرعة', tr:'Tam Gaz',
    descEn:'The complete daily circuit — including speaking out loud. Fastest results.',
    descAr:'الحلقة اليومية الكاملة — بما فيها التحدث بصوت عالٍ. أسرع النتائج.',
    descTr:'Tam günlük devre — sesli konuşma dahil. En hızlı sonuçlar.',
    targets:{ words:8, lessons:1, reading:2, practice:12, speaking:1 } },
];

const PLAN_FOR_LEVEL = { A1:'spark', A2:'builder', B1:'builder', B2:'builder', C1:'throttle', C2:'throttle' };

function HomeMode({ state, setState, lang, t, member, onMember, setMode }) {
  const [view, setView] = React.useState('dash');       // dash | gate | test | planpick
  const [gateNext, setGateNext] = React.useState('test'); // where to go after joining from the gate
  const isAr = lang === 'ar';
  const history = state.history || {};
  const today = history[todayKey()] || {};
  const streak = computeStreak(history);
  const placement = state.placement;
  const plan = state.plan ? LEARN_PLANS.find(p => p.id === state.plan.id) : null;
  const recPlanId = placement ? (PLAN_FOR_LEVEL[placement.level] || 'builder') : 'builder';

  const planName = (p) => isAr ? p.ar : lang === 'tr' ? p.tr : p.en;
  const lvlName = (id) => {
    const n = (window.LEVEL_NAMES || {})[id];
    return n ? (isAr ? n.ar : lang === 'tr' ? n.tr : n.en) : id;
  };
  const dateStr = new Date().toLocaleDateString(isAr ? 'ar' : lang === 'tr' ? 'tr' : 'en-GB', { weekday:'long', day:'numeric', month:'long' });

  const startTest = () => { if (member) setView('test'); else { setGateNext('test'); setView('gate'); } };

  /* ── gate: sign in before the test ── */
  if (view === 'gate') return (
    <div>
      <button className="lesson-back" onClick={() => setView('dash')}>← {t('Back to Learning','الرجوع إلى التعلّم','Öğrenmeye geri dön')}</button>
      <window.SignupCard t={t}
        context={gateNext === 'test' ? {
          emoji:'📐',
          title: t('The level test is for members','اختبار المستوى للأعضاء','Seviye testi üyeler içindir'),
          sub: t('Join free to take the full level test, save your result, and get a learning plan built around your level.',
                 'انضم مجاناً لتخوض اختبار المستوى الكامل، وتحفظ نتيجتك، وتحصل على خطة تعلّم مبنية على مستواك.',
                 'Seviye testine girmek, sonucunu kaydetmek ve seviyene göre bir plan almak için ücretsiz katıl.'),
        } : {
          emoji:'📧',
          title: t('Email reminders are for members','تذكير البريد للأعضاء','E-posta hatırlatıcıları üyeler içindir'),
          sub: t('Join free so we know where to send your daily study reminder — and to keep your progress saved.',
                 'انضم مجاناً لنعرف أين نرسل تذكيرك اليومي — ولنحفظ تقدمك.',
                 'Günlük hatırlatıcıyı nereye göndereceğimizi bilmek için ücretsiz katıl.'),
        }}
        onDone={(m) => { onMember(m); setView(gateNext); }} />
    </div>
  );

  /* ── the placement test ── */
  if (view === 'test') return (
    <window.PlacementTest t={t} lang={lang}
      onFinish={(res) => setState(s => bumpHistory({ ...s, placement: res }, 'test'))}
      onClose={() => setView('dash')} />
  );

  /* ── plan cards (picker) ── */
  const planPicker = (
    <div className="hm-plans">
      {LEARN_PLANS.map(p => {
        const current = plan && plan.id === p.id;
        return (
          <div key={p.id} className={'hm-plan' + (current ? ' current' : '')}>
            {p.id === recPlanId && <span className="rec">★ {t('Recommended','موصى بها','Önerilen')}</span>}
            <span className="pe">{p.emoji}</span>
            <div>
              <div className="pn">{planName(p)}</div>
              <div className="pm">~{p.minutes} {t('min / day','دقيقة / يوم','dk / gün')}</div>
            </div>
            <div className="pd">{isAr ? p.descAr : lang === 'tr' ? p.descTr : p.descEn}</div>
            <ul>
              {HOME_TASKS.filter(task => p.targets[task.key]).map(task => (
                <li key={task.key}>{p.targets[task.key]} × {t(task.en, task.ar, task.tr).toLowerCase()}</li>
              ))}
            </ul>
            <button className="quiz-btn" style={{marginTop:'auto'}} disabled={current}
                    onClick={() => { setState(s => ({ ...s, plan: { id: p.id, startedAt: Date.now() } })); setView('dash'); }}>
              {current ? '✓ ' + t('Your current plan','خطتك الحالية','Mevcut planın') : t('Choose this plan','اختر هذه الخطة','Bu planı seç')}
            </button>
          </div>
        );
      })}
    </div>
  );

  /* ── today's checklist ── */
  const checklist = plan && (() => {
    const tasks = HOME_TASKS.filter(task => plan.targets[task.key]);
    const allDone = tasks.every(task => (today[task.key] || 0) >= plan.targets[task.key]);
    return (
      <div className="hm-card">
        <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',gap:12,flexWrap:'wrap',marginBottom:18}}>
          <div>
            <div style={{fontFamily:'var(--font-d)',fontSize:21,fontWeight:700,color:'var(--navy)'}}>{plan.emoji} {planName(plan)}</div>
            <div style={{fontSize:12,color:'var(--text-lt)',marginTop:2}}>~{plan.minutes} {t('min / day','دقيقة / يوم','dk / gün')} · {t('Today\u2019s checklist','قائمة اليوم','Bugünün listesi')}</div>
          </div>
          <button className="su-btn2" onClick={() => setView('planpick')}>{t('Change plan','تغيير الخطة','Planı değiştir')}</button>
        </div>
        {tasks.map(task => {
          const target = plan.targets[task.key];
          const done = Math.min(today[task.key] || 0, target);
          const isDone = done >= target;
          return (
            <div key={task.key} className={'hm-task' + (isDone ? ' done' : '')}>
              <span className="ck" style={!isDone ? {color:'transparent'} : {}}>✓</span>
              <span className="tn">{task.emoji} {t(task.en, task.ar, task.tr)}</span>
              <span className="tp">{done} / {target}</span>
              {!isDone && <button className="go" onClick={() => setMode(task.mode)}>{t('Go','ابدأ','Git')} →</button>}
            </div>
          );
        })}
        {allDone && (
          <div className="hm-allday">🎉 {t('Perfect day — every task complete. See you tomorrow!','يوم مثالي — أنجزت كل المهام. نراك غداً!','Mükemmel gün — tüm görevler tamam. Yarın görüşürüz!')}</div>
        )}
      </div>
    );
  })();

  /* ── history numbers ── */
  const totLessons = (state.lessonsCompleted || []).length;
  const totReading = (state.readingCompleted || []).length;
  const totWords = (state.learned || []).length + (state.myWords || []).length;
  const spkMin = Math.round(((state.speaking || {}).seconds || 0) / 60);
  const ps = state.practiceScore || { correct:0, total:0 };
  const acc = ps.total ? Math.round(ps.correct / ps.total * 100) : null;

  const days = [];
  for (let i = 13; i >= 0; i--) {
    const d = new Date(Date.now() - i * 86400000);
    const rec = history[todayKey(d)] || {};
    days.push({ d, total: Object.values(rec).reduce((a, b) => a + b, 0), rec });
  }
  const maxDay = Math.max(4, ...days.map(x => x.total));

  return (
    <div style={{direction: isAr ? 'rtl' : 'ltr'}}>

      {/* WELCOME + STREAK */}
      <div className="hm-hello">
        <img src="assets/images/mascot-nour-welcome.png" alt="Nour welcomes you"
             style={{height:104, width:'auto', borderRadius:14, boxShadow:'0 10px 26px rgba(13,31,60,.18)', flexShrink:0}} />
        <div style={{flex:1, minWidth:220}}>
          <div className="hm-hi">
            {member
              ? t('Welcome back, ','مرحباً بعودتك، ','Tekrar hoş geldin, ') + member.name
              : t('Welcome to your learning home','أهلاً بك في صفحة تعلّمك','Öğrenme merkezine hoş geldin')}
          </div>
          <div className="hm-date">{dateStr}{!member && <> · <button className="su-btn2" style={{padding:0,fontSize:13}} onClick={() => setView('gate')}>{t('Join free to unlock everything','انضم مجاناً لفتح كل المحتوى','Her şeyi açmak için ücretsiz katıl')}</button></>}</div>
        </div>
        <div className="hm-streak">
          <span className="fl">🔥</span>
          <div>
            <div className="n">{streak}</div>
            <div className="l">{t('day streak','أيام متتالية','günlük seri')}</div>
          </div>
        </div>
      </div>

      {/* LEVEL */}
      <div className="hm-sec">
        <div className="lg-head">
          <span className="lg-emoji">📐</span>
          <h3 className="lg-title">{t('Your level','مستواك','Seviyen')}</h3>
          <span className="lg-line"></span>
        </div>
        {placement ? (
          <div className="hm-card hm-level-row">
            <div className="hm-lvlbadge" style={{background:(window.LEVEL_COLORS || {})[placement.level] || 'var(--navy)'}}>{placement.level}</div>
            <div style={{flex:1,minWidth:200}}>
              <div style={{fontFamily:'var(--font-d)',fontSize:22,fontWeight:700,color:'var(--navy)'}}>{lvlName(placement.level)}</div>
              <div style={{fontSize:12,color:'var(--text-lt)',marginBottom:12}}>
                {t('Tested on','تاريخ الاختبار:','Test tarihi:')} {new Date(placement.at).toLocaleDateString(isAr ? 'ar' : lang === 'tr' ? 'tr' : 'en-GB')}
              </div>
              <div className="hm-skills">
                {[['vocab','📖',t('Vocabulary','المفردات','Kelime')],['grammar','🧩',t('Grammar','القواعد','Dil bilgisi')],['reading','📕',t('Reading','القراءة','Okuma')]].map(([k, em, nm]) => {
                  const arr = (placement.skills || {})[k] || [0,0];
                  const pct = arr[1] ? Math.round(arr[0] / arr[1] * 100) : 0;
                  return (
                    <div key={k} className="hm-skill">
                      <span>{em} {nm}</span>
                      <span className="bar"><i style={{width:pct+'%'}}></i></span>
                      <span style={{textAlign:'end'}}>{arr[0]}/{arr[1]}</span>
                    </div>
                  );
                })}
              </div>
            </div>
            <button className="act-btn" onClick={startTest}>↻ {t('Retake test','أعد الاختبار','Testi tekrarla')}</button>
          </div>
        ) : (
          <div className="hm-card hm-level-row">
            <div style={{fontSize:44,flexShrink:0}}>🧭</div>
            <div style={{flex:1,minWidth:220}}>
              <div style={{fontFamily:'var(--font-d)',fontSize:20,fontWeight:700,color:'var(--navy)',marginBottom:4}}>
                {t('Start with the level test','ابدأ باختبار المستوى','Seviye testiyle başla')}
              </div>
              <div style={{fontSize:13.5,color:'var(--text-mid)',lineHeight:1.6,fontWeight:300}}>
                {t('10–15 minutes, adaptive, covers vocabulary, grammar and reading. Your result picks the right lessons and plan for you.',
                   '10–15 دقيقة، متكيّف، يغطي المفردات والقواعد والقراءة. نتيجتك تحدد الدروس والخطة المناسبة لك.',
                   '10–15 dakika, uyarlanabilir; kelime, dil bilgisi ve okumayı kapsar. Sonucun sana doğru dersleri ve planı seçer.')}
              </div>
              {!member && <div style={{fontSize:12,color:'var(--gold)',fontWeight:600,marginTop:8}}>🔒 {t('Members only — joining is free','للأعضاء فقط — الانضمام مجاني','Sadece üyeler — katılmak ücretsiz')}</div>}
            </div>
            <button className="spk-start" style={{margin:0}} onClick={startTest}>📐 {t('Take the test','ابدأ الاختبار','Teste başla')}</button>
          </div>
        )}
      </div>

      {/* PLAN */}
      <div className="hm-sec">
        <div className="lg-head">
          <span className="lg-emoji">🗓</span>
          <h3 className="lg-title">{t('Your daily plan','خطتك اليومية','Günlük planın')}</h3>
          <span className="lg-line"></span>
        </div>
        {(!plan || view === 'planpick') ? (
          <div>
            {view === 'planpick' && <button className="lesson-back" onClick={() => setView('dash')}>← {t('Back','رجوع','Geri')}</button>}
            {planPicker}
          </div>
        ) : checklist}
      </div>

      {/* REMINDER */}
      <div className="hm-sec">
        <div className="lg-head">
          <span className="lg-emoji">⏰</span>
          <h3 className="lg-title">{t('Reminders','التذكيرات','Hatırlatıcılar')}</h3>
          <span className="lg-line"></span>
        </div>
        {window.ReminderCard && <window.ReminderCard state={state} setState={setState} t={t} lang={lang} member={member} onNeedMember={() => { setGateNext('dash'); setView('gate'); }} />}
      </div>

      {/* HISTORY */}
      <div className="hm-sec">
        <div className="lg-head">
          <span className="lg-emoji">📊</span>
          <h3 className="lg-title">{t('Your learning history','سجلّ تعلّمك','Öğrenme geçmişin')}</h3>
          <span className="lg-line"></span>
        </div>
        <div className="hm-card">
          <div style={{display:'flex',gap:34,flexWrap:'wrap'}}>
            {[[totLessons, t('Lessons done','دروس منجزة','Biten ders')],
              [totReading, t('Texts read','نصوص مقروءة','Okunan metin')],
              [totWords, t('Words learned','كلمات متعلَّمة','Öğrenilen kelime')],
              [spkMin + 'm', t('Speaking time','وقت المحادثة','Konuşma süresi')],
              ...(acc !== null ? [[acc + '%', t('Practice accuracy','دقة التمرين','Alıştırma doğruluğu')]] : []),
            ].map(([num, lbl], i) => (
              <div key={i} className="cstat">
                <div className="cstat-num gold" style={{fontSize:30}}>{num}</div>
                <div className="cstat-lbl">{lbl}</div>
              </div>
            ))}
          </div>
          <div className="hm-days" style={{direction:'ltr'}}>
            {days.map((x, i) => {
              const isToday = i === days.length - 1;
              const parts = [];
              HOME_TASKS.forEach(task => { if (x.rec[task.key]) parts.push(`${x.rec[task.key]}× ${task.en.toLowerCase()}`); });
              return (
                <div key={i} className={'hm-day' + (x.total === 0 ? ' empty' : '') + (isToday ? ' today' : '')}
                     title={x.d.toLocaleDateString('en-GB') + (parts.length ? ' — ' + parts.join(', ') : ' — ' + t('no activity','لا نشاط','etkinlik yok'))}>
                  <div className="bar" style={{height: Math.max(4, Math.round(x.total / maxDay * 58)) + 'px'}}></div>
                  <div className="dl">{isToday ? t('Today','اليوم','Bugün') : x.d.getDate()}</div>
                </div>
              );
            })}
          </div>
          <div style={{fontSize:11.5,color:'var(--text-lt)',marginTop:10,textAlign:'center'}}>
            {t('Last 14 days — anything you complete anywhere on this page is counted here.',
               'آخر 14 يوماً — كل ما تنجزه في أي مكان بهذه الصفحة يُحتسب هنا.',
               'Son 14 gün — bu sayfada tamamladığın her şey burada sayılır.')}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { HomeMode, LEARN_PLANS, todayKey, bumpHistory, computeStreak });
