"use client";

import clsx from "clsx";
import { useEffect, useState } from "react";
import { useBranding } from "@/lib/branding";

type LogoSize = "sm" | "md" | "lg";

const sizeMap: Record<LogoSize, { frame: string; image: number; caption: string }> = {
  sm: {
    frame: "gap-3",
    image: 48,
    caption: "text-[11px]"
  },
  md: {
    frame: "gap-3.5",
    image: 56,
    caption: "text-xs"
  },
  lg: {
    frame: "gap-4",
    image: 120,
    caption: "text-sm"
  }
};

export function BrandLogo({
  size = "md",
  stacked = false,
  subtitle,
  dark = false,
  centered = false,
  imageSrc,
  brandName,
  alt,
  brandDomain,
  className
}: {
  size?: LogoSize;
  stacked?: boolean;
  subtitle?: string;
  dark?: boolean;
  centered?: boolean;
  imageSrc?: string;
  brandName?: string;
  alt?: string;
  brandDomain?: string;
  className?: string;
}) {
  const branding = useBranding(brandDomain);
  const token = sizeMap[size];
  const captionClass = dark ? "text-white/80" : "text-slate-500";
  const resolvedBrandName = brandName || branding.name;
  const resolvedImage = imageSrc || branding.logoUrl;
  const resolvedAlt = alt || branding.logoAlt || `${resolvedBrandName} logo`;
  const fallbackImage = branding.defaultLogoUrl;
  const [currentImage, setCurrentImage] = useState(resolvedImage);

  useEffect(() => {
    setCurrentImage(resolvedImage);
  }, [resolvedImage]);

  return (
    <div className={clsx("flex items-center", token.frame, stacked ? (centered ? "flex-col items-center text-center" : "flex-col items-start") : "flex-row", className)}>
      <div
        className="shrink-0 overflow-hidden"
        style={{ width: token.image, height: token.image }}
      >
        <img
          src={currentImage}
          alt={resolvedAlt}
          width={token.image}
          height={token.image}
          className="block h-full w-full object-contain"
          loading={size === "lg" ? "eager" : "lazy"}
          decoding="async"
          onError={() => {
            if (currentImage !== fallbackImage) {
              setCurrentImage(fallbackImage);
            }
          }}
        />
      </div>
      {subtitle ? (
        <div className={clsx("min-w-0", stacked && (centered ? "text-center" : "text-left"))}>
          <span className={clsx("block font-semibold leading-6", token.caption, captionClass)}>{resolvedBrandName}</span>
          <span className={clsx("block font-semibold leading-6", token.caption, captionClass)}>{subtitle}</span>
        </div>
      ) : null}
    </div>
  );
}
