/**
 * SEO Utilities for Visworks365
 * Provides helper functions for generating SEO meta tags, Open Graph, Twitter Cards, and more
 */

export interface SEOConfig {
  title: string;
  description: string;
  url?: string;
  image?: string;
  imageAlt?: string;
  type?: 'website' | 'article' | 'profile';
  publishedTime?: string;
  modifiedTime?: string;
  author?: string;
  tags?: string[];
  noIndex?: boolean;
  noFollow?: boolean;
  canonical?: string;
}

export const SITE_CONFIG = {
  name: 'Visworks365',
  shortName: 'Visworks365',
  tagline: 'Brand with Purpose - Grow with Clarity',
  description: 'We don\'t just build brands—we bring them into alignment. From startups to growing organizations, we help visionary founders and teams clarify who they are, what they stand for, and how they show up in the world.',
  siteUrl: 'https://visworks365.com', // Update with your actual domain
  logo: '/logo.png', // Update with your actual logo path
  defaultImage: '/og-image.png', // Update with your actual default OG image
  twitterHandle: '@visworks365', // Update with your actual Twitter handle
  facebookPage: 'https://facebook.com/visworks365', // Update with your actual Facebook page
  linkedInPage: 'https://linkedin.com/company/visworks365', // Update with your actual LinkedIn page
  instagramHandle: '@visworks365', // Update with your actual Instagram handle
  organizationType: 'Organization' as const,
  foundingDate: '2020', // Update with actual founding date
  address: {
    streetAddress: '', // Add your street address
    addressLocality: '', // Add your city
    addressRegion: '', // Add your state/region
    postalCode: '', // Add your postal code
    addressCountry: 'US', // Update with your country code
  },
  contactPoint: {
    telephone: '', // Add your phone number
    contactType: 'customer service',
    email: 'info@visworks365.com', // Update with your actual email
  },
  developer: {
    name: 'Sycamore Systems',
    url: 'https://sycamore.co.zw',
    description: 'A technology partner helping organisations prepare for and thrive in moments of growth.',
    linkedin: 'https://www.linkedin.com/company/sycamore-systems/',
    github: 'https://github.com/sycamore-systems',
  },
};

/**
 * Generate meta tags for SEO
 */
export function generateMetaTags(config: SEOConfig) {
  const {
    title,
    description,
    url = SITE_CONFIG.siteUrl,
    image = SITE_CONFIG.defaultImage,
    imageAlt = title,
    type = 'website',
    publishedTime,
    modifiedTime,
    author,
    tags,
    noIndex = false,
    noFollow = false,
    canonical,
  } = config;

  const fullTitle = title.includes(SITE_CONFIG.name) ? title : `${title} | ${SITE_CONFIG.name}`;
  const fullImageUrl = image.startsWith('http') ? image : `${SITE_CONFIG.siteUrl}${image}`;

  const metaTags: Array<{ title?: string; name?: string; property?: string; content: string; tagName?: string; charSet?: string }> = [
    { title: fullTitle },
    { name: 'description', content: description },
    
    // Robots
    ...(noIndex || noFollow ? [{ name: 'robots', content: `${noIndex ? 'noindex' : 'index'},${noFollow ? 'nofollow' : 'follow'}` }] : []),
    
    // Canonical
    ...(canonical ? [{ tagName: 'link', rel: 'canonical', href: canonical } as any] : []),
    
    // Open Graph
    { property: 'og:title', content: fullTitle },
    { property: 'og:description', content: description },
    { property: 'og:type', content: type },
    { property: 'og:url', content: url },
    { property: 'og:image', content: fullImageUrl },
    { property: 'og:image:alt', content: imageAlt },
    { property: 'og:site_name', content: SITE_CONFIG.name },
    { property: 'og:locale', content: 'en_US' },
    
    // Twitter Card
    { name: 'twitter:card', content: 'summary_large_image' },
    { name: 'twitter:site', content: SITE_CONFIG.twitterHandle },
    { name: 'twitter:title', content: fullTitle },
    { name: 'twitter:description', content: description },
    { name: 'twitter:image', content: fullImageUrl },
    { name: 'twitter:image:alt', content: imageAlt },
  ];

  // Article-specific meta tags
  if (type === 'article') {
    if (publishedTime) {
      metaTags.push({ property: 'article:published_time', content: publishedTime });
    }
    if (modifiedTime) {
      metaTags.push({ property: 'article:modified_time', content: modifiedTime });
    }
    if (author) {
      metaTags.push({ property: 'article:author', content: author });
    }
    if (tags && tags.length > 0) {
      tags.forEach(tag => {
        metaTags.push({ property: 'article:tag', content: tag });
      });
    }
  }

  return metaTags;
}

/**
 * Generate breadcrumb list for structured data
 */
export function generateBreadcrumbList(items: Array<{ name: string; url: string }>) {
  return {
    '@context': 'https://schema.org',
    '@type': 'BreadcrumbList',
    itemListElement: items.map((item, index) => ({
      '@type': 'ListItem',
      position: index + 1,
      name: item.name,
      item: item.url,
    })),
  };
}

/**
 * Generate FAQ schema
 */
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 Organization schema
 */
