/* eslint-disable jsx-a11y/click-events-have-key-events */
/* eslint-disable jsx-a11y/no-static-element-interactions */
import { PureComponent } from 'react';
import {
  Layout,
  Avatar,
  Badge,
  Divider,
  message,
  Tooltip,
  Dropdown,
  Menu,
  Card,
  Alert,
  Button
} from 'antd';
import { connect } from 'react-redux';
import dynamic from 'next/dynamic';
import Link from 'next/link';
import {
  IUser, StreamSettings, IUIConfig, ISettings
} from 'src/interfaces';
import { logout } from '@redux/auth/actions';
import {
  FlagOutlined,
  ShoppingCartOutlined,
  UserOutlined,
  ShoppingOutlined,
  LogoutOutlined,
  VideoCameraOutlined,
  PictureOutlined,
  DollarOutlined,
  NotificationOutlined,
  BlockOutlined,
  HeartOutlined,
  PlayCircleOutlined,
  TransactionOutlined,
  WalletOutlined,
  ClockCircleFilled,
  ClockCircleOutlined,
  DollarCircleOutlined,
  VideoCameraAddOutlined,
} from '@ant-design/icons';
import './header.less';
import Router, { withRouter, NextRouter } from 'next/router';
import { addCart } from 'src/redux/cart/actions';
import {
  cartService,
  messageService,
  authService,
  notificationService
} from 'src/services';
import { SocketContext } from 'src/socket';
import { addPrivateRequest } from '@redux/streaming/actions';
import { 
  openMenu, 
  openTopupWalletModal,
  openLoginModal,
  openForgotPasswordModal,
  openCustomerRegistration,
} from '@redux/ui/actions';
import { formatDate } from 'src/lib';
import { MessageIcon, ModelIcon, MenuIcon, UserIcon, SearchIcon, BellIcon, CommentsIcon, CartIcon } from 'src/icons';
import Sound from '@components/common/base/sound';
import { ITopupWalletModal } from '@components/wallet/topup-wallet-modal';
import LoginModal from '@components/auth/login-modal';
import ForgotpasswordModal from '@components/auth/forgotpassword-modal';
import FanRegisterModal from '@components/auth/fan-register-modal';
import ThemeSwitcher from '../theme-switcher';

const TopupWalletModal = dynamic<ITopupWalletModal>(() => import('@components/wallet/topup-wallet-modal'), { ssr: false });
const Popup18Plus = dynamic(() => import('src/components/common/popup-18plus-content'), { ssr: false });
const NotificationHeaderMenu = dynamic(() => import('@components/notification/NotificationHeaderMenu'), { ssr: false });
const StreamIcon = dynamic(() => import('@components/streaming/live-stream-icon'), { ssr: false });
const SearchBar = dynamic(() => import('@components/common/layout/search-bar'), { ssr: false });

const EVENT = {
  RECEIVED_PRIVATE_CHAT_REQUEST: 'private-chat-request',
  NOTIFY_READ_MESSAGE: 'nofify_read_messages_in_conversation',
  TIPPED: 'TIPPED',
  BALANCE_UPDATE: 'balance_update'
};

interface IProps {
  currentUser?: IUser;
  streamSettings: StreamSettings;
  privateRequests?: any;
  logout: Function;
  router: NextRouter;
  ui: IUIConfig;
  settings: ISettings;
  cart: any;
  addCart: Function;
  addPrivateRequest: Function;
  openMenu: Function;
  openTopupWalletModal: Function;
  openLoginModal: Function;
  openForgotPasswordModal: Function;
  loggedIn: boolean;
  clearCart: Function;
  notificationCount: number;
  openCustomerRegistration: Function;
}

function PrivateChatRequestMenuItem({
  streamSettings,
  privateRequests
}) {
  if (!privateRequests?.length) return null;

  const renderCardTitle = (user) => {
    const { username, balance = 0 } = user;

    return (
      <span>
        {username}
        {' '}
        <span className="wallet-content">
          <img
            src="/wallett.png"
            alt=""
            width="10"
            height="10"
          />
          {' '}
          {balance.toFixed(2)}
        </span>
      </span>
    );
  };

  return privateRequests.map((request) => (
    <Menu.Item
      key={request.conversationId}
      onClick={() => {
        Router.push(
          {
            pathname: `/model/live/${streamSettings.optionForPrivate
              === 'webrtc'
              ? 'webrtc/'
              : ''
              }privatechat`,
            query: { id: request.conversationId }
          },
          `/model/live/${streamSettings.optionForPrivate === 'webrtc'
            ? 'webrtc/'
            : ''
          }privatechat/${request.conversationId}`
        );
        message.destroy();
      }}
    >
      <Card bordered={false} hoverable={false}>
        <Card.Meta
          avatar={(
            <Avatar
              src={
                request.user.avatar || '/no-avatar.png'
              }
            />
          )}
          title={renderCardTitle(request.user)}
          description={formatDate(
            request.user.createdAt
          )}
        />
      </Card>
    </Menu.Item>
  ));
}

