import React from "react";
import {AbsoluteFill, Img, staticFile} from "remotion";
import type {VQStillEvent} from "../timeline";

const remoteUrlPattern = /^https?:\/\//;

const publicPathForStill = (imagePath: string) => {
  const normalizedPath = imagePath.replace(/\\/g, "/");
  const publicPathIndex = normalizedPath.lastIndexOf("/public/");

  return (
    publicPathIndex >= 0
      ? normalizedPath.slice(publicPathIndex + "/public/".length)
      : normalizedPath
  ).replace(/^\/+/, "");
};

const srcForStill = (imagePath: string) =>
  remoteUrlPattern.test(imagePath)
    ? imagePath
    : staticFile(publicPathForStill(imagePath));

export const VQStillBackground: React.FC<
  Readonly<{
    still?: VQStillEvent;
    style?: React.CSSProperties;
    imageStyle?: React.CSSProperties;
  }>
> = ({still, style, imageStyle}) => {
  if (!still) {
    return null;
  }

  return (
    <AbsoluteFill style={{overflow: "hidden", ...style}}>
      <Img
        src={srcForStill(still.imagePath)}
        style={{
          width: "100%",
          height: "100%",
          objectFit: still.fit ?? "cover",
          objectPosition: still.objectPosition ?? "center",
          opacity: still.opacity ?? 1,
          ...imageStyle,
        }}
      />
    </AbsoluteFill>
  );
};
