import { ChevronRight } from "lucide-react";
import { resolveAmbientMedia } from "../../entities/service/media";
import type { LauncherServiceView } from "../../entities/service/types";
import { cn } from "../../shared/lib/cn";

export function ServiceRail({
  services,
  selectedServiceId,
  onSelect,
}: {
  services: LauncherServiceView[];
  selectedServiceId?: string;
  onSelect: (serviceId: string) => void;
}) {
  const selectedService = services.find((service) => service.id === selectedServiceId);
  const railMedia = resolveAmbientMedia(selectedService);

  return (
    <div className="service-rail" aria-label="Доступные сервисы">
      <RailMedia className="service-rail__backdrop-media" src={railMedia.src} kind={railMedia.kind} />
      <div className="service-rail__glass" />
      <div className="service-rail__scroll">
        <div className="service-rail__track">
          {services.map((service) => (
            <button
              key={service.id}
              className={cn("service-tile", selectedServiceId === service.id && "service-tile--active")}
              onClick={() => onSelect(service.id)}
              type="button"
            >
              <span
                className="service-tile__media"
                style={{ "--tile-accent": service.accentColor ?? "#B5FF5A" } as React.CSSProperties}
              >
                <RailMedia
                  className="service-tile__media-asset"
                  src={service.media.coverImage ?? service.media.thumbnail ?? null}
                  kind={service.media.coverKind ?? "image"}
                />
              </span>
              <span className="service-tile__content">
                <strong>{service.title}</strong>
              </span>
              <span className="service-tile__arrow" aria-hidden="true">
                <ChevronRight size={18} strokeWidth={2.1} />
              </span>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

function RailMedia({
  src,
  kind,
  className,
}: {
  src?: string | null;
  kind?: LauncherServiceView["media"]["coverKind"];
  className: string;
}) {
  if (!src) return null;

  if (kind === "video" || isVideoSource(src)) {
    return <video className={className} src={src} autoPlay loop muted playsInline preload="metadata" />;
  }

  return <img className={className} src={src} alt="" loading="lazy" decoding="async" />;
}

function isVideoSource(src: string) {
  return /\.(mp4|webm|mov|m4v|avi|mkv)(\?.*)?$/i.test(src);
}