function RenderUserMenu(props) {
  const { router, currentUser, showWalletModal, beforeLogout } = props;
  return (
    <div className="profile-menu-item">
        <div className='inner-content'>

            <div className='menu-profile-content'>
              <span className="avatar-profile">
                  <Avatar src={currentUser?.avatar || '/no-avatar.png'} />
              </span>
              <span className='uname'>{currentUser?.username}</span>
            </div>
            <Divider />

            <div className='profile-menus'>

                { currentUser.isPerformer 
                  ?  (<>
                        <Link
                          href={{
                            pathname: '/model/profile',
                            query: {
                              username: currentUser.username || currentUser._id
                            }
                          }}
                          as={`/model/${currentUser.username || currentUser._id}`}
                        >
                          <a>
                            <UserOutlined />
                            {' '}
                            <span className="hide">My Profile</span>
                          </a>
                        </Link>
                        <Divider />
                        <Link href="/model/live" as="/live">
                            <div
                              className={
                                router.pathname === '/model/live'
                                  ? 'menu-item active'
                                  : 'menu-item'
                              }
                            >
                              <StreamIcon />
                              {' '}
                              Go Live
                            </div>
                        </Link>
                        <Divider />
                        <Link href="/model/account" as="/model/account">
                          <div
                            className={
                              router.pathname === '/model/account'
                                ? 'menu-item active'
                                : 'menu-item'
                            }
                          >
                            <UserOutlined />
                            {' '}
                            Edit Profile
                          </div>
                        </Link>
                        <Link href={{ pathname: '/model/black-list' }}>
                          <div
                            className={
                              router.pathname === '/model/black-list'
                                ? 'menu-item active'
                                : 'menu-item'
                            }
                          >
                            <BlockOutlined />
                            {' '}
                            Blacklist
                          </div>
                        </Link>
                        <Link href={{ pathname: '/model/violations-reported' }}>
                          <div
                            className={
                              router.pathname === '/model/violations-reported'
                                ? 'menu-item active'
                                : 'menu-item'
                            }
                          >
                            <FlagOutlined />
                            {' '}
                            Violations Reported
                          </div>
                        </Link>
                        <Divider />
                        <Link
                          href={{ pathname: '/model/my-subscriber' }}
                          as="/model/my-subscriber"
                        >
                          <div
                            className={
                              router.pathname === '/model/my-subscriber'
                                ? 'menu-item active'
                                : 'menu-item'
                            }
                          >
                            <HeartOutlined />
                            {' '}
                            My Subscribers
                          </div>
                        </Link>
                        <Link href="/model/my-video" as="/model/my-video">
                          <div
                            className={
                              router.pathname === '/model/my-video'
                                ? 'menu-item active'
                                : 'menu-item'
                            }
                          >
                            <VideoCameraOutlined />
                            {' '}
                            My Videos
                          </div>
                        </Link>
                        <Link
                          href="/model/my-gallery/listing"
                          as="/model/my-gallery/listing"
                        >
                          <div
                            className={
                              router.pathname === '/model/my-gallery/listing'
                                ? 'menu-item active'
                                : 'menu-item'
                            }
                          >
                            <PictureOutlined />
                            {' '}
                            My Galleries
                          </div>
                        </Link>
                        <Link href="/model/my-store" as="/model/my-store">
                          <div
                            className={
                              router.pathname === '/model/my-store'
                                ? 'menu-item active'
                                : 'menu-item'
                            }
                          >
                            <ShoppingOutlined />
                            {' '}
                            My Store
                          </div>
                        </Link>
                        <Divider />
                        <Link
                          href={{ pathname: '/model/product-orders' }}
                          as="/model/product-orders"
                        >
                          <div
                            className={
                              router.pathname === '/model/product-orders'
                                ? 'menu-item active'
                                : 'menu-item'
                            }
                          >
                            <ShoppingCartOutlined />
                            {' '}
                            Product Orders
                          </div>
                        </Link>
                        <Divider />
                        <Link href="/model/earning">
                          <div
                            className={
                              router.pathname === '/model/earning'
                                ? 'menu-item active'
                                : 'menu-item'
                            }
                          >
                            <DollarOutlined />
                            {' '}
                            Earning Report
                          </div>
                        </Link>
                        <Link href="/model/payout-request">
                          <div
                            className={
                              router.pathname === '/model/payout-request'
                                ? 'menu-item active'
                                : 'menu-item'
                            }
                          >
                            <NotificationOutlined />
                            {' '}
                            Payout Request
                          </div>
                        </Link>
                    </>)
                  : (<>
                      <Link 
                        href={{
                          pathname: '/user/profile',
                          query: {
                            username: currentUser.username
                          }
                        }}
                        as={`user/${currentUser?.username}`}>
                        <div
                          className={
                            router.pathname === '/users/profile'
                              ? 'menu-item active'
                              : 'menu-item'
                          }
                        >
                          <UserOutlined />
                          {' '}
                          My Profile
                        </div>
                      </Link>
                      <Divider />
                      <a onClick={showWalletModal}>
                        <div
                          className={
                            router.pathname === '/wallet-package'
                              ? 'menu-item active'
                              : 'menu-item'
                          }
                        >
                          <WalletOutlined width={15} height={15} />
                          {' '}
                          Buy Coins
                        </div>
                      </a>
                      <Divider />
                      <Link href="/user/my-favorite" as="/user/my-favorite">
                        <div
                          className={
                            router.pathname === '/user/my-favorite'
                              ? 'menu-item active'
                              : 'menu-item'
                          }
                        >
                          <HeartOutlined />
                          {' '}
                          My Favorites
                        </div>
                      </Link>
                      <Link href="/user/my-favorite-models" as="/user/my-favorite-models
                      ">
                        <div
                          className={
                            router.pathname === '/user/my-favorite-models'
                              ? 'menu-item active'
                              : 'menu-item'
                          }
                        >
                          <HeartOutlined />  
                          {' '}
                          My Favorite Models
                        </div>
                      </Link>
                      <Link href="/user/my-wishlist" as="/user/my-wishlist">
                        <div
                          className={
                            router.pathname === '/user/my-wishlist'
                              ? 'menu-item active'
                              : 'menu-item'
                          }
                        >
                          <ClockCircleOutlined width={15} height={15} />
                          {' '}
                          My Wishlist
                        </div>
                      </Link>
                      <Link href="/user/my-subscription" as="/user/my-subscription">
                        <div
                          className={
                            router.pathname === '/user/my-subscription'
                              ? 'menu-item active'
                              : 'menu-item'
                          }
                        >
                          <DollarCircleOutlined width={15} height={15} />
                          {' '}
                          My Subscriptions
                        </div>
                      </Link>
                      <Divider />
                      <Link href="/user/purchased-media" as="/user/purchased-media">
                        <div
                          className={
                            router.pathname === '/user/purchased-media'
                              ? 'menu-item active'
                              : 'menu-item'
                          }
                        >
                          <VideoCameraAddOutlined width={15} height={15} />
                          {' '}
                          Purchased Media
                        </div>
                      </Link>
                      <Link href="/user/purchased-product" as="/user/purchased-product">
                        <div
                          className={
                            router.pathname === '/user/purchased-product'
                              ? 'menu-item active'
                              : 'menu-item'
                          }
                        >
                          <ShoppingCartOutlined />
                          {' '}
                          Product Purchases
                        </div>
                      </Link>
                      <Divider />
                      <Link href="/user/payment-history" as="/user/payment-history">
                        <div
                          className={
                            router.pathname === '/user/payment-history'
                              ? 'menu-item active'
                              : 'menu-item'
                          }
                        >
                          <TransactionOutlined />
                          {' '}
                          Transactions
                        </div>
                      </Link>
                    </>)
                }

                <Divider />

                <div aria-hidden
                    className="menu-item"
                    onClick={beforeLogout} >
                    <LogoutOutlined />
                    {' '}
                    Log out
                </div>

            </div>

        </div>
    </div>
  )
}

