/* ============================================
   INBOX — notifications, mentions, assignments
   ============================================ */

// Synthesize notifications from tasks + activity
function buildInbox(tasks, currentUser) {
  const items = [];

  tasks.forEach(t => {
    // assigned to me (recent)
    if (t.assignee === currentUser.id && ['Backlog','In progress'].includes(t.status)) {
      const days = daysFromToday(t.createdAt);
      if (days !== null && days >= -7) {
        items.push({
          id: 'as-' + t.id,
          kind: 'assign',
          actor: t.pic || 'u3',
          taskId: t.id,
          text: <>assigned you to <b>{t.name}</b></>,
          time: t.createdAt,
          unread: days >= -3,
        });
      }
    }

    // mentioned in comments
    (t.comments || []).forEach(c => {
      if (c.text && (c.text.includes('@' + currentUser.id) || c.text.includes('@u1') && currentUser.id === 'u1')) {
        items.push({
          id: 'mn-' + t.id + '-' + c.id,
          kind: 'mention',
          actor: c.author,
          taskId: t.id,
          text: <>mentioned you in <b>{t.name}</b></>,
          preview: c.text,
          time: c.time,
          unread: daysFromToday(c.time) >= -2,
        });
      }
    });

    // due soon (mine)
    if (t.assignee === currentUser.id) {
      const days = daysFromToday(t.dueDate);
      if (days !== null && days >= 0 && days <= 2 && !['Done','Cancel','Archived'].includes(t.status)) {
        items.push({
          id: 'du-' + t.id,
          kind: 'due',
          actor: null,
          taskId: t.id,
          text: <>is due {days === 0 ? 'today' : days === 1 ? 'tomorrow' : `in ${days} days`}: <b>{t.name}</b></>,
          time: t.dueDate,
          unread: days <= 1,
        });
      }
      if (days !== null && days < 0 && !['Done','Cancel','Archived'].includes(t.status)) {
        items.push({
          id: 'ov-' + t.id,
          kind: 'overdue',
          actor: null,
          taskId: t.id,
          text: <>is <b style={{color:'var(--c-rose)'}}>{Math.abs(days)} days overdue</b>: {t.name}</>,
          time: t.dueDate,
          unread: true,
        });
      }
    }

    // comments on my tasks (others commenting)
    if (t.assignee === currentUser.id || t.pic === currentUser.id) {
      (t.comments || []).forEach(c => {
        if (c.author !== currentUser.id) {
          items.push({
            id: 'cm-' + t.id + '-' + c.id,
            kind: 'comment',
            actor: c.author,
            taskId: t.id,
            text: <>commented on <b>{t.name}</b></>,
            preview: c.text,
            time: c.time,
            unread: daysFromToday(c.time) >= -3,
          });
        }
      });
    }
  });

  // sort by time desc, dedupe
  const seen = new Set();
  return items
    .filter(i => { if (seen.has(i.id)) return false; seen.add(i.id); return true; })
    .sort((a, b) => new Date(b.time) - new Date(a.time));
}

const KIND_META = {
  assign:  { icon: 'user',     color: '#6D49F2', label: 'Assigned' },
  mention: { icon: 'message',  color: '#EC4899', label: 'Mention'  },
  comment: { icon: 'message',  color: '#3B82F6', label: 'Comment'  },
  due:     { icon: 'clock',    color: '#F59E0B', label: 'Due soon' },
  overdue: { icon: 'warning',  color: '#F43F5E', label: 'Overdue'  },
};

