import { useQuery } from '@tanstack/react-query'
import { useEffect, useState } from 'react'
import { fetchCollectorDigest, type DigestItem, type DigestSection } from '../../lib/collector-client'

const STORAGE_KEY = 'overdeck.digest.lastDay'

function localDayKey(): string {
  return new Intl.DateTimeFormat('en-CA', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
  }).format(new Date())
}

function DigestItemRow({ item }: { item: DigestItem }) {
  return (
    <li className="leading-snug">
      <span className="text-[var(--deck-text-primary)]">{item.title}</span>
      {item.detail ? (
        <span className="text-[var(--deck-text-muted)]"> ({item.detail})</span>
      ) : null}
    </li>
  )
}

function DigestSectionBlock({ section }: { section: DigestSection }) {
  const hasItems = section.items.length > 0
  const isScrollable = section.id === 'decisions' && section.items.length > 6

  return (
    <div className="min-w-0">
      <h3 className="text-xs font-medium uppercase tracking-wide text-[var(--deck-text-muted)]">
        {section.label}
      </h3>
      {hasItems ? (
        <ul
          className={`mt-1.5 list-disc space-y-0.5 pl-4 text-sm tabular-nums ${
            isScrollable ? 'max-h-40 overflow-y-auto pr-1' : ''
          }`}
        >
          {section.items.map((item, index) => (
            <DigestItemRow key={`${section.id}-${item.title}-${index}`} item={item} />
          ))}
        </ul>
      ) : section.id === 'scoreboard' ? null : (
        <p className="mt-1 text-sm text-[var(--deck-text-muted)]">None</p>
      )}
    </div>
  )
}

/** Shows the morning digest on the first Overview visit of each local day. */
export function MorningDigestBanner() {
  const [visible, setVisible] = useState(false)
  const digestQuery = useQuery({
    queryKey: ['collector-digest'],
    queryFn: fetchCollectorDigest,
    enabled: visible,
  })

  useEffect(() => {
    const today = localDayKey()
    if (localStorage.getItem(STORAGE_KEY) === today) return
    setVisible(true)
  }, [])

  useEffect(() => {
    if (!digestQuery.data) return
    localStorage.setItem(STORAGE_KEY, localDayKey())
  }, [digestQuery.data])

  if (!visible || !digestQuery.data) return null

  const sections = digestQuery.data.sections ?? []

  return (
    <section
      className="rounded-lg border border-[var(--deck-border)] bg-[var(--deck-surface-raised)] px-4 py-3"
      aria-label="Morning digest"
      data-testid="morning-digest-banner"
    >
      <h2 className="text-sm font-medium text-[var(--deck-text-primary)]">Good morning</h2>
      <p className="mt-1 text-sm text-[var(--deck-text-muted)]">{digestQuery.data.paragraph}</p>
      {sections.length > 0 ? (
        <div className="mt-3 grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
          {sections.map((section) => (
            <DigestSectionBlock key={section.id} section={section} />
          ))}
        </div>
      ) : null}
    </section>
  )
}
