'use client';

import { useEffect, useState } from 'react';
import { BannerStack, Announcement, type BannerItem } from '@bytelyst/notifications-ui';

/**
 * Top-of-page system messaging for the dashboard (UX-13.2).
 *
 * Tracker has no notifications feed yet, so UX-13.1 (NotificationCenter) is
 * deferred. Per the wave's data-gate we ship the client-side surfaces only:
 *  - `BannerStack` renders dismissible system/maintenance notices sourced from
 *    `NEXT_PUBLIC_SYSTEM_NOTICE` (renders nothing when unset).
 *  - `Announcement` shows a dismissible "what's new" pill, remembered per
 *    version in localStorage.
 *
 * All colors come from the bridged `--bl-*` tokens (no hardcoded literals).
 */

const SYSTEM_NOTICE = process.env.NEXT_PUBLIC_SYSTEM_NOTICE || '';
const WHATS_NEW_KEY = 'tracker_whatsnew_dismissed';
// Bump when the "what's new" copy changes to re-surface it once.
const WHATS_NEW_VERSION = '2026-05-ux';

export function SystemBanners() {
  const [banners, setBanners] = useState<BannerItem[]>([]);
  const [showWhatsNew, setShowWhatsNew] = useState(false);

  useEffect(() => {
    if (SYSTEM_NOTICE) {
      setBanners([
        {
          id: 'system-notice',
          kind: 'warning',
          title: 'System notice',
          body: SYSTEM_NOTICE,
        },
      ]);
    }
    if (typeof window !== 'undefined') {
      setShowWhatsNew(localStorage.getItem(WHATS_NEW_KEY) !== WHATS_NEW_VERSION);
    }
  }, []);

  const dismissWhatsNew = () => {
    if (typeof window !== 'undefined') {
      localStorage.setItem(WHATS_NEW_KEY, WHATS_NEW_VERSION);
    }
    setShowWhatsNew(false);
  };

  if (banners.length === 0 && !showWhatsNew) return null;

  return (
    <div className="mb-6 space-y-3">
      <BannerStack
        banners={banners}
        onDismiss={id => setBanners(prev => prev.filter(b => b.id !== id))}
      />
      {showWhatsNew && (
        <Announcement tag="NEW" cta={{ label: 'Got it', onSelect: dismissWhatsNew }}>
          Tracker now runs on the shared ByteLyst design system — consistent header band, accessible
          controls, and full dark-mode parity.
        </Announcement>
      )}
    </div>
  );
}
