// Single-user notifications. Surfaces what needs attention based on the user's
// notification preferences. Includes a new "Reminders" category driven by each
// routine's optional "X weeks before" reminder field.

const { FONT_DISPLAY: NT_DISPLAY, FONT_BODY: NT_BODY, FONT_MONO: NT_MONO } = window.HIFI;

// Build the live notification list, honouring the user's prefs.
function notificationsForMe() {
  const me = window.Account.current();
  const pref = me.notif || {};
  const out = [];
  const today = new Date(); today.setHours(0, 0, 0, 0);

  if (pref.overdue) {
    ROUTINES.filter(r => r.status === 'overdue').forEach(r =>
      out.push({ id: 'ov-' + r.id, kind: 'overdue', icon: 'repeat', title: r.task,
        sub: `${(findAsset(r.asset) || {}).name || 'Routine'} · ${r.nextLabel}`, rtype: 'routine', rid: r.id }));
    TODOS.filter(td => td.status !== 'Done' && td.priority === 'High').forEach(td =>
      out.push({ id: 'ovt-' + td.id, kind: 'overdue', icon: 'check', title: td.title,
        sub: `High-priority to-do${td.asset ? ' · ' + (findAsset(td.asset) || {}).name : ''}`, rtype: 'todo', rid: td.id }));
  }
  if (pref.reminders !== false) {
    // Reminders that have arrived (today or earlier) and aren't yet past their due date.
    ROUTINES.forEach(r => {
      const rd = window.Hub.reminderDate(r);
      if (!rd) return;
      if (rd <= today && r.status !== 'overdue') {
        out.push({ id: 'rem-' + r.id, kind: 'reminder', icon: 'bell', title: r.task,
          sub: `${(findAsset(r.asset) || {}).name || 'Routine'} · ${window.Hub.reminderLabel(r)} · due ${r.nextLabel}`,
          rtype: 'routine', rid: r.id });
      }
    });
  }
  if (pref.digest) {
    ROUTINES.filter(r => r.status === 'soon').forEach(r =>
      out.push({ id: 'soon-' + r.id, kind: 'soon', icon: 'cal', title: r.task,
        sub: `${(findAsset(r.asset) || {}).name || 'Routine'} · ${r.nextLabel}`, rtype: 'routine', rid: r.id }));
  }
  if (pref.gaps) {
    TODOS.filter(td => td.status !== 'Done' && td.type === 'Info Gap').forEach(td =>
      out.push({ id: 'gap-' + td.id, kind: 'gap', icon: 'search', title: td.title,
        sub: `Missing detail${td.asset ? ' · ' + (findAsset(td.asset) || {}).name : ''}`, rtype: 'todo', rid: td.id }));
  }
  return out;
}

const notificationCount = () => notificationsForMe().length;

// ---------- Notifications slide-over ----------
const NOTIF_GROUPS = [
  { kind: 'overdue', label: 'Overdue', tone: 'overdue' },
  { kind: 'reminder', label: 'Reminders', tone: 'info' },
  { kind: 'soon', label: 'Due soon', tone: 'soon' },
  { kind: 'gap', label: 'Info gaps', tone: 'info' },
];

