import { useEffect, useRef, useState } from 'react'
import {Button} from "../comps/button";
import { useText } from "../utils/usetext.jsx";
import { useNavigate } from "react-router-dom";

export default function Keywords() {

    const { getText, getKeywords, selectedKeyword, select } = useText();
    const keywords = getKeywords();
    const rowCount=3;
    const colCount = Math.ceil(keywords.length / rowCount);

    const refContainer=useRef();
    const navigate=useNavigate();


    useEffect(()=>{
        const container=refContainer.current;
        // scroll to center
        container.scrollLeft=(container.scrollWidth-container.clientWidth)/2;

        return () => {
    
        };

    }, [keywords]);

    

  return (
    <main className="!px-0 !justify-between">
        <h1 className="text-[1.125rem]">{getText('title_keywords')}</h1>

        <section className='w-full flex-1 flex items-center justify-center'>
            
            <div ref={refContainer} className="w-full overflow-x-auto">
                <div className='w-[264%] grid grid-cols-6 aspect-[1036/424] overflow-y-hidden'>
                    {keywords.map((keyword, index) => (
                        <div key={index} className="w-full h-full bg-no-repeat relative"                            >
                            <div className="absolute top-[-15%] w-[123%] h-[128%] bg-no-repeat bg-contain flex items-center justify-center"
                                style={{
                                    left: `${15*Math.floor(index/colCount)}%`,
                                    backgroundImage: `url(/topic${selectedKeyword.includes(keyword) ? '_select' : ''}.svg)`,
                                }}
                                onClick={()=>{
                                    console.log('clicked keyword', keyword.title);
                                    select(keyword);
                                }}>
                                <span className="break-word text-center w-[50%]">{keyword.title}</span>
                            </div>
                        </div>
                    ))}
                </div>
            </div>
            
        </section>
        
        <div className="w-full px-[1.5rem]">
            <Button onClick={()=>{
                    navigate('/explore');
                }}
                disabled={selectedKeyword.length<4}
            >
                {getText('button_explore')}
            </Button>
        </div>
    </main>
  );
}