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

export function initSidebarToggle(options = {}) {
  const {
    buttonSelector = '[data-sidebar-toggle]',
    asideSelector = '#app-sidebar',
    containerSelector = '.app-container',
    storageKey = 'app-sidebar-collapsed',
    hiddenStorageKey = 'app-sidebar-hidden'
  } = options;

  const aside = requireEl(asideSelector, { module: 'sidebar-toggle' });
  if (!aside) {return null;}

  const buttons = Array.from(document.querySelectorAll(buttonSelector));
  if (!buttons.length) {
    warnOnce('UI_EL_MISSING', `Missing sidebar toggle buttons: ${buttonSelector}`, { module: 'sidebar-toggle' });
  }
  const container = document.querySelector(containerSelector);
  const root = document.documentElement;

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

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

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

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

  const applyState = (collapsed, { persist = false } = {}) => {
    aside.classList.toggle('is-collapsed', collapsed);
    if (container) {
      container.classList.toggle('is-sidebar-collapsed', collapsed);
    }
    if (root) {
      root.classList.toggle('sidebar-collapsed', collapsed);
    }
    buttons.forEach((button) => {
      if (!button.getAttribute('aria-controls')) {
        button.setAttribute('aria-controls', aside.id || 'app-sidebar');
      }
      button.setAttribute('aria-expanded', collapsed ? 'false' : 'true');
    });
    if (persist) {
      writeStored(collapsed);
    }
  };

  const applyHidden = (hidden, { persist = false } = {}) => {
    aside.classList.toggle('is-hidden', hidden);
    if (container) {
      container.classList.toggle('is-sidebar-hidden', hidden);
    }
    if (root) {
      root.classList.toggle('sidebar-hidden', hidden);
    }
    buttons.forEach((button) => {
      if (!button.getAttribute('aria-controls')) {
        button.setAttribute('aria-controls', aside.id || 'app-sidebar');
      }
      button.setAttribute('aria-expanded', hidden ? 'false' : button.getAttribute('aria-expanded') || 'true');
    });
    if (persist) {
      writeHiddenStored(hidden);
    }
  };

  const isCollapsed = () => aside.classList.contains('is-collapsed');
  const isHidden = () => aside.classList.contains('is-hidden');

  const getInitialState = () => {
    const stored = readStored();
    if (stored === '1' || stored === '0') {
      return stored === '1';
    }
    return root?.classList.contains('sidebar-collapsed') ?? false;
  };

  const controller = {
    isCollapsed,
    isHidden,
    open: ({ persist = true } = {}) => applyState(false, { persist }),
    close: ({ persist = true } = {}) => applyState(true, { persist }),
    toggle: ({ persist = true } = {}) => applyState(!isCollapsed(), { persist }),
    apply: (collapsed, { persist = false } = {}) => applyState(!!collapsed, { persist }),
    show: ({ persist = true } = {}) => applyHidden(false, { persist }),
    hide: ({ persist = true } = {}) => applyHidden(true, { persist }),
    toggleVisibility: ({ persist = true } = {}) => applyHidden(!isHidden(), { persist }),
    applyVisibility: (hidden, { persist = false } = {}) => applyHidden(!!hidden, { persist })
  };

  applyState(getInitialState(), { persist: false });
  const hiddenStored = readHiddenStored();
  if (hiddenStored === '1' || hiddenStored === '0') {
    applyHidden(hiddenStored === '1', { persist: false });
  }

  buttons.forEach((button) => {
    button.addEventListener('click', (event) => {
      event.preventDefault();
      const action = (button.dataset.sidebarAction || '').toLowerCase();
      if (action === 'visibility') {
        controller.toggleVisibility({ persist: true });
        return;
      }
      controller.toggle({ persist: true });
    });
  });

  document.addEventListener('app:sidebar', (event) => {
    const detail = event.detail || {};
    const action = detail.action;
    const persist = detail.persist ?? false;
    if (action === 'open') {controller.open({ persist });}
    if (action === 'close') {controller.close({ persist });}
    if (action === 'toggle') {controller.toggle({ persist });}
    if (action === 'show') {controller.show({ persist });}
    if (action === 'hide') {controller.hide({ persist });}
    if (action === 'toggle-visibility') {controller.toggleVisibility({ persist });}
  });

  window.AppSidebar = controller;
  return controller;
}

const isEditableTarget = (target) => {
  if (!target) {return false;}
  if (target.isContentEditable) {return true;}
  const tag = target.tagName;
  return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT';
};

document.addEventListener('keydown', (event) => {
  if (!(event.metaKey || event.ctrlKey)) {return;}
  if (event.altKey) {return;}
  if (event.key.toLowerCase() !== 'b') {return;}
  if (isEditableTarget(event.target)) {return;}
  if (!window.AppSidebar || typeof window.AppSidebar.toggleVisibility !== 'function') {return;}
  event.preventDefault();
  window.AppSidebar.toggleVisibility({ persist: true });
});

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