/* ─────────────────────────────────────────────
   REMINDERS — daily study reminder
   Two channels: on the website (banner + optional
   browser notification) or by email (members).
   Exposes: window.ReminderCard, window.DueReminderBanner
   ───────────────────────────────────────────── */

const REM_TIMES = ['08:00','12:30','17:00','19:00','21:00'];

function remDefaults() {
  return { on:false, channel:'site', time:'19:00', browserNotif:false, dismissedOn:null, notifiedOn:null };
}

function remIsDue(rem) {
  if (!rem || !rem.on) return false;
  const [h, m] = (rem.time || '19:00').split(':').map(Number);
  const now = new Date();
  return now.getHours() > h || (now.getHours() === h && now.getMinutes() >= m);
}

function remTasksLeft(state) {
  const plan = state.plan && (window.LEARN_PLANS || []).find(p => p.id === state.plan.id);
  const today = (state.history || {})[window.todayKey ? window.todayKey() : ''] || {};
  if (!plan) return Object.values(today).reduce((a,b)=>a+b,0) === 0 ? 1 : 0; // no plan: remind if nothing done
  return Object.entries(plan.targets).filter(([k, n]) => (today[k] || 0) < n).length;
}

/* ── Settings card (Learning home) ── */
function ReminderCard({ state, setState, t, lang, member, onNeedMember }) {
  const rem = { ...remDefaults(), ...(state.reminder || {}) };
  const isAr = lang === 'ar';
  const upd = (patch) => setState(s => ({ ...s, reminder: { ...remDefaults(), ...(s.reminder || {}), ...patch } }));

  const pickChannel = (ch) => {
    if (ch === 'email' && !member) { if (onNeedMember) onNeedMember(); return; }
    upd({ channel: ch });
  };

  const askBrowserNotif = async () => {
    if (!('Notification' in window)) return;
    if (Notification.permission === 'default') {
      const p = await Notification.requestPermission();
      upd({ browserNotif: p === 'granted' });
    } else {
      upd({ browserNotif: Notification.permission === 'granted' && !rem.browserNotif });
    }
  };

  return (
    <div className="hm-card">
      <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',gap:12,flexWrap:'wrap',marginBottom: rem.on ? 18 : 0}}>
        <div>
          <div style={{fontFamily:'var(--font-d)',fontSize:20,fontWeight:700,color:'var(--navy)'}}>⏰ {t('Daily reminder','تذكير يومي','Günlük hatırlatıcı')}</div>
          <div style={{fontSize:12.5,color:'var(--text-lt)',marginTop:2}}>
            {rem.on
              ? t('We\u2019ll nudge you if your daily plan isn\u2019t done yet.','سنذكّرك إذا لم تُكمل خطتك اليومية بعد.','Günlük planın bitmediyse sana hatırlatırız.')
              : t('Turn it on so you never miss a study day.','فعّله حتى لا يفوتك يوم دراسة.','Aç ki hiçbir çalışma gününü kaçırma.')}
          </div>
        </div>
        <button className={'spk-chip ' + (rem.on ? 'on' : '')} onClick={() => upd({ on: !rem.on })}>
          {rem.on ? '✓ ' + t('On','مفعّل','Açık') : t('Turn on','تفعيل','Aç')}
        </button>
      </div>

      {rem.on && (
        <div style={{display:'flex',flexDirection:'column',gap:16}}>
          <div>
            <div className="spk-lbl" style={{marginBottom:8}}>{t('How should we remind you?','كيف نذكّرك؟','Nasıl hatırlatalım?')}</div>
            <div className="rem-channels">
              <button className={'rem-ch' + (rem.channel === 'site' ? ' on' : '')} onClick={() => pickChannel('site')}>
                <span className="ic">🔔</span>
                <span className="nm">{t('On the website','على الموقع','Web sitesinde')}</span>
                <span className="ds">{t('A banner at your reminder time whenever you\u2019re here.','شريط تنبيه في وقت التذكير عندما تكون هنا.','Buradayken hatırlatma saatinde bir bant.')}</span>
              </button>
              <button className={'rem-ch' + (rem.channel === 'email' ? ' on' : '')} onClick={() => pickChannel('email')}>
                <span className="ic">📧</span>
                <span className="nm">{t('By email','بالبريد الإلكتروني','E-posta ile')}{!member && ' 🔒'}</span>
                <span className="ds">{member
                  ? t('A short daily email to ','بريد يومي قصير إلى ','Şu adrese kısa bir günlük e-posta: ') + member.email
                  : t('Members only — join free to use email reminders.','للأعضاء فقط — انضم مجاناً لاستخدام تذكير البريد.','Sadece üyeler — ücretsiz katıl.')}</span>
              </button>
            </div>
          </div>

          <div>
            <div className="spk-lbl" style={{marginBottom:8}}>{t('Reminder time','وقت التذكير','Hatırlatma saati')}</div>
            <div className="spk-chips">
              {REM_TIMES.map(tm => (
                <button key={tm} className={'spk-chip ' + (rem.time === tm ? 'on' : '')} onClick={() => upd({ time: tm })}>{tm}</button>
              ))}
              <input type="time" className="rem-time" value={rem.time} onChange={e => e.target.value && upd({ time: e.target.value })} />
            </div>
          </div>

          {rem.channel === 'site' && ('Notification' in window) && (
            <button className={'spk-chip ' + (rem.browserNotif && Notification.permission === 'granted' ? 'on' : '')} style={{alignSelf:'start'}} onClick={askBrowserNotif}>
              💻 {t('Also show a browser notification','أظهر إشعار المتصفح أيضاً','Tarayıcı bildirimi de göster')}
              {Notification.permission === 'denied' && ' — ' + t('blocked in browser settings','محظور في إعدادات المتصفح','tarayıcı ayarlarında engelli')}
            </button>
          )}

          {rem.channel === 'email' && member && (
            <div className="rem-note">✓ {t('Email reminders are set. You\u2019ll get one at','تم ضبط تذكير البريد. سيصلك عند الساعة','E-posta hatırlatıcısı ayarlandı. Saat')} {rem.time} {t('every day you haven\u2019t studied yet.','كل يوم لم تدرس فيه بعد.','henüz çalışmadığın her gün.')}</div>
          )}
        </div>
      )}
    </div>
  );
}

