import { STATION_THEMES } from './constants.js';

export function prefersReducedMotion() {
  try {
    return window.matchMedia('(prefers-reduced-motion: reduce)').matches;
  } catch {
    return false;
  }
}

export function isMobileViewport() {
  return window.matchMedia('(max-width: 760px)').matches;
}

export function isStandalonePwa() {
  return window.matchMedia('(display-mode: standalone)').matches
    || window.matchMedia('(display-mode: fullscreen)').matches
    || window.navigator.standalone === true;
}

export function isMobileInstallViewport() {
  return window.matchMedia('(max-width: 760px)').matches;
}

export function toHttpsIfHttp(url) {
  if (!url || typeof url !== 'string') return '';
  return url.startsWith('http://') ? (`https://${url.slice('http://'.length)}`) : url;
}

function hashString(str) {
  let hash = 0;
  for (let i = 0; i < str.length; i++) {
    hash = ((hash << 5) - hash) + str.charCodeAt(i);
    hash |= 0;
  }
  return Math.abs(hash);
}

function hexToRgb(hex) {
  const normalized = String(hex || '').replace('#', '').trim();
  if (!/^[0-9a-f]{6}$/i.test(normalized)) return null;
  const num = parseInt(normalized, 16);
  return `${(num >> 16) & 255}, ${(num >> 8) & 255}, ${num & 255}`;
}

export function getStationTheme(station) {
  const rawTheme = station?.raw?.theme || station?.theme || {};
  const key = `${station?.id || ''}:${station?.name || station?.title || ''}`;
  const fallback = STATION_THEMES[hashString(key) % STATION_THEMES.length];
  return {
    accent: rawTheme.accent || rawTheme.primary || station?.raw?.color || fallback.accent,
    accent2: rawTheme.accent2 || rawTheme.secondary || fallback.accent2,
    accent3: rawTheme.accent3 || fallback.accent3,
    page: rawTheme.page || rawTheme.background || fallback.page,
    panel: rawTheme.panel || fallback.panel,
  };
}

export function applyStationTheme(station) {
  if (!station) return;
  const theme = getStationTheme(station);
  const root = document.documentElement;
  root.style.setProperty('--accent', theme.accent);
  root.style.setProperty('--accent-2', theme.accent2);
  root.style.setProperty('--accent-3', theme.accent3);
  root.style.setProperty('--page-bg', theme.page);
  root.style.setProperty('--theme-panel', theme.panel);
  root.style.setProperty('--accent-rgb', hexToRgb(theme.accent) || '77, 215, 200');
  root.style.setProperty('--accent-2-rgb', hexToRgb(theme.accent2) || '255, 180, 92');
  root.style.setProperty('--accent-3-rgb', hexToRgb(theme.accent3) || '143, 179, 255');
  root.style.setProperty('--theme-page-rgb', hexToRgb(theme.page) || '17, 19, 24');
  root.style.setProperty('--theme-panel-rgb', hexToRgb(theme.panel) || '16, 20, 27');
  root.style.setProperty('--accent-glow', `rgba(${hexToRgb(theme.accent) || '77, 215, 200'}, 0.34)`);
}

export function getStationStreamUrl(station) {
  if (!station) return '';
  return station.streamUrl
    || station.url
    || station.streams?.audio
    || station.streams?.primary
    || station.liveAudio
    || station.liveStream
    || station.liveVideo
    || '';
}

export function getStationHomepage(station) {
  if (!station) return '';
  return station.url
    || station.homepage
    || station.website
    || station.www
    || station.raw?.homepage
    || station.raw?.website
    || station.raw?.www
    || '';
}

export function getStationVideoUrl(station) {
  return station?.streams?.video || station?.liveVideo || '';
}

export function getStationMetadataUrl(station) {
  return station?.metadata?.lastSongs
    || station?.currentSong
    || station?.lastSongs
    || station?.raw?.metadata?.lastSongs
    || station?.raw?.currentSong
    || station?.raw?.lastSongs
    || '';
}

export function normalizeStationRecord(station, isUserStation = false) {
  const name = station?.name || station?.title || station?.id || 'Unknown';
  const url = getStationStreamUrl(station);
  const bitrate = Number(station?.bitrate);

  return {
    id: station?.id || `${isUserStation ? 'user' : 'station'}-${name.replace(/\s+/g, '-')}`,
    name,
    url,
    logo: station?.logoUrl || station?.assets?.logo || station?.logo || '',
    poster: station?.assets?.poster || station?.poster || '',
    slogan: station?.slogan || station?.description || station?.defaultText || '',
    category: station?.category || station?.genre || '',
    country: station?.country || '',
    countryCode: station?.countryCode || '',
    language: station?.language || '',
    region: station?.region || '',
    tags: Array.isArray(station?.tags) ? station.tags : [],
    codec: station?.codec || '',
    bitrate: Number.isFinite(bitrate) && bitrate > 0 ? bitrate : null,
    homepage: station?.homepage || station?.website || station?.www || '',
    website: station?.website || station?.homepage || station?.www || '',
    metadata: station?.metadata || (station?.lastSongs ? { lastSongs: station.lastSongs } : {}),
    streams: station?.streams || {
      audio: url,
      ...(getStationVideoUrl(station) ? { video: getStationVideoUrl(station) } : {}),
    },
    enabled: typeof station?.enabled === 'boolean' ? station.enabled : true,
    source: station?.source || station?.raw?.source || '',
    sourceStationUuid: station?.sourceStationUuid || station?.raw?.sourceStationUuid || '',
    raw: station,
    _user: isUserStation,
  };
}

export function getMetadataFetchUrl(url) {
  if (!url || typeof url !== 'string') return '';

  const safeUrl = toHttpsIfHttp(url) || url;
  if (!import.meta.env.DEV) {
    try {
      const parsed = new URL(safeUrl);
      if (parsed.hostname === 'data.radio.si') {
        return '';
      }
    } catch {
      return safeUrl;
    }

    return safeUrl;
  }

  try {
    const parsed = new URL(safeUrl);
    if (parsed.hostname === 'data.radio.si') {
      return `/radio-si-data${parsed.pathname}${parsed.search}`;
    }
  } catch {
    return safeUrl;
  }

  return safeUrl;
}

export function uniqueNonEmpty(urls) {
  const out = [];
  const seen = new Set();
  for (const url of urls) {
    if (!url || typeof url !== 'string') continue;
    const trimmed = url.trim();
    if (!trimmed || seen.has(trimmed)) continue;
    seen.add(trimmed);
    out.push(trimmed);
  }
  return out;
}

export function setImgWithFallback(imgEl, urls, onFinalError) {
  const candidates = uniqueNonEmpty(urls);
  let index = 0;

  if (!imgEl || candidates.length === 0) {
    if (imgEl) {
      imgEl.onload = null;
      imgEl.onerror = null;
      imgEl.src = '';
    }
    if (onFinalError) onFinalError();
    return;
  }

  const tryNext = () => {
    if (index >= candidates.length) {
      if (onFinalError) onFinalError();
      return;
    }
    imgEl.src = candidates[index++];
  };

  imgEl.onerror = tryNext;
  try {
    imgEl.referrerPolicy = 'no-referrer';
  } catch {
    // ignore
  }
  tryNext();
}
