import * as React from 'react';

import { GameDetails } from 'mweb/common/reducers/data/games';
import { BoxArtListItemCard } from 'mweb/common/components/boxArtCard';
import { List } from 'mweb/common/components/list';
import {
  estimateImageCountForViewport,
  ImageType,
} from 'mweb/common/utils/estimateImageCountForViewport';
import { extendInteractionMedium } from 'mweb/common/tracking/extendInteractionMedium';
import { BOX_ART_ASPECT_RATIO } from 'mweb/common/utils/imageUtils';

if (process.env.BROWSER) {
  require('./gameList.sass');
}

export interface GameListProps {
  games: GameDetails[];
  getNextPage: () => void;
}

const INITIAL_PAGE_SIZE = 12;
const BOX_ART_METADATA_HEIGHT = 50;
const INTERACTION_MEDIUM = 'game_list';
const BOX_ART_SIZES = [
  {
    size: '47vw',
    mediaCondition: '(max-width: 540px) and (orientation: portrait)',
  },
  { size: '24vw' },
];

export class GameList extends React.Component<GameListProps, {}> {
  totalLatencyCount: number = 0;

  constructor(props: GameListProps) {
    super(props);

    if (process.env.BROWSER) {
      this.totalLatencyCount = Math.min(
        INITIAL_PAGE_SIZE,
        estimateImageCountForViewport(
          BOX_ART_ASPECT_RATIO,
          BOX_ART_METADATA_HEIGHT,
          ImageType.BoxArt,
        ),
      );
    }
  }

  itemRenderer = (index: number, key: string): JSX.Element => {
    const game = this.props.games[index];
    return (
      <BoxArtListItemCard
        key={key}
        title={game.name}
        imageTemplate={game.boxArtURL}
        isLatencyCritical={index < this.totalLatencyCount}
        position={index}
        viewCount={game.viewersCount}
        srcSetSizes={BOX_ART_SIZES}
      />
    );
  };

  render(): JSX.Element {
    return (
      <List
        itemRenderer={this.itemRenderer}
        length={this.props.games.length}
        getNextPage={this.props.getNextPage}
        className="game-list"
        initialPageSize={INITIAL_PAGE_SIZE}
      />
    );
  }
}

export default extendInteractionMedium(GameList, INTERACTION_MEDIUM);
