/**
 * @module tgam-patterns/sub-pencil
 * JS logic specific to opening and closing the Pencil Ad
 */
import throttle from "lodash/throttle";
import ee from "./event-emitter";

const eventspace = "sub-pencil-ad";

// CSS selectors for various internal components
const select = {
  root: ".js-sub-pencil",
  control: ".js-sub-pencil-control",
  open: "o-sub-pencil--open",
  closed: "o-sub-pencil--closed"
};

// DOM elements of various internal components
const dom = {};

// track auto-open panel state
let allowExpand = true;

/**
 * @method init
 * @description Init method, adds event listeners
 * @param {String} root - of parent element
 * @param {Boolean} expanded - true for panel to become open; false to become closed.
 */
export default function init(root = select.root, expanded = false) {
  select.root = root;
  dom.root = document.querySelector(select.root);
  if (!dom.root) {
    return;
  }

  dom.control = document.querySelector(select.control);
  dom.control.addEventListener("click", onToggleClicked);

  // set the initial expand or collapsed state
  setPanelState(expanded);

  // throttled event handlers
  window.addEventListener("scroll", throttle(onWindowScroll, 50));

  // reveal the element, after it's initialized
  dom.root.removeAttribute("hidden");
}

/**
 * @method isPanelOpen
 * @description Determine if panel's state is expanded or collapsed
 * @returns {Boolean} true if panel is expanded; false if panel is collapsed.
 */
function isPanelOpen() {
  return dom.root.classList.contains(select.open);
}

/**
 * @method setPanelState
 * @description Update element classes and properties to set expanded/collapsed state.
 * @param {Boolean} expanded - true for panel to become open; false to become closed.
 */
function setPanelState(expanded) {
  dom.root.classList[expanded ? "add" : "remove"](select.open);
  dom.root.classList[expanded ? "remove" : "add"](select.closed);
  dom.control.setAttribute("aria-expanded", expanded);
}

/**
 * @method onToggleClicked
 * @description Callback for clicking on the left or right control button toggles
 */
function onToggleClicked() {
  const isOpen = !isPanelOpen();
  setPanelState(isOpen);
  // only broadcast event for user initiated toggling
  ee.emit(`${eventspace}:${isOpen ? "expand" : "collapse"}`);
}

/**
 * @method onWindowScroll
 * @description Callback for throttled window scroll event.
 */
function onWindowScroll() {
  const isOpen = isPanelOpen();
  const scrollTop = (document.body.scrollTop || document.documentElement.scrollTop) === 0;
  // we want to auto-open the panel only when the user scrolls away from the top of the page,
  // but not re-auto-open the panel again, after the user has manually closed the panel once.
  if (!scrollTop && !isOpen && allowExpand) {
    allowExpand = false;
    setPanelState(true);
  } else if (scrollTop && isOpen) {
    allowExpand = true;
    setPanelState(false);
  }
}
