import type { CSSProperties, ComponentPropsWithoutRef, Ref } from "react";

export interface MaritimeLoaderProps extends Omit<
  ComponentPropsWithoutRef<"span">,
  "children" | "color"
> {
  /** Size in pixels or CSS string. Defaults to 80. */
  size?: number | string;
  /** Primary accent color. Defaults to EMA Ocean Blue (#0284C7). */
  color?: string;
  /** Visual variant: 'full' (emblem + orbital radar) or 'compact' (sleek inline spinner). */
  variant?: "full" | "compact";
  /** Accessible label. */
  label?: string;
  ref?: Ref<HTMLSpanElement>;
}

const styles = `
  .ema-pro-loader {
    position: relative;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: var(--ema-size, var(--loader-size, 80px));
    height: var(--ema-size, var(--loader-size, 80px));
    vertical-align: middle;
    user-select: none;
  }

  .ema-pro-loader--full {
    width: calc(var(--ema-size, var(--loader-size, 80px)) * 1.15);
    height: calc(var(--ema-size, var(--loader-size, 80px)) * 1.15);
  }

  .ema-pro-loader__stage {
    position: relative;
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  /* --- Glowing Ambient Backdrop --- */
  .ema-pro-loader__glow {
    position: absolute;
    inset: 10%;
    border-radius: 50%;
    background: radial-gradient(circle, rgba(2, 132, 199, 0.28) 0%, rgba(14, 165, 233, 0.08) 55%, transparent 75%);
    filter: blur(8px);
    animation: ema-glow-pulse 3s ease-in-out infinite alternate;
  }

  /* --- SVG Overlay & Ring Animations --- */
  .ema-pro-loader__svg {
    position: absolute;
    inset: 0;
    width: 100%;
    height: 100%;
    overflow: visible;
  }

  .ema-pro-loader__ring-outer {
    transform-box: fill-box;
    transform-origin: center;
    animation: ema-spin-cw 16s linear infinite;
  }

  .ema-pro-loader__ring-inner {
    transform-box: fill-box;
    transform-origin: center;
    animation: ema-spin-ccw 10s cubic-bezier(0.4, 0, 0.2, 1) infinite;
  }

  .ema-pro-loader__sonar-wave {
    transform-box: fill-box;
    transform-origin: center;
    animation: ema-sonar-expand 2.6s cubic-bezier(0.1, 0.8, 0.3, 1) infinite;
  }

  .ema-pro-loader__core-logo {
    position: relative;
    z-index: 2;
    width: 54%;
    height: 54%;
    object-fit: contain;
    filter: drop-shadow(0 4px 10px rgba(11, 25, 44, 0.25));
    animation: ema-logo-float 3.5s ease-in-out infinite alternate;
  }

  .ema-pro-loader__center-sync {
    transform-box: fill-box;
    transform-origin: center;
    animation: ema-spin-cw 3s linear infinite;
  }

  /* --- Keyframe Animations --- */
  @keyframes ema-spin-cw {
    from { transform: rotate(0deg); }
    to { transform: rotate(360deg); }
  }

  @keyframes ema-spin-ccw {
    from { transform: rotate(360deg); }
    to { transform: rotate(0deg); }
  }

  @keyframes ema-glow-pulse {
    0% { transform: scale(0.92); opacity: 0.5; }
    100% { transform: scale(1.12); opacity: 0.9; }
  }

  @keyframes ema-sonar-expand {
    0% { transform: scale(0.65); opacity: 0.9; stroke-width: 3; }
    60% { opacity: 0.35; }
    100% { transform: scale(1.4); opacity: 0; stroke-width: 0.5; }
  }

  @keyframes ema-logo-float {
    0% { transform: translateY(1px) scale(0.98); }
    100% { transform: translateY(-2px) scale(1.02); }
  }

  @media (prefers-reduced-motion: reduce) {
    .ema-pro-loader__ring-outer,
    .ema-pro-loader__ring-inner,
    .ema-pro-loader__sonar-wave,
    .ema-pro-loader__core-logo,
    .ema-pro-loader__glow,
    .ema-pro-loader__center-sync {
      animation: none !important;
    }
  }

  [data-mantine-color-scheme='dark'] .ema-pro-loader__glow {
    background: radial-gradient(circle, rgba(56, 189, 248, 0.35) 0%, rgba(2, 132, 199, 0.12) 60%, transparent 80%);
  }
`;

function toCssSize(value: number | string | undefined) {
  return typeof value === "number" ? `${value}px` : value;
}

