// ===== 하단 추천 글 — 5초마다 2개씩 자동 슬라이드 =====
const BLOG_RSS  = 'https://choshg.tistory.com/rss';
const BLOG_HOME = 'https://choshg.tistory.com/';
const SLIDE_INTERVAL = 5000; // ms

async function fetchBlogPosts() {
  const res = await fetch(BLOG_RSS, { cache: 'no-cache' });
  const text = await res.text();
  const doc  = new DOMParser().parseFromString(text, 'application/xml');
  return [...doc.querySelectorAll('item')]
    .map((it) => {
      const get = (tag) => it.querySelector(tag)?.textContent?.trim() || '';
      return { title: get('title'), url: get('link') };
    })
    .filter((p) => p.title && p.url);
}

function renderPromoItems(posts) {
  const list = document.getElementById('promoList');
  if (!list) return;

  // 페이드아웃 → 내용 교체 → 페이드인
  list.style.opacity = '0';
  setTimeout(() => {
    list.innerHTML = '';
    const items = posts.length
      ? posts
      : [{ title: '블로그 방문하기 — choshg.tistory.com', url: BLOG_HOME }];

    items.forEach((post) => {
      const li = document.createElement('li');
      li.className = 'promo-item';
      const a  = document.createElement('a');
      a.className  = 'promo-link';
      a.href       = post.url;
      a.target     = '_blank';
      a.rel        = 'noopener noreferrer';
      a.textContent = post.title;
      a.title       = post.title;
      li.appendChild(a);
      list.appendChild(li);
    });
    list.style.opacity = '1';
  }, 250);
}

async function initPromo() {
  let posts = [];
  try {
    posts = await fetchBlogPosts();
  } catch (e) {
    console.warn('블로그 글 불러오기 실패:', e);
  }

  if (!posts.length) { renderPromoItems([]); return; }

  let idx = 0;

  const showNext = () => {
    const slice = [
      posts[idx % posts.length],
      posts[(idx + 1) % posts.length],
    ];
    renderPromoItems(slice);
    idx = (idx + 2) % posts.length;
  };

  showNext(); // 즉시 첫 2개 표시
  setInterval(showNext, SLIDE_INTERVAL); // 5초마다 다음 2개
}

initPromo();

const uploadArea = document.getElementById('uploadArea');
const fileInput = document.getElementById('fileInput');
const uploadContent = document.getElementById('uploadContent');
const previewArea = document.getElementById('previewArea');
const originalImg = document.getElementById('originalImg');
const resultImg = document.getElementById('resultImg');
const processingMsg = document.getElementById('processingMsg');
const processHint = document.getElementById('processHint');
const saveOptions = document.getElementById('saveOptions');
const saveBtn = document.getElementById('saveBtn');
const resetBtn = document.getElementById('resetBtn');
const customCheck = document.getElementById('customCheck');
const customInputs = document.getElementById('customInputs');

let resultBlob = null;
let originalFileName = 'logo';

// ── 컨텍스트 메뉴(우클릭)에서 이미지 URL 수신 ──
chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => {
  if (msg.type !== 'context-image' || !msg.imageUrl) return;
  sendResponse({ ok: true });
  handleImageUrl(msg.imageUrl);
});

async function handleImageUrl(url) {
  try {
    // 파일명 추출
    const name = decodeURIComponent(url.split('/').pop().split('?')[0])
      .replace(/\.[^.]+$/, '') || 'image';
    originalFileName = name;

    // URL → Blob으로 fetch
    const res = await fetch(url);
    if (!res.ok) throw new Error(`fetch 실패: ${res.status}`);
    const blob = await res.blob();

    // 이미지 파일처럼 처리
    const file = new File([blob], `${name}.png`, { type: blob.type || 'image/png' });
    handleFile(file);
  } catch (e) {
    console.error('URL 이미지 처리 실패:', e);
    alert(`이미지를 가져오지 못했습니다.\n${e.message}`);
  }
}

// --- Sandbox bridge: the heavy AI processing runs in sandbox.html (iframe) ---
const sandbox = document.getElementById('sandbox');
let sandboxReady = false;
let jobCounter = 0;
const pendingJobs = new Map(); // id -> { resolve, reject, onProgress }

