"use client";

import BoldIcon from "@/components/ui/BoldIcon";

export interface LocationData {
  lat: number;
  lng: number;
  label?: string;
}

interface LocationMessageBubbleProps {
  location: LocationData;
  isOutgoing?: boolean;
}

export function parseLocationContent(content: string): LocationData | null {
  try {
    const parsed = JSON.parse(content);
    if (typeof parsed.lat === "number" && typeof parsed.lng === "number") {
      return parsed as LocationData;
    }
  } catch {
    /* not JSON */
  }
  return null;
}

export default function LocationMessageBubble({
  location,
  isOutgoing = false,
}: LocationMessageBubbleProps) {
  const mapsUrl = `https://www.google.com/maps?q=${location.lat},${location.lng}`;
  const embedUrl = `https://maps.google.com/maps?q=${location.lat},${location.lng}&z=15&output=embed`;

  return (
    <div
      className={`overflow-hidden rounded-2xl ${
        isOutgoing ? "ring-1 ring-[#2aabee]/30" : "shadow-sm"
      }`}
    >
      <div className="relative h-32 w-56 overflow-hidden bg-neutral-200 dark:bg-neutral-800">
        <iframe
          title="موقعیت"
          src={embedUrl}
          className="pointer-events-none absolute inset-0 h-full w-full border-0"
          loading="lazy"
        />
        <div className="absolute inset-0 flex items-center justify-center">
          <BoldIcon name="location" size={30} tinted className="text-red-500 drop-shadow-md" />
        </div>
      </div>
      <div className="flex items-center justify-between gap-2 bg-white/90 px-3 py-2 dark:bg-neutral-900/90">
        <span className="truncate text-xs text-neutral-600 dark:text-neutral-400">
          {location.label || "موقعیت مکانی"}
        </span>
        <a
          href={mapsUrl}
          target="_blank"
          rel="noopener noreferrer"
          className="gentle-transition flex items-center gap-1 rounded-full bg-[#2aabee] px-2.5 py-1 text-[10px] text-white active:scale-95"
        >
          <BoldIcon name="routing" size={12} tinted className="text-white" />
          مسیریابی
        </a>
      </div>
    </div>
  );
}
