"use client"

import { useMemo, useState, useEffect, type ReactNode } from "react"
import { useRouter } from "next/navigation"
import { AnimatePresence, motion } from "motion/react"
import {
  ArrowRight,
  ArrowRightCircle,
  Check,
  ChevronLeft,
  ExternalLink,
  KeyRound,
  Terminal,
} from "lucide-react"

import LogoBox from "@/components/dashboard/logo-box"
import { Button } from "@/components/ui/button"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Input } from "@/components/ui/input"
import { ApiKeyCard, StepInstruction } from "@/components/onboarding/step-content-renderer"
import { generateToken } from "@/app/(dashboard)/apikeys/tokenfuncs"
import { getUserId } from "@/app/utils/auth"
import { completeUserOnboarding } from "./onboarding-action"

type ExperienceOption = "cli" | "vscode"

interface StepsState {
  current: {
    cli: number
  }
  completed: {
    cli: number[]
  }
}

interface ApiKeyState {
  name: string
  key: string
  error: string
}

const INSTALLATION_COMMANDS = {
  pip: "pip install codeflash",
  poetry: "poetry add codeflash --dev",
  uv: "uv add --dev codeflash",
}

const VS_MARKETPLACE_URL = "https://marketplace.visualstudio.com/items?itemName=codeflash.codeflash"
const OPEN_VSX_URL = "https://open-vsx.org/extension/codeflash/codeflash"

const fadeInAnimation = {
  initial: { opacity: 0, y: 20 },
  animate: { opacity: 1, y: 0 },
  transition: { duration: 0.6 },
} as const

const defaultApiKeyState: ApiKeyState = {
  name: "Secret Key",
  key: "",
  error: "",
}

const defaultStepsState: StepsState = {
  current: { cli: 0 },
  completed: { cli: [] },
}