function onScroll() {
  const div = document.getElementById('main-header');

  // TODO - check size
  const rightItemWidth = 35;
  const logoElems = document.querySelectorAll<HTMLElement>('.logo-nav');
  const logoWidth = 25; // logoElems.length ? logoElems[0].clientWidth : 50;
  const menuProfiles = document.querySelectorAll<HTMLElement>('.menu-profile');
  if (div.scrollLeft > logoWidth) {
    // logo-nav
    Array.from(logoElems).forEach((elem) => {
      // eslint-disable-next-line no-param-reassign
      elem.style.borderRight = '1px solid #fff';
    });
  } else {
    Array.from(logoElems).forEach((elem) => {
      // eslint-disable-next-line no-param-reassign
      elem.style.borderRight = 'none';
    });
  }

  if (div.scrollWidth - (div.clientWidth + div.scrollLeft) < rightItemWidth) {
    Array.from(menuProfiles).forEach((elem) => {
      // eslint-disable-next-line no-param-reassign
      elem.style.borderLeft = 'none';
    });
  } else {
    Array.from(menuProfiles).forEach((elem) => {
      // eslint-disable-next-line no-param-reassign
      elem.style.borderLeft = '1px solid #fff';
    });
  }
}

function attachScrollListener() {
  const div = document.getElementById('main-header');
  div.addEventListener('scroll', onScroll);
}

