export type PriceTrend = 'up' | 'down' | 'flat';

export interface MarketPrice {
  id: string;
  name: string;
  value: number;
  unit: string;
  change: number;
  changePercent: number;
  trend: PriceTrend;
}

export interface PriceHistoryPoint {
  month: string;
  price: number;
}

export interface GlobalComparison {
  country: string;
  flag: string;
  price: number;
  unit: string;
  currency: string;
}

export interface ExportData {
  month: string;
  tonnage: number;
}

export interface InstituteStats {
  totalReports: number;
  years: number;
  experts: number;
  memberOrgs: number;
  subscribers: number;
}

export const marketPrices: MarketPrice[] = [
  {
    id: 'steel-billet',
    name: 'شمش فولاد',
    value: 18400,
    unit: 'تومان/کیلو',
    change: 220,
    changePercent: 1.2,
    trend: 'up',
  },
  {
    id: 'rebar-a3',
    name: 'میلگرد A3',
    value: 17800,
    unit: 'تومان/کیلو',
    change: -90,
    changePercent: -0.5,
    trend: 'down',
  },
  {
    id: 'beam-14',
    name: 'تیرآهن ۱۴',
    value: 16900,
    unit: 'تومان/کیلو',
    change: 135,
    changePercent: 0.8,
    trend: 'up',
  },
  {
    id: 'scrap-iron',
    name: 'آهن قراضه',
    value: 550,
    unit: 'دلار/تن',
    change: -11,
    changePercent: -2.0,
    trend: 'down',
  },
  {
    id: 'cold-rolled-sheet',
    name: 'ورق سرد',
    value: 22100,
    unit: 'تومان/کیلو',
    change: 66,
    changePercent: 0.3,
    trend: 'up',
  },
  {
    id: 'angle-bar-80',
    name: 'نبشی ۸۰',
    value: 15600,
    unit: 'تومان/کیلو',
    change: -172,
    changePercent: -1.1,
    trend: 'down',
  },
  {
    id: 'mobarakeh-steel',
    name: 'فولاد مبارکه',
    value: 12840,
    unit: 'ریال',
    change: -143,
    changePercent: -1.1,
    trend: 'down',
  },
];

export const priceHistory: PriceHistoryPoint[] = [
  { month: 'خرداد ۱۴۰۳', price: 15200 },
  { month: 'تیر ۱۴۰۳', price: 15600 },
  { month: 'مرداد ۱۴۰۳', price: 16100 },
  { month: 'شهریور ۱۴۰۳', price: 15800 },
  { month: 'مهر ۱۴۰۳', price: 16400 },
  { month: 'آبان ۱۴۰۳', price: 17000 },
  { month: 'آذر ۱۴۰۳', price: 17500 },
  { month: 'دی ۱۴۰۳', price: 17200 },
  { month: 'بهمن ۱۴۰۳', price: 17800 },
  { month: 'اسفند ۱۴۰۳', price: 18100 },
  { month: 'فروردین ۱۴۰۴', price: 18600 },
  { month: 'اردیبهشت ۱۴۰۴', price: 18400 },
];

export const globalComparison: GlobalComparison[] = [
  {
    country: 'ایران',
    flag: '🇮🇷',
    price: 18400,
    unit: 'تومان/کیلو',
    currency: 'IRR',
  },
  {
    country: 'ترکیه',
    flag: '🇹🇷',
    price: 530,
    unit: 'دلار/تن',
    currency: 'USD',
  },
  {
    country: 'هند',
    flag: '🇮🇳',
    price: 510,
    unit: 'دلار/تن',
    currency: 'USD',
  },
  {
    country: 'چین',
    flag: '🇨🇳',
    price: 460,
    unit: 'دلار/تن',
    currency: 'USD',
  },
  {
    country: 'روسیه',
    flag: '🇷🇺',
    price: 485,
    unit: 'دلار/تن',
    currency: 'USD',
  },
];

