import { useAppStore } from '../store/useAppStore';

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

const getAuthToken = () => {
  const { authToken } = useAppStore.getState();
  if (!authToken) {
    throw new Error('Çeviri için giriş yapmalısın.');
  }
  return authToken;
};

export const translateChunkToTurkish = async (text) => {
  if (!text?.trim()) {
    throw new Error('Çevrilecek metin bulunamadı.');
  }

  const token = getAuthToken();
  const response = await fetch(`${API_BASE}/translate`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${token}`,
    },
    body: JSON.stringify({ text }),
  });

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

  const payload = await response.json();
  if (!payload?.text) {
    throw new Error('Çeviri yanıtı boş döndü.');
  }

  return payload.text.trim();
};

export const segmentOcrText = (text, maxChunkLength = 800) => {
  if (!text) return [];
  const normalized = text.replace(/\r\n/g, '\n');
  const paragraphs = normalized.split(/\n{2,}/).map((part) => part.trim()).filter(Boolean);
  const chunks = [];

  paragraphs.forEach((paragraph) => {
    if (paragraph.length <= maxChunkLength) {
      chunks.push(paragraph);
      return;
    }

    let remaining = paragraph;
    while (remaining.length > maxChunkLength) {
      let sliceIndex = remaining.lastIndexOf(' ', maxChunkLength);
      if (sliceIndex === -1 || sliceIndex < maxChunkLength * 0.6) {
        sliceIndex = maxChunkLength;
      }
      const chunk = remaining.slice(0, sliceIndex).trim();
      if (chunk) {
        chunks.push(chunk);
      }
      remaining = remaining.slice(sliceIndex).trim();
    }
    if (remaining.length) {
      chunks.push(remaining);
    }
  });

  return chunks;
};