function removeScrollListener() {
  const div = document.getElementById('main-header');
  div.removeEventListener('scroll', onScroll);
}

class Header extends PureComponent<IProps> {
  state = {
    totalUnreadMessage: 0,
    openWalletModal: false,
    showAlert: false,
    balance: this.props.currentUser?.balance || 0,
    userMenuVisible: false,
  };

  private socket: any;

  private soundRef;

  componentDidMount() {
    this.handleOpenMenu(false); 
    
    const {
      currentUser, loggedIn
    } = this.props;
    Router.events.on('routeChangeStart', () => this.setState({ userMenuVisible: false }));
    if (currentUser._id) {
      this.countTotalMessage();
    }
    if (loggedIn) {
      this.initSocketEvent();
      this.handleCart();
    }

    onScroll();
    attachScrollListener();
    window.addEventListener('resize', onScroll);
  }

  componentDidUpdate(prevProps: any) {
    const {
      currentUser, loggedIn
    } = this.props;
    if (prevProps?.currentUser._id !== currentUser?._id && currentUser?._id) {
      this.countTotalMessage();
      this.handleCart();
      this.handleModelInactive();
    }

    if (loggedIn && prevProps.loggedIn !== loggedIn) {
      setTimeout(this.initSocketEvent, 1000);
    }
  }

  componentWillUnmount() {
    if (this.socket) {
      this.socket.off(EVENT.NOTIFY_READ_MESSAGE, this.handleMessage);
      this.socket.off(EVENT.BALANCE_UPDATE, this.handleUpdateBalance);
      this.socket.off(EVENT.TIPPED, this.handleTipped);
      this.socket.off(
        EVENT.RECEIVED_PRIVATE_CHAT_REQUEST,
        this.handlePrivateChat
      );
    }

    removeScrollListener();
    window.removeEventListener('resize', onScroll);
  }

  handleCart() {
    const {
      cart, addCart: addCartHandler
    } = this.props;
    if (!cart || (cart && cart.items.length <= 0)) {
      const existCart = cartService.getCartItems();
      if (existCart && existCart.length > 0) {
        addCartHandler(existCart);
      }
    }
  }

  handleMessage = (event) => {
    event && this.setState({ totalUnreadMessage: event.total });
  };

  handlePrivateChat = (data: { conversationId: string; user: IUser }) => {
    const { addPrivateRequest: dispatchAddPrivateRequest } = this.props;
    message.success(`${data.user.username} sent you a private chat request!`);
    // this.soundRef.current && this.soundRef.current.play();
    dispatchAddPrivateRequest({ ...data, createdAt: new Date() });
  };

  handleOpenMenu = (action) => {
    const { openMenu: dispatchOpenMenu } = this.props;
    dispatchOpenMenu(action);
  };  

  handleTipped = ({ senderInfo, totalPrice, _id }) => {
    if (notificationService.hasHolderId(_id)) return;
    notificationService.addHolderId(_id);
    message.success(
      `You have received $${totalPrice} from ${senderInfo.name}`
    );
    // this.soundRef.current && this.soundRef.current.play();
  };

  handleUpdateBalance = (data) => {
    this.setState({ balance: data.balance });
  };

  async beforeLogout() {
    const { logout: logoutHandler } = this.props;
    const token = authService.getToken();
    const socket = this.context;
    token
      && socket
      && (await socket.emit('auth/logout', {
        token
      }));
    logoutHandler();
  }

  async countTotalMessage() {
    const data = await (await messageService.countTotalNotRead()).data;
    if (data) {
      this.setState({ totalUnreadMessage: data.total });
    }
  }

