// Static image widget dialog: upload, display-mode setting, and the
// rendered preview. Not a page-load script -- frame_layout.js fetches
// this widget's dialog HTML fragment, injects it into the shared
// <dialog>, points window.FRAME_API at this specific widget
// (/api/frames/{id}/widgets/{widget_id}), then calls initStaticDialog().

function loadStaticPreview() {
  document.getElementById('static-preview').src = `${window.FRAME_API}/preview/static?_=${Date.now()}`;
}

function initStaticDialog() {
  document.getElementById('static-upload').addEventListener('click', async () => {
    const input = document.getElementById('static-file');
    if (!input.files.length) {
      showStatus(false, 'Pick a file first.');
      return;
    }
    const form = new FormData();
    form.append('file', input.files[0]);
    try {
      const resp = await fetch(`${window.FRAME_API}/static-upload`, { method: 'POST', body: form });
      if (!resp.ok) throw new Error(await apiError(resp));
      const result = await resp.json();
      const currentFileEl = document.getElementById('static-current-file');
      currentFileEl.textContent = 'Currently showing: ';
      const nameEl = document.createElement('strong');
      nameEl.textContent = result.filename;
      currentFileEl.appendChild(nameEl);
      input.value = '';
      showStatus(true, 'Uploaded.');
      loadStaticPreview();
    } catch (e) {
      showStatus(false, e.message);
    }
  });

  document.getElementById('static-config-form').addEventListener('submit', async (e) => {
    e.preventDefault();
    const body = new URLSearchParams({
      display_mode: document.getElementById('display_mode').value,
    });
    try {
      const resp = await fetch(`${window.FRAME_API}/config`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body,
      });
      if (!resp.ok) throw new Error(await apiError(resp));
      showStatus(true, 'Saved.');
      loadStaticPreview();
    } catch (e) {
      showStatus(false, e.message);
    }
  });

  document.getElementById('static-preview-refresh').addEventListener('click', loadStaticPreview);
  loadStaticPreview();
}

function closeStaticDialog() {
  // Nothing to tear down -- no poll interval, unlike the photos dialog.
}
