import { useHomeStore } from "@/stores/home";
// SEO Configuration composable
export const useSeoConfig = () => {
  const { locale } = useI18n();
  // Access global website data for meta defaults
  const home = useHomeStore();

  const baseUrl = "https://khalejauto.sa";
  const siteName = "khalej Auto";
  const logoUrl = "https://khalejauto.sa/_nuxt/mainLogo-rtl.BJ0Ys74P.svg";

  // Organization Schema
  const organizationSchema = {
    "@context": "https://schema.org",
    "@type": "Organization",
    "@id": "https://khalejauto.sa/#organization",
    name: "Khalej Auto",
    alternateName: "خليج أوتو",
    description: "Khalej Auto - Your first destination for buying new and used cars in Saudi Arabia. Browse the widest collection of cars with the best prices and exclusive offers.",
    url: "https://khalejauto.sa",
    logo: {
      "@type": "ImageObject",
      url: "https://khalejauto.sa/_nuxt/mainLogo-rtl.BJ0Ys74P.svg",
      width: 200,
      height: 60,
    },
    email: "info@khalejauto.sa",
    telephone: "8001111873",
    address: {
      "@type": "PostalAddress",
      streetAddress: "Riyadh",
      addressLocality: "Riyadh",
      addressRegion: "Riyadh Province",
      postalCode: "12345",
      addressCountry: "SA",
    },
    contactPoint: {
      "@type": "ContactPoint",
      telephone: "8001111873",
      contactType: "customer service",
      availableLanguage: ["Arabic", "English"],
    },
    sameAs: [
      "https://www.instagram.com/khalejauto",
      "https://www.facebook.com/profile.php?id=61561189031205",
      "https://www.youtube.com/@khalejauto3359",
    ],
  };
  // Website Schema
  const websiteSchema = {
    "@context": "https://schema.org",
    "@type": "WebSite",
    "@id": "https://khalejauto.sa/#website",
    name: "Khalej Auto",
    description: "Khalej Auto - Your first destination for buying new and used cars in Saudi Arabia. Browse the widest collection of cars with the best prices and exclusive offers.",
    url: "https://khalejauto.sa",
    publisher: {
      "@id": "https://khalejauto.sa/#organization",
    },
    potentialAction: {
      "@type": "SearchAction",
      target: {
        "@type": "EntryPoint",
        urlTemplate: "https://khalejauto.sa/search?q={search_term_string}",
      },
      "query-input": "required name=search_term_string",
    },
  };

  // Get localized default description
  const getDefaultDescription = () => {
    const backendDesc =
      locale.value === "ar"
        ? home.websiteData?.meta_tag_description_ar
        : home.websiteData?.meta_tag_description_en;
    return backendDesc ??
      (locale.value === "ar"
        ? "وجهتك الأولى لاستكشاف أوسع مجموعة من السيارات"
        : "Your first destination to explore the widest range of cars");
  };

  // Get localized default keywords
  const getDefaultKeywords = () => {
    const backendKw =
      locale.value === "ar"
        ? home.websiteData?.meta_tag_keyword_ar
        : home.websiteData?.meta_tag_keyword_en;
    return backendKw ?? undefined;
  };

  // Get localized site title
  const getDefaultTitle = () => {
    return locale.value === "ar"
      ? "خليج أوتو - أوسع مجموعة من السيارات"
      : "Khalej Auto - Widest Range of Cars";
  };

  // Generate canonical URL
  const getCanonicalUrl = (path = "") => {
    const cleanPath = path.startsWith("/") ? path : `/${path}`;
    return `${baseUrl}${cleanPath}`;
  };

  // Generate BreadcrumbList schema
  // breadcrumbs: Array of { name: string, url: string } objects
  // Example: [{ name: 'Home', url: '/' }, { name: 'Cars', url: '/cars' }, { name: 'Toyota', url: '/cars/123' }]
  const generateBreadcrumbSchema = (breadcrumbs = []) => {
    if (!breadcrumbs || breadcrumbs.length === 0) return null;

    return {
      "@context": "https://schema.org",
      "@type": "BreadcrumbList",
      itemListElement: breadcrumbs.map((item, index) => {
        const listItem = {
          "@type": "ListItem",
          position: index + 1,
          name: item.name,
        };
        // Only add item URL if it exists (last item in breadcrumb shouldn't have URL)
        if (item.url) {
          listItem.item = `${baseUrl}${item.url}`;
        }
        return listItem;
      }),
    };
  };

  // Generate Open Graph meta tags
  const getOpenGraphMeta = (options = {}) => {
    const {
      title = getDefaultTitle(),
      description = getDefaultDescription(),
      url = baseUrl,
      image = logoUrl,
      type = "business.business",
    } = options;

    return [
      { property: "og:title", content: title },
      { property: "og:site_name", content: siteName },
      { property: "og:url", content: url },
      { property: "og:description", content: description },
      { property: "og:type", content: type },
      { property: "og:image", content: image },
      {
        property: "og:locale",
        content: locale.value === "ar" ? "ar_SA" : "en_US",
      },
    ];
  };

  // Set page SEO
  const setPageSeo = (options = {}) => {
    const {
      title,
      description,
      keywords,
      meta_desc_ar,
      meta_desc_en,
      meta_keyword_ar,
      meta_keyword_en,
      path = "",
      arPath, // Optional: explicit Arabic path for hreflang (for pages with locale-specific slugs)
      enPath, // Optional: explicit English path for hreflang (for pages with locale-specific slugs)
      image,
      type,
      additionalSchemas = [],
      breadcrumbs = [], // Array of { name: string, url: string }
    } = options;

    const canonicalUrl = getCanonicalUrl(path);
    const localizedDescription = description || getDefaultDescription();
    const localizedKeywords = keywords || getDefaultKeywords();
    
    const ogMeta = getOpenGraphMeta({
      title,
      description: localizedDescription,
      url: canonicalUrl,
      image,
      type,
    });

    // Generate breadcrumb schema if breadcrumbs provided
    const breadcrumbSchema = generateBreadcrumbSchema(breadcrumbs);

    // Combine schemas
    const schemas = [
      organizationSchema,
      websiteSchema,
      ...(breadcrumbSchema ? [breadcrumbSchema] : []),
      ...additionalSchemas,
    ];

    // Get the appropriate meta description and keywords based on current locale
    const metaDescription = locale.value === 'ar' 
      ? meta_desc_ar || localizedDescription
      : meta_desc_en || localizedDescription;
      
    const metaKeywords = locale.value === 'ar'
      ? meta_keyword_ar || localizedKeywords
      : meta_keyword_en || localizedKeywords;

    useSeoMeta({
      title: title || getDefaultTitle(),
      description: metaDescription,
      keywords: metaKeywords,
      ...ogMeta.reduce((acc, meta) => {
        acc[meta.property.replace("og:", "")] = meta.content;
        return acc;
      }, {}),
      twitterCard: "summary_large_image",
      twitterSite: "@khalejauto",
      twitterCreator: "@khalejauto",
    });

    useServerSeoMeta({
      ...ogMeta.reduce((acc, meta) => {
        acc[meta.property] = meta.content;
        return acc;
      }, {}),
      description: metaDescription,
      keywords: metaKeywords,
    });

    // Set canonical URL, hreflang links, and schemas
    // Note: description and keywords are already set via useSeoMeta/useServerSeoMeta above
    // Do NOT add them here again to avoid duplicate meta tags
    const localePath = locale.value === "ar" ? path : path.replace(/^\/en/, "");
    // Use explicit locale paths if provided (for pages with different slugs per locale)
    const hreflangArPath = arPath || localePath;
    const hreflangEnPath = enPath || `/en${localePath}`;
    useHead({
      link: [
        { rel: "canonical", href: canonicalUrl },
        { rel: "alternate", hreflang: "ar", href: `${baseUrl}${hreflangArPath}` },
        { rel: "alternate", hreflang: "en", href: `${baseUrl}${hreflangEnPath}` },
        { rel: "alternate", hreflang: "x-default", href: `${baseUrl}${hreflangArPath}` },
      ],
      script: schemas.map((schema, index) => ({
        key: `schema-${schema["@type"] || index}`,
        type: "application/ld+json",
        innerHTML: JSON.stringify(schema),
      })),
    });
    
  };
   

  return {
    organizationSchema,
    websiteSchema,
    getDefaultDescription,
    getDefaultKeywords,
    getDefaultTitle,
    getCanonicalUrl,
    getOpenGraphMeta,
    generateBreadcrumbSchema,
    setPageSeo,
    baseUrl,
    siteName,
    logoUrl,
  };
};
