"use client"

import { useEffect, useState, Suspense } from "react"
import { useRouter, useSearchParams } from "next/navigation"
import RepoByIdClient from "./repo-client"

// Component that uses useSearchParams - needs to be wrapped in Suspense
function RepoPageContent() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const [repositoryId, setRepositoryId] = useState<string>("")
  const [initialPath, setInitialPath] = useState<string>("")
  const [isLoading, setIsLoading] = useState(true)
  
  useEffect(() => {
    const id = searchParams.get('id')
    const path = searchParams.get('path') || ""
    
    if (id) {
      setRepositoryId(id)
      setInitialPath(path)
    }
    setIsLoading(false)
  }, [searchParams])

  if (isLoading) {
    return <div className="mx-auto max-w-3xl px-4 py-10 text-white/80">Loading...</div>
  }

  if (!repositoryId) {
    return (
      <div className="mx-auto max-w-3xl px-4 py-10 text-white/80">
        <h1 className="text-2xl font-semibold">Repository</h1>
        <p className="mt-2">Missing repository id. Go back to <a href="/github/repos" className="text-orange-400 underline">My GitHub Repositories</a>.</p>
      </div>
    )
  }

  return <RepoByIdClient repositoryId={repositoryId} initialPath={initialPath} />
}

export default function Page() {
  return (
    <Suspense fallback={<div className="mx-auto max-w-3xl px-4 py-10 text-white/80">Loading...</div>}>
      <RepoPageContent />
    </Suspense>
  )
}