window.addEventListener('message', (event) => {
  const msg = event.data;
  if (!msg) return;

  if (msg.type === 'sandbox-ready') {
    sandboxReady = true;
    return;
  }

  const job = pendingJobs.get(msg.id);
  if (!job) return;

  if (msg.type === 'progress') {
    job.onProgress?.(msg.key, msg.current, msg.total, msg.device);
  } else if (msg.type === 'result') {
    pendingJobs.delete(msg.id);
    job.resolve(msg.blob);
  } else if (msg.type === 'error') {
    pendingJobs.delete(msg.id);
    job.reject(new Error(msg.message));
  }
});

function waitForSandbox(timeoutMs = 5000) {
  if (sandboxReady) return Promise.resolve();
  return new Promise((resolve, reject) => {
    const start = Date.now();
    const iv = setInterval(() => {
      if (sandboxReady) { clearInterval(iv); resolve(); }
      else if (Date.now() - start > timeoutMs) { clearInterval(iv); reject(new Error('샌드박스 초기화 실패')); }
    }, 50);
  });
}

function removeBackgroundViaSandbox(file, onProgress) {
  const id = ++jobCounter;
  return new Promise(async (resolve, reject) => {
    try {
      await waitForSandbox();
      pendingJobs.set(id, { resolve, reject, onProgress });
      sandbox.contentWindow.postMessage({ type: 'remove-bg', id, file }, '*');
    } catch (e) {
      reject(e);
    }
  });
}

// 업로드 영역 클릭
uploadArea.addEventListener('click', () => fileInput.click());

// 드래그앤드롭
uploadArea.addEventListener('dragover', (e) => {
  e.preventDefault();
  uploadArea.classList.add('drag-over');
});

uploadArea.addEventListener('dragleave', () => {
  uploadArea.classList.remove('drag-over');
});

uploadArea.addEventListener('drop', (e) => {
  e.preventDefault();
  uploadArea.classList.remove('drag-over');
  const file = e.dataTransfer.files[0];
  if (file && file.type.startsWith('image/')) handleFile(file);
});

fileInput.addEventListener('change', (e) => {
  const file = e.target.files[0];
  if (file) handleFile(file);
});

// 커스텀 해상도 체크박스
customCheck.addEventListener('change', () => {
  customInputs.style.display = customCheck.checked ? 'flex' : 'none';
});

// 초기화
resetBtn.addEventListener('click', () => {
  resultBlob = null;
  fileInput.value = '';
  resultImg.style.display = 'none';
  processingMsg.style.display = 'none';
  saveOptions.style.display = 'none';
  document.getElementById('autoSavedBanner').style.display = 'none';
  previewArea.style.display = 'none';
  uploadArea.style.display = 'block';
});

async function handleFile(file) {
  originalFileName = file.name.replace(/\.[^.]+$/, '');

  // 원본 미리보기
  const reader = new FileReader();
  reader.onload = (e) => {
    originalImg.src = e.target.result;
  };
  reader.readAsDataURL(file);

  // UI 전환
  uploadArea.style.display = 'none';
  previewArea.style.display = 'block';
  resultImg.style.display = 'none';
  processingMsg.style.display = 'flex';
  processingMsg.style.flexDirection = 'column';
  processingMsg.style.alignItems = 'center';
  saveOptions.style.display = 'none';
  saveBtn.disabled = true;

  try {
    processHint.textContent = 'AI 모델 로딩 중 (최초 1회 약 30초)...';

    const result = await removeBackgroundViaSandbox(file, (key, current, total, device) => {
      const tag = device === 'webgpu' ? 'GPU 가속' : 'CPU';
      if (total > 0) {
        const pct = Math.round((current / total) * 100);
        processHint.textContent = `[${tag}] ${key}: ${pct}%`;
      } else {
        processHint.textContent = `[${tag}] 배경 제거 처리 중...`;
      }
    });

    resultBlob = result;
    const url = URL.createObjectURL(result);
    resultImg.src = url;
    resultImg.style.display = 'block';
    processingMsg.style.display = 'none';
    saveOptions.style.display = 'block';
    saveBtn.disabled = false;

    // 배경 제거 완료 → 원본 크기 PNG 자동 저장 후 추가 변환 대기
    await autoSaveDefault();
  } catch (err) {
    processingMsg.innerHTML = `<p style="color:#f87171">오류: ${err.message}</p>`;
    console.error(err);
  }
}

