namespace DragonISO.App.Services;

/// <summary>
/// The HTML / CSS / JS for the embedded control panel served at
/// <c>GET /ui</c>. Single self-contained string â€” no external CDN deps, no
/// build step, no React. Phone-friendly remote that connects via WebSocket
/// to <c>/ws</c> and posts to the existing REST endpoints.
///
/// v2 additions:
///   - Live preview tiles per participant via GET /participants/{id}/thumbnail.jpg
///     (engine encodes the latest ProcessedFrame as a 192-wide JPEG; refreshed
///     ~1Hz alongside the WebSocket state push).
///   - Topology toggle card â€” shows whether raw Teams NDI sources are
///     hidden from the LAN, with Apply / Restore buttons that hit the
///     /topology/apply + /topology/restore REST endpoints. Operator still
///     has to restart Teams afterward, surfaced in a banner on apply.
/// </summary>
internal static class ControlPanelHtml
{
    private const string Html = @"<!doctype html>
<html lang='en'>
<head>
<meta charset='utf-8'>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<title>Dragon-ISO Control</title>
<style>
  :root {
    --bg: #0a0a0a;
    --surface: #141414;
    --surface-elev: #1c1c1c;
    --border: #262626;
    --border-strong: #3a3b40;
    --text: #f5f5f5;
    --text-2: #a3a3a3;
    --text-3: #6b6b6b;
    --cyan: #97edf0;
    --cyan-mute: #1b3537;
    --cyan-text: #97edf0;
    --coral: #fb819c;
    --coral-bg: #3a1922;
    --green: #4ade80;
    --amber: #fbbf24;
  }
  * { box-sizing: border-box; }
  html, body { margin: 0; background: var(--bg); color: var(--text);
    font-family: 'Inter', 'Segoe UI', system-ui, sans-serif;
    -webkit-font-smoothing: antialiased;
  }
  body { padding: 16px; max-width: 920px; margin: 0 auto; }
  h1 {
    font-size: 11px; letter-spacing: 0.12em; font-weight: 600;
    text-transform: uppercase; color: var(--text-3); margin: 0 0 14px;
  }
  .card {
    background: var(--surface); border: 1px solid var(--border);
    border-radius: 12px; padding: 14px; margin-bottom: 12px;
  }
  .row { display: flex; align-items: center; gap: 10px; }
  .row + .row { margin-top: 10px; }
  .grow { flex: 1; min-width: 0; }
  button {
    background: var(--surface-elev); color: var(--text); border: 1px solid var(--border);
    border-radius: 8px; padding: 10px 14px; cursor: pointer;
    font: inherit; font-size: 13px;
    transition: background 80ms ease, border-color 80ms ease;
  }
  button:hover { background: #242424; border-color: var(--border-strong); }
  button.primary { background: var(--cyan); color: #042830; border-color: var(--cyan); font-weight: 500; }
  button.primary:hover { background: #b5f2f4; }
  button.danger { background: transparent; color: var(--coral); border-color: var(--coral); }
  button.danger:hover { background: var(--coral-bg); }
  button.live { background: var(--cyan-mute); color: var(--cyan-text); border-color: var(--cyan); }
  .dot { width: 8px; height: 8px; border-radius: 50%; display: inline-block; flex-shrink: 0; }
  .dot.cyan { background: var(--cyan); }
  .dot.coral { background: var(--coral); }
  .dot.green { background: var(--green); }
  .dot.amber { background: var(--amber); }
  .dot.gray { background: var(--text-3); }
  .name { font-weight: 500; font-size: 14px; }
  .sub { color: var(--text-3); font-size: 11px;
    font-family: 'JetBrains Mono', 'Cascadia Mono', monospace;
    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
  .label-caps { font-size: 10px; font-weight: 600; letter-spacing: 0.08em;
    color: var(--text-3); text-transform: uppercase; }
  .status {
    display: flex; gap: 16px; align-items: center; flex-wrap: wrap;
    font-family: 'JetBrains Mono', 'Cascadia Mono', monospace;
    font-size: 11px; color: var(--text-3);
  }
  .status .ok { color: var(--green); }
  .status .err { color: var(--coral); }
  .empty { color: var(--text-3); font-size: 12px; padding: 18px; text-align: center; }
  .global-actions { display: grid; grid-template-columns: repeat(2, 1fr); gap: 8px; }
  @media (min-width: 480px) { .global-actions { grid-template-columns: repeat(4, 1fr); } }
  .participant-wrap { border-radius: 10px; }
  .participant-wrap + .participant-wrap { margin-top: 6px; }
  .participant-wrap.override { box-shadow: inset 3px 0 0 var(--cyan); }
  .participant-row { display: flex; align-items: center; gap: 14px; padding: 10px; border-radius: 10px; }
  .participant-row.speaking { background: var(--cyan-mute); }
  .preview {
    width: 112px; height: 63px; flex-shrink: 0; border-radius: 6px;
    background: var(--surface-elev); border: 1px solid var(--border);
    object-fit: cover; display: block;
  }
  .preview.empty { display: flex; align-items: center; justify-content: center;
    color: var(--text-3); font-family: 'JetBrains Mono', monospace; font-size: 18px; }
  .ovr-pill { display: inline-block; margin-left: 6px; padding: 1px 6px;
    border-radius: 999px; background: var(--cyan-mute); color: var(--cyan-text);
    font-size: 9px; font-weight: 600; letter-spacing: 0.08em; text-transform: uppercase;
    vertical-align: middle; }
  .cfg-caption { font-family: 'JetBrains Mono', 'Cascadia Mono', monospace;
    font-size: 10px; color: var(--text-3); margin-right: 6px;
    overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
    max-width: 140px; }
  .gear-btn { padding: 6px 10px; font-size: 12px; }
  .row-right { display: flex; align-items: center; gap: 8px; flex-shrink: 0; }
  .override-panel { display: none; padding: 12px 10px 14px;
    border-top: 1px solid var(--border); background: var(--surface-elev);
    border-bottom-left-radius: 10px; border-bottom-right-radius: 10px; }
  .override-panel.open { display: block; }
  .override-grid { display: grid; grid-template-columns: 1fr; gap: 10px; }
  @media (min-width: 560px) {
    .override-grid { grid-template-columns: repeat(4, 1fr); }
  }
  .override-field { display: flex; flex-direction: column; gap: 4px; min-width: 0; }
  .override-field label { font-size: 10px; font-weight: 600; letter-spacing: 0.08em;
    color: var(--text-3); text-transform: uppercase; }
  .override-field select {
    background: var(--surface); color: var(--text);
    border: 1px solid var(--border); border-radius: 8px;
    padding: 8px 10px; font: inherit; font-size: 12px;
    appearance: none; -webkit-appearance: none;
  }
  .override-field select:focus { outline: none; border-color: var(--cyan); }
  .override-actions { display: flex; gap: 8px; margin-top: 12px; flex-wrap: wrap; }
  .topology-card { display: flex; align-items: center; gap: 14px; flex-wrap: wrap; }
  .topology-state { display: flex; align-items: center; gap: 10px; flex: 1; min-width: 200px; }
  .topology-state strong { font-size: 13px; color: var(--text); }
  .topology-banner { margin: 10px 0 0; padding: 10px 12px; border-radius: 8px;
    background: var(--cyan-mute); color: var(--cyan-text); font-size: 12px; display: none; }
  .topology-banner.show { display: block; }
</style>
</head>
<body>
  <h1>Dragon-ISO control surface</h1>

  <div class='card'>
    <div class='status'>
      <span><span id='conn' class='dot gray'></span> <span id='conn-text'>connectingâ€¦</span></span>
      <span id='count' class='sub'></span>
    </div>
  </div>

  <div class='card topology-card'>
    <div class='topology-state'>
      <span id='topo-dot' class='dot gray'></span>
      <div>
        <div class='label-caps'>Network topology</div>
        <strong id='topo-label'>â€”</strong>
        <div id='topo-detail' class='sub' style='margin-top: 2px;'></div>
      </div>
    </div>
    <div style='display: flex; gap: 8px;'>
      <button id='topo-apply' onclick='applyTopology()'>Hide Teams sources</button>
      <button id='topo-restore' onclick='restoreTopology()'>Restore defaults</button>
    </div>
  </div>
  <div id='topo-banner' class='topology-banner'></div>

  <div class='card'>
    <div class='global-actions'>
      <button onclick='post(""/teams/mute"")'>Mute</button>
      <button onclick='post(""/teams/camera"")'>Camera</button>
      <button onclick='post(""/teams/share"")'>Share</button>
      <button onclick='post(""/teams/leave"")'>Leave</button>
      <button onclick='dropNote()'>Noteâ€¦</button>
      <button onclick='post(""/presets/refresh-discovery"")'>Refresh</button>
      <button class='danger' onclick='post(""/presets/stop-all"")'>Stop all ISOs</button>
    </div>
  </div>

  <div id='participants'></div>

<script>
const list = document.getElementById('participants');
const conn = document.getElementById('conn');
const connText = document.getElementById('conn-text');
const count = document.getElementById('count');
const topoDot = document.getElementById('topo-dot');
const topoLabel = document.getElementById('topo-label');
const topoDetail = document.getElementById('topo-detail');
const topoBanner = document.getElementById('topo-banner');

function setConn(state, text) {
  conn.className = 'dot ' + state;
  connText.textContent = text;
}

async function post(path, body) {
  try {
    const opts = { method: 'POST' };
    if (body) { opts.headers = { 'Content-Type': 'application/json' }; opts.body = JSON.stringify(body); }
    const r = await fetch(path, opts);
    return r.ok ? await r.json().catch(() => null) : null;
  } catch (e) { console.warn(e); return null; }
}

function dropNote() {
  const text = prompt('Note (will be timestamped in the day file):');
  if (text && text.trim()) post('/notes', { text: text.trim() });
}

async function fetchTopology() {
  try {
    const r = await fetch('/topology');
    if (!r.ok) return;
    const t = await r.json();
    paintTopology(t);
  } catch (e) { console.warn(e); }
}

function paintTopology(t) {
  if (!t) return;
  if (t.mode === 'hidden') {
    topoDot.className = 'dot cyan';
    topoLabel.textContent = 'Teams hidden from LAN';
  } else if (t.mode === 'public') {
    topoDot.className = 'dot amber';
    topoLabel.textContent = 'Public â€” raw Teams visible';
  } else {
    topoDot.className = 'dot gray';
    topoLabel.textContent = 'Unknown';
  }
  const sends = (t.senders || []).join(', ') || 'â€”';
  const recvs = (t.receivers || []).join(', ') || 'â€”';
  topoDetail.textContent = 'send: ' + sends + '  Â·  recv: ' + recvs;
}

async function applyTopology() {
  const r = await post('/topology/apply');
  if (r && r.ok) {
    topoBanner.textContent = 'âœ“ ' + (r.note || 'Applied. Restart Microsoft Teams for it to take effect.');
    topoBanner.classList.add('show');
    setTimeout(() => topoBanner.classList.remove('show'), 8000);
  }
  fetchTopology();
}

async function restoreTopology() {
  if (!confirm('Restore default NDI groups? Teams will broadcast on public again after you restart it.')) return;
  const r = await post('/topology/restore');
  if (r && r.ok) {
    topoBanner.textContent = 'âœ“ Defaults restored. Restart Microsoft Teams for it to take effect.';
    topoBanner.classList.add('show');
    setTimeout(() => topoBanner.classList.remove('show'), 8000);
  }
  fetchTopology();
}

// Enum options for the per-participant override selects. Values match the
// .NET enum names so they round-trip through POST /participants/{id}/override
// without translation.
const FRAMERATE_OPTS = [
  ['Fps23_976', '23.976'], ['Fps24', '24'], ['Fps25', '25'],
  ['Fps29_97', '29.97'], ['Fps30', '30'], ['Fps50', '50'],
  ['Fps59_94', '59.94'], ['Fps60', '60'],
];
const RESOLUTION_OPTS = [
  ['R720p', '720p'], ['R1080p', '1080p'], ['R4K', '4K'],
];
const ASPECT_OPTS = [
  ['Pillarbox', 'Pillarbox'], ['Letterbox', 'Letterbox'], ['Stretch', 'Stretch'],
];
const AUDIO_OPTS = [
  ['Auto', 'Auto'], ['Isolated', 'Isolated'], ['Mixed', 'Mixed'],
];

// Track which participant rows have the override panel expanded so it
// survives re-renders driven by the WS state push (otherwise every
// 1Hz snapshot would collapse it under the operator's finger).
const openPanels = new Set();

function shortFps(v) {
  for (const [k, label] of FRAMERATE_OPTS) if (k === v) return label;
  return v || 'â€”';
}
function shortRes(v) {
  for (const [k, label] of RESOLUTION_OPTS) if (k === v) return label;
  return v || 'â€”';
}
function shortAudio(v) {
  for (const [k, label] of AUDIO_OPTS) if (k === v) return label;
  return v || 'â€”';
}

function buildSelect(opts, current) {
  let html = '';
  for (const [val, label] of opts) {
    const sel = (val === current) ? ' selected' : '';
    html += ""<option value='"" + val + ""'"" + sel + "">"" + label + ""</option>"";
  }
  return html;
}

function render(participants) {
  if (!participants || participants.length === 0) {
    list.innerHTML = ""<div class='card empty'>No participants visible. Open Teams and join a meeting; sources will populate within seconds.</div>"";
    count.textContent = '';
    return;
  }
  const live = participants.filter(p => p.isEnabled).length;
  count.textContent = live + ' / ' + participants.length + ' live';
  list.innerHTML = '';
  const card = document.createElement('div');
  card.className = 'card';
  for (const p of participants) {
    const wrap = document.createElement('div');
    wrap.className = 'participant-wrap';
    const eff = p.effective || {};
    const isOverride = !!eff.isOverride;
    if (isOverride) wrap.classList.add('override');

    const row = document.createElement('div');
    row.className = 'participant-row';
    const stateColor = p.isEnabled ? 'cyan' : (p.isOnline ? 'gray' : 'coral');
    // Live preview tile â€” cache-bust with a 1s-bucket query param so the
    // browser refreshes the image without flickering on every WS message.
    const bust = Math.floor(Date.now() / 1000);
    const previewUrl = '/participants/' + p.id + '/thumbnail.jpg?t=' + bust;
    row.innerHTML =
      ""<span class='dot "" + stateColor + ""'></span>"" +
      ""<img class='preview' alt='' onerror=\""this.style.display='none'; this.nextElementSibling.style.display='flex';\"" >"" +
      ""<div class='preview empty' style='display:none;'>â€”</div>"" +
      ""<div class='grow'>"" +
        ""<div class='name'></div>"" +
        ""<div class='sub'></div>"" +
      ""</div>"" +
      ""<div class='row-right'>"" +
        ""<span class='cfg-caption'></span>"" +
        ""<button class='gear-btn' title='Output settings'>âš™</button>"" +
        ""<button class='enable-btn'></button>"" +
      ""</div>"";
    const img = row.querySelector('img.preview');
    img.src = previewUrl;
    row.querySelector('.name').textContent = p.displayName;
    const subEl = row.querySelector('.sub');
    subEl.textContent =
      (p.stateLabel || (p.isOnline ? 'online' : 'offline')) +
      (p.customName ? ' Â· ' + p.customName : '');
    if (isOverride) {
      const pill = document.createElement('span');
      pill.className = 'ovr-pill';
      pill.textContent = 'OVR';
      subEl.appendChild(pill);
    }
    row.querySelector('.cfg-caption').textContent =
      shortFps(eff.framerate) + ' Â· ' + shortRes(eff.resolution) + ' Â· ' + shortAudio(eff.audio);
    const enableBtn = row.querySelector('.enable-btn');
    enableBtn.className = 'enable-btn ' + (p.isEnabled ? 'live' : '');
    enableBtn.textContent = p.isEnabled ? 'â— LIVE' : 'Enable';
    enableBtn.onclick = () => post('/participants/iso', {
      displayName: p.displayName,
      enabled: !p.isEnabled,
    });

    const panel = document.createElement('div');
    panel.className = 'override-panel' + (openPanels.has(p.id) ? ' open' : '');
    panel.innerHTML =
      ""<div class='override-grid'>"" +
        ""<div class='override-field'><label>Framerate</label>"" +
          ""<select data-k='framerate'>"" + buildSelect(FRAMERATE_OPTS, eff.framerate) + ""</select></div>"" +
        ""<div class='override-field'><label>Resolution</label>"" +
          ""<select data-k='resolution'>"" + buildSelect(RESOLUTION_OPTS, eff.resolution) + ""</select></div>"" +
        ""<div class='override-field'><label>Aspect</label>"" +
          ""<select data-k='aspect'>"" + buildSelect(ASPECT_OPTS, eff.aspect) + ""</select></div>"" +
        ""<div class='override-field'><label>Audio</label>"" +
          ""<select data-k='audio'>"" + buildSelect(AUDIO_OPTS, eff.audio) + ""</select></div>"" +
      ""</div>"" +
      ""<div class='override-actions'>"" +
        ""<button class='primary apply-btn'>Apply</button>"" +
        ""<button class='danger clear-btn'>Clear (use global)</button>"" +
      ""</div>"";

    const gearBtn = row.querySelector('.gear-btn');
    gearBtn.onclick = () => {
      if (openPanels.has(p.id)) {
        openPanels.delete(p.id);
        panel.classList.remove('open');
      } else {
        openPanels.add(p.id);
        panel.classList.add('open');
      }
    };

    panel.querySelector('.apply-btn').onclick = async () => {
      const body = {};
      panel.querySelectorAll('select[data-k]').forEach(s => { body[s.dataset.k] = s.value; });
      await fetch('/participants/' + p.id + '/override', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
      }).catch(e => console.warn(e));
      openPanels.delete(p.id);
      panel.classList.remove('open');
    };

    panel.querySelector('.clear-btn').onclick = async () => {
      await fetch('/participants/' + p.id + '/override', { method: 'DELETE' })
        .catch(e => console.warn(e));
      openPanels.delete(p.id);
      panel.classList.remove('open');
    };

    wrap.appendChild(row);
    wrap.appendChild(panel);
    card.appendChild(wrap);
  }
  list.appendChild(card);
}

function connect() {
  setConn('gray', 'connectingâ€¦');
  const ws = new WebSocket(
    (location.protocol === 'https:' ? 'wss://' : 'ws://') + location.host + '/ws');
  ws.onopen = () => { setConn('green', 'live'); fetchTopology(); };
  ws.onmessage = (ev) => {
    try {
      const m = JSON.parse(ev.data);
      if (m.type === 'participants') render(m.participants);
    } catch (e) { console.warn(e); }
  };
  ws.onclose = () => {
    setConn('coral', 'disconnected â€” retry in 3s');
    setTimeout(connect, 3000);
  };
  ws.onerror = () => setConn('coral', 'error');
}

connect();
// Re-poll topology every 30s in case the operator changes the machine NDI
// config externally (NDI Access Manager, manual edit). Cheap â€” one HTTP GET.
setInterval(fetchTopology, 30000);
</script>
</body>
</html>
";

    public static string Get() => Html;
}
