/**
 * Blog Configuration
 *
 * Centralized configuration for the blog system.
 * Edit this file to customize colors, styling, pagination, etc.
 */

// ============================================================================
// COLORS - Editorial Design System
// ============================================================================

export const BLOG_COLORS = {
  // Primary brand colors
  primary: "#10B981", // Brand green
  primaryHover: "#059669", // Darker green for hover

  // Text colors
  heading: "#1E293B", // Dark slate for headings
  body: "#64748B", // Slate for body text
  muted: "#94A3B8", // Light slate for meta text

  // Background colors
  bgPrimary: "#FFFFFF", // White
  bgSecondary: "#FAFAFA", // Light gray
  bgDark: "#1E293B", // Dark slate for CTAs

  // Border colors
  border: "#E2E8F0", // Slate 200
  borderDark: "#CBD5E1", // Slate 300
} as const;

// ============================================================================
// PAGINATION
// ============================================================================

export const BLOG_PAGINATION = {
  postsPerPage: 6,
  maxFeaturedPosts: 2,
  relatedPostsLimit: 3,
} as const;

// ============================================================================
// REVALIDATION
// ============================================================================

export const BLOG_REVALIDATION = {
  listPage: 3600, // 1 hour for blog listing
  postPage: 3600, // 1 hour for individual posts
  cache: 3600, // 1 hour for cached queries
} as const;

// ============================================================================
// SECTION NUMBERS - Editorial numbering
// ============================================================================

export const SECTION_NUMBERS = {
  hero: "00",
  featured: "01",
  latest: "02",
  cta: "CTA",
  more: "MORE",
} as const;

// ============================================================================
// STYLE CLASSES - Reusable Tailwind class strings
// ============================================================================

export const BLOG_STYLES = {
  // Section marker (00, 01, etc.)
  sectionMarker: "text-[#10B981] font-mono text-sm tracking-wider",

  // Divider line
  dividerLine: "w-12 h-px bg-[#10B981]",

  // Small dot indicator
  dotIndicator: "w-1.5 h-1.5 bg-[#10B981]",

  // Tag pill
  tagPill:
    "inline-flex items-center gap-1.5 px-3 py-1 bg-white/10 backdrop-blur-sm text-white text-xs font-bold uppercase tracking-wider",

  // Hover underline effect
  hoverUnderline:
    "w-0 group-hover:w-12 h-0.5 bg-[#10B981] transition-all duration-300",

  // Primary button
  buttonPrimary:
    "group relative inline-flex items-center gap-3 px-8 py-4 bg-[#10B981] text-white font-semibold overflow-hidden transition-all duration-300",

  // Secondary button (outline)
  buttonSecondary:
    "inline-flex items-center gap-2 px-8 py-4 border-2 border-white/30 text-white font-semibold hover:bg-white/10 transition-colors duration-300",

  // Card hover effect
  cardHover: "group bg-white hover:bg-[#FAFAFA] transition-colors duration-300",

  // Image scale on hover
  imageHover:
    "object-cover transition-transform duration-500 group-hover:scale-105",

  // Title hover color change
  titleHover: "group-hover:text-[#10B981] transition-colors duration-300",

  // Grid with gap-px pattern (editorial style)
  editorialGrid: "gap-px bg-slate-200",
} as const;

// ============================================================================
// TRANSLATIONS - Blog-specific i18n keys
// ============================================================================

export const BLOG_TRANSLATIONS = {
  en: {
    blog: "Blog",
    blogTitle: "Mawidi Blog",
    blogSubtitle: "Latest updates and articles on smart appointment management",
    featured: "Featured",
    featuredArticles: "Featured Articles",
    latestArticles: "Latest Articles",
    noPostsFound: "No posts found",
    noPostsDescription: "No posts available yet. Check back soon!",
    articles: "Articles",
    arabicEnglish: "Arabic & English",
    weeklyUpdates: "Weekly Updates",
    previous: "Previous",
    next: "Next",
    readMore: "Read More",
    backToBlog: "Back to Blog",
    relatedPosts: "Related Posts",
    continueReading: "Continue reading related articles",
    writtenBy: "Written by",
    shareArticle: "Share this article",
    ctaTitle: "Ready to transform your appointment management?",
    ctaDescription:
      "Join hundreds of businesses using Mawidi to provide a seamless booking experience for their customers via WhatsApp",
    tldr: "TL;DR",
  },
  ar: {
    blog: "المدونة",
    blogTitle: "مدونة موعدي",
    blogSubtitle: "آخر التحديثات والمقالات حول إدارة المواعيد الذكية",
    featured: "مميز",
    featuredArticles: "مقالات مميزة",
    latestArticles: "أحدث المقالات",
    noPostsFound: "لا توجد مقالات",
    noPostsDescription: "لا توجد مقالات متاحة حالياً. تحقق مرة أخرى قريباً!",
    articles: "مقالة",
    arabicEnglish: "عربي وإنجليزي",
    weeklyUpdates: "تحديثات أسبوعية",
    previous: "السابق",
    next: "التالي",
    readMore: "اقرأ المزيد",
    backToBlog: "العودة للمدونة",
    relatedPosts: "مقالات ذات صلة",
    continueReading: "مقالات ذات صلة قد تهمك",
    writtenBy: "بقلم",
    shareArticle: "شارك المقال",
    ctaTitle: "جاهز لتحويل إدارة المواعيد؟",
    ctaDescription:
      "انضم إلى مئات الأعمال التي تستخدم موعدي لتوفير تجربة حجز سلسة لعملائها عبر الواتساب",
    tldr: "ملخص",
  },
} as const;