  initSocketEvent = () => {
    this.socket = this.context;
    const { currentUser } = this.props;
    if (this.socket.connected) {
      if (currentUser.isPerformer) {
        this.socket.on(
          EVENT.RECEIVED_PRIVATE_CHAT_REQUEST,
          this.handlePrivateChat
        );
        this.socket.on(EVENT.TIPPED, this.handleTipped);
      }

      this.socket.on(EVENT.NOTIFY_READ_MESSAGE, this.handleMessage);
      this.socket.on(EVENT.BALANCE_UPDATE, this.handleUpdateBalance);
    } else {
      this.socket.on('connect', () => {
        if (currentUser.isPerformer) {
          this.socket.on(
            EVENT.RECEIVED_PRIVATE_CHAT_REQUEST,
            this.handlePrivateChat
          );
          this.socket.on(EVENT.TIPPED, this.handleTipped);
        }

        this.socket.on(EVENT.NOTIFY_READ_MESSAGE, this.handleMessage);
        this.socket.on(EVENT.BALANCE_UPDATE, this.handleUpdateBalance);
      });
    }
  };

  handleModelInactive() {
    const { currentUser } = this.props as any;
    if (
      currentUser.isPerformer
      && (currentUser.status !== 'active' || !currentUser.verifiedDocument)
    ) {
      this.setState({ showAlert: true });
    }
  }

  showWalletModal(e) {
    e?.preventDefault();
    // this.setState({ openWalletModal: true });
    const { openTopupWalletModal: dispatchOpenTopupWalletModal, ui, currentUser } = this.props;
    
    if (!currentUser._id) {
      message.error('Please login to buy coins.');
      return;
    }
    dispatchOpenTopupWalletModal(!ui?.openTopupWalletModal);
  }

  userMenuClick(e) {
    e?.preventDefault();
    this.setState({ userMenuVisible: !this.state.userMenuVisible })
  }
  
  showopenLoginModal(e) {
    const { openLoginModal: dispatchOpenLoginModal, ui } = this.props;
    dispatchOpenLoginModal(!ui?.openLoginModal)
  }

  showopenCustomerRegistration(e) {
    const { openCustomerRegistration: dispatchOpenCustomerRegistration, ui } = this.props;
    dispatchOpenCustomerRegistration(!ui?.openCustomerRegistration)
  }

  showopenForgotPasswordModal(e) {
    e?.preventDefault();
    const { openForgotPasswordModal: dispatchOpenForgotPasswordModal, ui } = this.props;
    dispatchOpenForgotPasswordModal(!ui?.forgotPasswordModal)
  }

  renderLoginSignup(currentUser) {
    const { router } = this.props;
    return (
      <li className='header-account'>
        {!currentUser._id && (
        <div className='align-center gap-15'>
          <span 
              onClick={this.showopenLoginModal.bind(this)}
              className='login-link cursor-pointer'>Log in</span>
          {/* <Link href="/auth/register"> */}
            <Button 
              onClick={this.showopenCustomerRegistration.bind(this)}
              className='ant-btn ant-btn-round btn-primary fs-20 fw-bold px-5 py-2'>
              Create a free account
            </Button>
          {/* </Link> */}
        </div>)}
        <div className='align-center gap-15'>
          <Link href="/search"><a className='text-white'><SearchIcon style={{width: '22px', height: '22px'}} /></a></Link>
          {!currentUser._id && (
            <Dropdown
                placement='bottomRight'
                trigger={['click']}
                overlay={(
                  <Menu>
                    <Menu.Item key="login" onClick={this.showopenLoginModal.bind(this)}>Login</Menu.Item>
                    <Menu.Item key="signup" onClick={this.showopenCustomerRegistration.bind(this)}>Create a free account</Menu.Item>
                  </Menu>
                )}
                overlayStyle={{position: 'fixed'}}
                overlayClassName={`menu-overlay`}
                forceRender
              >
              <span><UserIcon className='text-white' style={{width: '22px', height: '22px'}} /></span>
            </Dropdown>)}
        </div>
      </li>
    )
  }

  renderUserLoginMenu() {
    const { router } = this.props;
    return [
      <li
        key="model-page"
        className={
          router.pathname === '/model'
            ? 'custom active'
            : 'custom'
        }
      >
        <Link href={{ pathname: '/model' }} as="/model">
          <a>
            <Tooltip title="Models">
              <ModelIcon />
              {' '}
              <span className="hide">Models</span>
            </Tooltip>
          </a>
        </Link>
      </li>,
      <li
        key="search-video"
        className={
          router.pathname === '/search/video'
            ? 'custom active'
            : 'custom'
        }
      >
        <Link
          href={{ pathname: '/search/video' }}
          as="/search/video"
        >
          <a>
            <Tooltip title="Videos">
              <VideoCameraOutlined />
              {' '}
              <span className="hide">Videos</span>
            </Tooltip>
          </a>
        </Link>
      </li>,
      <li
        key="search-live"
        className={
          router.pathname === '/search/live'
            ? ' custom active'
            : ' custom'
        }
      >
        <Link
          href={{ pathname: '/search/live' }}
          as="/search/live"
        >
          <a>
            <Tooltip title="Live Models">
              <PlayCircleOutlined />
              {' '}
              <span className="hide">Live Models</span>
            </Tooltip>
          </a>
        </Link>
      </li>
    ];
  }

