/**
 * useCatalog — Produktkatalog von search.atlas-os.ai/catalog.json
 * 
 * Canonical product source for ATLAS Social Command Center.
 * display_status=active only when program_status=approved.
 */

import { useState, useEffect } from 'react';

const CATALOG_URL = 'https://search.atlas-os.ai/catalog.json';

export interface CatalogProduct {
  id: string;
  name: string;
  slug?: string;
  description?: string;
  category?: string;
  brand?: string;
  price?: number;
  currency?: string;
  affiliate_url?: string;
  affiliate_utm?: string;
  program_status?: 'approved' | 'pending' | 'rejected';
  display_status?: 'active' | 'inactive';
  image_url?: string;
  tags?: string[];
  commission_rate?: number;
  asin?: string;
  ean?: string;
}

export function useCatalog() {
  const [products, setProducts] = useState<CatalogProduct[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    fetch(CATALOG_URL)
      .then(r => {
        if (!r.ok) throw new Error(`HTTP ${r.status}`);
        return r.json();
      })
      .then(data => {
        const items = Array.isArray(data) ? data : data.products || data.items || [];
        setProducts(items);
      })
      .catch(e => {
        setError(e.message);
        // Fallback mock data
        setProducts(getMockProducts());
      })
      .finally(() => setLoading(false));
  }, []);

  // Only show products where display_status=active AND program_status=approved
  const activeProducts = products.filter(p => 
    p.display_status === 'active' && p.program_status === 'approved'
  );
  
  // All products for internal management view
  const allProducts = products;

  return { products: activeProducts, allProducts, loading, error };
}

export function buildAffiliateUrl(product: CatalogProduct, source = 'atlas-social'): string {
  if (!product.affiliate_url) return '#';
  
  const url = new URL(product.affiliate_url);
  url.searchParams.set('utm_source', source);
  url.searchParams.set('utm_medium', 'social');
  url.searchParams.set('utm_campaign', product.slug || product.id);
  
  if (product.affiliate_utm) {
    // Merge existing UTM params
    const existing = new URLSearchParams(product.affiliate_utm);
    existing.forEach((v, k) => url.searchParams.set(k, v));
  }
  
  return url.toString();
}

function getMockProducts(): CatalogProduct[] {
  return [
    {
      id: 'pit_001',
      name: 'Shelly Plus Plug S',
      slug: 'shelly-plus-plug-s',
      description: 'WLAN-Steckdose mit Energiemessung. Smart Home Grundausstattung.',
      category: 'Smart Home',
      brand: 'Shelly',
      price: 14.99,
      currency: 'EUR',
      affiliate_url: 'https://amzn.to/shelly-plus-plug-s',
      program_status: 'approved',
      display_status: 'active',
      commission_rate: 3.5,
      tags: ['smart-home', 'energie', 'wlan'],
    },
    {
      id: 'pit_002',
      name: 'Shelly Pro 4PM',
      slug: 'shelly-pro-4pm',
      description: 'DIN-Rail 4-Kanal Smart Switch mit Energiemessung.',
      category: 'Smart Home',
      brand: 'Shelly',
      price: 69.99,
      currency: 'EUR',
      affiliate_url: 'https://amzn.to/shelly-pro-4pm',
      program_status: 'pending',
      display_status: 'inactive',
      commission_rate: 4.0,
      tags: ['smart-home', 'profi', 'din-rail'],
    },
  ];
}
