/**
 * Saeeol News Component
 *
 * Self-contained component that fetches and displays Saeeol news/notifications.
 * Shows a banner on the home screen; clicking opens a dialog with all news items.
 */

import { createEffect, createMemo, createSignal, on, Show } from "solid-js"
import { useSync } from "@tui/context/sync"
import { useSDK } from "@tui/context/sdk"
import { useDialog } from "@tui/ui/dialog"
import type { SaeeolNotification } from "@saeeol/gateway"
import { NotificationBanner } from "./notification-banner.js"
import { DialogNotifications } from "./dialog-notifications.js"

export function SaeeolNews() {
  const sync = useSync()
  const sdk = useSDK()
  const dialog = useDialog()

  const [notifications, setNotifications] = createSignal<SaeeolNotification[]>([])
  const [fetched, setFetched] = createSignal(false)
  const isSaeeolConnected = createMemo(() => sync.data.provider_next.connected.includes("saeeol"))

  const openNewsDialog = () => {
    const items = notifications()
    if (items.length > 0) {
      dialog.replace(() => <DialogNotifications notifications={items} />)
    }
  }

  // Reactively wait for sync to complete, then fetch notifications once
  createEffect(
    on(
      () => sync.status,
      async (status) => {
        if (status !== "complete") return
        if (fetched()) return
        setFetched(true)

        if (!isSaeeolConnected()) return

        const result = await sdk.client.saeeol.notifications()
        const items = result.data?.filter(({ showIn }: SaeeolNotification) => !showIn || showIn.includes("cli"))
        if (items && items.length > 0) {
          setNotifications(items)
        }
      },
    ),
  )

  // Always render the container to reserve layout space and prevent shift.
  // The banner content appears once notifications are loaded; the fixed-height
  // placeholder keeps the surrounding elements stable during the async fetch.
  return (
    <Show when={notifications().length > 0} fallback={<box height={3} />}>
      <NotificationBanner
        notification={notifications()[0]}
        totalCount={notifications().length}
        onClick={openNewsDialog}
      />
    </Show>
  )
}
