import "./css/tab.scss";

/**
 * Tab 页创建参数类
 * @typedef TabOption
 * @property {HTMLElement} container - 父容器
 */

import { createElement } from "../functions";

/**
 * 创建 Tab 页
 * @param {TabOption | HTMLElement} options - 创建选项
 */
export function createTab(options) {
    if (options instanceof HTMLElement) {
        options = { container: options };
    }
    let container;
    if (options?.container instanceof HTMLElement) {
        container = options.container;
        if (!container.classList.contains('ui-tab-container')) {
            container.classList.add('ui-tab-container');
        }
    } else {
        container = createElement('div', 'ui-tab-container');
    }
    container.replaceChildren(
        createElement('div', header => {
            header.className = 'ui-tab-header';
            header.addEventListener('click', e => {
                const title = e.target;
                if (title.classList.contains('ui-tab-title')) {
                    // title
                    header.querySelectorAll('.ui-tab-title').forEach(t => t === title ? t.classList.add('selected') : t.classList.remove('selected'));
                    // pages
                    const page = title.dataset.for;
                    container.querySelectorAll('[data-page]').forEach(p => p.style.display = p.dataset.page === page ? 'block' : '');
                }
            });
        })
    );
}