
'use client';

import * as React from 'react';
import { Suspense } from 'react';
import { FileBrowser } from '@/components/file-browser';
import type { FileSystemNode } from '@/app/api/files/route';
import { FileBrowserSkeleton } from '@/components/file-browser-skeleton';
import { SplashScreen } from '@/components/splash-screen';

async function getFileSystemData(): Promise<FileSystemNode[]> {
  const res = await fetch(`/api/files`, { cache: 'no-store' });
  if (!res.ok) {
    console.error('Failed to fetch file system data', res.status, res.statusText);
    throw new Error('Failed to fetch file system data');
  }
  const data = await res.json();
  return data as FileSystemNode[];
}

function FileBrowserComponent({ onDataLoaded }: { onDataLoaded: () => void }) {
  const [data, setData] = React.useState<FileSystemNode[] | null>(null);

  React.useEffect(() => {
    getFileSystemData().then(fetchedData => {
      setData(fetchedData);
      onDataLoaded();
    });
  }, [onDataLoaded]);

  if (!data) {
    return <FileBrowserSkeleton />;
  }

  const rootFolder = {
      id: 'root',
      type: 'folder' as const,
      name: 'Files',
      path: '/',
      children: data,
  };

  return <FileBrowser initialData={rootFolder} />;
}


export default function Home() {
  const [isAppLoading, setIsAppLoading] = React.useState(true);

  React.useEffect(() => {
    const timer = setTimeout(() => {
       handleDataLoaded();
    }, 2000); 

    return () => clearTimeout(timer);
  }, []);

  const handleDataLoaded = () => {
    setIsAppLoading(false);
  };

  return (
    <main>
      <SplashScreen isVisible={isAppLoading} />
      <div className={`transition-opacity duration-500 ${isAppLoading ? 'opacity-0' : 'opacity-100'}`}>
        <Suspense fallback={<FileBrowserSkeleton />}>
          <FileBrowserComponent onDataLoaded={handleDataLoaded} />
        </Suspense>
      </div>
    </main>
  );
}
