(function () {
  'use strict';

  function parseData() {
    var node = document.getElementById('diar-executive-chart-data');
    if (!node) return null;
    try { return JSON.parse(node.textContent || '{}'); } catch (error) { return null; }
  }

  function formatMoney(value) {
    var number = Number(value || 0);
    if (Math.abs(number) >= 1000000) return 'SAR ' + (number / 1000000).toFixed(2) + 'M';
    if (Math.abs(number) >= 1000) return 'SAR ' + (number / 1000).toFixed(1) + 'K';
    return 'SAR ' + number.toFixed(0);
  }

  function renderPriority(data) {
    var el = document.getElementById('diar-priority-chart');
    if (!el || !window.echarts) return;
    var chart = window.echarts.init(el, null, { renderer: 'canvas' });
    chart.setOption({
      animationDuration: 550,
      tooltip: { trigger: 'item', formatter: '{b}: {c} ({d}%)' },
      series: [{
        type: 'pie', radius: ['57%', '78%'], center: ['50%', '49%'], avoidLabelOverlap: true,
        label: { show: false }, emphasis: { scale: true, scaleSize: 6 },
        data: [
          { value: Number(data.critical || 0), name: 'Critical', itemStyle: { color: '#d1435b' } },
          { value: Number(data.high || 0), name: 'High', itemStyle: { color: '#ef7c22' } },
          { value: Number(data.medium || 0), name: 'Medium', itemStyle: { color: '#e7b42e' } }
        ]
      }],
      graphic: [{ type: 'text', left: 'center', top: '42%', style: { text: String(data.total || 0), fontSize: 24, fontWeight: 800, fill: '#102a43' } },
                { type: 'text', left: 'center', top: '57%', style: { text: 'Total cases', fontSize: 10, fill: '#6b7e91' } }]
    });
    el.querySelector('.chart-fallback')?.remove();
    window.addEventListener('resize', function () { chart.resize(); }, { passive: true });
  }

  function renderTrend(rows) {
    var el = document.getElementById('diar-daily-trend-chart');
    if (!el || !window.echarts || !Array.isArray(rows) || rows.length === 0) return;
    var chart = window.echarts.init(el, null, { renderer: 'canvas' });
    chart.setOption({
      animationDuration: 600,
      grid: { left: 52, right: 54, top: 35, bottom: 35 },
      tooltip: {
        trigger: 'axis',
        formatter: function (params) {
          var index = params && params[0] ? params[0].dataIndex : 0;
          var row = rows[index] || {};
          return '<strong>' + (row.date || '') + '</strong><br>Cases: ' + (row.cases || 0) + '<br>Critical: ' + (row.critical || 0) + '<br>' + formatMoney(row.cost || 0);
        }
      },
      legend: { top: 0, right: 0, itemWidth: 12, textStyle: { color: '#61758b', fontSize: 10 } },
      xAxis: { type: 'category', boundaryGap: false, data: rows.map(function (r) { return r.label; }), axisLine: { lineStyle: { color: '#dce6f0' } }, axisTick: { show: false }, axisLabel: { color: '#718396', fontSize: 10 } },
      yAxis: [
        { type: 'value', name: 'Cases', nameTextStyle: { color: '#708196', fontSize: 9 }, splitLine: { lineStyle: { color: '#edf2f6' } }, axisLabel: { color: '#718396', fontSize: 9 } },
        { type: 'value', name: 'SAR', nameTextStyle: { color: '#708196', fontSize: 9 }, splitLine: { show: false }, axisLabel: { color: '#718396', fontSize: 9, formatter: function (v) { return v >= 1000 ? (v / 1000).toFixed(0) + 'K' : v; } } }
      ],
      series: [
        { name: 'Review cases', type: 'line', smooth: true, symbol: 'circle', symbolSize: 5, data: rows.map(function (r) { return Number(r.cases || 0); }), lineStyle: { width: 3, color: '#6d28d9' }, itemStyle: { color: '#6d28d9' }, areaStyle: { color: 'rgba(109,40,217,.09)' } },
        { name: 'Associated cost', type: 'line', yAxisIndex: 1, smooth: true, symbol: 'none', data: rows.map(function (r) { return Number(r.cost || 0); }), lineStyle: { width: 2, color: '#0f8f87' }, itemStyle: { color: '#0f8f87' } }
      ]
    });
    window.addEventListener('resize', function () { chart.resize(); }, { passive: true });
  }

  function boot() {
    var data = parseData();
    if (!data) return;
    renderPriority(data.priority || {});
    renderTrend(data.trend || []);
  }

  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot, { once: true });
  else boot();
})();
