const base64ToBlob = (base64, mimeType) => {
  const binary = atob(base64);
  const len = binary.length;
  const bytes = new Uint8Array(len);
  for (let i = 0; i < len; i += 1) {
    bytes[i] = binary.charCodeAt(i);
  }
  return new Blob([bytes], { type: mimeType });
};

const blobToBase64 = (blob) =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onloadend = () => {
      const result = reader.result;
      if (typeof result === 'string') {
        const commaIndex = result.indexOf(',');
        resolve(result.slice(commaIndex + 1));
      } else {
        reject(new Error('Kapak dosyası okunamadı.'));
      }
    };
    reader.onerror = () => reject(new Error('Kapak dosyası okunamadı.'));
    reader.readAsDataURL(blob);
  });

const API_BASE = import.meta.env.VITE_API_BASE_URL || 'http://localhost:4000';

export const createEpubFromOcr = async (text, coverImage) => {
  if (!text?.trim()) {
    throw new Error('Önce OCR adımını tamamlamalısın.');
  }

  let coverPayload = null;
  if (coverImage?.blob) {
    coverPayload = {
      data: await blobToBase64(coverImage.blob),
      mimeType: coverImage.blob.type || 'image/png',
      filename: coverImage.filename || `cover-${Date.now()}.png`,
    };
  }

  const response = await fetch(`${API_BASE}/generate-epub`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      text,
      meta: {
        title: 'imgPub OCR Export',
        author: 'imgPub',
        filename: `imgpub${Date.now()}.epub`,
      },
      cover: coverPayload,
    }),
  });

  if (!response.ok) {
    const message = await response.text();
    throw new Error(message || 'EPUB oluşturma isteği başarısız.');
  }

  const payload = await response.json();
  const blob = base64ToBlob(payload.data, 'application/epub+zip');
  const url = URL.createObjectURL(blob);

  return {
    filename: payload.filename,
    blob,
    url,
    generatedAt: Date.now(),
  };
};