export const monthlyExport: ExportData[] = [
  { month: 'خرداد ۱۴۰۳', tonnage: 285000 },
  { month: 'تیر ۱۴۰۳', tonnage: 310000 },
  { month: 'مرداد ۱۴۰۳', tonnage: 295000 },
  { month: 'شهریور ۱۴۰۳', tonnage: 320000 },
  { month: 'مهر ۱۴۰۳', tonnage: 350000 },
  { month: 'آبان ۱۴۰۳', tonnage: 375000 },
  { month: 'آذر ۱۴۰۳', tonnage: 390000 },
  { month: 'دی ۱۴۰۳', tonnage: 360000 },
  { month: 'بهمن ۱۴۰۳', tonnage: 415000 },
  { month: 'اسفند ۱۴۰۳', tonnage: 420000 },
  { month: 'فروردین ۱۴۰۴', tonnage: 400000 },
  { month: 'اردیبهشت ۱۴۰۴', tonnage: 410000 },
];

export const stats: InstituteStats = {
  totalReports: 280,
  years: 12,
  experts: 45,
  memberOrgs: 60,
  subscribers: 2800,
};

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

/** Map an institute_stats row id back onto the InstituteStats object key. */
const STAT_KEY_BY_ID: Record<string, keyof InstituteStats> = {
  'total-reports': 'totalReports',
  'years': 'years',
  'experts': 'experts',
  'member-orgs': 'memberOrgs',
  'subscribers': 'subscribers',
}

/**
 * Fetch CMS-managed market data and mutate the exported arrays/object in place.
 * Mirrors bootstrapEvents(): silent try/catch, keeps static fallback when the
 * panel is offline or returns nothing. Endpoints fetched in parallel.
 */
export async function bootstrapMarket(): Promise<void> {
  try {
    const [statsRes, pricesRes, pointsRes] = await Promise.all([
      fetch(`${PANEL_API}/api/institute-stats`),
      fetch(`${PANEL_API}/api/market-prices`),
      fetch(`${PANEL_API}/api/market-chart-points?limit=500`),
    ])

    /* ── institute stats → stats object ── */
    if (statsRes.ok) {
      const rows = await statsRes.json()
      if (Array.isArray(rows) && rows.length) {
        for (const row of rows as Array<Record<string, unknown>>) {
          const key = STAT_KEY_BY_ID[String(row.id)]
          if (key) stats[key] = Number(row.value) || 0
        }
      }
    }

    /* ── market prices → marketPrices[] ── */
    if (pricesRes.ok) {
      const rows = await pricesRes.json()
      if (Array.isArray(rows) && rows.length) {
        marketPrices.length = 0
        marketPrices.push(...(rows as Array<Record<string, unknown>>).map((r) => ({
          id: String(r.id),
          name: String(r.name ?? ''),
          value: Number(r.value) || 0,
          unit: String(r.unit ?? ''),
          change: Number(r.change) || 0,
          changePercent: Number(r.changePercent) || 0,
          trend: (['up', 'down', 'flat'].includes(String(r.trend)) ? r.trend : 'flat') as PriceTrend,
        })))
      }
    }

    /* ── chart points → priceHistory / monthlyExport / globalComparison ── */
    if (pointsRes.ok) {
      const rows = await pointsRes.json()
      if (Array.isArray(rows) && rows.length) {
        const points = rows as Array<Record<string, unknown>>
        const history = points.filter((p) => p.series === 'history')
        const exports = points.filter((p) => p.series === 'export')
        const comparison = points.filter((p) => p.series === 'comparison')

        if (history.length) {
          priceHistory.length = 0
          priceHistory.push(...history.map((p) => ({
            month: String(p.label ?? ''),
            price: Number(p.value) || 0,
          })))
        }

        if (exports.length) {
          monthlyExport.length = 0
          monthlyExport.push(...exports.map((p) => ({
            month: String(p.label ?? ''),
            tonnage: Number(p.value) || 0,
          })))
        }

        if (comparison.length) {
          globalComparison.length = 0
          globalComparison.push(...comparison.map((p) => {
            // `meta` carries flag + currency + unit packed by the panel.
            let meta: { flag?: string; currency?: string; unit?: string } = {}
            if (p.meta) {
              try { meta = typeof p.meta === 'string' ? JSON.parse(p.meta) : (p.meta as Record<string, string>) } catch { /* keep {} */ }
            }
            return {
              country: String(p.label ?? ''),
              flag: String(meta.flag ?? ''),
              price: Number(p.value) || 0,
              unit: String(meta.unit ?? ''),
              currency: String(meta.currency ?? ''),
            }
          }))
        }
      }
    }
  } catch { /* panel offline → keep static fallback */ }
}
