/* image-upload.js — 클라이언트 이미지 리사이즈 + WebP 변환 + Supabase Storage 업로드
 * 2026-04-29: 후기 사진 첨부 기능 (최대 3장)
 * 2026-04-30: bucket 'review-images' → 'site-images'로 통합 (제품/공지/QnA/후기 모두)
 *
 * 흐름:
 *   File → canvas 리사이즈(1200px max) → WebP blob (quality 0.85)
 *   → Supabase Storage POST → public URL 반환
 *
 * DEMO 모드: data: URL 그대로 반환 (localStorage 공간 한정)
 */

const MAX_W = 1200;
const QUALITY = 0.85;
// DEMO 모드 (localStorage)는 quota 5~10MB 제약이라 더 작게 압축
const DEMO_MAX_W = 600;
const DEMO_QUALITY = 0.7;

/**
 * 단일 파일 → 리사이즈 + WebP blob
 */
async function fileToWebpBlob(file, opts = {}) {
  const maxW = opts.maxW || MAX_W;
  const quality = opts.quality || QUALITY;
  const dataUrl = await new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = e => resolve(e.target.result);
    reader.onerror = reject;
    reader.readAsDataURL(file);
  });
  const img = await new Promise((resolve, reject) => {
    const i = new Image();
    i.onload = () => resolve(i);
    i.onerror = reject;
    i.src = dataUrl;
  });
  const ratio = Math.min(1, maxW / Math.max(img.naturalWidth, img.naturalHeight));
  const w = Math.round(img.naturalWidth * ratio);
  const h = Math.round(img.naturalHeight * ratio);
  const canvas = document.createElement('canvas');
  canvas.width = w; canvas.height = h;
  const ctx = canvas.getContext('2d');
  ctx.drawImage(img, 0, 0, w, h);
  return await new Promise(resolve => canvas.toBlob(resolve, 'image/webp', quality));
}

/**
 * Supabase Storage 업로드 — public URL 반환
 */
async function uploadToSupabase(blob, cfg) {
  const filename = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}.webp`;
  const url = `${cfg.SUPABASE_URL}/storage/v1/object/site-images/${filename}`;
  const r = await fetch(url, {
    method: 'POST',
    headers: {
      apikey: cfg.SUPABASE_ANON,
      Authorization: `Bearer ${cfg.SUPABASE_ANON}`,
      'Content-Type': 'image/webp',
    },
    body: blob,
  });
  if (!r.ok) throw new Error(`Storage ${r.status}: ${await r.text()}`);
  return `${cfg.SUPABASE_URL}/storage/v1/object/public/site-images/${filename}`;
}

/**
 * DEMO 모드 — blob → data: URL (localStorage에 저장)
 */
async function blobToDataUrl(blob) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = e => resolve(e.target.result);
    reader.onerror = reject;
    reader.readAsDataURL(blob);
  });
}

/**
 * 파일 배열 → URL 배열 (Supabase 또는 data:)
 * DEMO 모드에서는 더 작게 압축 (localStorage quota 회피)
 */
export async function uploadImages(files, cfg) {
  if (!files || !files.length) return [];
  const isDemo = cfg.DEMO_MODE
    || !cfg.SUPABASE_URL.includes('supabase.co')
    || cfg.SUPABASE_URL.startsWith('https://YOUR-');
  const opts = isDemo ? { maxW: DEMO_MAX_W, quality: DEMO_QUALITY } : { maxW: MAX_W, quality: QUALITY };
  const urls = [];
  for (const f of files) {
    const blob = await fileToWebpBlob(f, opts);
    const url = isDemo ? await blobToDataUrl(blob) : await uploadToSupabase(blob, cfg);
    urls.push(url);
  }
  return urls;
}
