const PivotItem = ({ children }) => {
  return <>{children}</>;
};

const Pivot = ({ children, selectedKey, defaultKey, onChange }) => {
  const items = React.Children.toArray(children);

  const visibleItems = items.filter(
    item => !item.props.hidden
  );

  const firstKey = visibleItems[0]?.props.itemKey;

  const isControlled = selectedKey !== undefined;

  const [internalKey, setInternalKey] = React.useState(
    defaultKey || firstKey
  );

  const activeKey = isControlled ? selectedKey : internalKey;

  const setKey = (key) => {
    if (!isControlled) {
      setInternalKey(key);
    }
    onChange?.(key);
  };

  const styles = {
    root: {
      width: "100%",
    },
    headerRow: {
      display: "flex",
      borderBottom: "1px solid #e1e1e1",
      marginBottom: "4px",
    },
    tab: (active) => ({
      padding: "12px 16px",
      cursor: "pointer",
      fontSize: "16px",
      fontWeight: active ? 600 : 400,
      color: active ? "#000" : "#605e5c",
      borderBottom: active ? "2px solid #FBC116" : "2px solid transparent",
      marginBottom: "-1px",
      transition: "all 0.15s ease",
    }),
  };

  return (
    <div style={styles.root}>
      <div style={styles.headerRow}>
        {visibleItems.map(item => (
          <div
            key={item.props.itemKey}
            style={styles.tab(item.props.itemKey === activeKey)}
            onClick={() => setKey(item.props.itemKey)}
          >
            {item.props.headerText}
          </div>
        ))}
      </div>

      {visibleItems.find(i => i.props.itemKey === activeKey)}
    </div>
  );
};

window.Pivot = Pivot;
window.PivotItem = PivotItem;