  renderMenuAllUserType() {
    const {
      router,
      notificationCount
    } = this.props;
    const {
      totalUnreadMessage
    } = this.state;
    return [
      <li className='md-d-none d-block' key="notification">
        <Dropdown
          placement='bottomRight'
          overlay={<NotificationHeaderMenu />}
          overlayStyle={{position: 'fixed'}}
          forceRender
        >
          <a href="#" aria-label="notification">
            <BellIcon style={{width:'20px'}} />
            <Badge
              className="cart-total"
              count={notificationCount}
            />
          </a>
        </Dropdown>
      </li>,
      <li
        key="messenger"
        className={`md-d-none d-block ${router.pathname === '/messages' ? 'active' : ''}`}
      >
        <Link href="/messages">
          <a>
            <Tooltip title="Messenger">
              <CommentsIcon style={{width:'26px'}} />
              <Badge
                overflowCount={9}
                className="cart-total"
                count={totalUnreadMessage}
              />
            </Tooltip>
          </a>
        </Link>
      </li>
    ];
  }

  render() {
    const {
      privateRequests,
      streamSettings,
      currentUser,
      router,
      ui,
      cart
    } = this.props;
    const {
      showAlert,
      balance,
      userMenuVisible,
      // theme
    } = this.state;

    return (
      <div className='main-header' id='main-header'>

        <Layout.Header className='header' id='layoutHeader'>
            <div className='header-navbar d-flex justify-space-between align-content-center'>

                <div className='d-flex align-center gap-5'>

                    <span
                      className='menu-btn cursor-pointer'
                      onClick={() => this.handleOpenMenu(!ui?.menuCollapsed)}>
                        <MenuIcon 
                          className='text-inherit d-flex align-center'
                        />
                    </span>

                    <Link href="/">
                      <a
                        title="Homepage"
                        className="logo-nav">
                        {ui?.logo ? (
                          <img alt="logo" src={ui?.logo} />
                        ) : (
                          <span style={{fontSize:14}}>{ui?.siteName}</span>
                        )}
                      </a>
                    </Link>

                </div>

                <div className='xlg-d-none d-flex align-center gap-20'>
                  <SearchBar />
                  <ThemeSwitcher />
                </div>

                {/* <div className="mid-conner" style={{ marginRight: currentUser._id ? currentUser.isPerformer ? '70px' : '70px' : '' }}> */}
                <div className='d-flex align-center'>
                  <ul className={`d-flex align-center gap-15 pa-0 mr-4 ${currentUser._id ? 'nav-icons' : 'nav-icons custom'}`} >
                    {currentUser && currentUser._id && (
                      <li className={`md-d-none d-block ${currentUser.isPerformer ? '' : 'custom'}`}>
                        {currentUser.isPerformer ? (
                          <Link
                            href="/model/earning"
                            as="/model/earning"
                          >
                            <a>
                              <Tooltip title={(balance || 0).toFixed(2)}>
                                <img src="/glamcore-1x.png" width={25} alt="" />
                                {' '}
                                <span className="hide">
                                  {(balance || 0).toFixed(2)}
                                </span>
                              </Tooltip>
                            </a>
                          </Link>
                        ) : (
                        
                          <a
                            style={{ whiteSpace: 'nowrap' }}
                            onClick={this.showWalletModal.bind(this)}
                          >
                            <Tooltip title={(balance || 0).toFixed(2)}>
                              <img src="/glamcore-1x.png" width={25} alt=""/>
                              {' '}
                              <span
                                className="hide"
                              >
                                {(balance || 0).toFixed(2)}
                              </span>
                            </Tooltip>
                          </a>
                        
                        )}
                      </li>
                    )}
                    {currentUser._id && this.renderMenuAllUserType()}
                    {currentUser._id && !currentUser.isPerformer && (
                      <li className={`md-d-none d-block ${router.pathname === '/cart' ? 'active' : ''} `}>
                        <Tooltip title="Shopping Cart">
                          <Link href="/cart">
                            <a>
                              <Tooltip title="Shopping">
                                <CartIcon style={{width:'25px'}} />
                                <Badge className="cart-total" count={cart.total} />
                              </Tooltip>
                            </a>
                          </Link>
                        </Tooltip>
                      </li>
                    )}
                    {/* {currentUser && currentUser._id && currentUser.isPerformer && (
                      <li>
                        <Dropdown
                          overlay={(
                            <Menu>
                              {privateRequests.length > 0
                                ? <PrivateChatRequestMenuItem privateRequests={privateRequests} streamSettings={streamSettings} />
                                : <Menu.Item key="no-request">There is no private requests</Menu.Item>}
                            </Menu>
                          )}
                        >
                          <li
                            style={{
                              cursor: 'pointer',
                              color: '#ffffff'
                            }}
                          >
                            <UsergroupAddOutlined />
                            <Badge
                              className="cart-total"
                              count={privateRequests.length}
                            />
                          </li>
                        </Dropdown>
                      </li>
                    )} */}
                    
                    { this.renderLoginSignup(currentUser) }
                  </ul>
                  {currentUser._id && (
                    <Dropdown
                      // visible={userMenuVisible}
                      trigger={['click']}
                      overlay={<RenderUserMenu 
                          showWalletModal={this.showWalletModal.bind(this)} 
                          router={router} 
                          currentUser={currentUser} 
                          beforeLogout={this.beforeLogout.bind(this)}/>}
                      // overlayClassName='user-dropdown'
                      overlayClassName='position-fixed user-dropdown'
                      forceRender
                    >
                      <span
                        key="menu-profile"
                        aria-hidden
                        className="menu-profile"
                        style={{
                          top: currentUser.isPerformer ? '5px' : 0
                        }}
                        // onClick={this.userMenuClick.bind(this)}
                      >
                        {/* <img
                          src="/information.png"
                          alt=""
                          width="23"
                          height="23"
                          className="icon-profile"
                        /> */}
                        {' '}
                        <span className="avatar-profile">
                          <Avatar src={currentUser?.avatar || '/no-avatar.png'} />
                        </span>
                      </span>
                    </Dropdown>
                  )}
                </div>
            </div>
            

            {/* Header Links */}
            <div className={`header-links ${!ui?.menuCollapsed ? 'open' : ''}`}>
              <nav>
                  <Link 
                    href={{ pathname: '/search/live' }}
                    as="/search/live"><a>Live Cams</a></Link>
                  {/* <Link href={{ pathname: '/escorts' }}
                    as="/escorts"><a>Escorts</a></Link> */}
                  <Link href={{ pathname: '/phone-chat' }}
                    as="/phone-chat"><a>Phone Chat</a></Link>
                  <Link href={{ pathname: '/photo-collections' }}
                    as="/photo-collection"><a>Photo Collection</a></Link>
                  <Link 
                    href={{ pathname: '/search/video' }}
                    as="/search/video"><a>Videos</a></Link>
                  <Link href={{ pathname: '/glam-club' }}
                    as="/glam-club"><a>Glam Club</a></Link>
                  <Link href={{ pathname: '/glam-tv' }}
                    as="/glam-tv"><a>Glam TV</a></Link>
                  <Link 
                    href={{ pathname: '/store'}}
                    as="/store"><a>Shop</a></Link>

                  <div className='d-flex align-center flex-auto gap-5'>
                    <span className='online-streams d-flex align-center gap-8 flex-auto fs-16'>
                        <span className='status'></span>
                        <span className='fw-bold'>0</span> LIVE {` `}|
                    </span>
                    <Link 
                      href={{ pathname: '/model'}}
                      as="/model"><a className='fw-bold fs-16'>Search all categories</a>
                    </Link>
                  </div>

              </nav>
            </div>

        </Layout.Header>
        {/* </div> */}
                  
        <Popup18Plus />

        {/* Top up modal */}
        <TopupWalletModal 
          visible={ui?.openTopupWalletModal} 
          onClose={this.showWalletModal.bind(this)} />

        {/* Login modal */}
        <LoginModal 
          visible={ui?.openLoginModal}
          onClose={this.showopenLoginModal.bind(this)}
        />

        {/* Forgot password modal */}
        <ForgotpasswordModal 
          visible={ui?.forgotPasswordModal}
          onClose={this.showopenForgotPasswordModal.bind(this)}
        />

        {/* Customer registration */}
        <FanRegisterModal 
          visible={ui?.openCustomerRegistration}
          onClose={this.showopenCustomerRegistration.bind(this)}
        />
        
        {showAlert && (
            <Alert
              type="info"
              description={(
                <>
                  <p className="text-center" style={{ margin: 0 }}>
                    Feel free to look around, set up your profile, and load
                    content. Your profile will be made public once your account is
                    approved. We will notify you on email when you are in
                    business!
                  </p>
                  <a
                    href="/contact"
                    style={{ position: 'absolute', bottom: '5px', right: '5px' }}
                  >
                    Contact us
                  </a>
                </>
              )}
              message={(
                <h4 className="text-center">
                  We are in the process of approving your account.
                </h4>
              )}
              closable
            />
          )
        }
      </div>
    );
  }
}