export default function OnboardingPage() {
  const router = useRouter()
  const [loading, setLoading] = useState(true)
  const [showIntro, setShowIntro] = useState(true)
  const [userId, setUserId] = useState<string>("")

  const [experience, setExperience] = useState<ExperienceOption>("vscode")
  const [stepsState, setStepsState] = useState<StepsState>(defaultStepsState)
  const [activeInitStep, setActiveInitStep] = useState(1)
  const [apiKeyState, setApiKeyState] = useState<ApiKeyState>(defaultApiKeyState)
  const [generatingKey, setGeneratingKey] = useState(false)
  const [isMobile, setIsMobile] = useState(false)

  const steps = useMemo(
    () => [
      { id: 0, title: "Choose how you want to use Codeflash" },
      {
        id: 1,
        title: experience === "vscode" ? "VS Code Extension Setup" : "CLI & GitHub Actions Setup",
      },
      { id: 2, title: "You're all set" },
    ],
    [experience],
  )

  const getCurrentStep = (): number => stepsState.current.cli
  const getCompletedSteps = (): number[] => stepsState.completed.cli
  const getSteps = () => steps

  useEffect(() => {
    // Reduced from 2400ms to 1200ms to improve LCP — the intro blocks
    // the main content which is the Largest Contentful Paint element.
    const timer = showIntro ? setTimeout(() => setShowIntro(false), 1200) : null
    return () => {
      if (timer) clearTimeout(timer)
    }
  }, [showIntro])

  useEffect(() => {
    const checkOnboardingStatus = async () => {
      try {
        const currentUserId = await getUserId()
        if (!currentUserId) {
          router.replace("/login")
          setLoading(false)
          return
        }

        setUserId(currentUserId)
      } catch (error) {
        console.error("Failed to load onboarding prerequisites:", error)
      } finally {
        setLoading(false)
      }
    }

    checkOnboardingStatus()
  }, [router])

  useEffect(() => {
    const updateIsMobile = () => {
      if (typeof window !== "undefined") {
        setIsMobile(window.innerWidth < 768)
      }
    }

    updateIsMobile()
    window.addEventListener("resize", updateIsMobile)

    return () => {
      window.removeEventListener("resize", updateIsMobile)
    }
  }, [])

  const nextStep = async () => {
    const currentStep = getCurrentStep()
    const stepsArr = getSteps()
    const isLastStep = currentStep === stepsArr.length - 1
    const wasAlreadyCompleted = getCompletedSteps().includes(currentStep)

    if (!wasAlreadyCompleted) {
      setStepsState(prev => ({
        ...prev,
        completed: {
          ...prev.completed,
          cli: [...prev.completed.cli, currentStep],
        },
      }))
    }

    if (!isLastStep) {
      setStepsState(prev => ({
        ...prev,
        current: {
          ...prev.current,
          cli: prev.current.cli + 1,
        },
      }))
    } else {
      await handleCompleteOnboarding()
    }
  }

  const prevStep = () => {
    setStepsState(prev => ({
      ...prev,
      current: {
        ...prev.current,
        cli: Math.max(prev.current.cli - 1, 0),
      },
    }))
  }

  const handleExperienceSelect = (option: ExperienceOption) => {
    setExperience(option)
    setStepsState(prev => ({
      ...prev,
      current: {
        ...prev.current,
        cli: 1,
      },
      completed: {
        ...prev.completed,
        cli: prev.completed.cli.includes(0) ? prev.completed.cli : [...prev.completed.cli, 0],
      },
    }))

    if (option === "cli") {
      setActiveInitStep(1)
      setApiKeyState(defaultApiKeyState)
    }
  }

  const handleSkipOnboarding = async () => {
    try {
      if (userId) {
        await completeUserOnboarding(userId)
      }
      router.push("/app/apikeys")
    } catch (error) {
      console.error("Failed to mark onboarding as skipped:", error)
    }
  }

  const handleCompleteOnboarding = async () => {
    try {
      if (userId) {
        await completeUserOnboarding(userId)
      }
      sessionStorage.setItem("showOnboardingConfetti", "true")
      router.push("/app/apikeys")
    } catch (error) {
      console.error("Failed to mark onboarding as completed:", error)
    }
  }

  const handleGitHubAppInstall = () => {
    window.open("https://github.com/apps/codeflash-ai/installations/select_target", "_blank")
    markInitStep(4)
  }

  const handleGenerateApiKey = async (): Promise<void> => {
    if (!apiKeyState.name.trim()) {
      setApiKeyState(prev => ({
        ...prev,
        error: "API Key Name is required",
      }))
      return
    }

    setGeneratingKey(true)
    setApiKeyState(prev => ({
      ...prev,
      error: "",
    }))

    try {
      const data = await generateToken(apiKeyState.name)
      if (data.success) {
        setApiKeyState(prev => ({
          ...prev,
          key: data.token ?? "",
        }))
        markInitStep(4)
      } else {
        setApiKeyState(prev => ({
          ...prev,
          error: data.err ?? "Failed to generate API key. Please try again.",
        }))
      }
    } catch (error) {
      console.error("Failed to generate token:", error)
      setApiKeyState(prev => ({
        ...prev,
        error: "Failed to generate API key. Please try again.",
      }))
    } finally {
      setGeneratingKey(false)
    }
  }

  const markInitStep = (step: number) => setActiveInitStep(prev => (prev < step ? step : prev))

  const getInitStatus = (target: number) => {
    if (activeInitStep === target) return "active"
    if (activeInitStep > target) return "completed"
    return "default"
  }

  if (loading) {
    return (
      <div className="flex justify-center items-center min-h-screen bg-background">
        <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary"></div>
      </div>
    )
  }

  if (showIntro) {
    return (
      <div className="flex flex-col items-center justify-center min-h-screen bg-background">
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ duration: 0.5 }}
        >
          <motion.div
            initial={{ scale: 0.8, opacity: 0 }}
            animate={{ scale: 1, opacity: 1 }}
            transition={{
              type: "spring",
              stiffness: 260,
              damping: 20,
              delay: 0.1,
            }}
          >
            <LogoBox />
          </motion.div>

          <motion.h1
            className="text-3xl font-bold mt-6 text-foreground tracking-tight text-center"
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.4, delay: 0.3 }}
          >
            Getting Started
          </motion.h1>

          <motion.p
            className="text-muted-foreground mt-3 text-center max-w-sm font-medium"
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.4, delay: 0.5 }}
          >
            {"Let's set up your Codeflash account"}
          </motion.p>

          <motion.div
            initial={{ width: 0 }}
            animate={{ width: 120 }}
            transition={{ duration: 0.6, delay: 0.6, ease: "easeInOut" }}
            className="h-1 bg-primary/80 rounded-full mt-8 mx-auto"
          />
        </motion.div>
      </div>
    )
  }

  const totalSteps = getSteps().length
  const currentStepIndex = getCurrentStep()

  return (
    <div className="min-h-screen bg-background">
      {currentStepIndex > 0 && (
        <div className="fixed top-0 left-0 w-full h-1 bg-muted z-50">
          <motion.div
            className="h-full bg-primary"
            initial={{ width: `${((currentStepIndex - 1) / (totalSteps - 1)) * 100}%` }}
            animate={{ width: `${(currentStepIndex / (totalSteps - 1)) * 100}%` }}
            transition={{ duration: 0.4 }}
          />
        </div>
      )}

      <AnimatePresence mode="wait">
        <motion.div
          key={`${currentStepIndex}-${experience}`}
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          transition={{ duration: 0.4 }}
          className="min-h-screen flex flex-col"
        >
          {currentStepIndex === 0 && (
            <div className="min-h-screen flex flex-col p-6">
              <Header onSkip={handleSkipOnboarding} isMobile={isMobile} />

              <main className="flex-grow flex flex-col items-center max-w-4xl mx-auto pt-10 pb-12">
                <motion.div {...fadeInAnimation} className="w-full space-y-8">
                  <div className="text-center space-y-3">
                    <h1 className="text-3xl font-semibold text-foreground">
                      How do you want to use Codeflash?
                    </h1>
                  </div>

                  <div className="grid gap-6 md:grid-cols-2">
                    <ExperienceCard
                      icon={
                        <svg
                          xmlns="http://www.w3.org/2000/svg"
                          viewBox="0 0 24 24"
                          width="24"
                          height="24"
                          fill="none"
                          stroke="currentColor"
                          strokeWidth="2"
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          className="text-primary"
                        >
                          <path d="M15.5 4.5 9 12l6.5 7.5L21 17V7l-5.5-2.5Z"></path>
                          <path d="M9 12 3 7.5v9L9 12Z"></path>
                        </svg>
                      }
                      title="VS Code / Cursor Extension"
                      //description="Stay in flow with inline suggestions, CodeLens, and instant optimization diffs."
                      selected={experience === "vscode"}
                      onSelect={() => handleExperienceSelect("vscode")}
                      useCases={[]}
                      cta="Optimize your code locally within the IDE with easy one-click optimizations and setup auto-optimization for your new code with every git commit."
                      tag="Recommended for developers & getting started"
                      tagTone="primary"
                    />
                    <ExperienceCard
                      icon={<Terminal className="w-6 h-6 text-primary" />}
                      title="CLI & GitHub Actions"
                      //description="Automate high-impact performance improvements directly in your repositories."
                      selected={experience === "cli"}
                      onSelect={() => handleExperienceSelect("cli")}
                      useCases={[]}
                      cta="Optimize your entire codebase and end to end workflows with the CLI, or automate optimization for every Pull Request with GitHub Actions."
                      tag="Recommended for teams & projects"
                      //tagTone="muted"
                    />
                  </div>
                </motion.div>
              </main>
            </div>
          )}

          {currentStepIndex === 1 && experience === "cli" && (
            <div className="min-h-screen flex flex-col p-6">
              <Header onSkip={handleSkipOnboarding} isMobile={isMobile} />

              <main className="flex-grow flex flex-col items-center justify-start max-w-4xl mx-auto pt-6 pb-12">
                <motion.div {...fadeInAnimation} className="w-full space-y-10">
                  <section className="space-y-6">
                    <div>
                      <h1 className="text-3xl font-semibold text-foreground mb-2">
                        CLI & GitHub Actions Setup
                      </h1>
                    </div>
                  </section>

                  <section className="space-y-6">
                    <StepInstruction
                      number={1}
                      title="Install the Codeflash CLI"
                      status={getInitStatus(1)}
                    >
                      <p className="text-sm text-muted-foreground mb-3 font-medium">
                        Install Codeflash in the repository you want to optimize using your
                        preferred package manager.
                      </p>
                      <Tabs defaultValue="pip" className="w-full">
                        <TabsList className="w-full justify-start mb-4">
                          <TabsTrigger value="pip" className="font-medium">
                            pip
                          </TabsTrigger>
                          <TabsTrigger value="poetry" className="font-medium">
                            Poetry
                          </TabsTrigger>
                          <TabsTrigger value="uv" className="font-medium">
                            uv
                          </TabsTrigger>
                        </TabsList>

                        <AnimatePresence mode="wait">
                          {Object.entries(INSTALLATION_COMMANDS).map(([manager, command]) => (
                            <TabsContent key={manager} value={manager} className="mt-0 w-full">
                              <motion.div
                                initial={{ opacity: 0, y: 5 }}
                                animate={{ opacity: 1, y: 0 }}
                                exit={{ opacity: 0, y: -5 }}
                                transition={{ duration: 0.2 }}
                              >
                                <ApiKeyCard
                                  label="Terminal"
                                  value={command}
                                  onCopied={() => markInitStep(2)}
                                />
                                {manager !== "pip" && (
                                  <p className="text-sm text-muted-foreground mt-2 font-medium max-w-md">
                                    Installs Codeflash as a development dependency (recommended). To
                                    install it as a main dependency, remove the --dev flag.
                                  </p>
                                )}
                              </motion.div>
                            </TabsContent>
                          ))}
                        </AnimatePresence>
                      </Tabs>
                    </StepInstruction>

                    <div className="space-y-6">
                      <StepInstruction
                        number={2}
                        title="Run the initialization command"
                        status={getInitStatus(2)}
                      >
                        <p className="text-sm text-muted-foreground mb-3 font-medium">
                          Run this at the directory where your pyproject.toml file is located for
                          the project. codeflash init will ask you to login, and then a few
                          questions about your project like the location of your code and tests.
                          <a
                            href="https://docs.codeflash.ai/getting-started/local-installation"
                            target="_blank"
                            className="text-primary hover:underline ml-1"
                          >
                            Docs
                          </a>
                        </p>
                        <ApiKeyCard
                          label="Terminal"
                          value="codeflash init"
                          onCopied={() => markInitStep(3)}
                        />
                      </StepInstruction>

                      <StepInstruction
                        number={3}
                        title="Optional: Generate a Codeflash API Key"
                        status={getInitStatus(3)}
                      >
                        {!apiKeyState.key ? (
                          <div className="space-y-4">
                            <p className="text-sm text-muted-foreground font-medium">
                              Generate an API key to authenticate your GitHub actions or optionally
                              CLI sessions. You can manage your keys in the dashboard.
                            </p>

                            <div className="flex flex-col md:flex-row md:items-center gap-3">
                              <Input
                                value={apiKeyState.name}
                                onChange={e =>
                                  setApiKeyState(prev => ({
                                    ...prev,
                                    name: e.target.value,
                                    error: "",
                                  }))
                                }
                                className="h-12 flex-1"
                                placeholder="API key name"
                              />
                              <Button
                                onClick={handleGenerateApiKey}
                                disabled={!apiKeyState.name.trim() || generatingKey}
                                variant="outline"
                                className="border-amber-500/30 bg-amber-500/10 hover:bg-amber-500/20 text-amber-700 font-medium"
                              >
                                {generatingKey ? (
                                  <>
                                    <span className="animate-spin mr-2">⟳</span>
                                    Generating...
                                  </>
                                ) : (
                                  <>
                                    <KeyRound className="w-4 h-4 mr-2" />
                                    Generate API Key
                                  </>
                                )}
                              </Button>
                            </div>

                            {apiKeyState.error && (
                              <p className="text-red-500 text-sm font-medium">
                                {apiKeyState.error}
                              </p>
                            )}
                          </div>
                        ) : (
                          <div className="space-y-5">
                            <p className="text-sm text-muted-foreground font-medium">
                              Paste this key when{" "}
                              <code className="px-1 py-0.5 bg-muted rounded">codeflash init</code>{" "}
                              prompts you for it, or export it as an environment variable in your
                              shell rc file
                            </p>

                            <ApiKeyCard label="API Key" value={apiKeyState.key} />
                            <ApiKeyCard
                              label="Environment Variable"
                              value={`export CODEFLASH_API_KEY='${apiKeyState.key}'`}
                            />
                          </div>
                        )}
                      </StepInstruction>

                      <StepInstruction
                        number={4}
                        title="Install the Codeflash GitHub App"
                        status={getInitStatus(4)}
                      >
                        <div className="space-y-4">
                          <p className="text-sm text-muted-foreground font-medium">
                            Codeflash requires this to open pull requests with the optimizations for
                            your review. If you are unable to install the GitHub App, then we would
                            recommend you to instead use the VS Code Extesnsion that does not
                            require the GitHub App.
                          </p>
                          <Button
                            className="bg-[#24292f] hover:bg-[#0d1117] text-white transition-colors duration-200 w-auto px-6 py-5 font-medium"
                            onClick={handleGitHubAppInstall}
                          >
                            Install GitHub App
                            <ExternalLink className="w-4 h-4 ml-2" />
                          </Button>
                        </div>
                      </StepInstruction>
                    </div>
                  </section>

                  <NavigationButtons
                    currentStep={currentStepIndex}
                    onBack={prevStep}
                    onNext={nextStep}
                  />
                </motion.div>
              </main>
            </div>
          )}

          {currentStepIndex === 1 && experience === "vscode" && (
            <div className="min-h-screen flex flex-col p-6">
              <Header onSkip={handleSkipOnboarding} isMobile={isMobile} />

              <main className="flex-grow flex flex-col items-center justify-start max-w-4xl mx-auto pt-6 pb-12">
                <motion.div {...fadeInAnimation} className="w-full space-y-10">
                  <section className="space-y-6">
                    <div>
                      <h1 className="text-3xl font-semibold text-foreground mb-2">
                        VS Code Extension Installation
                      </h1>
                    </div>
                  </section>

                  <section className="grid gap-6 md:grid-cols-2">
                    <div className="bg-card border border-border rounded-xl p-6 shadow-sm space-y-4">
                      <h2 className="text-lg font-semibold text-foreground">
                        Install from VS Code Marketplace
                      </h2>
                      <p className="text-sm text-muted-foreground font-medium">
                        Search for <strong>Codeflash</strong> inside VS Code or open the listing
                        below. You will need VS Code 1.94.0 (September 2024) or newer.
                      </p>
                      <Button asChild className="w-full gap-2 font-medium" variant="secondary">
                        <a href={VS_MARKETPLACE_URL} target="_blank" rel="noopener noreferrer">
                          Open Marketplace listing
                          <ExternalLink className="w-4 h-4" />
                        </a>
                      </Button>
                    </div>

                    <div className="bg-card border border-border rounded-xl p-6 shadow-sm space-y-4">
                      <h2 className="text-lg font-semibold text-foreground">Install via VSIX</h2>
                      <p className="text-sm text-muted-foreground font-medium">
                        Using Cursor, Windsurf, VS Code desktop offline without marketplace access?
                        Download the VSIX package and install it manually.
                      </p>
                      <Button asChild className="w-full gap-2 font-medium" variant="outline">
                        <a href={OPEN_VSX_URL} target="_blank" rel="noopener noreferrer">
                          Download VSIX
                          <ExternalLink className="w-4 h-4" />
                        </a>
                      </Button>
                    </div>
                  </section>

                  <NavigationButtons
                    currentStep={currentStepIndex}
                    onBack={prevStep}
                    onNext={nextStep}
                    nextLabel="Continue"
                  />
                </motion.div>
              </main>
            </div>
          )}

          {currentStepIndex === 2 && (
            <div className="min-h-screen flex flex-col p-6">
              <Header onSkip={handleSkipOnboarding} isMobile={isMobile} />

              <main className="flex-grow flex flex-col items-center justify-start max-w-4xl mx-auto pt-6 pb-12">
                <motion.div
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ duration: 0.5 }}
                  className="w-full space-y-8"
                >
                  <div className="text-center mb-10 relative">
                    <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-32 h-32 md:w-40 md:h-40 bg-primary/10 rounded-full blur-2xl -z-10"></div>

                    <div className="inline-block mb-6 relative">
                      <div className="flex items-center justify-center p-4 bg-gradient-to-b from-primary/20 to-transparent rounded-full shadow-sm">
                        <svg
                          xmlns="http://www.w3.org/2000/svg"
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          strokeWidth="2"
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          className="w-12 h-12 text-primary"
                        >
                          <path d="M6 9H4.5a2.5 2.5 0 0 1 0-5H6"></path>
                          <path d="M18 9h1.5a2.5 2.5 0 0 0 0-5H18"></path>
                          <path d="M4 22h16"></path>
                          <path d="M10 14.66V17c0 .55-.47.98-.97 1.21C7.85 18.75 7 20.24 7 22"></path>
                          <path d="M14 14.66V17c0 .55.47.98.97 1.21C16.15 18.75 17 20.24 17 22"></path>
                          <path d="M9 2v7.5"></path>
                          <path d="M15 2v7.5"></path>
                          <path d="M12 12a4 4 0 0 0 4-4V4a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v4a4 4 0 0 0 4 4Z"></path>
                        </svg>
                      </div>
                    </div>

                    <h3 className="text-2xl md:text-3xl font-bold text-primary">
                      🎉 Setup Complete! 🎉
                    </h3>
                    <p className="text-muted-foreground font-medium max-w-xl mx-auto">
                      {experience === "cli"
                        ? "You’ve finished connecting the CLI. Here are a few power moves to ship faster."
                        : "VS Code and Codeflash are talking! Try these quick wins to keep optimizations at your fingertips."}
                    </p>
                  </div>

                  {experience === "cli" ? (
                    <div className="space-y-4 max-w-2xl mx-auto">
                      <div className="bg-card p-5 rounded-lg border border-border hover:border-primary/40 transition-all duration-300 shadow-sm">
                        <h4 className="font-medium mb-3 flex items-center">
                          <div className="flex items-center justify-center p-1.5 bg-primary/10 rounded-md mr-2">
                            <svg
                              xmlns="http://www.w3.org/2000/svg"
                              viewBox="0 0 24 24"
                              width="16"
                              height="16"
                              fill="none"
                              stroke="currentColor"
                              strokeWidth="2"
                              strokeLinecap="round"
                              strokeLinejoin="round"
                              className="text-primary"
                            >
                              <path d="M15.5 4.5 9 12l6.5 7.5L21 17V7l-5.5-2.5Z"></path>
                              <path d="M9 12 3 7.5v9L9 12Z"></path>
                            </svg>
                          </div>
                          Install VS Code Extension
                          <span className="ml-2 text-xs bg-amber-500/10 text-amber-600 dark:text-amber-500 px-2 py-0.5 rounded font-medium">
                            Beta
                          </span>
                        </h4>
                        <p className="text-sm text-muted-foreground mb-3 font-medium">
                          Get Codeflash directly in your VS Code editor for a seamless development
                          experience.
                        </p>
                        <a
                          href="https://marketplace.visualstudio.com/items?itemName=codeflash.codeflash"
                          target="_blank"
                          rel="noopener noreferrer"
                          className="inline-flex items-center gap-2 text-sm text-primary hover:text-primary/80 font-medium"
                        >
                          Install from VS Code Marketplace
                          <ExternalLink className="w-4 h-4" />
                        </a>
                      </div>
                      <SuggestionCard
                        title="Optimize the repo you just initialized"
                        command="codeflash --all"
                        icon={
                          <svg
                            xmlns="http://www.w3.org/2000/svg"
                            width="16"
                            height="16"
                            viewBox="0 0 24 24"
                            fill="none"
                            stroke="currentColor"
                            strokeWidth="2"
                            strokeLinecap="round"
                            strokeLinejoin="round"
                            className="text-primary"
                          >
                            <path d="m8 3 4 8 5-5 5 15H2L8 3z"></path>
                          </svg>
                        }
                        docsHref="https://docs.codeflash.ai/optimizing-with-codeflash/codeflash-all"
                        docsLabel="Docs: Optimize your entire codebase"
                      />
                      <SuggestionCard
                        title="Target a workflow or benchmark"
                        command="codeflash optimize benchmark.py"
                        icon={
                          <svg
                            xmlns="http://www.w3.org/2000/svg"
                            width="16"
                            height="16"
                            viewBox="0 0 24 24"
                            fill="none"
                            stroke="currentColor"
                            strokeWidth="2"
                            strokeLinecap="round"
                            strokeLinejoin="round"
                            className="text-primary"
                          >
                            <circle cx="12" cy="12" r="10"></circle>
                            <path d="m8 12 3 3 5-5"></path>
                          </svg>
                        }
                        docsHref="https://docs.codeflash.ai/optimizing-with-codeflash/trace-and-optimize"
                        docsLabel="Docs: Trace & Optimize E2E Workflows"
                      />
                      <SuggestionCard
                        title="Improve a single function"
                        command="codeflash --file path/to/your/file.py --function function_name"
                        icon={
                          <svg
                            xmlns="http://www.w3.org/2000/svg"
                            width="16"
                            height="16"
                            viewBox="0 0 24 24"
                            fill="none"
                            stroke="currentColor"
                            strokeWidth="2"
                            strokeLinecap="round"
                            strokeLinejoin="round"
                            className="text-primary"
                          >
                            <rect width="18" height="18" x="3" y="3" rx="2" ry="2"></rect>
                            <path d="M9 9h6v6H9z"></path>
                          </svg>
                        }
                        docsHref="https://docs.codeflash.ai/optimizing-with-codeflash/one-function"
                        docsLabel="Docs: Optimize a Single Function"
                      />
                      <SuggestionCard
                        title="Set up GitHub Actions"
                        command="codeflash init-actions"
                        icon={
                          <svg
                            xmlns="http://www.w3.org/2000/svg"
                            width="16"
                            height="16"
                            viewBox="0 0 24 24"
                            fill="none"
                            stroke="currentColor"
                            strokeWidth="2"
                            strokeLinecap="round"
                            strokeLinejoin="round"
                            className="text-primary"
                          >
                            <path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"></path>
                          </svg>
                        }
                        docsHref="https://docs.codeflash.ai/optimizing-with-codeflash/codeflash-github-actions"
                        docsLabel="Docs: GitHub Actions"
                      />
                    </div>
                  ) : (
                    <div className="space-y-4 max-w-2xl mx-auto">
                      <ExtensionSuggestion
                        icon={
                          <svg
                            xmlns="http://www.w3.org/2000/svg"
                            width="16"
                            height="16"
                            viewBox="0 0 24 24"
                            fill="none"
                            stroke="currentColor"
                            strokeWidth="2"
                            strokeLinecap="round"
                            strokeLinejoin="round"
                            className="text-primary"
                          >
                            <path d="m5 3 3 9"></path>
                            <path d="m2 9 3 3"></path>
                            <path d="m13 9 3 3"></path>
                            <path d="m10 9 3-6"></path>
                            <path d="m16 21 3-6"></path>
                            <path d="m8 21 3-6"></path>
                          </svg>
                        }
                        title="See inline hints"
                        description="Open a Python file and you’ll immediately see which functions Codeflash recommends optimizing with `optimize` button."
                      />
                      <ExtensionSuggestion
                        icon={
                          <svg
                            xmlns="http://www.w3.org/2000/svg"
                            width="16"
                            height="16"
                            viewBox="0 0 24 24"
                            fill="none"
                            stroke="currentColor"
                            strokeWidth="2"
                            strokeLinecap="round"
                            strokeLinejoin="round"
                            className="text-primary"
                          >
                            <rect width="18" height="18" x="3" y="3" rx="2"></rect>
                            <path d="M3 15h18"></path>
                            <path d="M12 3v12"></path>
                          </svg>
                        }
                        title="Monitor progress"
                        description="The extension sidebar shows queued, running, and completed optimizations at a glance."
                      />
                      <ExtensionSuggestion
                        icon={
                          <svg
                            xmlns="http://www.w3.org/2000/svg"
                            width="16"
                            height="16"
                            viewBox="0 0 24 24"
                            fill="none"
                            stroke="currentColor"
                            strokeWidth="2"
                            strokeLinecap="round"
                            strokeLinejoin="round"
                            className="text-primary"
                          >
                            <path d="M6.5 6.5 11 11"></path>
                            <path d="M13 13 17.5 17.5"></path>
                            <path d="M19 11a8 8 0 0 1-8 8"></path>
                            <path d="M5 13a8 8 0 0 1 8-8"></path>
                            <path d="M8 21h8"></path>
                            <path d="M12 17v4"></path>
                          </svg>
                        }
                        title="Pair with the CLI"
                        description="Kick off batch runs with the terminal"
                      />
                    </div>
                  )}

                  <div className="flex justify-between items-center pt-6">
                    <Button variant="outline" onClick={prevStep} className="gap-2 font-medium">
                      <ChevronLeft className="w-4 h-4" />
                      Back
                    </Button>
                    <Button
                      onClick={handleCompleteOnboarding}
                      className="px-8 py-6 rounded-lg gap-2 bg-gradient-to-r from-primary to-primary/90 hover:from-primary/90 hover:to-primary font-medium"
                      size="lg"
                    >
                      Go to Dashboard
                      <ArrowRightCircle className="w-5 h-5 ml-1" />
                    </Button>
                  </div>
                </motion.div>
              </main>
            </div>
          )}
        </motion.div>
      </AnimatePresence>
    </div>
  )
}