export function MaritimeLoader({
  size,
  color,
  variant = "full",
  label = "Ethiopian Maritime Authority Loading",
  className,
  style,
  ref,
  ...props
}: MaritimeLoaderProps) {
  const cssVariables = {
    ...(size ? { "--ema-size": toCssSize(size) } : {}),
    ...(color ? { "--ema-color": color } : {}),
    ...style,
  } as CSSProperties;

  return (
    <span
      {...props}
      ref={ref}
      className={[
        "ema-pro-loader",
        variant === "full" ? "ema-pro-loader--full" : "ema-pro-loader--compact",
        className,
      ]
        .filter(Boolean)
        .join(" ")}
      style={cssVariables}
      role="status"
      aria-label={label}
    >
      <style href="ema-maritime-loader-v3" precedence="low">
        {styles}
      </style>

      <div className="ema-pro-loader__stage">
        {/* Soft Ambient Radial Light Aura */}
        <div className="ema-pro-loader__glow" />

        {/* Precision Orbital Rings & Sonar Radar SVG */}
        <svg
          className="ema-pro-loader__svg"
          viewBox="0 0 120 120"
          aria-hidden="true"
          focusable="false"
        >
          <defs>
            {/* Ethiopian Maritime Brand Gradients */}
            <linearGradient id="ema-ring-grad-1" x1="0%" y1="0%" x2="100%" y2="100%">
              <stop offset="0%" stopColor="#0284C7" />
              <stop offset="50%" stopColor="#38BDF8" />
              <stop offset="100%" stopColor="#078930" />
            </linearGradient>

            <linearGradient id="ema-ring-grad-2" x1="0%" y1="0%" x2="100%" y2="100%">
              <stop offset="0%" stopColor="#F59E0B" />
              <stop offset="50%" stopColor="#D4AF37" />
              <stop offset="100%" stopColor="#FCD116" />
            </linearGradient>

            <linearGradient id="ema-sonar-grad" x1="0%" y1="0%" x2="100%" y2="0%">
              <stop offset="0%" stopColor="#38BDF8" stopOpacity="0.8" />
              <stop offset="100%" stopColor="#0284C7" stopOpacity="0" />
            </linearGradient>
          </defs>

          {/* Sonar Pulsing Wave */}
          <circle
            className="ema-pro-loader__sonar-wave"
            cx="60"
            cy="60"
            r="42"
            fill="none"
            stroke="url(#ema-ring-grad-1)"
          />

          {/* Outer Precision Nautical Tick Ring */}
          <g className="ema-pro-loader__ring-outer">
            <circle
              cx="60"
              cy="60"
              r="54"
              fill="none"
              stroke="url(#ema-ring-grad-1)"
              strokeWidth="1.8"
              strokeDasharray="8 6 2 6"
              opacity="0.85"
            />
            <circle
              cx="60"
              cy="60"
              r="48"
              fill="none"
              stroke="url(#ema-ring-grad-2)"
              strokeWidth="1"
              strokeDasharray="40 18"
              opacity="0.9"
            />
            {/* 4 Cardinal Anchor Points */}
            <circle cx="60" cy="6" r="2.5" fill="#FCD116" />
            <circle cx="114" cy="60" r="2.5" fill="#0284C7" />
            <circle cx="60" cy="114" r="2.5" fill="#078930" />
            <circle cx="6" cy="60" r="2.5" fill="#DA121A" />
          </g>

          {/* Inner Counter-Rotating Golden Ring */}
          <g className="ema-pro-loader__ring-inner">
            <circle
              cx="60"
              cy="60"
              r="39"
              fill="none"
              stroke="url(#ema-ring-grad-2)"
              strokeWidth="2"
              strokeDasharray="28 14"
              strokeLinecap="round"
            />
            <circle
              cx="60"
              cy="60"
              r="34"
              fill="none"
              stroke="#38BDF8"
              strokeWidth="1"
              strokeDasharray="4 8"
              opacity="0.6"
            />
          </g>

          {/* Vector EMA Emblem Backup for Instant Render */}
          {variant === "compact" && (
            <g transform="translate(36, 36) scale(0.4)">
              <path
                d="M 60 10 L 110 100 L 85 100 L 60 48 L 35 100 L 10 100 Z"
                fill="url(#ema-ring-grad-1)"
              />
              <circle
                className="ema-pro-loader__center-sync"
                cx="60"
                cy="64"
                r="12"
                fill="none"
                stroke="#FCD116"
                strokeWidth="3.5"
                strokeDasharray="14 8"
              />
            </g>
          )}
        </svg>

        {/* Official EMA Crest Logo Image */}
        <img
          src="/ema-logo.png"
          alt="Ethiopian Maritime Authority"
          className="ema-pro-loader__core-logo"
          onError={(e) => {
            // Fallback if image path is not resolving in dev iframe
            (e.target as HTMLElement).style.display = "none";
          }}
        />
      </div>
    </span>
  );
}

export default MaritimeLoader;


