import { optionalEl, warnOnce } from '../core/app-dom.js';

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

  const button = optionalEl(buttonSelector);
  const aside = optionalEl(asideSelector);
  if (!button || !aside) {return;}

  const container = aside.closest(containerSelector) || document.querySelector(containerSelector);
  if (!container) {
    warnOnce('UI_EL_MISSING', `Missing details container: ${containerSelector}`, { module: 'details-aside' });
    return;
  }

  if (!button.getAttribute('aria-controls')) {
    button.setAttribute('aria-controls', aside.id || 'app-details-aside-section');
  }

  const readStored = () => {
    try {
      return window.localStorage.getItem(storageKey);
    } catch (error) {
      return null;
    }
  };

  const writeStored = (collapsed) => {
    try {
      window.localStorage.setItem(storageKey, collapsed ? '1' : '0');
    } catch (error) {
      // ignore storage errors
    }
  };

  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);

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

if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', () => initDetailsAsideToggle());
} else {
  initDetailsAsideToggle();
}
