// §15.2 — the inbox panel.
//
// One mental space across every RFC the contributor has any relationship
// to. Filter chips (Unread only, RFC: …, Category: personal-direct /
// structural / churn) are AND-combined. The bundle toggle collapses
// rows by (RFC, event_kind) per §15.2's per-bundle markable surface.
//
// The header badge in App.jsx subscribes to the same SSE stream and so
// stays in lockstep with the inbox per §15.3.

import { useEffect, useMemo, useState } from 'react'
import { Link } from 'react-router-dom'
import {
  listNotifications,
  markNotificationRead,
  markNotificationsReadByFilter,
} from '../api.js'
import './Inbox.css'

const CATEGORIES = [
  { value: '', label: 'All categories' },
  { value: 'personal-direct', label: 'Personal' },
  { value: 'structural', label: 'Structural' },
  { value: 'churn', label: 'Churn' },
]

export default function Inbox({ onClose, lastChangeTick }) {
  const [items, setItems] = useState([])
  const [unreadCount, setUnreadCount] = useState(0)
  const [filters, setFilters] = useState({
    unread: false, rfcSlug: '', category: '', bundled: false,
  })
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    setLoading(true)
    listNotifications({
      unread: filters.unread,
      rfcSlug: filters.rfcSlug || undefined,
      category: filters.category || undefined,
      bundled: filters.bundled,
    })
      .then(r => {
        setItems(r.items || [])
        setUnreadCount(r.unread_count || 0)
      })
      .finally(() => setLoading(false))
  }, [filters, lastChangeTick])

  const rfcOptions = useMemo(() => {
    const seen = new Map()
    for (const it of items) {
      if (it.rfc_slug && !seen.has(it.rfc_slug)) {
        seen.set(it.rfc_slug, it.rfc_title || it.rfc_slug)
      }
    }
    return Array.from(seen.entries())
  }, [items])

  async function markOneRead(item) {
    if (item.read_at) return
    await markNotificationRead(item.id)
    setItems(prev => prev.map(p => p.id === item.id ? { ...p, read_at: new Date().toISOString() } : p))
    setUnreadCount(c => Math.max(0, c - 1))
  }

  async function handleRowClick(item) {
    await markOneRead(item)
  }

  async function markAllUnderFilter() {
    await markNotificationsReadByFilter({
      rfc_slug: filters.rfcSlug || undefined,
      category: filters.category || undefined,
    })
    setItems(prev => prev.map(p => ({ ...p, read_at: p.read_at || new Date().toISOString() })))
    setUnreadCount(0)
  }

  return (
    <div className="inbox-overlay" onClick={onClose}>
      <div className="inbox-panel" onClick={e => e.stopPropagation()}>
        <header className="inbox-header">
          <h2>Inbox</h2>
          <button className="btn-link" onClick={onClose}>Close</button>
        </header>

        <div className="inbox-filters">
          <label className="chip">
            <input
              type="checkbox"
              checked={filters.unread}
              onChange={e => setFilters(f => ({ ...f, unread: e.target.checked }))}
            />
            Unread only
          </label>

          <select
            value={filters.rfcSlug}
            onChange={e => setFilters(f => ({ ...f, rfcSlug: e.target.value }))}
            className="chip"
          >
            <option value="">All RFCs</option>
            {rfcOptions.map(([slug, title]) => (
              <option key={slug} value={slug}>{title}</option>
            ))}
          </select>

          <select
            value={filters.category}
            onChange={e => setFilters(f => ({ ...f, category: e.target.value }))}
            className="chip"
          >
            {CATEGORIES.map(c => (
              <option key={c.value} value={c.value}>{c.label}</option>
            ))}
          </select>

          <label className="chip">
            <input
              type="checkbox"
              checked={filters.bundled}
              onChange={e => setFilters(f => ({ ...f, bundled: e.target.checked }))}
            />
            Bundle by RFC
          </label>

          <button
            className="btn-link inbox-mark-all"
            onClick={markAllUnderFilter}
            disabled={items.every(i => i.read_at)}
            title="Mark every notification matching the current filter as read"
          >
            Mark all read
          </button>
        </div>

        <div className="inbox-body">
          {loading && <p className="inbox-state muted">Loading your inbox…</p>}
          {!loading && items.length === 0 && (
            <div className="inbox-empty">
              <p className="inbox-empty-title">You're all caught up.</p>
              <p className="muted">
                {filters.unread || filters.rfcSlug || filters.category
                  ? 'Nothing matches the current filters. Clear them to see everything.'
                  : 'New activity on RFCs you follow will show up here.'}
              </p>
            </div>
          )}
          <ul className="inbox-list">
            {items.map(item => (
              <InboxRow
                key={item.id}
                item={item}
                onClick={handleRowClick}
                onMarkRead={markOneRead}
                onClose={onClose}
              />
            ))}
          </ul>
        </div>
      </div>
    </div>
  )
}

function InboxRow({ item, onClick, onMarkRead, onClose }) {
  const unread = !item.read_at
  const target = deepLink(item)
  const handle = async () => {
    await onClick(item)
    if (target) onClose?.()
  }
  const handleMarkRead = async (e) => {
    // Don't let the row's Link fire — this affordance only marks read,
    // it never navigates.
    e.preventDefault()
    e.stopPropagation()
    await onMarkRead(item)
  }
  return (
    <li className={`inbox-row ${unread ? 'unread' : 'read'}`}>
      <Link to={target || '#'} onClick={handle} className="inbox-row-link">
        <span className="inbox-unread-dot" aria-hidden />
        <span className={`inbox-cat cat-${item.category || 'unknown'}`}>{item.category || '·'}</span>
        <span className="inbox-summary">{item.summary}</span>
        {item.bundled_count > 1 && (
          <span className="inbox-bundle-count">+{item.bundled_count - 1}</span>
        )}
        <span className="inbox-when">{formatWhen(item.created_at)}</span>
      </Link>
      {unread && (
        <button
          type="button"
          className="inbox-row-dismiss"
          onClick={handleMarkRead}
          aria-label="Mark as read"
          title="Mark as read"
        >
          {/* check glyph — dependency-free inline SVG */}
          <svg
            width="14" height="14" viewBox="0 0 24 24"
            fill="none" stroke="currentColor" strokeWidth="2.25"
            strokeLinecap="round" strokeLinejoin="round" aria-hidden
          >
            <path d="m5 13 4 4 10-11" />
          </svg>
        </button>
      )}
    </li>
  )
}

function deepLink(item) {
  if (item.rfc_slug && item.pr_number) return `/rfc/${item.rfc_slug}/pr/${item.pr_number}`
  if (item.rfc_slug && item.branch_name) return `/rfc/${item.rfc_slug}?branch=${item.branch_name}`
  if (item.rfc_slug) return `/rfc/${item.rfc_slug}`
  return ''
}

function formatWhen(iso) {
  if (!iso) return ''
  const dt = new Date(iso.replace(' ', 'T') + (iso.endsWith('Z') ? '' : 'Z'))
  if (Number.isNaN(dt.getTime())) return iso
  const diffMs = Date.now() - dt.getTime()
  const m = Math.floor(diffMs / 60000)
  if (m < 1) return 'just now'
  if (m < 60) return `${m}m`
  const h = Math.floor(m / 60)
  if (h < 24) return `${h}h`
  const d = Math.floor(h / 24)
  return `${d}d`
}