Header.contextType = SocketContext;
const mapState = (state: any) => ({
  loggedIn: state.auth.loggedIn,
  currentUser: state.user.current,
  streamSettings: state.streaming.settings,
  ui: state.ui,
  cart: state.cart,
  ...state.streaming,
  notificationCount: state.notification.total
});

const mapDispatch = { 
  logout, 
  addCart, 
  addPrivateRequest, 
  openMenu, 
  openTopupWalletModal, 
  openLoginModal,
  openForgotPasswordModal,
  openCustomerRegistration
};

export default withRouter(connect(mapState, mapDispatch)(Header)) as any;

 

Javascript Online Compiler

Write, Run & Share Javascript code online using OneCompiler's JS online compiler for free. It's one of the robust, feature-rich online compilers for Javascript language. Getting started with the OneCompiler's Javascript editor is easy and fast. The editor shows sample boilerplate code when you choose language as Javascript and start coding.

About Javascript

Javascript(JS) is a object-oriented programming language which adhere to ECMA Script Standards. Javascript is required to design the behaviour of the web pages.

Key Features

  • Open-source
  • Just-in-time compiled language
  • Embedded along with HTML and makes web pages alive
  • Originally named as LiveScript.
  • Executable in both browser and server which has Javascript engines like V8(chrome), SpiderMonkey(Firefox) etc.