function Header({ onSkip, isMobile }: { onSkip: () => void; isMobile: boolean }) {
  return (
    <header className="pt-6 pb-8">
      <div className="max-w-4xl mx-auto flex flex-col gap-4">
        <div className="flex items-center justify-between">
          <LogoBox />
          <div className="flex items-center gap-4">
            <p className="text-xs text-muted-foreground font-medium hidden sm:block">
              Need help? Chat with us in the bottom-right widget.
            </p>
            <Button
              variant="ghost"
              onClick={onSkip}
              className="text-muted-foreground hover:text-foreground text-sm font-medium"
            >
              Skip setup
            </Button>
          </div>
        </div>
        {isMobile && (
          <div className="mt-2 rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-xs sm:text-sm text-amber-900">
            For the best experience, complete this setup on a desktop or laptop where you do your
            development work. You can always log in on that device and continue from there.
          </div>
        )}
      </div>
    </header>
  )
}

function NavigationButtons({
  currentStep,
  onBack,
  onNext,
  nextDisabled = false,
  nextLabel = "Continue",
}: {
  currentStep: number
  onBack: () => void
  onNext: () => void
  nextDisabled?: boolean
  nextLabel?: string
}) {
  return (
    <div className="flex justify-between items-center">
      <Button
        variant="outline"
        onClick={onBack}
        className="gap-2 font-medium"
        disabled={currentStep === 0}
      >
        <ChevronLeft className="w-4 h-4" />
        Back
      </Button>

      <Button
        onClick={onNext}
        disabled={nextDisabled}
        className="px-8 py-6 rounded-lg gap-2 font-medium"
      >
        {nextLabel}
        <ArrowRight className="w-4 h-4" />
      </Button>
    </div>
  )
}

