import { useParams } from "react-router-dom";
import { useLiveParticle } from "@/hooks/use-particle";
import { particlePath } from "@/lib/particle-path";
import { isContainerType } from "@/api/types";
import { StreamView } from "@/features/particles/stream-view";
import { FolderView } from "@/features/particles/folder-view";
import { ParticleListView } from "@/features/particles/particle-list-view";

/**
 * Route-level component for /:networkId/*.
 * Reads params from the router, resolves the particle, and renders
 * the appropriate view based on particle type.
 */
export default function ParticleViewResolver() {
  const { networkId, "*": rest } = useParams();
  const segments = (rest ?? "").split("/").filter(Boolean);
  const path = particlePath(networkId!, segments); // path of current container particle

  const { particle, isLoading, error } = useLiveParticle(path);

  if (isLoading) {
    return (
      <div className="flex h-full items-center justify-center">
        <p className="text-muted-foreground text-sm">Loading...</p>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex h-full items-center justify-center">
        <p className="text-destructive text-sm">Failed to load particle</p>
      </div>
    );
  }

  if (!particle) {
    return (
      <div className="flex h-full items-center justify-center">
        <p className="text-muted-foreground text-sm">
          Particle: {segments.join(" / ")}
        </p>
      </div>
    );
  }

  switch (particle.type) {
    case "stream":
      return <StreamView streamParticle={particle} path={path} />;
    case "folder":
      return <FolderView folderParticle={particle} path={path} />;
    default:
      if (isContainerType(particle.type)) {
        return <ParticleListView path={path} />;
      }
      return (
        <div className="flex h-full items-center justify-center">
          <p className="text-muted-foreground text-sm">
            {particle.type} particle: {particle.id}
          </p>
        </div>
      );
  }
}
