/* eslint-disable @next/next/no-img-element */
interface OGSocialPreviewProps {
  platform: 'twitter' | 'facebook' | 'telegram';
  title?: string;
  description?: string;
  image?: string;
  url?: string;
}

const PLATFORM_LABEL: Record<OGSocialPreviewProps['platform'], string> = {
  telegram: 'Telegram',
  twitter: 'Twitter / X',
  facebook: 'Facebook / LinkedIn',
};

const PLATFORM_ASPECT_CLASS: Record<OGSocialPreviewProps['platform'], string> = {
  telegram: 'aspect-[4/3]',
  twitter: 'aspect-[2/1]',
  facebook: 'aspect-[1.91/1]',
};

const getHostname = (rawUrl?: string) => {
  const trimmedUrl = rawUrl?.trim();
  if (!trimmedUrl) return '';

  const hasScheme = /^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(trimmedUrl);
  const normalizedUrl = hasScheme ? trimmedUrl : `https://${trimmedUrl}`;

  try {
    return new URL(normalizedUrl).hostname.replace(/^www\./, '');
  } catch {
    return '';
  }
};

export default function OGSocialPreview({
  platform,
  title,
  description,
  image,
  url,
}: OGSocialPreviewProps) {
  const hostname = getHostname(url);

  return (
    <div className="overflow-hidden rounded-xl border border-white/10 bg-black/45">
      <div className="border-b border-white/10 px-3 py-2 text-[11px] uppercase tracking-[0.14em] text-gray-500">
        {PLATFORM_LABEL[platform]}
      </div>

      {image ? (
        <div className={`relative w-full overflow-hidden ${PLATFORM_ASPECT_CLASS[platform]}`}>
          <img
            src={image}
            alt={`${PLATFORM_LABEL[platform]} preview`}
            className="h-full w-full object-cover"
            loading="lazy"
          />
        </div>
      ) : (
        <div className={`flex w-full items-center justify-center bg-white/[0.03] ${PLATFORM_ASPECT_CLASS[platform]}`}>
          <svg className="h-10 w-10 text-gray-600" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
            <rect x="3" y="3" width="18" height="18" rx="2" />
            <circle cx="8.5" cy="8.5" r="1.5" />
            <path d="M21 15l-5-5L5 21" />
          </svg>
        </div>
      )}

      <div className="space-y-1.5 p-3">
        {hostname ? (
          <p className="text-[11px] uppercase tracking-[0.12em] text-violet-300">{hostname}</p>
        ) : null}
        {title ? (
          <h4 className="line-clamp-2 text-sm font-semibold text-white">{title}</h4>
        ) : null}
        {description ? (
          <p className="line-clamp-3 text-xs text-gray-400">{description}</p>
        ) : null}
      </div>
    </div>
  );
}
