"use client"

import NextImage from "next/image"

import type { ImageLoaderProps } from "next/image"
import type { CSSProperties } from "react"

import type { ImageProps } from "@/types/components/image"

function isBlockedByFirewall(src: string): boolean {
  return (
    src.includes("test.scandichotels.com") ||
    src.includes("test2.scandichotels.com") ||
    src.includes("test3.scandichotels.com") ||
    src.includes("stage.scandichotels.com") ||
    src.includes("prod.scandichotels.com")
  )
}

function imageLoader({ quality, src, width }: ImageLoaderProps) {
  const isAbsoluteUrl = src.startsWith("https://") || src.startsWith("http://")
  const hasQS = src.indexOf("?") !== -1

  if (!isAbsoluteUrl || isBlockedByFirewall(src)) {
    return `${src}${hasQS ? "&" : "?"}w=${width}${quality ? "&q=" + quality : ""}`
  }

  return `https://image-scandic-hotels.netlify.app/.netlify/images?url=${src}&w=${width}${quality ? "&q=" + quality : ""}`
  //return `https://img.scandichotels.com/.netlify/images?url=${src}&w=${width}${quality ? "&q=" + quality : ""}` //TODO: use this when Daniel fixed DNS in citrix
}

// Next/Image adds & instead of ? before the params
export default function Image({ focalPoint, style, ...props }: ImageProps) {
  const styles: CSSProperties = focalPoint
    ? {
        objectFit: "cover",
        objectPosition: `${focalPoint.x}% ${focalPoint.y}%`,
        ...style,
      }
    : { ...style }

  return <NextImage {...props} style={styles} loader={imageLoader} />
}