/* ── Due banner (shown on every tab) ── */
function DueReminderBanner({ state, setState, t, setMode }) {
  const rem = { ...remDefaults(), ...(state.reminder || {}) };
  const tk = window.todayKey ? window.todayKey() : '';
  const left = remTasksLeft(state);
  const due = rem.channel === 'site' && remIsDue(rem) && left > 0 && rem.dismissedOn !== tk;

  // one browser notification per day, if enabled
  React.useEffect(() => {
    if (!due || !rem.browserNotif || rem.notifiedOn === tk) return;
    if (!('Notification' in window) || Notification.permission !== 'granted') return;
    try {
      new Notification('The Fluent Engineer', { body: t('Time to study — your daily plan is waiting!','حان وقت الدراسة — خطتك اليومية بانتظارك!','Çalışma zamanı — günlük planın seni bekliyor!') });
      setState(s => ({ ...s, reminder: { ...remDefaults(), ...(s.reminder || {}), notifiedOn: tk } }));
    } catch {}
  }, [due]);

  if (!due) return null;
  return (
    <div className="rem-banner">
      <span className="be">⏰</span>
      <span className="bt">
        {t('Study reminder — ','تذكير بالدراسة — ','Çalışma hatırlatması — ')}
        {state.plan
          ? left + ' ' + t('tasks left on today\u2019s plan.','مهام متبقية في خطة اليوم.','görev bugünkü planında kaldı.')
          : t('you haven\u2019t studied yet today.','لم تدرس اليوم بعد.','bugün henüz çalışmadın.')}
      </span>
      <button className="quiz-btn" style={{padding:'8px 16px',fontSize:12}} onClick={() => setMode('home')}>{t('Go to my plan','اذهب إلى خطتي','Planıma git')} →</button>
      <button className="bx" title={t('Dismiss for today','تجاهل لليوم','Bugünlük kapat')}
              onClick={() => setState(s => ({ ...s, reminder: { ...remDefaults(), ...(s.reminder || {}), dismissedOn: tk } }))}>✕</button>
    </div>
  );
}

Object.assign(window, { ReminderCard, DueReminderBanner });
