import { h, proxyCustomElement, HTMLElement, createEvent, Host } from '@stencil/core/internal/client';
import Taro from '@rtarojs/taro';
import { c as classnames } from './index2.js';
import { i as isVisible } from './index3.js';

const splitUrl = _url => {
  let url = _url || '';
  let pos;
  const res = {
    path: null,
    query: null,
    fragment: null
  };
  pos = url.indexOf('#');
  if (pos > -1) {
    res.fragment = url.substring(pos + 1);
    url = url.substring(0, pos);
  }
  pos = url.indexOf('?');
  if (pos > -1) {
    res.query = url.substring(pos + 1);
    url = url.substring(0, pos);
  }
  res.path = url;
  return res;
};

// export const removeLeadingSlash = (str = '') => str.replace(/^\.?\//, '')
// export const removeTrailingSearch = (str = '') => str.replace(/\?[\s\S]*$/, '')
const addLeadingSlash = (url = '') => (url.charAt(0) === '/' ? url : '/' + url);
const hasBasename = (path = '', prefix = '') => new RegExp('^' + prefix + '(\\/|\\?|#|$)', 'i').test(path) || path === prefix;
const stripBasename = (path = '', prefix = '') => hasBasename(path, prefix) ? path.substring(prefix.length) : path;
const stripSuffix = (path = '', suffix = '') => path.includes(suffix) ? path.substring(0, path.length - suffix.length) : path;
const getCurrentPage = (routerMode = 'hash', basename = '/') => {
    const pagePath = routerMode === 'hash'
        ? location.hash.slice(1).split('?')[0]
        : location.pathname;
    return addLeadingSlash(stripBasename(pagePath, basename));
};

function isAbsolute(pathname) {
  return pathname.charAt(0) === '/';
}

// About 1.5x faster than the two-arg version of Array#splice()
function spliceOne(list, index) {
  for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) {
    list[i] = list[k];
  }

  list.pop();
}

// This implementation is based heavily on node's url.parse
function resolvePathname(to, from) {
  if (from === undefined) from = '';

  var toParts = (to && to.split('/')) || [];
  var fromParts = (from && from.split('/')) || [];

  var isToAbs = to && isAbsolute(to);
  var isFromAbs = from && isAbsolute(from);
  var mustEndAbs = isToAbs || isFromAbs;

  if (to && isAbsolute(to)) {
    // to is absolute
    fromParts = toParts;
  } else if (toParts.length) {
    // to is relative, drop the filename
    fromParts.pop();
    fromParts = fromParts.concat(toParts);
  }

  if (!fromParts.length) return '/';

  var hasTrailingSlash;
  if (fromParts.length) {
    var last = fromParts[fromParts.length - 1];
    hasTrailingSlash = last === '.' || last === '..' || last === '';
  } else {
    hasTrailingSlash = false;
  }

  var up = 0;
  for (var i = fromParts.length; i >= 0; i--) {
    var part = fromParts[i];

    if (part === '.') {
      spliceOne(fromParts, i);
    } else if (part === '..') {
      spliceOne(fromParts, i);
      up++;
    } else if (up) {
      spliceOne(fromParts, i);
      up--;
    }
  }

  if (!mustEndAbs) for (; up--; up) fromParts.unshift('..');

  if (
    mustEndAbs &&
    fromParts[0] !== '' &&
    (!fromParts[0] || !isAbsolute(fromParts[0]))
  )
    fromParts.unshift('');

  var result = fromParts.join('/');

  if (hasTrailingSlash && result.substr(-1) !== '/') result += '/';

  return result;
}

const TabbarItem = ({ index, isSelected = false, textColor, iconPath, badgeText, showRedDot = false, pagePath, text, onSelect }) => {
  const className = classnames('weui-tabbar__item', {
    'weui-bar__item_on': isSelected
  });
  const badgeStyle = {
    position: 'absolute',
    top: '-2px',
    right: '-13px'
  };
  const dotStyle = {
    position: 'absolute',
    top: '0',
    right: '-6px'
  };
  function onClick() {
    const page = Taro.getCurrentPages().shift();
    if (typeof (page === null || page === void 0 ? void 0 : page.onTabItemTap) === 'function' && isVisible(this)) {
      page.onTabItemTap({ index, pagePath, text });
    }
    onSelect(index);
  }
  return (h("a", { key: index, href: 'javascript:;', class: className, onClick: onClick },
    h("span", { style: { display: 'inline-block', position: 'relative' } },
      h("img", { src: iconPath, alt: '', class: 'weui-tabbar__icon' }),
      !!badgeText && (h("span", { class: 'weui-badge taro-tabbar-badge', style: badgeStyle }, badgeText)),
      showRedDot && (h("span", { class: 'weui-badge weui-badge_dot', style: dotStyle }))),
    h("p", { class: 'weui-tabbar__label', style: { color: textColor } }, text)));
};

