/* رادار آینده — block articles from the panel (articles?type=radarfuture).
   Each radar sub-page (/radar/<slug>) shows the articles whose category == the
   sub-menu label. Falls back to an empty list when the panel is offline. */

import type { RadarItem, RadarCategory } from './radar'

export type RFBlock = { type: 'text' | 'image'; value?: string; url?: string; caption?: string }

export type RadarFutureArticle = {
  id: string
  category: string            // one of the 5 sub-menu labels
  img: string
  tags: string[]
  sources: { title: string; url: string }[]
  blocks: RFBlock[]
  author: { name: string; avatar: string }
  fa: { title: string; date: string; excerpt: string }
  en: { title: string; date: string; excerpt: string }
}

export const RADAR_FUTURE: RadarFutureArticle[] = []

// same data in the RadarItem shape (for the /radar index + home «رادار آینده» strip)
export const RADAR_FUTURE_ITEMS: RadarItem[] = []
const LABEL_TO_ENUM: Record<string, RadarCategory> = {
  'بازار و زنجیره فولاد': 'market',
  'فناوری و نوآوری': 'tech',
  'پایداری و فولاد سبز': 'energy',
  'ژئوپلیتیک و اقتصاد جهانی': 'geo',
}

// /radar/<slug> → the رادار آینده sub-menu category label stored on the article
export const RADAR_SLUG_LABEL: Record<string, string> = {
  market:         'بازار و زنجیره فولاد',
  sustainability: 'پایداری و فولاد سبز',
  geopolitics:    'ژئوپلیتیک و اقتصاد جهانی',
  technology:     'فناوری و نوآوری',
}

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

export async function bootstrapRadarFuture(): Promise<void> {
  try {
    const res = await fetch(`${PANEL_API}/api/articles?type=radarfuture&limit=200`)
    if (!res.ok) return
    const rows = await res.json()
    if (!Array.isArray(rows) || rows.length === 0) return
    RADAR_FUTURE.length = 0
    RADAR_FUTURE.push(...rows.map((a: Record<string, unknown>): RadarFutureArticle => {
      const title = String(a.title ?? '')
      const date = String(a.publishDate ?? '')
      const excerpt = String(a.summary ?? '')
      const blocks = Array.isArray(a.blocks) ? (a.blocks as RFBlock[]) : []
      const cover = String(a.coverImage ?? '') || (blocks.find(b => b.type === 'image')?.url ?? '')
      return {
        id: String(a.id),
        category: String(a.category ?? ''),
        img: cover,
        tags: Array.isArray(a.tags) ? (a.tags as string[]) : [],
        sources: Array.isArray(a.sources) ? (a.sources as { title: string; url: string }[]) : [],
        blocks,
        author: { name: String(a.author ?? ''), avatar: '' },
        fa: { title, date, excerpt },
        en: { title, date, excerpt },
      }
    }))
    RADAR_FUTURE_ITEMS.length = 0
    RADAR_FUTURE_ITEMS.push(...RADAR_FUTURE.map((a): RadarItem => {
      const body = a.blocks.filter(b => b.type === 'text').map(b => b.value || '').filter(Boolean)
      return {
        id: a.id,
        category: LABEL_TO_ENUM[a.category] || 'market',
        img: a.img,
        author: a.author,
        fa: { title: a.fa.title, date: a.fa.date, excerpt: a.fa.excerpt, body },
        en: { title: a.en.title, date: a.en.date, excerpt: a.en.excerpt, body },
      }
    }))
  } catch { /* panel offline → keep empty */ }
}
