"use client";

import Image from "next/image";
import { useState } from "react";

import { InstagramIcon } from "@/components/social/instagram-icon";
import { instagramAvatarUrl } from "@/lib/constants/instagram";
import { cn } from "@/lib/utils";

type Mode = "cover" | "avatar" | "empty";

type Props = {
  handle: string;
  /** On-site portrait — shown first with face-friendly crop. */
  coverImage?: string;
  className?: string;
};

/**
 * Short strip: real photography first; tiny IG badge; minimal fallback if both fail.
 */
export function InstagramProfilePhoto({ handle, coverImage, className }: Props) {
  const [mode, setMode] = useState<Mode>(coverImage ? "cover" : "avatar");

  if (mode === "cover" && coverImage) {
    return (
      <div className={cn("relative size-full overflow-hidden bg-muted", className)}>
        <Image
          src={coverImage}
          alt=""
          fill
          className="object-cover object-[center_15%] sm:object-[center_20%]"
          sizes="(max-width:640px) 50vw, 280px"
          onError={() => setMode("avatar")}
        />
        <div
          className="pointer-events-none absolute bottom-2 right-2 rounded-full bg-black/50 p-1.5 text-white backdrop-blur-sm"
          aria-hidden
        >
          <InstagramIcon className="size-3.5" />
        </div>
      </div>
    );
  }

  if (mode === "avatar") {
    return (
      <div className={cn("relative size-full overflow-hidden bg-muted", className)}>
        {/* eslint-disable-next-line @next/next/no-img-element */}
        <img
          src={instagramAvatarUrl(handle)}
          alt=""
          className="size-full object-cover object-top"
          loading="lazy"
          decoding="async"
          referrerPolicy="no-referrer"
          onError={() => setMode("empty")}
        />
        <div
          className="pointer-events-none absolute bottom-2 right-2 rounded-full bg-black/50 p-1.5 text-white backdrop-blur-sm"
          aria-hidden
        >
          <InstagramIcon className="size-3.5" />
        </div>
      </div>
    );
  }

  return (
    <div
      className={cn(
        "flex size-full items-end justify-start bg-gradient-to-br from-zinc-800 via-zinc-900 to-black p-3",
        className,
      )}
      aria-hidden
    >
      <InstagramIcon className="size-7 text-white/80" />
    </div>
  );
}
