/**
 * Converts an array of block formats to TinyMCE format string
 * @param {Array<{title: string, tag: string}>} formats - Array of block formats
 * @returns {string} TinyMCE format string
 */
export const getFormatsString = (formats) => {
  return formats.map(format => `${format.title}=${format.tag}`).join(';');
};

/**
 * Converts toolbar styles to format string
 * @param {string} toolbar - Comma-separated list of styles
 * @returns {Object} Object containing formats array and custom classes array
 */
export const getToolbarFormats = (toolbar) => {
  if (!toolbar || typeof toolbar !== 'string') return { formats: [], customClasses: [] };

  const formats = [];
  const customClasses = [];

  toolbar.split(',').forEach((style) => {
    const trimmedStyle = style.trim();

    if (trimmedStyle.startsWith('h')) {
      const level = trimmedStyle.match(/\d+/)[0];
      formats.push({
        title: `Heading ${level}`,
        tag: trimmedStyle
      });
    } else if (trimmedStyle === 'p') {
      formats.push({
        title: 'Paragraph',
        tag: 'p'
      });
    } else if (trimmedStyle.startsWith('custom[')) {
      // Extract custom class name from custom[className]
      const match = trimmedStyle.match(/custom\[([^\]]+)\]/);
      if (match && match[1]) {
        customClasses.push(match[1]);
      }
    }
  });

  return { formats, customClasses };
};

/**
 * Gets the link type based on the URL
 * @param {string} url - The URL to check
 * @returns {string} The link type
 */
export const getLinkType = (url) => {
  if (!url) return LINK_TYPES.URL;

  try {
    const urlObj = new URL(encodeURI(url));
    if (urlObj.protocol.includes('mailto')) return LINK_TYPES.MAILTO;
    if (urlObj.protocol.includes('tel')) return LINK_TYPES.TELEPHONE;
  } catch (error) {
    // Invalid URL, check if it's an internal link
    if (url.startsWith('#')) return LINK_TYPES.INTERNAL;
  }

  return LINK_TYPES.URL;
}; 