import server_names from "@/data/server_names.json";
import servers from "@/data/servers.json";

import top_server_tags_data from "@/data/server_top_tags.json";
import { locales } from '@/utils/locales';

const top_server_tags: {[server: string]: string[]} = top_server_tags_data;

//const ServerCards: React.FC = (topServerIds: number[]) => {
interface Server {
    domain: string;
    description: string;
    proxied_thumbnail: string;
    top_tags: string[];
    languages: string[];
}

// map { code: "be", language: "Беларуская" } to dictionary
const localeDictionary = locales.reduce((acc, locale) => {
  acc[locale.code] = locale.language;
  return acc;
}, {} as { [key: string]: string });

console.log(localeDictionary);
    
const server_data: {[id: number]: Server} = {};
for (let i = 0; i < servers.length; i++) {
    let s_name: string = servers[i].domain;
    let index = server_names.indexOf(s_name);
    if (index > -1) {
        server_data[index] = {
            domain: servers[i].domain,
            description: servers[i].description,
            proxied_thumbnail: servers[i].proxied_thumbnail,
            top_tags: [],
            languages: servers[i].languages
        };
        if (top_server_tags[s_name] !== undefined) {
            server_data[index].top_tags = top_server_tags[s_name];
        }
    };
};

export function ServerCards(props: {topServerIds: number[], tagCount: number}) {
  let server_info = props.topServerIds.map((id) => server_data[id]);
  return (
    <div>
    {props.tagCount >= 2 ? (
      <div className='col-span-4 md:col-start-4 md:col-end-13'>
        <div className='grid gap-gutter sm:grid-cols-2 md:grid-cols-2 xl:grid-cols-4'>
          {server_info.filter((data) => data !== undefined).map((data) => (
            <div key={data.domain} className='grid grid-rows-[auto_1fr_auto] rounded-md border border-gray-3 p-4'>
              <div>
                <img src={data.proxied_thumbnail} decoding='async' />
              </div>
              <div className='pb-5'>
                <p className='b1 !font-700 font-bold mb-2 text-lg'>{data.domain}</p>
                <p>{data.languages.map((lang) => (
                  <span className="mr-1 text-xs" key={lang}>{localeDictionary[lang]}</span>
                ))}</p>
                <p className='b3 line-clamp-5 [unicode-bidi:plaintext] text-sm'>{data.description}</p>
                <ul>
                  {data.top_tags.map((tag) => (
                    <li key={tag} className={`inline-block ${tag.endsWith("_sensitive") ? 'bg-red-100' : 'bg-gray-100'} text-gray-800 px-2 py-1 text-xs mr-2 mb-2 uppercase font-mono`}>{tag.split('_')[0]}</li>
                  ))}
                </ul>
              </div>
            </div>
          ))}
        </div>
      </div>
    ) : (
      <div>Please select at least two tags.</div>
    )}
    </div>
    );
}