const DEFAULT_API_BASE = process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost:8006';

export const getApiBaseUrl = () => {
  return typeof window === 'undefined' ? DEFAULT_API_BASE : '';
};

export const isAbsoluteUrl = (url: string) => /^https?:\/\//i.test(url);

export const joinBaseUrl = (base: string, path: string) => {
  if (!base) return path;
  if (!path.startsWith('/')) return `${base}/${path}`;
  return `${base}${path}`;
};

export const resolveMediaUrl = (url?: string | null) => {
  if (!url) return null;
  if (isAbsoluteUrl(url)) return url;
  return joinBaseUrl(getApiBaseUrl(), url);
};

export const encodePathSegments = (value: string) =>
  value.split('/').map(encodeURIComponent).join('/');

export const resolveAssetUrl = (assetPath?: string | null) => {
  if (!assetPath) return null;
  const encoded = encodePathSegments(assetPath);
  return joinBaseUrl(getApiBaseUrl(), `/assets/${encoded}`);
};

export const resolveBgmUrl = (bgmId?: string | null) => {
  if (!bgmId) return null;
  return resolveAssetUrl(`bgm/${bgmId}`);
};

export const getFontFormat = (fontFile?: string) => {
  if (!fontFile) return 'truetype';
  const ext = fontFile.split('.').pop()?.toLowerCase();
  if (ext === 'otf') return 'opentype';
  return 'truetype';
};

export const buildTextShadow = (color: string, size: number) => {
  return [
    `-${size}px -${size}px 0 ${color}`,
    `${size}px -${size}px 0 ${color}`,
    `-${size}px ${size}px 0 ${color}`,
    `${size}px ${size}px 0 ${color}`,
    `0 0 ${size * 4}px rgba(0,0,0,0.9)`,
    `0 4px 8px rgba(0,0,0,0.6)`
  ].join(',');
};

export const formatDate = (timestamp: number) => {
  const d = new Date(timestamp * 1000);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  const hour = String(d.getHours()).padStart(2, '0');
  const minute = String(d.getMinutes()).padStart(2, '0');
  return `${year}/${month}/${day} ${hour}:${minute}`;
};