const NotificationsPanel = ({ t, nav }) => {
  const me = window.Account.current();
  const pref = me.notif || {};
  const items = notificationsForMe();
  const toneColor = { overdue: t.overdue, soon: t.soon, info: t.info || t.inkSoft };
  const toneBg = { overdue: t.overdueBg, soon: t.soonBg, info: t.infoBg };

  const offNotes = [];
  if (!pref.overdue) offNotes.push('Overdue reminders');
  if (pref.reminders === false) offNotes.push('Routine reminders');
  if (!pref.digest) offNotes.push('Due-soon digest');
  if (!pref.gaps) offNotes.push('Info-gap nudges');

  const openItem = (it) => { nav.closeNotifications(); if (it.rtype === 'routine') nav.openRoutine(it.rid); else nav.go('todos'); };

  return (
    <>
      <div onClick={nav.closeNotifications} style={{ position: 'absolute', inset: 0, background: 'rgba(20,18,12,0.28)', zIndex: 36 }}/>
      <div className="hh-overlay-panel" style={{
        position: 'absolute', top: 0, bottom: 0, right: 0, width: 420, zIndex: 37,
        background: t.card, borderLeft: `1px solid ${t.border}`,
        boxShadow: '-8px 0 30px rgba(20,18,12,0.10)', display: 'flex', flexDirection: 'column',
      }}>
        <div style={{ padding: '20px 22px 16px', borderBottom: `1px solid ${t.border}` }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <HIcon kind="bell" size={16} style={{ color: t.inkSoft }}/>
              <span style={{ fontSize: 12, color: t.inkSoft, fontWeight: 600, letterSpacing: 0.5 }}>NOTIFICATIONS</span>
            </div>
            <IconBtn t={t} kind="plus" onClick={nav.closeNotifications} title="Close" style={{ transform: 'rotate(45deg)' }}/>
          </div>
          <div style={{ fontFamily: NT_DISPLAY, fontSize: 24, fontWeight: 600, letterSpacing: -0.5, color: t.ink, marginTop: 8 }}>
            {items.length ? `${items.length} need${items.length === 1 ? 's' : ''} attention` : "You're all caught up"}
          </div>
          <div style={{ fontSize: 12.5, color: t.inkSoft, marginTop: 6 }}>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
              <span style={{ width: 6, height: 6, borderRadius: '50%', background: t.soon, display: 'inline-block' }}/>
              In-app preview · {pref.channel} delivery isn’t wired up yet
            </span>
          </div>
        </div>

        <div style={{ flex: 1, overflowY: 'auto', padding: '8px 16px 16px' }}>
          {items.length === 0 && (
            <div style={{ padding: '28px 8px', textAlign: 'center', color: t.inkFaint }}>
              <div style={{ width: 46, height: 46, borderRadius: '50%', background: t.okBg, color: t.ok, display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 12px' }}><HIcon kind="check" size={22}/></div>
              <div style={{ fontSize: 13.5, color: t.inkSoft }}>Nothing needs your attention right now.</div>
            </div>
          )}

          {NOTIF_GROUPS.map(g => {
            const gi = items.filter(it => it.kind === g.kind);
            if (!gi.length) return null;
            return (
              <div key={g.kind} style={{ marginTop: 14 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 7, padding: '0 6px 8px' }}>
                  <StatusDot color={toneColor[g.tone]} size={8}/>
                  <span style={{ fontSize: 11, color: t.inkFaint, fontWeight: 700, letterSpacing: 0.6, textTransform: 'uppercase' }}>{g.label}</span>
                  <span style={{ fontSize: 11, color: t.inkFaint, fontFamily: NT_MONO }}>{gi.length}</span>
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
                  {gi.map(it => (
                    <div key={it.id} onClick={() => openItem(it)} style={{
                      display: 'flex', alignItems: 'center', gap: 11, padding: '11px 12px',
                      border: `1px solid ${g.kind === 'reminder' ? toneColor[g.tone] : t.border}`,
                      borderStyle: g.kind === 'reminder' ? 'dashed' : 'solid',
                      borderRadius: 10, cursor: 'pointer', background: t.card,
                    }}>
                      <span style={{ width: 30, height: 30, borderRadius: 8, flex: '0 0 auto', background: toneBg[g.tone], color: toneColor[g.tone], display: 'flex', alignItems: 'center', justifyContent: 'center' }}><HIcon kind={it.icon} size={15}/></span>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontSize: 13.5, color: t.ink, fontWeight: 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{it.title}</div>
                        <div style={{ fontSize: 12, color: t.inkSoft, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{it.sub}</div>
                      </div>
                      <HIcon kind="chev" size={14} style={{ color: t.inkFaint, flex: '0 0 auto' }}/>
                    </div>
                  ))}
                </div>
              </div>
            );
          })}

          {offNotes.length > 0 && (
            <div style={{ marginTop: 18, padding: '12px 14px', background: t.inputBg, border: `1px solid ${t.border}`, borderRadius: 10 }}>
              <div style={{ fontSize: 12, color: t.inkSoft, lineHeight: 1.5 }}>
                <span style={{ fontWeight: 600 }}>Off for you:</span> {offNotes.join(' · ')}.
              </div>
              <TLink t={t} onClick={() => { nav.closeNotifications(); nav.go('profile'); }} style={{ fontSize: 12.5, display: 'inline-block', marginTop: 6 }}>Manage notifications →</TLink>
            </div>
          )}
        </div>

        <div style={{ padding: '12px 22px', borderTop: `1px solid ${t.border}`, display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{ fontSize: 12, color: t.inkFaint, marginRight: 'auto' }}>Reminders use the offset you set on each routine</span>
          <Btn t={t} onClick={() => { nav.closeNotifications(); nav.go('profile'); }}><HIcon kind="settings" size={13}/> Settings</Btn>
        </div>
      </div>
    </>
  );
};

Object.assign(window, { notificationsForMe, notificationCount, NotificationsPanel });
