"use client"

import { useEffect, useRef, useState } from "react"
import Image from "next/image"
import { ExternalLink, Play } from "lucide-react"
import CarouselThumbnail from "./carousel-thumbnail"
import ImageViewer from "./image-viewer"

type Category = "all" | "games" | "graphics" | "ui" | "web" | "writing"

interface Project {
  title: string
  category: Category[]
  image: string
  description: string
  link?: string
  gallery?: string[]
  video?: string
  uiGroup?: string
}

export default function Portfolio() {
  const [currentIndex, setCurrentIndex] = useState(0)
  const [selectedCategory, setSelectedCategory] = useState<Category>("all")
  const carouselRef = useRef<HTMLDivElement>(null)

  const [viewerOpen, setViewerOpen] = useState(false)
  const [viewerImages, setViewerImages] = useState<string[]>([])
  const [viewerIndex, setViewerIndex] = useState(0)

  const openImageViewer = (images: string[], index = 0) => {
    setViewerImages(images)
    setViewerIndex(index)
    setViewerOpen(true)
  }

  const companies = [
    {
      name: "HYPER+",
      logo: "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/hyperlogo-TSirk2XfqN2xBXsT3GqxibMSjitdC9.png",
    },
    {
      name: "Bethesda",
      logo: "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/client-logo2-SAIwzDJtr1aIbkOVAsRiWsXXWvMGhL.png",
    },
    {
      name: "Cloud Games",
      logo: "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-vNGX2CTKuUK4RwJFBAdyE9cjyLCt3G.png",
    },
    {
      name: "Shuffle Tactics",
      logo: "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/shuffletacticslogo-iOMuU6HZk8tgPe7WHPi0LJaUFY6Df2.png",
    },
  ]

  const projects: Project[] = [
    // Game projects
    {
      title: "Axima",
      category: ["games"],
      image: "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-MwwJs3ZZG8SbFbxnqiCY5ib9ih2Emj.png",
      description: "A charming adventure game featuring lovable characters in a vibrant world.",
      link: "https://store.steampowered.com/app/2425050/Axima/",
    },
    {
      title: "Slip N' Slime",
      category: ["games"],
      image: "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-AhKiBMz4FpXLQUiUvzMEJ4St2m1A5U.png",
      description: "A cute puzzle platformer where you control an adorable slime character.",
      link: "https://store.steampowered.com/app/1402700/Slip_N_Slime/",
    },
    {
      title: "Loftia",
      category: ["games"],
      image: "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-O6rshJsKKdzBxWfpgkxvCrtiS93OZn.png",
      description: "A heartwarming story-driven adventure game set in a magical world.",
      link: "https://store.steampowered.com/app/1898870/Loftia/",
    },
    {
      title: "Shuffle Tactics",
      category: ["games"],
      image: "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-BQ2EVXEDnkZfNPWksVIIPQ4MnfolnB.png",
      description: "A strategic deck-building game with unique feline characters.",
      link: "https://store.steampowered.com/app/2251870/Shuffle_Tactics/",
    },
    {
      title: "Atomic Owl",
      category: ["games"],
      image: "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-lPneqb1c3FZKjLuZ6MJgcR0SZym1Fy.png",
      description: "A retro-futuristic action game featuring a mysterious owl protagonist.",
      link: "https://store.steampowered.com/app/1796810/Atomic_Owl/",
    },
    // UI Design Projects
    {
      title: "Casino Game",
      category: ["ui"],
      image: "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-yIvkOSy644gu4hHHjLn54pwqMckqcS.png",
      description: "Anime-inspired casino game interface with elegant character design and intuitive menu layout.",
      gallery: [
        "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-yIvkOSy644gu4hHHjLn54pwqMckqcS.png",
        "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-iKvtuFEajaauNIQeTJOl0Hv7RpLAKU.png",
        "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-LCKRgG1mZMutWDREm7zvcjpRDyGaos.png",
      ],
      uiGroup: "Casino Game",
    },
    {
      title: "Axima - Main Menu",
      category: ["ui"],
      image: "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-ayBbfmVmhc0laXFDL3jyzB7qF4aCja.png",
      description: "Main menu that has a intro screen and shows save file details ontop of a dynamic background..",
      gallery: [
        "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-ayBbfmVmhc0laXFDL3jyzB7qF4aCja.png",
        "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-lXprrfxD9iGdgBvqm7rCb9HP53Yiyv.png",
        "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-IQ9FsYs9TD6fRth8VYPJCUgrJSgZTI.png",
        "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-obayfqLsj7zKOPHkd9EGYvrSIWoOs0.png",
        "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-taz89wjrd4SLh9lxGRmPuQl8q8vaXk.png",
        "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-ZkciBbTsHxbOknFkWPqanxnp3nFkXp.png",
      ],
      uiGroup: "Axima - Main Menu",
    },
    {
      title: "Axima - Battle UI",
      category: ["ui"],
      image: "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-67inU2KN2Ur6Ws54DoAlY9bXcUXA8z.png",
      description: "Strategic battle interface with dynamic move selection.",
      gallery: [
        "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-67inU2KN2Ur6Ws54DoAlY9bXcUXA8z.png",
        "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-txajX6ZWo6srnhERc8X8RUlmvwY6u2.png",
        "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-TWUkLlUeaIYJWu3jDhrH0LCn6wovoH.png",
      ],
      uiGroup: "Axima - Battle UI",
    },
    {
      title: "Subversion RP",
      category: ["ui"],
      image: "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-kCgMqS79vCxnYYEKMeJVfP7bq5uROn.png",
      description: "Noir-themed roleplay interface with character customization and profile selection screens.",
      gallery: [
        "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-kCgMqS79vCxnYYEKMeJVfP7bq5uROn.png",
        "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-MEBRSml4n3rS3ZDkRROtZXA48pBzOf.png",
        "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-MyN6U0nawBcdKK54wwArSy2ox3f3Gp.png",
      ],
      uiGroup: "Subversion RP",
    },
    {
      title: "Shooter HUD",
      category: ["ui"],
      image: "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-KakpLJMblyqGKNDbqGYw5IjdBmCCfZ.png",
      description: "Minimalist first-person shooter heads-up display with health, ammo, and objective indicators.",
      gallery: ["https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-KakpLJMblyqGKNDbqGYw5IjdBmCCfZ.png"],
      uiGroup: "Shooter HUD",
    },
    {
      title: "Paws & Pals",
      category: ["ui"],
      image: "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-46zHNFQ0zsSo0zw75veJsFiLbv1CnT.png",
      description: "Minimalist logo design for a pet-focused brand featuring a heart and paw print motif.",
      uiGroup: "Paws & Pals",
    },
    {
      title: "App Design",
      category: ["ui"],
      image: "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-byMl9CvQuV1fRu8biTJEasHtAfoyoQ.png",
      description: "Interactive mobile app interface with smooth animations and intuitive navigation.",
      video:
        "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/Untitled%20video-qA5uVGV3UWv1c29HWzJf0X5pMgX3b3.mp4",
      uiGroup: "App Design",
    },
    // Graphics Projects
    {
      title: "Space Background",
      category: ["graphics"],
      image: "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-n9zNCEgXD3i5LgL2fWeoxZCBByoHWy.png",
      description: "Cosmic nebula design with rich purple hues and ethereal star formations.",
      gallery: ["https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-n9zNCEgXD3i5LgL2fWeoxZCBByoHWy.png"],
      uiGroup: "Space Design",
    },
    {
      title: "Abberations & Epithets",
      category: ["graphics"],
      image: "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-6fF0o3I2qJLBCZhzD6NVg0KqW9XMtP.png",
      description: "TTRPG book design featuring mystical symbolism and elegant fantasy typography.",
      gallery: [
        "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-6fF0o3I2qJLBCZhzD6NVg0KqW9XMtP.png",
        "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-SSlLfGcRYQ75fSlAOCYw2JQUtiVHFS.png",
      ],
      uiGroup: "TTRPG Book",
    },
    {
      title: "Lexicon Arcanis",
      category: ["graphics"],
      image: "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-xNma36g9598lpF57i620AIku314HQT.png",
      description: "Ancient tome design with mystical symbols and weathered aesthetic for a tabletop RPG spellbook.",
      gallery: [
        "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-xNma36g9598lpF57i620AIku314HQT.png",
        "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-Xzkbep6yiQenZ5hBUJ6ce7IuAve2ap.png",
      ],
      uiGroup: "TTRPG Book",
    },
    {
      title: "RPForge Logo",
      category: ["graphics"],
      image: "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-7p0IXxWg8MDdWOzIRFqbKrEwgG2EUW.png",
      description:
        "Discord bot logo featuring a d20 dice design with crossed hammers and flame elements for tabletop RPG communities.",
      uiGroup: "RPForge Logo",
    },
    // Web Design Projects
    {
      title: "My Portfolio",
      category: ["web"],
      image: "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-VuzYiKP7BvqidPySFseqNkBC8PcFVF.png",
      description:
        "Personal portfolio website featuring a modern dark theme with purple accents and interactive elements.",
      link: "https://ameliapetrie.com",
    },
    {
      title: "Pastel Puppy Studios",
      category: ["web"],
      image: "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-TXeTMqAzmw06hcw1GvrNtbV8N07aqJ.png",
      description: "E-commerce website for a creative studio featuring a playful design and intuitive navigation.",
      link: "https://pastelpuppystudios.com",
    },
    {
      title: "Ironworks",
      category: ["web"],
      image: "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-D3uoagC3snLLJLtuH1kgW6A86UYOtT.png",
      description: "Creative agency website with neon aesthetics and dynamic constellation animations.",
    },
    {
      title: "Zyndrax",
      category: ["web"],
      image: "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-oGEezTHVbQarFntnX6wj35I8YiH7aI.png",
      description: "Tech company website with modern design and striking visuals.",
    },
    // Writing Projects
    {
      title: "Axima GDD",
      category: ["writing"],
      image: "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-ylL8su9DphIkEFHiTU4bHhgw97rUOI.png",
      description:
        "Comprehensive game design document for Axima, detailing gameplay mechanics, world design, and character development.",
      link: "https://docs.google.com/document/d/1JHwN5K_bPqxWw0JuNZHST85-kZ1aW_ijN6x7f4e6Haw/edit?usp=sharing",
    },
    {
      title: "Elmoreden",
      category: ["writing"],
      image: "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-F8GSCs0w9UCjhWXWN86C50teTwm2Uj.png",
      description:
        "Extensive fantasy world-building project featuring unique magic systems, civilizations, and mythologies.",
      link: "https://www.worldanvil.com/w/elmoreden-cyndergate",
    },
    {
      title: "Hum of the World",
      category: ["writing"],
      image: "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-Ofu9eDh5U9A7bDlJ97JPMVZNG6KWCh.png",
      description: "Detailed magic system design exploring the mystical energy that permeates the world of Elmoreden.",
      link: "https://www.worldanvil.com/w/elmoreden-cyndergate/a/hum-of-the-world-law",
    },
    {
      title: "The Whispers",
      category: ["writing"],
      image: "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-euScecaV78IPRvcH8caG4YnRscQBDk.png",
      description: "Lore article about the divine beings that once shaped the world of Elmoreden.",
      link: "https://www.worldanvil.com/w/elmoreden-cyndergate/a/the-whispers-species",
    },
    {
      title: "Kingdom of Oremouth",
      category: ["writing"],
      image: "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-iBTfPSQx3KS9V3BeJMto3N2lQW9eXU.png",
      description: "Detailed settlement design for a technologically advanced city in a fantasy setting.",
      link: "https://www.worldanvil.com/w/elmoreden-cyndergate/a/kingdom-of-oremouth-settlement",
    },
    {
      title: "Luminous Ascent",
      category: ["writing"],
      image: "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-5Wqse79hQGGEAmnkdgDFXoybjtVHzh.png",
      description: "Fantasy novel exploring themes of light, darkness, and personal growth.",
      link: "https://www.wattpad.com/story/140907068-luminous-ascent",
    },
    {
      title: "Chronicles of Wonder",
      category: ["writing"],
      image: "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-5Wqse79hQGGEAmnkdgDFXoybjtVHzh.png", // Using same image as placeholder
      description: "Early creative writing project showcasing fantasy storytelling and character development.",
      link: "https://www.deviantart.com/cyndergate/art/Chronicles-of-Wonder-Chapter-One-677828976",
    },
  ]

  // Auto-scroll the carousel
  useEffect(() => {
    const interval = setInterval(() => {
      if (companies.length <= 4) return

      setCurrentIndex((prevIndex) => {
        const nextIndex = (prevIndex + 1) % (companies.length - 3)
        return nextIndex
      })
    }, 3000)

    return () => clearInterval(interval)
  }, [])

  // Update carousel position when currentIndex changes
  useEffect(() => {
    if (carouselRef.current) {
      carouselRef.current.style.transform = `translateX(-${currentIndex * 25}%)`
    }
  }, [currentIndex])

  const filteredProjects = projects.filter(
    (project) => selectedCategory === "all" || project.category.includes(selectedCategory),
  )

  // Get unique UI groups
  const uiGroups = [...new Set(projects.filter((p) => p.category.includes("ui")).map((p) => p.uiGroup))]

  // Get unique writing groups for potential future organization
  const writingGroups = [
    {
      name: "Game Design & Fiction",
      projects: projects.filter(
        (p) =>
          p.category.includes("writing") &&
          (p.title.includes("GDD") || p.title.includes("Luminous") || p.title.includes("Chronicles")),
      ),
    },
    {
      name: "Elmoreden Worldbuilding",
      projects: projects.filter(
        (p) =>
          p.category.includes("writing") &&
          (p.title.includes("Elmoreden") ||
            p.title.includes("Kingdom") ||
            p.title.includes("Whispers") ||
            p.title.includes("Hum")),
      ),
    },
  ]

  return (
    <section id="portfolio" className="py-20 dark-section">
      <div className="container mx-auto px-4 md:px-6">
        {/* Section heading */}
        <div className="relative text-center mb-16">
          <h2 className="text-[6rem] font-bold text-purple-900/20 uppercase absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 w-full">
            PORTFOLIO
          </h2>
          <p className="text-3xl font-semibold text-purple-200 relative z-10">
            My Work
            <span className="block w-24 h-1 bg-primary mx-auto mt-4"></span>
          </p>
        </div>

        {/* Notable Clients - Scrolling Carousel */}
        <div className="mb-16">
          <h4 className="text-xl font-medium mb-4 text-purple-200">Notable Clients</h4>
          <div className="relative overflow-hidden">
            <div
              ref={carouselRef}
              className="flex transition-transform duration-700 ease-in-out"
              style={{ width: `${companies.length * 25}%` }}
            >
              {companies.map((company, index) => (
                <div key={index} className="w-1/4 px-2">
                  <div className="flex items-center justify-center h-20 transition-all hover:scale-105 group">
                    <div className="relative h-full w-full">
                      <Image
                        src={company.logo || "/placeholder.svg"}
                        alt={company.name}
                        fill
                        className="object-contain filter transition-all duration-300 group-hover:brightness-125"
                        style={{
                          filter: "drop-shadow(0 4px 6px rgba(168, 85, 247, 0.3))",
                        }}
                      />
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* Portfolio Filter */}
        <div className="flex justify-center mb-10 flex-wrap">
          <div className="inline-flex rounded-full shadow-sm overflow-hidden mb-2">
            <button
              onClick={() => setSelectedCategory("all")}
              className={`px-4 py-2 text-sm font-medium ${
                selectedCategory === "all"
                  ? "bg-primary text-white"
                  : "bg-purple-900/50 text-purple-200 hover:bg-purple-800/50"
              } rounded-l-full`}
            >
              All
            </button>
            <button
              onClick={() => setSelectedCategory("games")}
              className={`px-4 py-2 text-sm font-medium ${
                selectedCategory === "games"
                  ? "bg-primary text-white"
                  : "bg-purple-900/50 text-purple-200 hover:bg-purple-800/50"
              }`}
            >
              Games
            </button>
            <button
              onClick={() => setSelectedCategory("ui")}
              className={`px-4 py-2 text-sm font-medium ${
                selectedCategory === "ui"
                  ? "bg-primary text-white"
                  : "bg-purple-900/50 text-purple-200 hover:bg-purple-800/50"
              }`}
            >
              UI Design
            </button>
            <button
              onClick={() => setSelectedCategory("web")}
              className={`px-4 py-2 text-sm font-medium ${
                selectedCategory === "web"
                  ? "bg-primary text-white"
                  : "bg-purple-900/50 text-purple-200 hover:bg-purple-800/50"
              }`}
            >
              Web Design
            </button>
            <button
              onClick={() => setSelectedCategory("graphics")}
              className={`px-4 py-2 text-sm font-medium ${
                selectedCategory === "graphics"
                  ? "bg-primary text-white"
                  : "bg-purple-900/50 text-purple-200 hover:bg-purple-800/50"
              }`}
            >
              Graphics
            </button>
            <button
              onClick={() => setSelectedCategory("writing")}
              className={`px-4 py-2 text-sm font-medium ${
                selectedCategory === "writing"
                  ? "bg-primary text-white"
                  : "bg-purple-900/50 text-purple-200 hover:bg-purple-800/50"
              } rounded-r-full`}
            >
              Writing
            </button>
          </div>
        </div>

        {/* UI Design Section View */}
        {selectedCategory === "graphics" ? (
          <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
            {[...new Set(projects.filter((p) => p.category.includes("graphics")).map((p) => p.uiGroup))].map(
              (group) => {
                const groupProjects = projects.filter((p) => p.uiGroup === group && p.category.includes("graphics"))
                const mainProject = groupProjects[0]

                return (
                  <div key={group} className="animate-fade-in">
                    <div className="glossy-card p-6 rounded-3xl h-full flex flex-col">
                      <h3 className="text-2xl font-semibold text-purple-200 mb-3">{group}</h3>
                      <p className="text-purple-300 text-sm mb-4">{mainProject.description}</p>

                      {mainProject.gallery ? (
                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 flex-grow">
                          {mainProject.gallery.map((img, imgIndex) => (
                            <div
                              key={`${mainProject.title}-${imgIndex}`}
                              className="relative rounded-xl overflow-hidden cursor-pointer"
                              onClick={() => openImageViewer(mainProject.gallery || [mainProject.image], imgIndex)}
                            >
                              <div className="aspect-auto relative min-h-[200px]">
                                <Image
                                  src={img || "/placeholder.svg"}
                                  alt={`${mainProject.title} - Image ${imgIndex + 1}`}
                                  fill
                                  className="object-contain"
                                />
                              </div>
                            </div>
                          ))}
                        </div>
                      ) : (
                        <div
                          className="relative rounded-xl overflow-hidden aspect-auto min-h-[200px] flex-grow cursor-pointer"
                          onClick={() => openImageViewer([mainProject.image])}
                        >
                          <Image
                            src={mainProject.image || "/placeholder.svg"}
                            alt={mainProject.title}
                            fill
                            className="object-contain"
                          />
                        </div>
                      )}
                    </div>
                  </div>
                )
              },
            )}
          </div>
        ) : selectedCategory === "ui" ? (
          <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
            {uiGroups.map((group) => {
              const groupProjects = projects.filter((p) => p.uiGroup === group)
              const mainProject = groupProjects[0]

              return (
                <div key={group} className="animate-fade-in">
                  <div className="glossy-card p-6 rounded-3xl h-full flex flex-col">
                    <h3 className="text-2xl font-semibold text-purple-200 mb-3">{group}</h3>
                    <p className="text-purple-300 text-sm mb-4">{mainProject.description}</p>

                    {group === "App Design" && mainProject.video ? (
                      <div className="relative rounded-xl overflow-hidden mb-4 flex-grow">
                        <video
                          src={mainProject.video}
                          controls
                          className="w-full h-full object-cover"
                          poster={mainProject.image}
                        />
                      </div>
                    ) : mainProject.gallery ? (
                      <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 flex-grow">
                        {mainProject.gallery.map((img, imgIndex) => (
                          <div
                            key={`${mainProject.title}-${imgIndex}`}
                            className="relative rounded-xl overflow-hidden cursor-pointer"
                            onClick={() => openImageViewer(mainProject.gallery || [mainProject.image], imgIndex)}
                          >
                            <div className="aspect-auto relative min-h-[200px]">
                              <Image
                                src={img || "/placeholder.svg"}
                                alt={`${mainProject.title} - Image ${imgIndex + 1}`}
                                fill
                                className="object-contain"
                              />
                            </div>
                          </div>
                        ))}
                      </div>
                    ) : (
                      <div
                        className="relative rounded-xl overflow-hidden aspect-auto min-h-[200px] flex-grow cursor-pointer"
                        onClick={() => openImageViewer([mainProject.image])}
                      >
                        <Image
                          src={mainProject.image || "/placeholder.svg"}
                          alt={mainProject.title}
                          fill
                          className="object-contain"
                        />
                      </div>
                    )}
                  </div>
                </div>
              )
            })}
          </div>
        ) : selectedCategory === "writing" ? (
          <div className="grid grid-cols-1 gap-8">
            <div className="animate-fade-in">
              <div className="glossy-card p-6 rounded-3xl">
                <h3 className="text-2xl font-semibold text-purple-200 mb-6">Game Design & Fiction</h3>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  {writingGroups[0].projects.map((project) => (
                    <div key={project.title} className="border-t border-purple-800/30 pt-4 first:border-0 first:pt-0">
                      <h4 className="text-lg font-medium text-purple-200 mb-1">{project.title}</h4>
                      <p className="text-purple-300 text-sm mb-3">{project.description}</p>
                      <div className="flex items-center gap-4">
                        <div className="relative w-20 h-20 rounded-md overflow-hidden">
                          <Image
                            src={project.image || "/placeholder.svg"}
                            alt={project.title}
                            fill
                            className="object-cover"
                          />
                        </div>
                        {project.link && (
                          <a
                            href={project.link}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="inline-flex items-center gap-2 text-purple-300 hover:text-purple-100 transition-colors"
                          >
                            View Project <ExternalLink size={16} />
                          </a>
                        )}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </div>

            <div className="animate-fade-in">
              <div className="glossy-card p-6 rounded-3xl">
                <h3 className="text-2xl font-semibold text-purple-200 mb-6">Elmoreden Worldbuilding</h3>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  {writingGroups[1].projects.map((project) => (
                    <div key={project.title} className="border-t border-purple-800/30 pt-4 first:border-0 first:pt-0">
                      <h4 className="text-lg font-medium text-purple-200 mb-1">{project.title}</h4>
                      <p className="text-purple-300 text-sm mb-3">{project.description}</p>
                      <div className="flex items-center gap-4">
                        <div className="relative w-20 h-20 rounded-md overflow-hidden">
                          <Image
                            src={project.image || "/placeholder.svg"}
                            alt={project.title}
                            fill
                            className="object-cover"
                          />
                        </div>
                        {project.link && (
                          <a
                            href={project.link}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="inline-flex items-center gap-2 text-purple-300 hover:text-purple-100 transition-colors"
                          >
                            View Project <ExternalLink size={16} />
                          </a>
                        )}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </div>
        ) : (
          /* Standard Portfolio Grid for other categories */
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
            {filteredProjects.map((project, index) => (
              <div
                key={index}
                className="group relative overflow-hidden rounded-3xl cute-shadow animate-float"
                style={{ animationDelay: `${index * 0.2}s` }}
              >
                {project.category.includes("ui") && (project.gallery?.length || 0) > 1 ? (
                  <CarouselThumbnail
                    images={project.gallery || [project.image]}
                    title={project.title}
                    description={project.description}
                    category="UI Design"
                    onImageClick={(images, index) => openImageViewer(images, index)}
                  />
                ) : (
                  <div className="relative h-48 w-full">
                    {project.video ? (
                      <div className="absolute inset-0 flex items-center justify-center">
                        <Image
                          src={project.image || "/placeholder.svg"}
                          alt={project.title}
                          fill
                          className="object-cover"
                        />
                        <div className="absolute inset-0 flex items-center justify-center">
                          <div className="w-12 h-12 rounded-full bg-purple-500/80 flex items-center justify-center">
                            <Play className="w-6 h-6 text-white" />
                          </div>
                        </div>
                      </div>
                    ) : (
                      <Image
                        src={project.image || "/placeholder.svg"}
                        alt={project.title}
                        fill
                        className="object-cover transition-transform duration-300 group-hover:scale-110"
                        onClick={(e) => {
                          e.stopPropagation()
                          openImageViewer(project.gallery || [project.image])
                        }}
                      />
                    )}

                    {project.category.includes("ui") && (
                      <div className="absolute top-3 right-3 px-3 py-1 rounded-full bg-purple-600/80 text-white text-xs font-medium opacity-0 group-hover:opacity-100 transition-opacity">
                        UI Design
                      </div>
                    )}

                    {project.category.includes("web") && (
                      <div className="absolute top-3 right-3 px-3 py-1 rounded-full bg-blue-600/80 text-white text-xs font-medium opacity-0 group-hover:opacity-100 transition-opacity">
                        Web Design
                      </div>
                    )}

                    {project.category.includes("writing") && (
                      <div className="absolute top-3 right-3 px-3 py-1 rounded-full bg-amber-600/80 text-white text-xs font-medium opacity-0 group-hover:opacity-100 transition-opacity">
                        Writing
                      </div>
                    )}

                    {project.category.includes("graphics") && (
                      <div className="absolute top-3 right-3 px-3 py-1 rounded-full bg-emerald-600/80 text-white text-xs font-medium opacity-0 group-hover:opacity-100 transition-opacity">
                        Graphics
                      </div>
                    )}
                  </div>
                )}
                <div className="absolute inset-0 bg-gradient-to-t from-purple-900/90 via-purple-800/70 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300 flex flex-col items-center justify-center p-6">
                  <h5 className="text-white text-xl font-medium mb-2">{project.title}</h5>
                  <p className="text-purple-200 text-center mb-4">{project.description}</p>
                  {project.gallery ? (
                    <div className="flex gap-2 mt-2">
                      {project.gallery.slice(0, 4).map((img, i) => (
                        <div key={i} className="w-8 h-8 rounded-md overflow-hidden border border-purple-400/30">
                          <Image
                            src={img || "/placeholder.svg"}
                            alt={`${project.title} preview ${i + 1}`}
                            width={32}
                            height={32}
                            className="object-cover"
                          />
                        </div>
                      ))}
                      {project.gallery.length > 4 && (
                        <div className="w-8 h-8 rounded-md overflow-hidden border border-purple-400/30 flex items-center justify-center bg-purple-800/50">
                          <span className="text-xs text-white">+{project.gallery.length - 4}</span>
                        </div>
                      )}
                    </div>
                  ) : project.video ? (
                    <span className="inline-flex items-center gap-2 text-white">
                      Video Preview <Play size={16} />
                    </span>
                  ) : (
                    project.link && (
                      <a
                        href={project.link}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="inline-flex items-center gap-2 text-white hover:text-purple-300 transition-colors"
                      >
                        View Project <ExternalLink size={16} />
                      </a>
                    )
                  )}
                </div>
              </div>
            ))}
          </div>
        )}
        {/* Image Viewer */}
        <ImageViewer
          isOpen={viewerOpen}
          onClose={() => setViewerOpen(false)}
          images={viewerImages}
          currentIndex={viewerIndex}
        />
      </div>
    </section>
  )
}

