'use client';

import React, { useState } from 'react';
import { useBranding } from '@/context/BrandingContext';

import { normalizeAssetUrl } from '@/lib/utils/asset';

interface AppLogoProps {
  className?: string;
  imageClassName?: string;
  size?: 'xs' | 'sm' | 'md' | 'lg' | 'xl';
  showText?: boolean;
  textClassName?: string;
  fallbackIcon?: string;
  customInitial?: string;
}

export default function AppLogo({
  className = '',
  imageClassName = '',
  size = 'md',
  showText = false,
  textClassName = 'font-bold text-slate-900',
  fallbackIcon,
  customInitial,
}: AppLogoProps) {
  const { branding } = useBranding();
  const [imgError, setImgError] = useState(false);

  const initial = customInitial || (branding.appName ? branding.appName.trim().charAt(0).toUpperCase() : 'D');

  const sizeDimensions = {
    xs: { box: 'w-6 h-6 rounded-lg text-[10px]', img: 'h-6 w-6 rounded-md object-contain shrink-0' },
    sm: { box: 'w-7 h-7 rounded-lg text-xs', img: 'h-7 w-7 rounded-lg object-contain shrink-0' },
    md: { box: 'w-8 h-8 sm:w-9 sm:h-9 rounded-xl text-xs sm:text-sm', img: 'h-8 w-8 sm:h-9 sm:w-9 rounded-xl object-contain shrink-0' },
    lg: { box: 'w-10 h-10 sm:w-11 sm:h-11 rounded-2xl text-base sm:text-lg', img: 'h-10 w-10 sm:h-11 sm:w-11 rounded-2xl object-contain shrink-0' },
    xl: { box: 'w-14 h-14 sm:w-16 sm:h-16 rounded-3xl text-2xl sm:text-3xl', img: 'h-14 w-14 sm:h-16 sm:w-16 rounded-3xl object-contain shrink-0' },
  }[size];

  const pixelSizes = {
    xs: 24,
    sm: 28,
    md: 36,
    lg: 44,
    xl: 64,
  }[size];

  const logoSrc = normalizeAssetUrl(branding.logoUrl || '/images/logo.png');
  const hasValidLogo = Boolean(logoSrc && !imgError);

  return (
    <div className={`inline-flex items-center gap-2.5 ${className}`}>
      {hasValidLogo ? (
        <img
          src={logoSrc}
          alt={branding.appName || 'Logo'}
          width={pixelSizes}
          height={pixelSizes}
          onError={() => setImgError(true)}
          className={`transition-transform duration-200 ${sizeDimensions.img} ${imageClassName}`}
        />
      ) : (
        <div
          className={`${sizeDimensions.box} bg-theme flex items-center justify-center text-white font-black shadow-xs shrink-0 select-none`}
        >
          {fallbackIcon ? <i className={fallbackIcon} /> : initial}
        </div>
      )}

      {showText && (
        <span className={textClassName}>
          {branding.appName}
        </span>
      )}
    </div>
  );
}
