"use client";

import { use, useState, useEffect } from "react";
import { FloatingAvatar } from "@/app/FloatingAvatar";
import type { TrailStop } from "@/data/queries";

type Props = {
  stops: TrailStop[];
  stopRects: Map<number, { top: number; left: number; width: number; height: number }>;
  isActive: boolean;
};

const MOBILE_BREAKPOINT = 768;
const CONTENT_WIDTH = 800;

export function TrailWalkersOverlay({ stops, stopRects, isActive }: Props) {
  const [isMobile, setIsMobile] = useState(false);
  const [sideSpace, setSideSpace] = useState(0);

  useEffect(() => {
    const updateLayout = () => {
      const width = window.innerWidth;
      setIsMobile(width < MOBILE_BREAKPOINT);
      // How much space is available on each side of the content
      setSideSpace(Math.max(0, (width - CONTENT_WIDTH) / 2));
    };
    updateLayout();
    window.addEventListener("resize", updateLayout);
    return () => window.removeEventListener("resize", updateLayout);
  }, []);

  // Unwrap promises for all stops
  const stopsWithWalkers = stops.map((stop) => ({
    ...stop,
    walkersHere: use(stop.walkersHere),
  }));

  // Flatten all walkers with their stop context
  const allWalkers = stopsWithWalkers
    .flatMap((stop, stopIndex) =>
      (stop.walkersHere || []).map((walker: any, walkerIndex: number) => ({
        walker,
        stopIndex,
        walkerIndex,
      })),
    )
    .sort((a: any, b: any) => a.walker.did.localeCompare(b.walker.did));

  // Calculate walker position based on stop rect
  const getWalkerPosition = (stopIndex: number, did: string) => {
    const stopRect = stopRects.get(stopIndex);
    if (!stopRect) return null;

    // Use did hash for consistent positioning
    const didHash = did.split("").reduce((a, b) => a + b.charCodeAt(0), 0);
    const seed = didHash + stopIndex;

    const random = (offset: number) => {
      const x = Math.sin(seed + offset) * 10000;
      return x - Math.floor(x);
    };

    if (isMobile) {
      // Mobile: just sides, range from visible to half-clipped
      const side = didHash % 2 === 0 ? "left" : "right";
      const verticalPercent = 5 + random(1) * 90;
      const distance = 5 - random(2) * 30; // +5 to -25px, so some inside margin, some clipped

      const translateY = stopRect.top + (stopRect.height * verticalPercent) / 100;
      const translateX =
        side === "left" ? stopRect.left + distance : stopRect.left + stopRect.width - distance;

      return { transform: `translate(${translateX}px, ${translateY}px)` };
    }

    // Desktop: position at left/right edges, distance scales with available space
    const side = didHash % 2 === 0 ? "left" : "right";
    const verticalPercent = 5 + random(1) * 75;
    // Min and max distance scale with available space
    const minDistance = Math.min(80, 20 + sideSpace * 0.2);
    const maxDistance = Math.min(160, 40 + sideSpace * 0.5);
    const distance = -minDistance - random(2) * (maxDistance - minDistance);

    const absoluteY = stopRect.top + (stopRect.height * verticalPercent) / 100;
    const translateX =
      side === "left" ? stopRect.left + distance : stopRect.left + stopRect.width - distance;

    return {
      transform: `translate(${translateX}px, ${absoluteY}px)`,
    };
  };

  return (
    <div
      className={`TrailWalk-walkersOverlay ${isActive ? "TrailWalk-walkersOverlay--active" : ""}`}
    >
      {allWalkers.map(({ walker, stopIndex }) => {
        const position = getWalkerPosition(stopIndex, walker.did);
        if (!position) return null;

        return (
          <div key={walker.did} className="TrailWalk-walker" style={position}>
            <FloatingAvatar
              src={walker.avatar}
              title={walker.handle}
              handle={walker.handle}
              opaque
            />
          </div>
        );
      })}
    </div>
  );
}