Syntax help

STDIN Example

var readline = require('readline');
var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});

rl.on('line', function(line){
    console.log("Hello, " + line);
});

variable declaration

KeywordDescriptionScope
varVar is used to declare variables(old way of declaring variables)Function or global scope
letlet is also used to declare variables(new way)Global or block Scope
constconst is used to declare const values. Once the value is assigned, it can not be modifiedGlobal or block Scope

Backtick Strings

Interpolation

let greetings = `Hello ${name}`

Multi line Strings

const msg = `
hello
world!
`

Arrays

An array is a collection of items or values.

Syntax:

let arrayName = [value1, value2,..etc];
// or
let arrayName = new Array("value1","value2",..etc);

Example:

let mobiles = ["iPhone", "Samsung", "Pixel"];

// accessing an array
console.log(mobiles[0]);

// changing an array element
mobiles[3] = "Nokia";

Arrow functions

Arrow Functions helps developers to write code in concise way, it’s introduced in ES6.
Arrow functions can be written in multiple ways. Below are couple of ways to use arrow function but it can be written in many other ways as well.

Syntax:

() => expression

Example:

const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
const squaresOfEvenNumbers = numbers.filter(ele => ele % 2 == 0)
                                    .map(ele => ele ** 2);
console.log(squaresOfEvenNumbers);

De-structuring

Arrays

let [firstName, lastName] = ['Foo', 'Bar']

Objects

let {firstName, lastName} = {
  firstName: 'Foo',
  lastName: 'Bar'
}

rest(...) operator

 const {
    title,
    firstName,
    lastName,
    ...rest
  } = record;

Spread(...) operator

//Object spread
const post = {
  ...options,
  type: "new"
}
//array spread
const users = [
  ...adminUsers,
  ...normalUsers
]

Functions

function greetings({ name = 'Foo' } = {}) { //Defaulting name to Foo
  console.log(`Hello ${name}!`);
}
 
greet() // Hello Foo
greet({ name: 'Bar' }) // Hi Bar

Loops

1. If:

IF is used to execute a block of code based on a condition.

Syntax

if(condition){
    // code
}

2. If-Else:

Else part is used to execute the block of code when the condition fails.

Syntax

if(condition){
    // code
} else {
    // code
}

3. Switch:

Switch is used to replace nested If-Else statements.

Syntax

switch(condition){
    case 'value1' :
        //code
        [break;]
    case 'value2' :
        //code
        [break;]
    .......
    default :
        //code
        [break;]
}

4. For

For loop is used to iterate a set of statements based on a condition.

for(Initialization; Condition; Increment/decrement){  
//code  
} 

5. While

While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.

while (condition) {  
  // code 
}  

6. Do-While

Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.

do {  
  // code 
} while (condition); 

Classes

ES6 introduced classes along with OOPS concepts in JS. Class is similar to a function which you can think like kind of template which will get called when ever you initialize class.

Syntax:

class className {
  constructor() { ... } //Mandatory Class method
  method1() { ... }
  method2() { ... }
  ...
}

Example:

class Mobile {
  constructor(model) {
    this.name = model;
  }
}

mbl = new Mobile("iPhone");