/**
 * Toggles visibility of the detail page aside column.
 */
import { warnOnce, resolveHost } from '../core/app-dom.js';
import { createUiStorage } from '../core/app-ui-storage.js';

export function initDetailsAsideToggle(root = document, options = {}) {
  const {
    buttonSelector = '#toggle-main-content-aside',
    asideSelector = '#app-details-aside-section',
    containerSelector = '.app-details-container',
    storageNamespace = 'app-ui',
    storageVersion = 'v1',
    storageScope = 'details-aside',
    storageKey = 'details-aside-collapsed'
  } = options;

  const host = resolveHost(root);
  const button = host.querySelector(buttonSelector);
  const aside = host.querySelector(asideSelector);
  if (!button || !aside) {
    return { destroy: () => {} };
  }

  const container = aside.closest(containerSelector) || host.querySelector(containerSelector);
  if (!container) {
    warnOnce('UI_EL_MISSING', `Missing details container: ${containerSelector}`, { module: 'details-aside' });
    return { destroy: () => {} };
  }
  if (button.dataset.detailsAsideToggleBound === '1') {
    return { destroy: () => {} };
  }
  button.dataset.detailsAsideToggleBound = '1';

  if (!button.getAttribute('aria-controls')) {
    button.setAttribute('aria-controls', aside.id || 'app-details-aside-section');
  }
  const storage = createUiStorage({
    namespace: storageNamespace,
    version: storageVersion,
    scope: storageScope,
  });
  const scopedStorageKey = storage.buildKey('state', storageKey);

  const readStored = () => {
    if (!scopedStorageKey) {
      return null;
    }
    return storage.getItem(scopedStorageKey);
  };

  const writeStored = (collapsed) => {
    if (!scopedStorageKey) {
      return;
    }
    storage.setItem(scopedStorageKey, collapsed ? '1' : '0');
  };

  const applyState = (collapsed, persist = false) => {
    container.classList.toggle('is-aside-collapsed', collapsed);
    aside.hidden = collapsed;
    button.setAttribute('aria-expanded', collapsed ? 'false' : 'true');
    if (persist) {
      writeStored(collapsed);
    }
  };

  const getInitialState = () => {
    const stored = readStored();
    if (stored === '1' || stored === '0') {
      return stored === '1';
    }
    return false;
  };

  applyState(getInitialState(), false);

  const onClick = (event) => {
    event.preventDefault();
    const collapsed = !container.classList.contains('is-aside-collapsed');
    applyState(collapsed, true);
  };
  button.addEventListener('click', onClick);

  const destroy = () => {
    button.removeEventListener('click', onClick);
    delete button.dataset.detailsAsideToggleBound;
  };

  return { destroy };
}