function ExperienceCard({
  icon,
  title,
  description,
  selected,
  onSelect,
  useCases,
  cta,
  tag,
  tagTone = "primary",
}: {
  icon: ReactNode
  title: string
  description?: string
  selected: boolean
  onSelect: () => void
  useCases: string[]
  cta: string
  tag?: string
  tagTone?: "primary" | "muted"
}) {
  const tagStyles =
    tagTone === "muted" ? "bg-muted/40 text-muted-foreground" : "bg-primary/10 text-primary"

  return (
    <button
      type="button"
      onClick={onSelect}
      className={`flex flex-col gap-4 rounded-2xl border p-6 text-left transition-all ${
        selected
          ? "border-primary bg-primary/5 shadow-lg ring-2 ring-primary/20"
          : "border-border hover:border-primary/40 hover:shadow-md bg-card"
      }`}
    >
      <div className="flex items-start gap-3">
        <div className="rounded-full bg-primary/10 p-3">{icon}</div>
        <div className="flex flex-col gap-1 min-w-0">
          <div className="flex flex-wrap items-center gap-2">
            <h3 className="text-xl px-2 font-semibold text-foreground leading-tight">{title}</h3>
            {tag && (
              <span
                className={`inline-flex items-center rounded-full px-2 py-0 text-xs font-medium ${tagStyles}`}
              >
                {tag}
              </span>
            )}
          </div>
          {description && (
            <p className="text-sm text-muted-foreground font-medium">{description}</p>
          )}
        </div>
      </div>
      <UseCaseList items={useCases} />
      <p className="text-sm text-muted-foreground font-medium">{cta}</p>
    </button>
  )
}

