'use strict';

// Kamera-Konfiguration: liest GET /api/config, baut pro Kamera eine ComboBox
// (Aus + erlaubte Auflösungen), POSTet die Auswahl zurück. Server wendet die
// Auflösung sofort an (Hot-Reload) und persistiert in cameras.json.

const OFF = '__off__';
let liveSizes = [];

// UI bietet nur diese zwei Modi an (mjpeg-Re-Encode bleibt API/Env vorbehalten).
const ENCODE_OPTIONS = [
  { value: 'copybsf', label: 'MJPEG' },
  { value: 'h264', label: 'H.264 (GPU)' },
];

async function load() {
  const r = await fetch('/api/config');
  if (!r.ok) throw new Error(`HTTP ${r.status}`);
  const cfg = await r.json();
  liveSizes = cfg.liveSizes || [];
  render(cfg.cameras || []);
  setStatus('bereit', '');
  document.getElementById('saveBtn').disabled = false;
}

function render(cameras) {
  const tbody = document.getElementById('rows');
  tbody.innerHTML = '';
  for (const cam of cameras) {
    const tr = document.createElement('tr');

    const tdId = document.createElement('td');
    tdId.textContent = cam.id;

    const tdName = document.createElement('td');
    tdName.textContent = cam.name || cam.id;
    if (cam.id === 'cam2') {
      const w = document.createElement('span');
      w.className = 'warn-badge';
      w.textContent = ' ⚠';
      w.title = 'C920: bei kleinen 4:3-Auflösungen überdurchschnittlich Bandbreite';
      tdName.appendChild(w);
    }

    const tdSel = document.createElement('td');
    const sel = document.createElement('select');
    sel.dataset.id = cam.id;
    const isOff = cam.stream === false;
    sel.add(new Option('Aus', OFF, false, isOff));
    for (const s of liveSizes) {
      sel.add(new Option(s.replace('x', '×'), s, false, !isOff && cam.liveSize === s));
    }
    tdSel.appendChild(sel);

    const tdEnc = document.createElement('td');
    const encSel = document.createElement('select');
    encSel.dataset.encId = cam.id;
    // copybsf und (unsichtbar) mjpeg gelten beide als „MJPEG" in der UI.
    const curEnc = cam.encode === 'h264' ? 'h264' : 'copybsf';
    for (const o of ENCODE_OPTIONS) {
      encSel.add(new Option(o.label, o.value, false, curEnc === o.value));
    }
    tdEnc.appendChild(encSel);

    const tdCur = document.createElement('td');
    tdCur.className = 'cur';
    tdCur.textContent = isOff ? 'aus' : `${cam.liveSize || '?'} · ${curEnc === 'h264' ? 'H.264' : 'MJPEG'}`;

    tr.append(tdId, tdName, tdSel, tdEnc, tdCur);
    tbody.appendChild(tr);
  }
}

function collect() {
  const encOf = (id) => {
    const e = document.querySelector(`select[data-enc-id="${id}"]`);
    return e ? e.value : undefined;
  };
  return Array.from(document.querySelectorAll('select[data-id]')).map((sel) => {
    const id = sel.dataset.id;
    const encode = encOf(id);
    if (sel.value === OFF) return { id, stream: false, ...(encode ? { encode } : {}) };
    return { id, stream: true, liveSize: sel.value, ...(encode ? { encode } : {}) };
  });
}

async function save() {
  const btn = document.getElementById('saveBtn');
  btn.disabled = true;
  setStatus('speichert…', '');
  try {
    const r = await fetch('/api/config', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ cameras: collect() }),
    });
    const body = await r.json().catch(() => ({}));
    if (!r.ok) throw new Error(body.error || `HTTP ${r.status}`);
    render(body.cameras || []);
    setStatus('gespeichert & angewendet', 'ok');
  } catch (e) {
    setStatus('Fehler: ' + e.message, 'err');
  } finally {
    btn.disabled = false;
  }
}

function setStatus(text, cls) {
  const el = document.getElementById('status');
  el.textContent = text;
  el.className = cls || '';
}

document.getElementById('saveBtn').addEventListener('click', save);
load().catch((e) => setStatus('Laden fehlgeschlagen: ' + e.message, 'err'));