export function generateOrganizationSchema() {
  return {
    '@context': 'https://schema.org',
    '@type': SITE_CONFIG.organizationType,
    name: SITE_CONFIG.name,
    alternateName: SITE_CONFIG.shortName,
    url: SITE_CONFIG.siteUrl,
    logo: `${SITE_CONFIG.siteUrl}${SITE_CONFIG.logo}`,
    description: SITE_CONFIG.description,
    foundingDate: SITE_CONFIG.foundingDate,
    address: {
      '@type': 'PostalAddress',
      ...SITE_CONFIG.address,
    },
    contactPoint: {
      '@type': 'ContactPoint',
      ...SITE_CONFIG.contactPoint,
    },
    sameAs: [
      SITE_CONFIG.facebookPage,
      SITE_CONFIG.linkedInPage,
      `https://twitter.com/${SITE_CONFIG.twitterHandle.replace('@', '')}`,
      `https://instagram.com/${SITE_CONFIG.instagramHandle.replace('@', '')}`,
    ],
  };
}

/**
 * Generate WebPage schema with developer credit
 */
export function generateWebPageSchema(pageInfo: {
  name: string;
  description: string;
  url: string;
}) {
  return {
    '@context': 'https://schema.org',
    '@type': 'WebPage',
    name: pageInfo.name,
    description: pageInfo.description,
    url: pageInfo.url,
    creator: {
      '@type': 'Organization',
      name: SITE_CONFIG.developer.name,
      url: SITE_CONFIG.developer.url,
      description: SITE_CONFIG.developer.description,
      sameAs: [
        SITE_CONFIG.developer.linkedin,
        SITE_CONFIG.developer.github,
      ],
    },
    isPartOf: {
      '@type': 'WebSite',
      name: SITE_CONFIG.name,
      url: SITE_CONFIG.siteUrl,
    },
  };
}

/**
 * Generate WebSite schema with search action
 */
export function generateWebSiteSchema() {
  return {
    '@context': 'https://schema.org',
    '@type': 'WebSite',
    name: SITE_CONFIG.name,
    alternateName: SITE_CONFIG.shortName,
    url: SITE_CONFIG.siteUrl,
    description: SITE_CONFIG.description,
    publisher: {
      '@type': SITE_CONFIG.organizationType,
      name: SITE_CONFIG.name,
      logo: {
        '@type': 'ImageObject',
        url: `${SITE_CONFIG.siteUrl}${SITE_CONFIG.logo}`,
      },
    },
  };
}

/**
 * Generate Article schema for blog posts
 */
export function generateArticleSchema(article: {
  title: string;
  description: string;
  image: string;
  datePublished: string;
  dateModified?: string;
  author: string;
  url: string;
}) {
  return {
    '@context': 'https://schema.org',
    '@type': 'Article',
    headline: article.title,
    description: article.description,
    image: article.image.startsWith('http') ? article.image : `${SITE_CONFIG.siteUrl}${article.image}`,
    datePublished: article.datePublished,
    dateModified: article.dateModified || article.datePublished,
    author: {
      '@type': 'Person',
      name: article.author,
    },
    publisher: {
      '@type': SITE_CONFIG.organizationType,
      name: SITE_CONFIG.name,
      logo: {
        '@type': 'ImageObject',
        url: `${SITE_CONFIG.siteUrl}${SITE_CONFIG.logo}`,
      },
    },
    mainEntityOfPage: {
      '@type': 'WebPage',
      '@id': article.url,
    },
  };
}

/**
 * Generate Service schema
 */
export function generateServiceSchema(service: {
  name: string;
  description: string;
  provider?: string;
}) {
  return {
    '@context': 'https://schema.org',
    '@type': 'Service',
    name: service.name,
    description: service.description,
    provider: {
      '@type': SITE_CONFIG.organizationType,
      name: service.provider || SITE_CONFIG.name,
      url: SITE_CONFIG.siteUrl,
    },
  };
}

/**
 * Generate Review/Testimonial schema
 */
export function generateReviewSchema(review: {
  author: string;
  reviewBody: string;
  reviewRating?: number;
  datePublished?: string;
}) {
  const schema: any = {
    '@context': 'https://schema.org',
    '@type': 'Review',
    author: {
      '@type': 'Person',
      name: review.author,
    },
    reviewBody: review.reviewBody,
    itemReviewed: {
      '@type': SITE_CONFIG.organizationType,
      name: SITE_CONFIG.name,
    },
  };

  if (review.reviewRating) {
    schema.reviewRating = {
      '@type': 'Rating',
      ratingValue: review.reviewRating,
      bestRating: '5',
    };
  }

  if (review.datePublished) {
    schema.datePublished = review.datePublished;
  }

  return schema;
}

/**
 * Generate aggregate rating schema
 */
export function generateAggregateRatingSchema(rating: {
  ratingValue: number;
  reviewCount: number;
  bestRating?: number;
  worstRating?: number;
}) {
  return {
    '@context': 'https://schema.org',
    '@type': 'Organization',
    name: SITE_CONFIG.name,
    aggregateRating: {
      '@type': 'AggregateRating',
      ratingValue: rating.ratingValue,
      reviewCount: rating.reviewCount,
      bestRating: rating.bestRating || 5,
      worstRating: rating.worstRating || 1,
    },
  };
}

/**
 * Helper to convert schema object to JSON-LD script tag
 */
export function schemaToJsonLd(schema: object | object[]) {
  return {
    tagName: 'script',
    type: 'application/ld+json',
    children: JSON.stringify(Array.isArray(schema) ? schema : [schema], null, 2),
  };
}

/**
 * Truncate description to a specific length for SEO
 */
export function truncateDescription(text: string, maxLength: number = 155): string {
  if (text.length <= maxLength) return text;
  return text.substr(0, maxLength - 3).trimEnd() + '...';
}

/**
 * Generate keywords from tags
 */
export function generateKeywords(tags: string[]): string {
  return tags.join(', ');
}
