import { createClient } from 'npm:@supabase/supabase-js@^2.89.0';

const supabase = createClient(
  Deno.env.get('SUPABASE_URL') ?? '',
  Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? '',
);

// Base URL for sitemap links
const BASE_URL = Deno.env.get('FRONTEND_URL') || 'https://www.kidzmaps.com';

// Helper: slugify a string for URL-friendly paths
function slugify(text: string): string {
  return text
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/^-+|-+$/g, '');
}

export async function generateSitemap(): Promise<string> {
  const now = new Date().toISOString().split('T')[0]; // YYYY-MM-DD

  // ========================================
  // STATIC PAGES (must match App.tsx routes)
  // ========================================
  const staticPages = [
    // High-priority public pages
    { loc: '/', changefreq: 'daily', priority: '1.0' },
    { loc: '/activities', changefreq: 'daily', priority: '0.9' },
    { loc: '/for-providers', changefreq: 'weekly', priority: '0.9' },

    // Informational pages
    { loc: '/about', changefreq: 'monthly', priority: '0.8' },
    { loc: '/how-it-works', changefreq: 'monthly', priority: '0.8' },
    { loc: '/faq', changefreq: 'monthly', priority: '0.7' },
    { loc: '/contact', changefreq: 'monthly', priority: '0.7' },
    { loc: '/pricing', changefreq: 'weekly', priority: '0.7' },

    // Category filter pages (pre-filtered activity searches)
    { loc: '/activities?category=Sports', changefreq: 'weekly', priority: '0.8' },
    { loc: '/activities?category=Arts', changefreq: 'weekly', priority: '0.8' },
    { loc: '/activities?category=Education', changefreq: 'weekly', priority: '0.8' },
    { loc: '/activities?category=STEM', changefreq: 'weekly', priority: '0.8' },
    { loc: '/activities?category=Religious', changefreq: 'weekly', priority: '0.8' },
    { loc: '/activities?category=Outdoors', changefreq: 'weekly', priority: '0.8' },
    { loc: '/activities?category=Special%20Interests', changefreq: 'weekly', priority: '0.8' },

    // Location-based browsing pages (/{city} and /{city}/{category})
    ...(() => {
      const cities = [
        'new-york', 'los-angeles', 'chicago', 'houston', 'phoenix',
        'san-antonio', 'san-diego', 'dallas', 'austin', 'san-francisco',
        'seattle', 'denver', 'boston', 'miami', 'atlanta', 'nashville',
        'portland', 'charlotte',
      ];
      const categories = ['sports', 'arts', 'education', 'stem', 'outdoors', 'special-interests'];
      const activityTypes = ['summer-camps', 'coding-classes', 'swimming', 'martial-arts'];
      const pages: { loc: string; changefreq: string; priority: string }[] = [];
      // City-only pages
      for (const city of cities) {
        pages.push({ loc: `/${city}`, changefreq: 'weekly', priority: '0.7' });
      }
      // City + category pages (top 6 cities × all categories)
      const topCities = cities.slice(0, 6);
      for (const city of topCities) {
        for (const cat of categories) {
          pages.push({ loc: `/${city}/${cat}`, changefreq: 'weekly', priority: '0.6' });
        }
        for (const type of activityTypes) {
          pages.push({ loc: `/${city}/${type}`, changefreq: 'weekly', priority: '0.6' });
        }
      }

      // ── SEO URL Type 1: /summer-camps/{city} ──
      for (const city of cities) {
        pages.push({ loc: `/summer-camps/${city}`, changefreq: 'weekly', priority: '0.8' });
      }

      // ── SEO URL Type 2: /{category}-camps/{city} (top categories × top cities) ──
      const campPrefixes = [
        'stem', 'sports', 'art', 'coding', 'music', 'dance', 'nature',
        'robotics', 'science', 'basketball', 'soccer', 'swimming', 'tennis',
        'gymnastics', 'theater', 'day', 'overnight',
      ];
      for (const city of topCities) {
        for (const prefix of campPrefixes) {
          pages.push({ loc: `/${prefix}-camps/${city}`, changefreq: 'weekly', priority: '0.7' });
        }
      }

      // ── SEO URL Type 3: /summer-camps-for-{age}-year-olds-{alias} ──
      const cityAliases = ['nyc', 'la', 'chicago', 'miami', 'austin', 'sf'];
      for (const alias of cityAliases) {
        for (let age = 3; age <= 15; age++) {
          pages.push({ loc: `/summer-camps-for-${age}-year-olds-${alias}`, changefreq: 'weekly', priority: '0.6' });
        }
      }

      return pages;
    })(),

    // Legal / policy pages
    { loc: '/privacy-policy', changefreq: 'monthly', priority: '0.4' },
    { loc: '/terms-of-service', changefreq: 'monthly', priority: '0.4' },
    { loc: '/cookie-policy', changefreq: 'monthly', priority: '0.4' },
    { loc: '/coppa-policy', changefreq: 'monthly', priority: '0.4' },
    { loc: '/security', changefreq: 'monthly', priority: '0.4' },
    { loc: '/activity-waiver', changefreq: 'monthly', priority: '0.3' },
    { loc: '/data-processing-agreement', changefreq: 'monthly', priority: '0.3' },
    { loc: '/refund-cancellation-policy', changefreq: 'monthly', priority: '0.4' },
    { loc: '/provider-terms-of-service', changefreq: 'monthly', priority: '0.3' },
  ];

  // ========================================
  // DYNAMIC PAGES: Published Activities
  // ========================================
  let activityPages: { loc: string; changefreq: string; priority: string }[] = [];
  try {
    const { data: activities, error } = await supabase
      .from('activities')
      .select('id, name, city, updated_at')
      .eq('status', 'published')
      .limit(1000);

    if (!error && activities) {
      activityPages = activities.map((activity: any) => {
        const parts = [activity.name || ''];
        if (activity.city) parts.push(activity.city);
        const slug = slugify(parts.join(' ')) || 'activity';
        return {
          loc: `/activities/${slug}`,
          changefreq: 'weekly',
          priority: '0.7',
        };
      });
    }
  } catch (err) {
    console.error('Error fetching activities for sitemap:', err);
  }

  // ========================================
  // DYNAMIC PAGES: Provider Profiles
  // ========================================
  let providerPages: { loc: string; changefreq: string; priority: string }[] = [];
  try {
    const { data: providers, error } = await supabase
      .from('profiles')
      .select('id, business_name, updated_at')
      .eq('role', 'provider')
      .eq('onboarding_complete', true)
      .limit(1000);

    if (!error && providers) {
      providerPages = providers.map((provider: any) => {
        const slug = provider.business_name ? slugify(provider.business_name) : 'provider';
        return {
          loc: `/provider/${slug}`,
          changefreq: 'weekly',
          priority: '0.6',
        };
      });
    }
  } catch (err) {
    console.error('Error fetching providers for sitemap:', err);
  }

  // ========================================
  // BUILD XML
  // ========================================
  const allPages = [...staticPages, ...activityPages, ...providerPages];

  const urls = allPages
    .map(
      (page) => `  <url>
    <loc>${BASE_URL}${page.loc}</loc>
    <lastmod>${now}</lastmod>
    <changefreq>${page.changefreq}</changefreq>
    <priority>${page.priority}</priority>
  </url>`
    )
    .join('\n');

  return `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${urls}
</urlset>`;
}
