/**
 * Risk Radar — customer portfolio risk view.
 */
import { getJson } from '/js/core/app-http.js';
import { resolveHost } from '/js/core/app-dom.js';

const EMPTY_API = Object.freeze({ destroy: () => {} });

const resolveContainer = (root) => {
  const host = resolveHost(root);
  if (host instanceof HTMLElement && host.matches('.app-details-container[data-app-component="helpdesk-risk-radar"]')) {
    return host;
  }
  return host.querySelector('.app-details-container[data-app-component="helpdesk-risk-radar"]');
};

export function initHelpdeskRiskRadar(root = document) {
  const container = resolveContainer(root);
  if (!container) {
    return EMPTY_API;
  }

  const listenerController = new AbortController();
  const requestController = new AbortController();
  const on = (target, type, handler, options = {}) => {
    if (!target || typeof target.addEventListener !== 'function') {
      return;
    }
    target.addEventListener(type, handler, { ...options, signal: listenerController.signal });
  };

  const dataUrl = container.dataset.riskRadarUrl;
  const debitorBaseUrl = container.dataset.debitorBaseUrl || '';
  const d = (key, fallback) => container.dataset[key] || fallback;

  const elLoading = document.getElementById('radar-loading');
  const elError = document.getElementById('radar-error');
  const elEmpty = document.getElementById('radar-empty');
  const elTruncated = document.getElementById('radar-truncated');
  const elContent = document.getElementById('radar-content');
  const elCards = document.getElementById('radar-cards');
  const elRefresh = container.querySelector('button[name="radar-refresh"]');
  const periodSelector = document.getElementById('radar-period-selector');
  const dialog = document.getElementById('radar-detail-dialog');
  const dialogTitle = document.getElementById('radar-detail-title');
  const dialogBody = document.getElementById('radar-detail-body');
  const dialogClose = dialog ? dialog.querySelector('.close') : null;

  let currentPeriod = 90;

  const showState = (state) => {
    if (elLoading) elLoading.hidden = state !== 'loading';
    if (elError) elError.hidden = state !== 'error';
    if (elEmpty) elEmpty.hidden = state !== 'empty';
    if (elContent) elContent.hidden = state !== 'success';
  };

  const h = (tag, cls, text) => {
    const element = document.createElement(tag);
    if (cls) element.className = cls;
    if (text !== undefined) element.textContent = text;
    return element;
  };

  const levelClass = (level) => `helpdesk-risk-level-${level}`;

  const formatAge = (hours) => {
    if (hours < 24) return `${hours}h`;
    return `${Math.floor(hours / 24)}d`;
  };

  const dimLabel = (id) => {
    const map = {
      'open_pressure': d('labelOpenPressure', 'Open pressure'),
      'trend': d('labelTrend', 'Trend'),
      'sla_overdue': d('labelSla', 'SLA overdue'),
      'inactivity': d('labelInactivity', 'Inactivity'),
    };
    return map[id] || id;
  };

  const openDetail = (customer) => {
    if (!dialog || !dialogTitle || !dialogBody) {
      return;
    }

    dialogTitle.textContent = `${customer.customer_name || customer.customer_no} — ${customer.risk_score}/100`;
    dialogBody.replaceChildren();

    const dims = customer.dimensions || [];
    const dimTable = h('table', 'helpdesk-risk-detail-tickets');
    const dimHead = h('thead');
    const dimHeadRow = h('tr');
    dimHeadRow.appendChild(h('th', '', 'Dimension'));
    dimHeadRow.appendChild(h('th', '', d('labelScore', 'Score')));
    dimHead.appendChild(dimHeadRow);
    dimTable.appendChild(dimHead);
    const dimBody = h('tbody');
    for (const dim of dims) {
      const tr = h('tr');
      tr.appendChild(h('td', '', dimLabel(dim.id)));
      const points = Math.round(dim.weighted_points || 0);
      tr.appendChild(h('td', '', `${points} / ${dim.weight}`));
      dimBody.appendChild(tr);
    }
    const totalTr = h('tr');
    const totalLabel = h('td', '');
    totalLabel.style.fontWeight = '700';
    totalLabel.textContent = 'Total';
    totalTr.appendChild(totalLabel);
    const totalVal = h('td', '');
    totalVal.style.fontWeight = '700';
    totalVal.textContent = `${customer.risk_score} / 100`;
    totalTr.appendChild(totalVal);
    dimBody.appendChild(totalTr);
    dimTable.appendChild(dimBody);
    dialogBody.appendChild(dimTable);

    const tickets = customer.open_tickets || [];
    if (tickets.length > 0) {
      dialogBody.appendChild(h('h3', 'helpdesk-support-section-title', `${d('labelTickets', 'Tickets')} (${tickets.length})`));
      const table = h('table', 'helpdesk-risk-detail-tickets');
      const thead = h('thead');
      const headRow = h('tr');
      headRow.appendChild(h('th', '', d('labelTicket', 'Ticket')));
      headRow.appendChild(h('th', '', d('labelSla', 'SLA')));
      headRow.appendChild(h('th', '', d('labelStatus', 'Status')));
      headRow.appendChild(h('th', '', d('labelAge', 'Age')));
      thead.appendChild(headRow);
      table.appendChild(thead);
      const tbody = h('tbody');
      for (const ticket of tickets) {
        const tr = h('tr', ticket.age_hours > 48 ? 'helpdesk-risk-detail-ticket-critical' : '');
        tr.appendChild(h('td', '', ticket.no));
        tr.appendChild(h('td', '', ticket.escalation_code || '—'));
        tr.appendChild(h('td', '', ticket.state));
        tr.appendChild(h('td', '', formatAge(ticket.age_hours)));
        tbody.appendChild(tr);
      }
      table.appendChild(tbody);
      dialogBody.appendChild(table);
    }

    if (debitorBaseUrl && customer.customer_no) {
      const link = h('a', 'helpdesk-risk-detail-link', customer.customer_name || customer.customer_no);
      link.href = debitorBaseUrl + encodeURIComponent(customer.customer_no);
      link.target = '_blank';
      link.rel = 'noopener noreferrer';
      dialogBody.appendChild(link);
    }

    dialog.showModal();
  };

  const buildCard = (customer) => {
    const card = h('article', `helpdesk-risk-card ${levelClass(customer.risk_level)}`);
    card.setAttribute('aria-label', customer.customer_name || customer.customer_no);

    const header = h('div', 'helpdesk-risk-card-header');
    const info = h('div', 'helpdesk-risk-card-info');
    info.appendChild(h('span', 'helpdesk-risk-card-name', customer.customer_name || customer.customer_no));
    const levelLabels = {
      high: d('labelHigh', 'High risk'),
      medium: d('labelMedium', 'Medium risk'),
      low: d('labelLow', 'Low risk'),
    };
    info.appendChild(h('span', 'helpdesk-risk-card-level', levelLabels[customer.risk_level] || ''));
    header.appendChild(info);
    const scoreEl = h('span', `helpdesk-risk-card-score ${levelClass(customer.risk_level)}`, String(customer.risk_score));
    header.appendChild(scoreEl);
    card.appendChild(header);

    const kpis = customer.kpis || {};
    const parts = [];
    if (kpis.open > 0) parts.push(`${kpis.open} ${d('labelOpen', 'open')}`);
    if (kpis.critical > 0) parts.push(`${kpis.critical} ${d('labelCritical', 'critical')}`);
    if (kpis.sla_overdue > 0) parts.push(`${kpis.sla_overdue} SLA`);
    if (kpis.net_flow > 0) parts.push(`↑${kpis.net_flow}`);
    else if (kpis.net_flow < 0) parts.push(`↓${Math.abs(kpis.net_flow)}`);

    if (parts.length > 0) {
      card.appendChild(h('p', 'helpdesk-risk-card-facts', parts.join(' · ')));
    }

    card.tabIndex = 0;
    on(card, 'click', () => openDetail(customer));
    on(card, 'keydown', (event) => {
      if (event.key === 'Enter' || event.key === ' ') {
        event.preventDefault();
        openDetail(customer);
      }
    });

    return card;
  };

  on(dialogClose, 'click', () => {
    dialog?.close();
  });
  on(dialog, 'click', (event) => {
    if (event.target === dialog) {
      dialog.close();
    }
  });

  const renderCards = (customers) => {
    if (!elCards) {
      return;
    }
    elCards.replaceChildren();
    for (const customer of customers) {
      elCards.appendChild(buildCard(customer));
    }
  };

  const fetchData = async (refresh = false) => {
    showState('loading');
    if (elTruncated) elTruncated.hidden = true;

    const params = new URLSearchParams({ periodDays: String(currentPeriod) });
    if (refresh) params.set('refresh', '1');

    try {
      const json = await getJson(`${dataUrl}?${params.toString()}`, {
        signal: requestController.signal,
      });
      if (!json.ok) { showState('error'); return; }
      if (!json.customers || json.customers.length === 0) { showState('empty'); return; }

      renderCards(json.customers);
      showState('success');

      if (json.meta && json.meta.truncated && elTruncated) {
        elTruncated.hidden = false;
      }
    } catch (error) {
      if (error instanceof Error && error.name === 'AbortError') {
        return;
      }
      showState('error');
    }
  };

  on(periodSelector, 'change', (event) => {
    const radio = event.target.closest('input[name="radar-period"]');
    if (!radio) return;
    const period = parseInt(radio.value, 10);
    if (!period || period === currentPeriod) return;
    currentPeriod = period;
    void fetchData();
  });

  on(elRefresh, 'click', () => {
    void fetchData(true);
  });

  void fetchData();

  return {
    destroy: () => {
      listenerController.abort();
      requestController.abort();
      if (dialog?.open) {
        dialog.close();
      }
    },
  };
}
