(function () {
  'use strict';

  const form = document.getElementById('workbenchForm');
  const clearButton = document.getElementById('workbenchClear');
  const status = document.getElementById('workbenchStatus');
  const storageKey = 'dbn.caseWorkbench.v1';
  let statusTimer = 0;

  if (!form) {
    return;
  }

  function setStatus(message) {
    if (!status) {
      return;
    }
    status.textContent = message;
    window.clearTimeout(statusTimer);
    statusTimer = window.setTimeout(function () {
      status.textContent = '';
    }, 2200);
  }

  function collect() {
    const data = {};
    const fields = form.querySelectorAll('input, select, textarea');
    fields.forEach(function (field) {
      if (!field.name) {
        return;
      }
      if (field.type === 'checkbox') {
        if (!Array.isArray(data[field.name])) {
          data[field.name] = [];
        }
        if (field.checked) {
          data[field.name].push(field.value);
        }
        return;
      }
      data[field.name] = field.value;
    });
    data.saved_at = new Date().toISOString();
    return data;
  }

  function restore(data) {
    if (!data || typeof data !== 'object') {
      return;
    }
    const fields = form.querySelectorAll('input, select, textarea');
    fields.forEach(function (field) {
      if (!field.name) {
        return;
      }
      if (field.type === 'checkbox') {
        const values = Array.isArray(data[field.name]) ? data[field.name] : [];
        field.checked = values.indexOf(field.value) !== -1;
        return;
      }
      if (Object.prototype.hasOwnProperty.call(data, field.name)) {
        field.value = data[field.name] || '';
      }
    });
  }

  function save() {
    try {
      window.sessionStorage.setItem(storageKey, JSON.stringify(collect()));
      setStatus('Saved in this browser session.');
    } catch (error) {
      setStatus('Could not save this session locally.');
    }
  }

  try {
    const raw = window.sessionStorage.getItem(storageKey);
    if (raw) {
      restore(JSON.parse(raw));
      setStatus('Restored local workbench notes.');
    }
  } catch (error) {
    window.sessionStorage.removeItem(storageKey);
  }

  form.addEventListener('input', save);
  form.addEventListener('change', save);

  if (clearButton) {
    clearButton.addEventListener('click', function () {
      window.sessionStorage.removeItem(storageKey);
      form.reset();
      setStatus('Workbench session cleared.');
    });
  }
}());
