'use client'

import { useEffect, useState } from 'react'
import { getApiBase } from '../lib/auth'

const STORAGE_KEY = 'branding_version'

type BrandingLogoProps = {
  className?: string
  alt?: string
}

export default function BrandingLogo({ className, alt = 'Magent logo' }: BrandingLogoProps) {
  const [src, setSrc] = useState<string | null>(null)

  useEffect(() => {
    const baseUrl = getApiBase()
    const version =
      (typeof window !== 'undefined' && window.localStorage.getItem(STORAGE_KEY)) || ''
    const versionSuffix = version ? `?v=${encodeURIComponent(version)}` : ''
    setSrc(`${baseUrl}/branding/logo.png${versionSuffix}`)
  }, [])

  if (!src) {
    return null
  }

  return (
    <img
      className={className}
      src={src}
      alt={alt}
      onError={() => setSrc(null)}
    />
  )
}
