'use client'; import { NewsTileType } from '@utils/validationSchemas'; import { usePathname } from 'next/navigation'; import { useCallback, useEffect, useState } from 'react'; import Tile from './components/Tile'; interface TilesProps { children: React.ReactNode; } export default function Tiles({ children }: TilesProps) { const pathname = usePathname(); const [windowSize, setWindowSize] = useState<{ width: number; height: number; }>({ width: 0, height: 0 }); const [news, setNews] = useState(); useEffect(() => { async function getNews() { const news: NewsTileType[] = await fetch('/api/news').then(res => res.json() ); setNews(news); } if (!news) { getNews(); setWindowSize({ width: window.innerWidth, height: window.innerHeight }); } const handleResize = () => { setWindowSize({ width: window.innerWidth, height: window.innerHeight }); }; window.addEventListener('resize', handleResize); return () => { window.removeEventListener('resize', handleResize); }; }, [news]); const renderTile = useCallback( (key: number) => { if (!news) return
; const randomA = Math.floor(Math.random() * news?.length); const randomB = Math.floor( Math.random() * news?.filter((_, index) => index !== randomA)?.length ); return (
); }, [news] ); const renderRow = useCallback( (columns: number, key: number) => { return (
{Array.from({ length: columns }).map((_, index) => renderTile(index))}
); }, [renderTile] ); const renderGrid = useCallback(() => { const columns = Math.ceil(windowSize.width / (40 * 4)); const rows = Math.ceil(windowSize.height / (40 * 4)); return (
{Array.from({ length: rows }).map((_, index) => renderRow(columns, index) )}
{children}
); }, [children, renderRow, windowSize]); if (pathname === '/maintenance') return
{children}
; return
{renderGrid()}
; }