function UseCaseList({ items }: { items: string[] }) {
  return (
    <ul className="space-y-2">
      {items.map(item => (
        <li key={item} className="flex items-start gap-2 text-sm text-muted-foreground font-medium">
          <Check className="w-4 h-4 text-primary mt-0.5 flex-shrink-0" />
          <span>{item}</span>
        </li>
      ))}
    </ul>
  )
}

function SuggestionCard({
  title,
  description,
  command,
  icon,
  docsHref,
  docsLabel,
}: {
  title: string
  description?: string
  command?: string
  icon?: ReactNode
  docsHref?: string
  docsLabel?: string
}) {
  return (
    <div className="bg-card border border-border rounded-xl p-5 shadow-sm space-y-3">
      <h4 className="font-medium mb-2 flex items-center">
        {icon && (
          <div className="flex items-center justify-center p-1.5 bg-primary/10 rounded-md mr-2">
            {icon}
          </div>
        )}
        {title}
      </h4>
      {description && <p className="text-sm text-muted-foreground font-medium">{description}</p>}
      {command && <ApiKeyCard label="Terminal" value={command} />}
      {docsHref && (
        <a
          href={docsHref}
          target="_blank"
          rel="noopener noreferrer"
          className="inline-flex items-center gap-1 text-sm text-primary hover:text-primary/80 font-medium"
        >
          {docsLabel ?? "View docs"}
          <ExternalLink className="w-4 h-4" />
        </a>
      )}
    </div>
  )
}

function ExtensionSuggestion({
  title,
  description,
  icon,
}: {
  title: string
  description?: string
  icon?: ReactNode
}) {
  return (
    <div className="bg-card border border-border rounded-xl p-5 shadow-sm flex items-start gap-3">
      {icon && (
        <div className="rounded-md bg-primary/10 text-primary p-2 flex-shrink-0">{icon}</div>
      )}
      <div className="space-y-2">
        <h4 className="font-medium text-foreground">{title}</h4>
        {description && <p className="text-sm text-muted-foreground font-medium">{description}</p>}
      </div>
    </div>
  )
}
