/* ─────────────────────────────────────────────────────────────
   Banner content layer (featured-report promo banner on the home
   page, plus any future hero/announcement/promo banners).
   Static fallback below mirrors the original hardcoded banner; it
   is replaced at startup by `bootstrapBanners()` when the panel is
   reachable. Mutated in place so component imports stay live.
   ───────────────────────────────────────────────────────────── */

export interface Banner {
  id: string
  position: string            // 'featured' | 'hero' | 'announcement' | 'promo'
  active: boolean
  image: string
  ctaUrl: string
  fa: { overline: string; title: string; subtitle: string; cta: string }
  en: { overline: string; title: string; subtitle: string; cta: string }
}

/* TEMP fallback — swap for panel/API data via bootstrapBanners(). */
export const banners: Banner[] = [
  {
    id: 'featured-report',
    position: 'featured',
    active: true,
    image: '/Horizontal_Book_Mockup_6 1.webp',
    ctaUrl: '',
    fa: {
      overline: 'ماهنامه شماره ۱۲ منتشر شد…',
      title: 'دیپلماسی معدنی در عصر انسدادهای ژئوپلیتیک',
      subtitle: 'Mineral Diplomacy in the Era of Geopolitical Blockades',
      cta: 'دانلود گزارش',
    },
    en: {
      overline: 'Monthly issue #12 is out…',
      title: 'Mineral Diplomacy in the Era of Geopolitical Blockades',
      subtitle: 'دیپلماسی معدنی در عصر انسدادهای ژئوپلیتیک',
      cta: 'Download report',
    },
  },
]

/** Only allow http(s) or relative URLs to reach window.open/href; null out javascript:/data:/etc. */
const safeUrl = (u: unknown): string =>
  typeof u === 'string' && (/^https?:\/\//i.test(u) || u.startsWith('/')) ? u : ''

/** First active banner for a given position (used by section components). */
export function bannerFor(position: string): Banner | undefined {
  return banners.find((b) => b.active && b.position === position)
}

const PANEL_API =
  (import.meta as ImportMeta & { env?: Record<string, string> }).env?.VITE_PANEL_API ||
  ''

export async function bootstrapBanners(): Promise<void> {
  try {
    const res = await fetch(`${PANEL_API}/api/banners?active=1`)
    if (!res.ok) return
    const fetched = await res.json()
    if (!Array.isArray(fetched) || fetched.length === 0) return
    banners.length = 0
    banners.push(
      ...fetched.map((b: Record<string, unknown>) => ({
        id: String(b.id),
        position: String(b.position ?? 'featured'),
        active: Boolean(b.active),
        image: String(b.image ?? ''),
        ctaUrl: safeUrl(b.ctaUrl),
        fa: {
          overline: String(b.overlineFa ?? ''),
          title: String(b.titleFa ?? ''),
          subtitle: String(b.subtitleFa ?? ''),
          cta: String(b.ctaLabelFa ?? ''),
        },
        en: {
          overline: String(b.overlineEn ?? ''),
          title: String(b.titleEn ?? ''),
          subtitle: String(b.subtitleEn ?? ''),
          cta: String(b.ctaLabelEn ?? ''),
        },
      })),
    )
  } catch {
    /* panel offline → keep static fallback */
  }
}
