// SEO Utility Functions
// Helpers for generating meta tags, structured data, and canonical URLs

export interface SEOMetadata {
  title: string;
  description: string;
  keywords?: string[];
  canonicalUrl?: string;
  ogImage?: string;
  ogType?: 'website' | 'article' | 'profile';
  twitterCard?: 'summary' | 'summary_large_image' | 'player';
  publishedTime?: string;
  modifiedTime?: string;
  author?: string;
  noIndex?: boolean;
}

/**
 * Generate page title with site name
 */
export function generatePageTitle(title: string, siteName: string = 'WorkRoot IT Solutions'): string {
  if (title === 'Home' || title.includes(siteName)) {
    return siteName;
  }
  return `${title} | ${siteName}`;
}

/**
 * Generate keywords from tags and categories
 */
export function generateKeywords(tags: string[], additionalKeywords: string[] = []): string {
  const baseKeywords = [
    'web development',
    'mobile apps',
    'AI solutions',
    'cloud services',
    'IT consulting',
  ];

  const allKeywords = [...new Set([...baseKeywords, ...tags, ...additionalKeywords])];
  return allKeywords.join(', ');
}

/**
 * Generate breadcrumb structured data
 */
export function generateBreadcrumbSchema(breadcrumbs: Array<{ name: string; url: string }>, siteUrl: string = 'https://workroot.in') {
  return {
    '@context': 'https://schema.org',
    '@type': 'BreadcrumbList',
    itemListElement: breadcrumbs.map((item, index) => ({
      '@type': 'ListItem',
      position: index + 1,
      name: item.name,
      item: `${siteUrl}${item.url}`,
    })),
  };
}

/**
 * Generate Article structured data for blog posts
 */
export function generateArticleSchema(
  title: string,
  description: string,
  author: string,
  publishedTime: string,
  modifiedTime: string,
  imageUrl: string,
  url: string,
  keywords: string[] = []
) {
  return {
    '@context': 'https://schema.org',
    '@type': 'Article',
    headline: title,
    description: description,
    image: imageUrl,
    datePublished: publishedTime,
    dateModified: modifiedTime,
    author: {
      '@type': 'Person',
      name: author,
    },
    publisher: {
      '@type': 'Organization',
      name: 'WorkRoot IT Solutions LLP',
      logo: {
        '@type': 'ImageObject',
        url: 'https://workroot.in/logo.png',
      },
    },
    mainEntityOfPage: {
      '@type': 'WebPage',
      '@id': url,
    },
    keywords: keywords.join(', '),
  };
}

/**
 * Generate FAQ structured data
 */
export function generateFAQSchema(faqs: Array<{ question: string; answer: string }>) {
  return {
    '@context': 'https://schema.org',
    '@type': 'FAQPage',
    mainEntity: faqs.map((faq) => ({
      '@type': 'Question',
      name: faq.question,
      acceptedAnswer: {
        '@type': 'Answer',
        text: faq.answer,
      },
    })),
  };
}

/**
 * Generate Service structured data
 */
export function generateServiceSchema(
  serviceName: string,
  description: string,
  features: string[] = [],
  siteUrl: string = 'https://workroot.in'
) {
  return {
    '@context': 'https://schema.org',
    '@type': 'Service',
    name: serviceName,
    description: description,
    provider: {
      '@type': 'Organization',
      name: 'WorkRoot IT Solutions LLP',
      url: siteUrl,
    },
    areaServed: {
      '@type': 'GeoShape',
      name: 'Worldwide',
    },
    serviceType: serviceName,
    offers: {
      '@type': 'Offer',
      availability: 'https://schema.org/InStock',
    },
    hasOfferCatalog: {
      '@type': 'OfferCatalog',
      name: `${serviceName} Features`,
      itemListElement: features.map((feature, index) => ({
        '@type': 'Offer',
        itemOffered: {
          '@type': 'Service',
          name: feature,
        },
      })),
    },
  };
}

/**
 * Generate canonical URL
 */
export function generateCanonicalUrl(pathname: string, siteUrl: string = 'https://workroot.in'): string {
  // Remove trailing slash for consistency (except for root)
  const cleanPath = pathname === '/' ? pathname : pathname.replace(/\/$/, '');
  return `${siteUrl}${cleanPath}`;
}

/**
 * Truncate description to optimal length
 */
export function truncateDescription(description: string, maxLength: number = 160): string {
  if (description.length <= maxLength) {
    return description;
  }

  // Find last complete word before maxLength
  const truncated = description.substring(0, maxLength);
  const lastSpace = truncated.lastIndexOf(' ');

  return truncated.substring(0, lastSpace) + '...';
}

/**
 * Generate Open Graph image URL
 */
export function generateOGImageUrl(imagePath: string, siteUrl: string = 'https://workroot.in'): string {
  if (imagePath.startsWith('http://') || imagePath.startsWith('https://')) {
    return imagePath;
  }
  return `${siteUrl}${imagePath.startsWith('/') ? imagePath : `/${imagePath}`}`;
}

/**
 * Check if URL should be indexed
 */
export function shouldIndexPage(pathname: string): boolean {
  const noIndexPatterns = [
    '/admin',
    '/private',
    '/api',
    '/preview',
    '/draft',
  ];

  return !noIndexPatterns.some(pattern => pathname.startsWith(pattern));
}

/**
 * Generate social media share URLs
 */
export function generateShareUrls(url: string, title: string) {
  const encodedUrl = encodeURIComponent(url);
  const encodedTitle = encodeURIComponent(title);

  return {
    twitter: `https://twitter.com/intent/tweet?url=${encodedUrl}&text=${encodedTitle}`,
    facebook: `https://www.facebook.com/sharer/sharer.php?u=${encodedUrl}`,
    linkedin: `https://www.linkedin.com/sharing/share-offsite/?url=${encodedUrl}`,
    email: `mailto:?subject=${encodedTitle}&body=${encodedUrl}`,
  };
}