const indexCss = "html,body{height:100%}#app{height:100%}.taro-tabbar__border-white::before{border-top-color:#fff !important}.taro-tabbar__container{display:-ms-flexbox;display:flex;overflow:hidden;-ms-flex-direction:column;flex-direction:column;height:100%}.taro-tabbar__panel{overflow:auto;position:relative;-ms-flex:1;flex:1;-webkit-overflow-scrolling:auto}.taro-tabbar__tabbar{position:relative;width:100%;height:50px;-webkit-transition:bottom 0.2s, top 0.2s;transition:bottom 0.2s, top 0.2s}.taro-tabbar__tabbar-top{top:0}.taro-tabbar__tabbar-bottom{bottom:0;margin-bottom:constant(safe-area-inset-bottom);margin-bottom:env(safe-area-inset-bottom)}.taro-tabbar__tabbar-hide{display:none}.taro-tabbar__tabbar-slideout{top:-52px;-ms-flex:0 0;flex:0 0}.taro-tabbar__panel+.taro-tabbar__tabbar-slideout{top:auto;bottom:-52px}";

const STATUS_SHOW = 0;
const STATUS_HIDE = 1;
const STATUS_SLIDEOUT = 2;
const basicTabBarClassName = 'taro-tabbar__tabbar';
const hideTabBarClassName = 'taro-tabbar__tabbar-hide';
const hideTabBarWithAnimationClassName = 'taro-tabbar__tabbar-slideout';
const Tabbar = /*@__PURE__*/ proxyCustomElement(class extends HTMLElement {
  constructor() {
    super();
    this.__registerHost();
    this.onLongPress = createEvent(this, "longpress", 7);
    this.homePage = '';
    this.customRoutes = [];
    this.tabbarPos = 'bottom';
    this.getOriginUrl = (url) => {
      const customRoute = this.customRoutes.filter(([, customUrl]) => {
        const pathA = splitUrl(customUrl).path;
        const pathB = splitUrl(url).path;
        return pathA === pathB;
      });
      return stripSuffix(customRoute.length ? customRoute[0][0] : url, '.html');
    };
    this.getSelectedIndex = (url) => {
      let foundIndex = -1;
      this.list.forEach(({ pagePath }, idx) => {
        const pathA = splitUrl(url).path;
        const pathB = splitUrl(pagePath).path;
        if (pathA === pathB) {
          foundIndex = idx;
        }
      });
      return foundIndex;
    };
    this.switchTab = (index) => {
      this.selectedIndex = index;
      Taro.switchTab({
        url: this.list[index].pagePath
      });
    };
    this.switchTabHandler = ({ url, successHandler, errorHandler }) => {
      const currentUrl = this.getOriginUrl(this.getCurrentUrl() || this.homePage);
      const nextTab = resolvePathname(url, currentUrl);
      const foundIndex = this.getSelectedIndex(nextTab);
      if (foundIndex > -1) {
        this.switchTab(foundIndex);
        successHandler({
          errMsg: 'switchTab:ok'
        });
      }
      else {
        errorHandler({
          errMsg: `switchTab:fail page "${nextTab}" is not found`
        });
      }
    };
    this.routerChangeHandler = (options) => {
      var _a;
      const to = (_a = options === null || options === void 0 ? void 0 : options.toLocation) === null || _a === void 0 ? void 0 : _a.path;
      let currentPage;
      if (typeof to === 'string') {
        const routerBasename = this.conf.basename || '/';
        currentPage = stripBasename(addLeadingSlash(to || this.homePage), routerBasename) || '/';
      }
      else {
        currentPage = this.getCurrentUrl();
      }
      this.selectedIndex = this.getSelectedIndex(this.getOriginUrl(currentPage));
    };
    this.setTabBarBadgeHandler = ({ index, text, successHandler, errorHandler }) => {
      const list = [...this.list];
      if (index in list) {
        list[index].showRedDot = false;
        list[index].badgeText = text;
        successHandler({
          errMsg: 'setTabBarBadge:ok'
        });
      }
      else {
        errorHandler({
          errMsg: 'setTabBarBadge:fail tabbar item not found'
        });
      }
      this.list = list;
    };
    this.removeTabBarBadgeHandler = ({ index, successHandler, errorHandler }) => {
      const list = [...this.list];
      if (index in list) {
        list[index].badgeText = null;
        list[index].badgeText = null;
        successHandler({
          errMsg: 'removeTabBarBadge:ok'
        });
      }
      else {
        errorHandler({
          errMsg: 'removeTabBarBadge:fail tabbar item not found'
        });
      }
      this.list = list;
    };
    this.showTabBarRedDotHandler = ({ index, successHandler, errorHandler }) => {
      const list = [...this.list];
      if (index in list) {
        list[index].badgeText = null;
        list[index].showRedDot = true;
        successHandler({
          errMsg: 'showTabBarRedDot:ok'
        });
      }
      else {
        errorHandler({
          errMsg: 'showTabBarRedDot:fail tabbar item not found'
        });
      }
      this.list = list;
    };
    this.hideTabBarRedDotHandler = ({ index, successHandler, errorHandler }) => {
      const list = [...this.list];
      if (index in list) {
        list[index].showRedDot = false;
        successHandler({
          errMsg: 'hideTabBarRedDot:ok'
        });
      }
      else {
        errorHandler({
          errMsg: 'hideTabBarRedDot:fail tabbar item not found'
        });
      }
      this.list = list;
    };
    this.showTabBarHandler = ({ successHandler }) => {
      this.status = STATUS_SHOW;
      successHandler({
        errMsg: 'showTabBar:ok'
      });
    };
    this.hideTabBarHandler = ({ animation, successHandler }) => {
      this.status = animation ? STATUS_SLIDEOUT : STATUS_HIDE;
      successHandler({
        errMsg: 'hideTabBar:ok'
      });
    };
    this.setTabBarStyleHandler = ({ color, selectedColor, backgroundColor, borderStyle, successHandler }) => {
      if (backgroundColor)
        this.backgroundColor = backgroundColor;
      if (borderStyle)
        this.borderStyle = borderStyle;
      if (color)
        this.color = color;
      if (selectedColor)
        this.selectedColor = selectedColor;
      successHandler({
        errMsg: 'setTabBarStyle:ok'
      });
    };
    this.setTabBarItemHandler = ({ index, iconPath, selectedIconPath, text, successHandler, errorHandler }) => {
      const list = [...this.list];
      if (index in list) {
        if (iconPath)
          list[index].iconPath = iconPath;
        if (selectedIconPath)
          list[index].selectedIconPath = selectedIconPath;
        if (text)
          list[index].text = text;
        successHandler({
          errMsg: 'setTabBarItem:ok'
        });
      }
      else {
        errorHandler({
          errMsg: 'setTabBarItem:fail tabbar item not found'
        });
      }
      this.list = list;
    };
    this.conf = undefined;
    this.list = undefined;
    this.borderStyle = undefined;
    this.backgroundColor = undefined;
    this.color = undefined;
    this.selectedColor = undefined;
    this.selectedIndex = -1;
    this.status = STATUS_SHOW;
    const list = this.conf.list;
    const customRoutes = this.conf.customRoutes;
    if (Object.prototype.toString.call(list) !== '[object Array]' ||
      list.length < 2 ||
      list.length > 5) {
      throw new Error('tabBar 配置错误');
    }
    this.homePage = addLeadingSlash(this.conf.homePage);
    for (let key in customRoutes) {
      const path = customRoutes[key];
      key = addLeadingSlash(key);
      if (typeof path === 'string') {
        this.customRoutes.push([key, addLeadingSlash(path)]);
      }
      else if ((path === null || path === void 0 ? void 0 : path.length) > 0) {
        this.customRoutes.push(...path.map(p => [key, addLeadingSlash(p)]));
      }
    }
    list.forEach(item => {
      if (item.pagePath.indexOf('/') !== 0) {
        item.pagePath = '/' + item.pagePath;
      }
    });
    this.list = list;
    this.borderStyle = this.conf.borderStyle;
    this.backgroundColor = this.conf.backgroundColor;
    this.color = this.conf.color;
    this.selectedColor = this.conf.selectedColor;
  }
  getCurrentUrl() {
    const routePath = getCurrentPage(this.conf.mode, this.conf.basename);
    return decodeURI(routePath === '/' ? this.homePage : routePath);
  }
  bindEvent() {
    Taro.eventCenter.on('__taroRouterChange', this.routerChangeHandler);
    Taro.eventCenter.on('__taroSwitchTab', this.switchTabHandler);
    Taro.eventCenter.on('__taroSetTabBarBadge', this.setTabBarBadgeHandler);
    Taro.eventCenter.on('__taroRemoveTabBarBadge', this.removeTabBarBadgeHandler);
    Taro.eventCenter.on('__taroShowTabBarRedDotHandler', this.showTabBarRedDotHandler);
    Taro.eventCenter.on('__taroHideTabBarRedDotHandler', this.hideTabBarRedDotHandler);
    Taro.eventCenter.on('__taroShowTabBar', this.showTabBarHandler);
    Taro.eventCenter.on('__taroHideTabBar', this.hideTabBarHandler);
    Taro.eventCenter.on('__taroSetTabBarStyle', this.setTabBarStyleHandler);
    Taro.eventCenter.on('__taroSetTabBarItem', this.setTabBarItemHandler);
  }
  removeEvent() {
    Taro.eventCenter.off('__taroRouterChange', this.routerChangeHandler);
    Taro.eventCenter.off('__taroSwitchTab', this.switchTabHandler);
    Taro.eventCenter.off('__taroSetTabBarBadge', this.setTabBarBadgeHandler);
    Taro.eventCenter.off('__taroRemoveTabBarBadge', this.removeTabBarBadgeHandler);
    Taro.eventCenter.off('__taroShowTabBarRedDotHandler', this.showTabBarRedDotHandler);
    Taro.eventCenter.off('__taroHideTabBarRedDotHandler', this.hideTabBarRedDotHandler);
    Taro.eventCenter.off('__taroShowTabBar', this.showTabBarHandler);
    Taro.eventCenter.off('__taroHideTabBar', this.hideTabBarHandler);
    Taro.eventCenter.off('__taroSetTabBarStyle', this.setTabBarStyleHandler);
    Taro.eventCenter.off('__taroSetTabBarItem', this.setTabBarItemHandler);
  }
  componentDidLoad() {
    this.tabbarPos = this.tabbar.nextElementSibling ? 'top' : 'bottom';
    this.bindEvent();
    this.routerChangeHandler();
  }
  disconnectedCallback() {
    this.removeEvent();
  }
  render() {
    const { tabbarPos = 'bottom' } = this;
    const status = this.status;
    const containerCls = classnames('weui-tabbar', {
      [`taro-tabbar__border-${this.borderStyle || 'black'}`]: true
    });
    const shouldHideTabBar = this.selectedIndex === -1 || status === STATUS_HIDE;
    const shouldSlideout = status === STATUS_SLIDEOUT;
    return (h(Host, { class: classnames(basicTabBarClassName, `${basicTabBarClassName}-${tabbarPos}`, {
        [hideTabBarClassName]: shouldHideTabBar,
        [hideTabBarWithAnimationClassName]: shouldSlideout
      }) }, h("div", { class: containerCls, style: {
        backgroundColor: this.backgroundColor || '',
        height: 'inherit'
      } }, this.list.map((item, index) => {
      const isSelected = this.selectedIndex === index;
      let textColor;
      let iconPath;
      if (isSelected) {
        textColor = this.selectedColor || '';
        iconPath = item.selectedIconPath;
      }
      else {
        textColor = this.color || '';
        iconPath = item.iconPath;
      }
      return (h(TabbarItem, { index: index, onSelect: this.switchTab.bind(this), isSelected: isSelected, textColor: textColor, iconPath: iconPath, pagePath: item.pagePath, text: item.text, badgeText: item.badgeText, showRedDot: item.showRedDot }));
    }))));
  }
  get tabbar() { return this; }
  static get style() { return indexCss; }
}, [0, "taro-tabbar", {
    "conf": [16],
    "list": [32],
    "borderStyle": [32],
    "backgroundColor": [32],
    "color": [32],
    "selectedColor": [32],
    "selectedIndex": [32],
    "status": [32]
  }]);
function defineCustomElement$1() {
  if (typeof customElements === "undefined") {
    return;
  }
  const components = ["taro-tabbar"];
  components.forEach(tagName => { switch (tagName) {
    case "taro-tabbar":
      if (!customElements.get(tagName)) {
        customElements.define(tagName, Tabbar);
      }
      break;
  } });
}

const TaroTabbar = Tabbar;
const defineCustomElement = defineCustomElement$1;

export { TaroTabbar, defineCustomElement };

//# sourceMappingURL=taro-tabbar.js.map