'use client'

import { useEffect, useState } from 'react'
import { tone } from './Badge'

interface Event {
  _id: string
  tone: string
  text: string
  source: string
  createdAt: string
}

function timeAgo(iso: string): string {
  const sec = Math.max(0, Math.round((Date.now() - new Date(iso).getTime()) / 1000))
  if (sec < 60) return `${sec}s ago`
  if (sec < 3600) return `${Math.floor(sec / 60)}m ago`
  return `${Math.floor(sec / 3600)}h ago`
}

export function ActivityPanel() {
  const [events, setEvents] = useState<Event[]>([])

  useEffect(() => {
    async function load() {
      try {
        const res = await fetch('/api/events?limit=20', { cache: 'no-store' })
        if (res.ok) {
          const data = await res.json()
          setEvents(data.events || [])
        }
      } catch { /* ignore */ }
    }
    load()
    const interval = setInterval(load, 30000)
    return () => clearInterval(interval)
  }, [])

  return (
    <section className="panel activity-panel">
      <div className="panel-heading">
        <div>
          <h2>Recent activity</h2>
          <p>Live events from your monitoring workspace.</p>
        </div>
        <span style={{ fontSize: '11px', color: '#94a3b8' }}>{events.length} events</span>
      </div>
      <div className="timeline">
        {events.length === 0 ? (
          <div className="muted empty-cell" style={{ padding: '1rem', textAlign: 'center', fontSize: '12px' }}>
            No events yet — monitoring will log changes here.
          </div>
        ) : (
          events.map((ev) => (
            <div className="event" key={ev._id}>
              <div className={`event-dot ${tone(ev.tone)}`} />
              <div>
                <b>{ev.text}</b>
                <small>{timeAgo(ev.createdAt)} · {ev.source}</small>
              </div>
            </div>
          ))
        )}
      </div>
    </section>
  )
}