/**
 * 이미지 저장 유틸
 * mode:
 *  { type: 'original' }          — 원본 크기 그대로
 *  { type: 'long', px: N }       — 긴 변을 N px로, 비율 유지
 *  { type: 'square', px: N }     — N×N 정사각형 (여백 투명)
 *  { type: 'custom', w: W, h: H }— 직접 지정
 */
async function saveOne(mode, format, suffix) {
  if (!resultBlob) return;
  const mimeType = format === 'webp' ? 'image/webp' : 'image/png';
  const ext = format;
  const bmp = await createImageBitmap(resultBlob);

  let cw, ch, dx = 0, dy = 0, dw, dh;

  if (mode.type === 'original') {
    cw = bmp.width; ch = bmp.height;
    dw = cw; dh = ch;
  } else if (mode.type === 'long') {
    const scale = mode.px / Math.max(bmp.width, bmp.height);
    dw = Math.round(bmp.width * scale);
    dh = Math.round(bmp.height * scale);
    cw = dw; ch = dh;
  } else if (mode.type === 'square') {
    cw = ch = mode.px;
    const scale = Math.min(cw / bmp.width, ch / bmp.height);
    dw = Math.round(bmp.width * scale);
    dh = Math.round(bmp.height * scale);
    dx = Math.round((cw - dw) / 2);
    dy = Math.round((ch - dh) / 2);
  } else { // custom
    cw = mode.w; ch = mode.h;
    const scale = Math.min(cw / bmp.width, ch / bmp.height);
    dw = Math.round(bmp.width * scale);
    dh = Math.round(bmp.height * scale);
    dx = Math.round((cw - dw) / 2);
    dy = Math.round((ch - dh) / 2);
  }

  const canvas = document.createElement('canvas');
  canvas.width = cw; canvas.height = ch;
  const ctx = canvas.getContext('2d');
  ctx.clearRect(0, 0, cw, ch);
  ctx.drawImage(bmp, dx, dy, dw, dh);

  return new Promise((resolve) => {
    canvas.toBlob(async (blob) => {
      const url = URL.createObjectURL(blob);
      await chrome.downloads.download({
        url,
        filename: `${originalFileName}_실BG${suffix}.${ext}`,
        saveAs: false,
      });
      resolve();
    }, mimeType, 0.95);
  });
}

// 원본 크기 자동 저장
async function autoSaveDefault() {
  try {
    await saveOne({ type: 'original' }, 'png', '');
    const banner = document.getElementById('autoSavedBanner');
    if (banner) banner.style.display = 'flex';
  } catch (e) {
    console.error('자동 저장 실패:', e);
  }
}

// 추가 저장
saveBtn.addEventListener('click', async () => {
  if (!resultBlob) return;
  const format = document.querySelector('input[name="format"]:checked').value;

  const jobs = [];

  document.querySelectorAll('.resolution-grid input[type="checkbox"]:not(#customCheck)').forEach(cb => {
    if (!cb.checked) return;
    const val = cb.value;
    if (val.startsWith('long-')) {
      const px = parseInt(val.split('-')[1]);
      jobs.push({ mode: { type: 'long', px }, suffix: `_${px}` });
    } else if (val.startsWith('square-')) {
      const px = parseInt(val.split('-')[1]);
      jobs.push({ mode: { type: 'square', px }, suffix: `_${px}x${px}` });
    }
  });

  if (customCheck.checked) {
    const w = parseInt(document.getElementById('customWidth').value);
    const h = parseInt(document.getElementById('customHeight').value);
    if (w > 0 && h > 0) {
      jobs.push({ mode: { type: 'custom', w, h }, suffix: `_${w}x${h}` });
    } else {
      alert('직접 입력 해상도를 올바르게 입력해주세요.');
      return;
    }
  }

  if (jobs.length === 0) {
    alert('저장할 옵션을 하나 이상 선택해주세요.');
    return;
  }

  saveBtn.disabled = true;
  saveBtn.textContent = '저장 중...';

  for (const { mode, suffix } of jobs) {
    await saveOne(mode, format, suffix);
  }

  saveBtn.disabled = false;
  saveBtn.textContent = `✅ ${jobs.length}개 파일 저장 완료!`;
  setTimeout(() => { saveBtn.textContent = '💾 추가 저장하기'; }, 3000);
});
