'use client';
import { RenderComponents } from '@/src/components/builder/config/renderComponent';
import { BuilderProvider } from '@/src/components/builder/context/BuilderContext';
import { BuilderSkeleton } from '@/src/components/skeletons/BuilderSkeleton';
import { usePublishedPortfolio } from '@/src/services/PortfolioService';
import { setGlobalColors } from '@/src/lib/theme';
import { setGlobalTypography } from '@/src/lib/typography';
import { notFound, useParams } from 'next/navigation';

export default function Page() {
  const { username, portfolioTitle } = useParams();
  const { portfolio, isLoading, error, projects } = usePublishedPortfolio(username as string, portfolioTitle as string);

  if (isLoading) {
    return <BuilderSkeleton />;
  }

  if (error || !portfolio || !projects) {
    return notFound();
  }

  if (portfolio) {
    if (portfolio.config.colors) {
      setGlobalColors(portfolio.config.colors);
    }
    if (portfolio.config.typography) {
      setGlobalTypography(portfolio.config.typography);
    }
  }

  return (
    <BuilderProvider value={{ isPreview: true, portfolioProjects: projects }}>
      <div
        className='flex flex-col gap-0 w-full items-center bg-[var(--color-background)] text-[var(--color-text)]'
        style={{
          fontFamily: portfolio.config.typography?.textFontFamily,
        }}
      >
        <div className='w-full'>
          <div className=''>
              <style>{`
              ::selection {
                background: var(--color-accent);
                color: var(--color-background);
              }
            `}</style>
            <RenderComponents elements={portfolio.config.elements} />
          </div>
        </div>
      </div>
    </BuilderProvider>
  );
}
