// EN: API interaction logic for the 3D printing web application.
//     - Loads resources and triggers cost calculation via backend endpoints.
// DE: API-Interaktionslogik für die 3D-Druck-Webanwendung.
//     - Lädt Ressourcen und löst Kostenberechnung über Backend-Endpunkte aus.

import { translations } from './config.js';
import { showNotification, fillSelect, setResultsState, populateMaterialGrid } from './ui.js';

/**
 * DE: Lädt Initialressourcen (Drucker, Materialien, Qualitäten) vom Server.
 * EN: Load initial resources (printers, materials, qualities) from the server.
 * @param {object} dom - Das Objekt mit den Referenzen zu den DOM-Elementen des Moduls.
 */
export async function loadInitialResources(dom) {
  try {
    const response = await fetch('/api/resources');
    if (!response.ok) throw new Error('Server response was not ok.');
    const data = await response.json();

    fillSelect(dom.printerSelect, data.printers);
    // Anstatt ein Auswahlfeld zu füllen, befüllen wir unser neues Materialraster
    populateMaterialGrid(data.materials, dom);
    fillSelect(dom.qualitySelect, data.qualities);

  } catch (error) {
    console.error("Error loading resources:", error);
    const lang = dom.languageSelect.value || 'de';
    showNotification(translations[lang].dataLoadError, dom, 'error');
  }
}

/**
 * EN: Send form data to backend for cost calculation.
 * DE: Sendet Formulardaten an das Backend zur Kostenberechnung.
 * @param {object} dom - Das Objekt mit den Referenzen zu den DOM-Elementen des Moduls.
 */
export async function triggerCalculation(dom) {
  const printer = dom.printerSelect.value;
  // Wir holen das Material aus dem Datensatz-Attribut, das wir im Wurzelelement gespeichert haben
  const material = dom.root.dataset.selectedMaterial;
  const quality = dom.qualitySelect.value;
  const file = dom.fileInput.files[0];
  const lang = dom.languageSelect.value;

  if (!printer || !material || !quality || !file) {
    setResultsState('reset', dom);
    if (!material) {
      showNotification('Please select a material before calculating.', dom, 'error');
    }
    return;
  }

  setResultsState('loading', dom);

  const formData = new FormData();
  formData.append('printer', printer);
  formData.append('material', material);
  formData.append('quality', quality);
  formData.append('file', file);

  try {
    const response = await fetch('/api/calculate', {
      method: 'POST',
      body: formData,
    });

    const result = await response.json();

    if (!response.ok) {
      const errorMessage = result.error?.[lang] || result.error || translations[lang].unknownServerError;
      throw new Error(errorMessage);
    }

    setResultsState('success', dom, result);

  } catch (error) {
    console.error("Calculation failed:", error);
    showNotification(`${translations[lang].calculationError}: ${error.message}`, dom, 'error');
    setResultsState('reset', dom);
  }
}