"use client";

import Link from "next/link";
import "./FloatingAvatar.css";

interface FloatingAvatarProps {
  src?: string;
  handle: string;
  title: string;
  contained?: boolean;
  opaque?: boolean;
}

export function FloatingAvatar({
  src,
  handle,
  title,
  contained = false,
  opaque = false,
}: FloatingAvatarProps) {
  if (!src) return null;

  // Simple string hash function (deterministic across server/client)
  const hashString = (str: string) => {
    let hash = 0;
    for (let i = 0; i < str.length; i++) {
      hash = ((hash << 5) - hash + str.charCodeAt(i)) | 0;
    }
    return Math.abs(hash);
  };

  // Use handle for seeding - same handle always gets same animation
  const baseHash = hashString(handle);

  // Generate stable random values based on hash
  const random = (offset: number) => {
    // Simple LCG (Linear Congruential Generator) for deterministic randomness
    const a = 1664525;
    const c = 1013904223;
    const m = 2 ** 32;
    const value = ((baseHash + offset) * a + c) % m;
    return value / m;
  };

  // More varied random animation duration (3s to 9s for bigger range)
  const duration = 3 + random(0) * 6;
  // Random animation delay (0s to 4s for more spread)
  const delay = random(1) * 4;
  // Random timing function index
  const timingFunctions = ["ease-in-out", "ease-in", "ease-out", "linear"];
  const timingFunction = timingFunctions[Math.floor(random(2) * timingFunctions.length)];

  return (
    <Link
      href={`/@${handle}/walking`}
      prefetch={false}
      onClick={(e) => e.stopPropagation()}
      target="_blank"
      rel="noopener noreferrer"
      className="FloatingAvatar-link"
      tabIndex={-1}
    >
      <img
        src={src}
        alt={handle}
        title={title}
        className={`FloatingAvatar ${contained ? "FloatingAvatar-contained" : ""} ${opaque ? "FloatingAvatar-opaque" : ""} FloatingAvatar-clickable`}
        style={{
          animationDuration: `${duration}s`,
          animationDelay: `${delay}s`,
          animationTimingFunction: timingFunction,
        }}
      />
    </Link>
  );
}
