moodboard.jpg
moodboard.jpg
"use client"

import { useEffect, useRef, useState } from "react"
import { createPortal } from "react-dom"
import { cva, type VariantProps } from "class-variance-authority"
import {
  ImageIcon,
  ImageOffIcon,
  Loader2Icon,
  XIcon,
} from "lucide-react"

import { cn } from "@/lib/utils"

const imageVariants = cva("relative overflow-hidden rounded-lg", {
  variants: {
    variant: {
      outline: "border-border border",
      ghost: "",
      muted: "bg-muted/50",
    },
    size: {
      sm: "max-w-64",
      default: "max-w-96",
      lg: "max-w-[512px]",
      full: "w-full",
    },
  },
  defaultVariants: {
    variant: "outline",
    size: "default",
  },
})

export type ImageRootProps = React.ComponentProps<"div"> &
  VariantProps<typeof imageVariants>

function ImageRoot({
  className,
  variant,
  size,
  children,
  ...props
}: ImageRootProps) {
  return (
    <div
      data-slot="image-root"
      className={cn(imageVariants({ variant, size, className }))}
      {...props}
    >
      {children}
    </div>
  )
}

function ImagePreview({
  className,
  containerClassName,
  alt = "Image content",
  src,
  onClick,
  ...props
}: Omit<React.ComponentProps<"img">, "children"> & {
  containerClassName?: string
}) {
  const imgRef = useRef<HTMLImageElement>(null)
  const [loadedSrc, setLoadedSrc] = useState<string | undefined>(undefined)
  const [errorSrc, setErrorSrc] = useState<string | undefined>(undefined)
  const loaded = loadedSrc === src
  const error = errorSrc === src

  useEffect(() => {
    const image = imgRef.current
    if (typeof src !== "string" || !image?.complete) return
    if (image.naturalWidth > 0) setLoadedSrc(src)
    else setErrorSrc(src)
  }, [src])

  return (
    <div
      data-slot="image-preview"
      className={cn("relative min-h-32", containerClassName)}
    >
      {!loaded && !error && (
        <div className="bg-muted/40 absolute inset-0 flex items-center justify-center">
          <Loader2Icon className="text-muted-foreground size-5 animate-spin" />
        </div>
      )}
      {error ? (
        <div className="bg-muted/40 text-muted-foreground flex min-h-32 flex-col items-center justify-center gap-2 p-4 text-sm">
          <ImageOffIcon className="size-5" />
          Failed to load image
        </div>
      ) : (
        // eslint-disable-next-line @next/next/no-img-element
        <img
          ref={imgRef}
          src={src}
          alt={alt}
          onLoad={() => {
            if (typeof src === "string") setLoadedSrc(src)
          }}
          onError={() => {
            if (typeof src === "string") setErrorSrc(src)
          }}
          onClick={onClick}
          className={cn(
            "h-auto w-full cursor-zoom-in object-cover transition-opacity",
            !loaded && "opacity-0",
            className
          )}
          {...props}
        />
      )}
    </div>
  )
}

function ImageZoom({
  src,
  alt = "Image content",
  open,
  onOpenChange,
}: {
  src: string
  alt?: string
  open: boolean
  onOpenChange: (open: boolean) => void
}) {
  const [mounted, setMounted] = useState(false)
  useEffect(() => setMounted(true), [])
  if (!mounted || !open) return null

  return createPortal(
    <div
      role="dialog"
      aria-modal="true"
      aria-label={alt}
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/80 p-6"
      onClick={() => onOpenChange(false)}
    >
      <button
        type="button"
        aria-label="Close"
        className="text-background absolute top-4 right-4 rounded-full p-2 hover:bg-white/10"
        onClick={() => onOpenChange(false)}
      >
        <XIcon className="size-5" />
      </button>
      {/* eslint-disable-next-line @next/next/no-img-element */}
      <img
        src={src}
        alt={alt}
        className="max-h-full max-w-full object-contain"
        onClick={(event) => event.stopPropagation()}
      />
    </div>,
    document.body
  )
}

export function ImagePart({
  src,
  alt,
  filename,
  variant,
  size,
  className,
}: {
  src: string
  alt?: string
  filename?: string
  variant?: ImageRootProps["variant"]
  size?: ImageRootProps["size"]
  className?: string
}) {
  const [open, setOpen] = useState(false)

  return (
    <ImageRoot variant={variant} size={size} className={className}>
      <ImagePreview src={src} alt={alt ?? filename ?? "Image"} onClick={() => setOpen(true)} />
      {filename ? (
        <div className="text-muted-foreground flex items-center gap-1.5 border-t px-2.5 py-1.5 text-xs">
          <ImageIcon className="size-3.5" />
          <span className="truncate">{filename}</span>
        </div>
      ) : null}
      <ImageZoom
        src={src}
        alt={alt ?? filename ?? "Image"}
        open={open}
        onOpenChange={setOpen}
      />
    </ImageRoot>
  )
}

export { ImageRoot, ImagePreview, ImageZoom, imageVariants }