import { SITE, type Lang } from '@/lib/config';
import { getAppBaseUrl } from '@/lib/url';

/**
 * Structured Data (JSON-LD) generators for SEO
 * These generate schema.org compliant JSON-LD for rich snippets in search results
 */

interface ServiceData {
  name: Record<Lang, string>;
  description: Record<Lang, string>;
  slug: Record<Lang, string>;
}

interface LocationData {
  name: Record<Lang, string>;
  slug: Record<Lang, string>;
  countryCode: string;
}

/**
 * Generate WebSite schema - used on homepage
 */
export function generateWebSiteSchema() {
  const baseUrl = getAppBaseUrl();
  return {
    '@context': 'https://schema.org',
    '@type': 'WebSite',
    name: SITE.brand,
    url: baseUrl,
    potentialAction: {
      '@type': 'SearchAction',
      target: `${baseUrl}/en/search?q={search_term_string}`,
      'query-input': 'required name=search_term_string',
    },
  };
}

/**
 * Generate Organization schema - used site-wide
 */
export function generateOrganizationSchema() {
  const baseUrl = getAppBaseUrl();
  return {
    '@context': 'https://schema.org',
    '@type': 'Organization',
    name: SITE.brand,
    url: baseUrl,
    logo: `${baseUrl}/brand/logo-icon.png`,
    sameAs: [
      // Add social media links here when available
    ],
    contactPoint: {
      '@type': 'ContactPoint',
      telephone: SITE.contact.whatsapp,
      contactType: 'customer service',
      availableLanguage: ['English', 'Arabic'],
    },
    address: {
      '@type': 'PostalAddress',
      addressLocality: 'Doha',
      addressCountry: 'QA',
    },
  };
}

/**
 * Generate Service schema for service pages
 */
export function generateServiceSchema(service: ServiceData, lang: Lang) {
  const baseUrl = getAppBaseUrl();
  return {
    '@context': 'https://schema.org',
    '@type': 'Service',
    name: service.name[lang],
    description: service.description[lang],
    url: `${baseUrl}/${lang}/services/${service.slug[lang]}`,
    provider: {
      '@type': 'Organization',
      name: SITE.brand,
      url: baseUrl,
    },
    areaServed: {
      '@type': 'GeoCircle',
      geoMidpoint: {
        '@type': 'GeoCoordinates',
        latitude: 25.2854, // GCC central (approximate)
        longitude: 51.531,
      },
      geoRadius: '2000',
    },
    serviceType: 'WhatsApp Appointment Management',
  };
}

/**
 * Generate LocalBusiness schema for location pages
 */
export function generateLocalBusinessSchema(location: LocationData, lang: Lang) {
  const baseUrl = getAppBaseUrl();

  // Coordinates for GCC cities (approximate)
  const coordinates: Record<string, { lat: number; lng: number }> = {
    'sa-riyadh': { lat: 24.7136, lng: 46.6753 },
    'sa-jeddah': { lat: 21.4858, lng: 39.1925 },
    'sa-dammam': { lat: 26.4207, lng: 50.0888 },
    'ae-dubai': { lat: 25.2048, lng: 55.2708 },
    'ae-abu-dhabi': { lat: 24.4539, lng: 54.3773 },
    'qa-doha': { lat: 25.2854, lng: 51.5310 },
    'kw-kuwait-city': { lat: 29.3759, lng: 47.9774 },
    'bh-manama': { lat: 26.2285, lng: 50.5860 },
    'om-muscat': { lat: 23.5880, lng: 58.3829 },
  };

  const coords = coordinates[`${location.countryCode.toLowerCase()}-${location.slug.en}`] || { lat: 25.2854, lng: 51.531 };

  return {
    '@context': 'https://schema.org',
    '@type': 'LocalBusiness',
    name: `${SITE.brand} - ${location.name[lang]}`,
    url: `${baseUrl}/${lang}/locations/${location.slug[lang]}`,
    telephone: SITE.contact.whatsapp,
    address: {
      '@type': 'PostalAddress',
      addressLocality: location.name.en,
      addressCountry: location.countryCode,
    },
    geo: {
      '@type': 'GeoCoordinates',
      latitude: coords.lat,
      longitude: coords.lng,
    },
    parentOrganization: {
      '@type': 'Organization',
      name: SITE.brand,
      url: baseUrl,
    },
  };
}

/**
 * Generate BreadcrumbList schema for nested pages
 */
export function generateBreadcrumbSchema(
  segments: Array<{ name: string; path: string }>,
  lang: Lang
) {
  const baseUrl = getAppBaseUrl();

  const items = [
    {
      '@type': 'ListItem',
      position: 1,
      name: lang === 'ar' ? 'الرئيسية' : 'Home',
      item: `${baseUrl}/${lang}`,
    },
    ...segments.map((segment, index) => ({
      '@type': 'ListItem',
      position: index + 2,
      name: segment.name,
      item: `${baseUrl}/${lang}${segment.path}`,
    })),
  ];

  return {
    '@context': 'https://schema.org',
    '@type': 'BreadcrumbList',
    itemListElement: items,
  };
}

/**
 * Generate SoftwareApplication schema for product/features pages
 */
export function generateSoftwareApplicationSchema(lang: Lang) {
  const baseUrl = getAppBaseUrl();
  return {
    '@context': 'https://schema.org',
    '@type': 'SoftwareApplication',
    name: SITE.brand,
    applicationCategory: 'BusinessApplication',
    operatingSystem: 'Web',
    url: `${baseUrl}/${lang}/features`,
    description: lang === 'ar'
      ? 'نظام إدارة مواعيد ذكي عبر واتساب للعيادات ومراكز التجميل في الخليج'
      : 'AI-powered WhatsApp appointment management for GCC clinics and aesthetics',
    offers: {
      '@type': 'Offer',
      priceCurrency: 'QAR',
      price: '0',
      description: lang === 'ar' ? 'تجربة مجانية متاحة' : 'Free trial available',
    },
    featureList: lang === 'ar'
      ? ['أتمتة الحجز', 'تحصيل العربون', 'التذكيرات الذكية', 'قائمة الانتظار']
      : ['Booking automation', 'Deposit collection', 'Smart reminders', 'Waitlist management'],
    provider: {
      '@type': 'Organization',
      name: SITE.brand,
      url: baseUrl,
    },
  };
}

/**
 * Generate WebApplication schema for tools like ROI calculator
 */
export function generateWebApplicationSchema(
  name: Record<Lang, string>,
  description: Record<Lang, string>,
  path: string,
  lang: Lang
) {
  const baseUrl = getAppBaseUrl();
  return {
    '@context': 'https://schema.org',
    '@type': 'WebApplication',
    name: name[lang],
    description: description[lang],
    url: `${baseUrl}/${lang}${path}`,
    applicationCategory: 'BusinessApplication',
    browserRequirements: 'Requires JavaScript',
    offers: {
      '@type': 'Offer',
      price: '0',
      priceCurrency: 'QAR',
    },
    provider: {
      '@type': 'Organization',
      name: SITE.brand,
      url: baseUrl,
    },
  };
}

/**
 * Generate FAQ schema for FAQ sections
 */
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,
      },
    })),
  };
}