const InboxView = ({ tasks, currentUser, onOpenTask }) => {
  const [filter, setFilter] = React.useState('all');
  const [readIds, setReadIds] = React.useState(() => new Set());

  const items = React.useMemo(() => buildInbox(tasks, currentUser), [tasks, currentUser.id]);
  const filtered = items.filter(i => {
    if (filter === 'unread') return i.unread && !readIds.has(i.id);
    if (filter === 'mentions') return i.kind === 'mention';
    if (filter === 'assigned') return i.kind === 'assign';
    if (filter === 'due') return i.kind === 'due' || i.kind === 'overdue';
    return true;
  });

  const unreadCount = items.filter(i => i.unread && !readIds.has(i.id)).length;

  const markRead = (id) => setReadIds(s => new Set([...s, id]));
  const markAllRead = () => setReadIds(new Set(items.map(i => i.id)));

  const groups = React.useMemo(() => {
    const out = { today: [], week: [], earlier: [] };
    filtered.forEach(i => {
      const days = daysFromToday(i.time);
      if (days === 0 || days === null) out.today.push(i);
      else if (days >= -7) out.week.push(i);
      else out.earlier.push(i);
    });
    return out;
  }, [filtered]);

  const FILTERS = [
    { id: 'all',      label: 'All',       count: items.length },
    { id: 'unread',   label: 'Unread',    count: unreadCount },
    { id: 'mentions', label: 'Mentions',  count: items.filter(i => i.kind === 'mention').length },
    { id: 'assigned', label: 'Assigned to me', count: items.filter(i => i.kind === 'assign').length },
    { id: 'due',      label: 'Due & overdue', count: items.filter(i => i.kind === 'due' || i.kind === 'overdue').length },
  ];

  return (
    <div style={{ maxWidth: 880, margin: '0 auto', padding: '24px 24px 60px' }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 16, marginBottom: 20 }}>
        <div style={{ flex: 1 }}>
          <h1 style={{ fontSize: 24, fontWeight: 800, letterSpacing: '-0.03em', marginBottom: 4 }}>Inbox</h1>
          <p style={{ fontSize: 13.5, color: 'var(--text-muted)', margin: 0 }}>
            Notifications, mentions, and updates from your team
          </p>
        </div>
        {unreadCount > 0 && (
          <Btn kind="ghost" icon="check" onClick={markAllRead}>Mark all read</Btn>
        )}
      </div>

      <div style={{ display: 'flex', gap: 4, marginBottom: 14, borderBottom: '1px solid var(--border)', overflowX: 'auto' }}>
        {FILTERS.map(f => (
          <button
            key={f.id}
            className={`tab${filter === f.id ? ' active' : ''}`}
            onClick={() => setFilter(f.id)}
          >
            {f.label}
            <span className="count">{f.count}</span>
          </button>
        ))}
      </div>

      {filtered.length === 0 ? (
        <div className="empty-state">
          <div className="empty-state-icon"><Icon name="inbox" size={28} /></div>
          <h3>You're all caught up 🎉</h3>
          <p>No notifications match this filter.</p>
        </div>
      ) : (
        <>
          {groups.today.length > 0 && <InboxGroup label="Today" items={groups.today} readIds={readIds} markRead={markRead} onOpenTask={onOpenTask} />}
          {groups.week.length > 0 && <InboxGroup label="This week" items={groups.week} readIds={readIds} markRead={markRead} onOpenTask={onOpenTask} />}
          {groups.earlier.length > 0 && <InboxGroup label="Earlier" items={groups.earlier} readIds={readIds} markRead={markRead} onOpenTask={onOpenTask} />}
        </>
      )}
    </div>
  );
};

const InboxGroup = ({ label, items, readIds, markRead, onOpenTask }) => (
  <div style={{ marginBottom: 18 }}>
    <div style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 700, color: 'var(--text-subtle)', margin: '14px 4px 8px' }}>
      {label}
    </div>
    <div style={{ background: 'var(--bg-elevated)', border: '1px solid var(--border)', borderRadius: 12, overflow: 'hidden' }}>
      {items.map((i, idx) => {
        const meta = KIND_META[i.kind] || KIND_META.comment;
        const actor = i.actor ? getUser(i.actor) : null;
        const isUnread = i.unread && !readIds.has(i.id);
        return (
          <div
            key={i.id}
            onClick={() => { markRead(i.id); onOpenTask(i.taskId); }}
            style={{
              display: 'flex', alignItems: 'flex-start', gap: 12,
              padding: '12px 16px',
              borderTop: idx > 0 ? '1px solid var(--border)' : 'none',
              cursor: 'pointer',
              background: isUnread ? 'var(--brand-50)' : 'transparent',
              position: 'relative',
            }}
            onMouseEnter={(e) => { if (!isUnread) e.currentTarget.style.background = 'var(--surface-2)'; }}
            onMouseLeave={(e) => { if (!isUnread) e.currentTarget.style.background = 'transparent'; }}
          >
            {isUnread && (
              <span style={{ position: 'absolute', left: 6, top: 22, width: 6, height: 6, borderRadius: '50%', background: 'var(--brand-500)' }} />
            )}
            {actor ? <Avatar user={actor} size="md" /> : (
              <span style={{ width: 28, height: 28, borderRadius: '50%', background: `${meta.color}1A`, color: meta.color, display: 'grid', placeItems: 'center', flexShrink: 0 }}>
                <Icon name={meta.icon} size={14} />
              </span>
            )}
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13.5, lineHeight: 1.45, color: 'var(--text)' }}>
                {actor && <b style={{ fontWeight: 600 }}>{actor.short} </b>}
                {i.text}
              </div>
              {i.preview && (
                <div style={{
                  marginTop: 4,
                  padding: '6px 10px',
                  borderLeft: '2px solid var(--border-strong)',
                  fontSize: 12.5,
                  color: 'var(--text-muted)',
                  lineHeight: 1.4,
                  fontStyle: 'italic',
                }}>
                  "{i.preview}"
                </div>
              )}
              <div style={{ fontSize: 11.5, color: 'var(--text-subtle)', marginTop: 4, display: 'flex', alignItems: 'center', gap: 6 }}>
                <span style={{ background: `${meta.color}1A`, color: meta.color, padding: '1px 6px', borderRadius: 4, fontWeight: 600, fontSize: 10.5 }}>{meta.label}</span>
                <span>·</span>
                <span>{formatDate(i.time)}</span>
              </div>
            </div>
          </div>
        );
      })}
    </div>
  </div>
);

Object.assign(window, { InboxView });
