import { useState } from 'react';
import { Music } from 'lucide-react';
import { hueFromString } from '../lib/color';

interface ArtworkProps {
  seed: string;
  src?: string | null;
  className?: string;
  rounded?: 'sm' | 'md' | 'lg' | 'xl' | 'full';
  /** Skip native lazy-loading — set true for above-the-fold artwork (e.g. PlaybackBar). */
  eager?: boolean;
  /** Drop the note glyph. For callers that draw their own icon on top (TrackRow's play overlay). */
  glyph?: boolean;
}

const API_BASE = import.meta.env.VITE_API_URL || '/api';

/**
 * Rewrite external image URLs through the backend proxy so the browser gets
 * cache headers (1 year, immutable) and avoids per-domain connection limits
 * to Discogs / Cover Art Archive etc.
 */
function proxySrc(src: string): string {
  if (src.startsWith('http://') || src.startsWith('https://')) {
    return `${API_BASE}/images/proxy?url=${encodeURIComponent(src)}`;
  }
  return src;
}

export function Artwork({ seed, src, className = '', rounded = 'md', eager = false, glyph = true }: ArtworkProps) {
  const hue = hueFromString(seed);
  // Symmetric top sheen over a diagonal base — the highlight is centered
  // horizontally so it reads as even behind the centered note glyph.
  const gradient =
    `radial-gradient(110% 90% at 50% 0%, hsl(${hue},42%,26%) 0%, transparent 60%), ` +
    `linear-gradient(160deg, hsl(${hue},36%,19%), hsl(${hue - 6},30%,10%))`;
  const r = { sm: 'rounded-sm', md: 'rounded-md', lg: 'rounded-lg', xl: 'rounded-xl', full: 'rounded-full' }[rounded];

  // If an image source is supplied we render it lazily over the gradient
  // fallback, so a slow or broken cover never produces a blank rectangle:
  // the gradient (with the music glyph) is painted underneath and only
  // swapped out once the <img> fires its onLoad. A 404 falls back too.
  const [loaded, setLoaded] = useState(false);
  const [errored, setErrored] = useState(false);

  if (src && !errored) {
    const proxied = proxySrc(src);
    return (
      <div className={`relative overflow-hidden ${r} ${className}`} style={{ background: gradient }}>
        {!loaded && glyph && <Music className="absolute inset-0 m-auto h-2/5 w-2/5 text-on-accent/20" strokeWidth={1.5} aria-hidden />}
        <img
          src={proxied}
          alt={seed}
          loading={eager ? 'eager' : 'lazy'}
          decoding="async"
          onLoad={() => setLoaded(true)}
          onError={() => setErrored(true)}
          className={`h-full w-full object-cover transition-opacity duration-300 ${loaded ? 'opacity-100' : 'opacity-0'}`}
        />
      </div>
    );
  }
  return (
    <div className={`relative flex items-center justify-center overflow-hidden ${r} ${className}`} style={{ background: gradient }}>
      {glyph && <Music className="h-2/5 w-2/5 text-on-accent/20" strokeWidth={1.5} aria-hidden />}
    </div>
  );
}
