export const createAnnotationData = () => ({
  highlights: [],
  comments: [],
  version: '2.0.0',
  createdAt: Date.now()
});

export const generateId = () => {
  return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
};

const migrateHighlight = (highlight) => {
  if ('positions' in highlight) {
    return highlight;
  }
  if ('position' in highlight) {
    return {
      ...highlight,
      positions: [highlight.position]
    };
  }
  return highlight;
};

export const addHighlight = (
  data,
  highlight
) => {
  const newHighlight = {
    ...highlight,
    id: generateId()
  };

  return {
    ...data,
    highlights: [...data.highlights, newHighlight]
  };
};

export const removeHighlight = (
  data,
  highlightId
) => {
  return {
    ...data,
    highlights: data.highlights.filter(h => h.id !== highlightId),
    comments: data.comments.filter(c => c.highlightId !== highlightId)
  };
};

export const addComment = (
  data,
  highlightId,
  text,
  pageNumber = null,
  content = null
) => {
  const newComment = {
    id: generateId(),
    highlightId,
    text,
    pageNumber,
    content,
    createdAt: Date.now()
  };

  return {
    ...data,
    comments: [...data.comments, newComment]
  };
};

export const removeComment = (
  data,
  commentId
) => {
  return {
    ...data,
    comments: data.comments.filter(c => c.id !== commentId)
  };
};

export const exportAnnotations = (data) => {
  const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = `annotations-${new Date().toISOString().slice(0, 10)}.json`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
};

export const importAnnotations = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = (e) => {
      try {
        const data = JSON.parse(e.target?.result);
        const migratedData = {
          ...data,
          highlights: data.highlights.map(migrateHighlight),
          version: '2.0.0'
        };
        resolve(migratedData);
      } catch (err) {
        reject(err);
      }
    };
    reader.onerror = reject;
    reader.readAsText(file);
  });
};