// ============================================================================
// HELPER FUNCTIONS
// ============================================================================

/**
 * Get blog translations for a specific language
 */
export function getBlogTranslations(lang: "ar" | "en") {
  return BLOG_TRANSLATIONS[lang];
}

/**
 * Format date for display
 */
export function formatBlogDate(date: string, lang: "ar" | "en"): string {
  return new Date(date).toLocaleDateString(lang === "ar" ? "ar-SA" : "en-US", {
    year: "numeric",
    month: "short",
    day: "numeric",
  });
}

/**
 * Format date with full month name
 */
export function formatBlogDateLong(date: string, lang: "ar" | "en"): string {
  return new Date(date).toLocaleDateString(lang === "ar" ? "ar-SA" : "en-US", {
    year: "numeric",
    month: "long",
    day: "numeric",
  });
}

/**
 * Clean excerpt text (remove markdown characters)
 */
export function cleanExcerpt(excerpt: string, maxLength: number = 120): string {
  const cleaned = excerpt.replace(/[#*_`]/g, "");
  return cleaned.length > maxLength
    ? `${cleaned.slice(0, maxLength)}...`
    : cleaned;
}

/**
 * Get section number based on context
 */
export function getSectionNumber(
  section: "hero" | "featured" | "latest" | "cta" | "more",
  hasFeatured: boolean = false,
): string {
  if (section === "latest" && hasFeatured) {
    return "02";
  }
  return SECTION_NUMBERS[section];
}

/**
 * Pad number with leading zero (01, 02, etc.)
 */
export function padNumber(num: number): string {
  return String(num).padStart(2, "0");
}

// ============================================================================
// METADATA HELPERS - For SEO and structured data
// ============================================================================

/** Site configuration for metadata generation */
export const SITE_CONFIG = {
  domain: "mawidi.com",
  name: "Mawidi",
  twitter: "@mawidi",
} as const;

/**
 * Generate blog listing page metadata
 */
export function generateBlogListMetadata(lang: "ar" | "en") {
  const t = getBlogTranslations(lang);
  const isAr = lang === "ar";

  const title = isAr
    ? "مدونة موعدي — آخر التحديثات والمقالات حول إدارة المواعيد"
    : "Mawidi Blog — Latest Updates on Smart Appointment Management";

  const description = isAr
    ? "اكتشف أحدث الرؤى والنصائح حول إدارة المواعيد عبر الواتساب، تحسين تجربة المرضى، وحلول الأعمال للعيادات والمراكز الطبية في الخليج"
    : "Discover the latest insights and tips on WhatsApp appointment management, patient experience optimization, and business solutions for clinics and medical centers in the GCC";

  return {
    title,
    description,
    alternates: {
      languages: {
        en: `https://${SITE_CONFIG.domain}/en/blog`,
        ar: `https://${SITE_CONFIG.domain}/ar/blog`,
      },
      canonical: `https://${SITE_CONFIG.domain}/${lang}/blog`,
    },
    openGraph: {
      title,
      description,
      url: `https://${SITE_CONFIG.domain}/${lang}/blog`,
      siteName: SITE_CONFIG.name,
      locale: isAr ? "ar" : "en",
      type: "website" as const,
    },
  };
}

/**
 * Generate blog post JSON-LD schema
 */
export function generateBlogPostSchema(
  post: {
    title: string;
    excerpt: string;
    date: string;
    author: string;
    tags: string[];
    coverImage?: string;
  },
  lang: "ar" | "en",
  slug: string,
) {
  const siteUrl = `https://${SITE_CONFIG.domain}`;
  const postUrl = `${siteUrl}/${lang}/blog/${slug}`;
  const imageUrl = post.coverImage || `${siteUrl}/og-image.png`;

  return {
    "@context": "https://schema.org",
    "@type": "BlogPosting",
    headline: post.title,
    description: post.excerpt,
    image: imageUrl,
    datePublished: post.date,
    dateModified: post.date,
    author: {
      "@type": "Person",
      name: post.author,
    },
    publisher: {
      "@type": "Organization",
      name: SITE_CONFIG.name,
      logo: {
        "@type": "ImageObject",
        url: `${siteUrl}/logo.png`,
      },
    },
    url: postUrl,
    mainEntityOfPage: {
      "@type": "WebPage",
      "@id": postUrl,
    },
    keywords: post.tags.join(", "),
    inLanguage: lang === "ar" ? "ar-SA" : "en-US",
  };
}

/**
 * Generate breadcrumb JSON-LD schema
 */
export function generateBreadcrumbSchema(
  lang: "ar" | "en",
  postTitle: string,
  slug: string,
  homeLabel: string,
  blogLabel: string,
) {
  const siteUrl = `https://${SITE_CONFIG.domain}`;

  return {
    "@context": "https://schema.org",
    "@type": "BreadcrumbList",
    itemListElement: [
      {
        "@type": "ListItem",
        position: 1,
        name: homeLabel,
        item: `${siteUrl}/${lang}`,
      },
      {
        "@type": "ListItem",
        position: 2,
        name: blogLabel,
        item: `${siteUrl}/${lang}/blog`,
      },
      {
        "@type": "ListItem",
        position: 3,
        name: postTitle,
        item: `${siteUrl}/${lang}/blog/${slug}`,
      },
    ],
  };
}

// ============================================================================
// CONTENT PROCESSING - For MDX content
// ============================================================================

/**
 * Balance unclosed HTML tags
 */
export function balanceTags(content: string): string {
  let result = content;

  // Count and balance div tags
  const divOpenCount = (result.match(/<div[^>]*>/g) || []).length;
  const divCloseCount = (result.match(/<\/div>/g) || []).length;
  if (divOpenCount > divCloseCount) {
    result += "</div>".repeat(divOpenCount - divCloseCount);
  }

  // Count and balance span tags
  const spanOpenCount = (result.match(/<span[^>]*>/g) || []).length;
  const spanCloseCount = (result.match(/<\/span>/g) || []).length;
  if (spanOpenCount > spanCloseCount) {
    result += "</span>".repeat(spanOpenCount - spanCloseCount);
  }

  return result;
}

/**
 * Process blog content to fix JSX/HTML compatibility and common HTML errors
 */
export function processContent(content: string): string {
  let processed = content;

  // Fix common mismatched tags FIRST (before className conversion)
  for (let i = 1; i <= 6; i++) {
    processed = processed.replace(
      new RegExp(`<h${i}([^>]*)>([^<]+)</div>`, "g"),
      `<h${i}$1>$2</h${i}>`,
    );
    processed = processed.replace(
      new RegExp(`<h${i}([^>]*)>([^<]+)</span>`, "g"),
      `<h${i}$1>$2</h${i}>`,
    );
  }

  // Fix div opened but closed with other tags
  processed = processed
    .replace(/<div([^>]*)>([^<]+)<\/h[1-6]>/g, "<div$1>$2</div>")
    .replace(/<span([^>]*)>([^<]+)<\/div>/g, "<span$1>$2</span>");

  // Convert JSX to HTML and escape special characters
  processed = processed
    .replace(/className=/g, "class=")
    .replace(/<div([^>]*)\s*\/>/g, "<div$1></div>")
    .replace(/<span([^>]*)\s*\/>/g, "<span$1></span>")
    .replace(/([:\s>])<(\d+%?)/g, "$1&lt;$2")
    .replace(/([:\s<])>(\d+%?)/g, "$1&gt;$2");

  // Balance unclosed HTML tags
  processed = balanceTags(processed);

  return processed;
}

// ============================================================================
// TYPE EXPORTS
// ============================================================================

export type BlogColor = keyof typeof BLOG_COLORS;
export type BlogStyle = keyof typeof BLOG_STYLES;
export type SectionNumber = keyof typeof SECTION_NUMBERS;
export type BlogTranslationKey = keyof typeof BLOG_TRANSLATIONS.en;
