// Static data access layer - replaces tRPC for static deployment
import { PRODUCTS } from "./products";
import type { Product } from "./products";
export type { Product } from "./products";

// ─── Products ───────────────────────────────────────────────

export function getAllProducts(): Product[] {
  return PRODUCTS;
}

export function getProductBySlug(slug: string): Product | undefined {
  return PRODUCTS.find((p) => p.slug === slug);
}

export function getProductsByCategory(category: string): Product[] {
  return PRODUCTS.filter((p) => p.category === category);
}

export function getFeaturedProducts(): Product[] {
  return PRODUCTS.filter((p) => p.isBestseller).slice(0, 8);
}

export function getNewArrivals(): Product[] {
  return PRODUCTS.filter((p) => p.isNew).slice(0, 8);
}

export function getOnSaleProducts(): Product[] {
  // Products with >50% discount calculated from price vs originalPrice
  return PRODUCTS.filter((p) => p.originalPrice > 0 && ((p.originalPrice - p.price) / p.originalPrice) > 0.5);
}

export function getTrendingProducts(): Product[] {
  // Top 8 products with highest discount percentage — these are "trending"
  return [...PRODUCTS]
    .sort((a, b) => ((b.originalPrice - b.price) / b.originalPrice) - ((a.originalPrice - a.price) / a.originalPrice))
    .slice(0, 8);
}

export function getRelatedProducts(product: Product, limit = 4): Product[] {
  return PRODUCTS
    .filter((p) => p.category === product.category && p.id !== product.id)
    .slice(0, limit);
}

export function searchProducts(query: string): Product[] {
  const q = query.toLowerCase();
  return PRODUCTS.filter(
    (p) =>
      p.name.toLowerCase().includes(q) ||
      (p.shortDesc && (p.shortDesc as string).toLowerCase().includes(q)) ||
      p.category.toLowerCase().includes(q) ||
      (p.keywords && Array.isArray(p.keywords) && p.keywords.some((k: string) => k.toLowerCase().includes(q)))
  );
}

export function filterAndSortProducts({
  category,
  search,
  sort,
  minPrice,
  maxPrice,
}: {
  category?: string;
  search?: string;
  sort?: string;
  minPrice?: number;
  maxPrice?: number;
}): Product[] {
  let results = [...PRODUCTS];

  if (category && category !== "all") {
    results = results.filter((p) => p.category === category);
  }

  if (search) {
    const q = search.toLowerCase();
    results = results.filter(
      (p) =>
        p.name.toLowerCase().includes(q) ||
        (p.shortDesc && (p.shortDesc as string).toLowerCase().includes(q)) ||
        (p.keywords && Array.isArray(p.keywords) && p.keywords.some((k: string) => k.toLowerCase().includes(q)))
    );
  }

  if (minPrice !== undefined) {
    results = results.filter((p) => p.price >= minPrice);
  }

  if (maxPrice !== undefined) {
    results = results.filter((p) => p.price <= maxPrice);
  }

  switch (sort) {
    case "price-asc":
      results.sort((a, b) => a.price - b.price);
      break;
    case "price-desc":
      results.sort((a, b) => b.price - a.price);
      break;
    case "newest":
      results.sort((a, b) => {
        const aTime = a.createdAt ? new Date(a.createdAt as string).getTime() : 0;
        const bTime = b.createdAt ? new Date(b.createdAt as string).getTime() : 0;
        return bTime - aTime;
      });
      break;
    case "discount":
      results.sort((a, b) => (Number(b.discount) || 0) - (Number(a.discount) || 0));
      break;
    default:
      // Most popular - bestsellers first
      results.sort((a, b) => (b.isBestseller ? 1 : 0) - (a.isBestseller ? 1 : 0));
      break;
  }

  return results;
}

// ─── Product Images ──────────────────────────────────────────

/** Maps product slug → product-specific image path.
 *  Products not listed here will fall back to their category image.
 *  Related product variants (different plans/durations) share the same image.
 */
const PRODUCT_IMAGES: Record<string, string> = {
  // ── AI Tools ──
  "chatgpt-plus": "/product-chatgpt.jpg",
  "chatgpt-business": "/product-chatgpt.jpg",
  "chatgpt-full-team": "/product-chatgpt.jpg",
  "gemini-ai": "/product-gemini-ai.jpg",
  "gemini-ai-pro-2tb": "/product-gemini-ai.jpg",
  "gemini-ai-pro-5tb": "/product-gemini-ai.jpg",

  // ── Design Tools ──
  "canva-pro-1-year": "/product-canva.jpg",
  "canva-pro-lifetime": "/product-canva.jpg",
  "canva-business": "/product-canva.jpg",
  "adobe-creative-cloud": "/product-adobe-creative-cloud.jpg",
  "adobe-creative-cloud-6-months": "/product-adobe-creative-cloud.jpg",
  "adobe-creative-cloud-1-month": "/product-adobe-creative-cloud.jpg",
  "combo-design-pro": "/product-combo-design-pro.jpg",

  // ── Streaming ──
  "netflix-4k-private": "/product-netflix.jpg",
  "spotify-premium": "/product-spotify.jpg",
  "youtube-premium": "/product-youtube-premium.jpg",
  "prime-video": "/product-prime-video.jpg",
  "prime-video-4k": "/product-prime-video.jpg",
  "combo-streaming-pack": "/product-combo-streaming-pack.jpg",

  // ── Productivity ──
  "notion-business": "/product-notion-business.jpg",
  "notion-invite": "/product-notion-business.jpg",
  "notion-workspace": "/product-notion-business.jpg",
  "notion-own-billing": "/product-notion-business.jpg",
  "notion-ai-plus": "/product-notion-business.jpg",
  "combo-creators-bundle": "/product-combo-creators-bundle.jpg",

  // ── Security ──
  "nordvpn": "/product-nordvpn.jpg",
  "surfshark-vpn": "/product-surfshark-vpn.jpg",

  // ── Developer ──
  "combo-developer-suite": "/product-combo-developer-suite.jpg",

  // ── Microsoft ──
  "microsoft-365": "/product-microsoft-365.jpg",
  "office-365-a1-plus": "/product-microsoft-365.jpg",
  "microsoft-family": "/product-microsoft-365.jpg",
  "office-2024-pro-plus": "/product-office-2024-pro-plus.jpg",
  "office-2021-pro-plus": "/product-office-2024-pro-plus.jpg",
  "office-2019-pro-plus": "/product-office-2024-pro-plus.jpg",
  "office-2016-pro-plus": "/product-office-2024-pro-plus.jpg",
  "windows-11-pro": "/product-windows-11-pro.jpg",
  "windows-10-pro": "/product-windows-11-pro.jpg",
  "windows-11-home": "/product-windows-11-pro.jpg",
  "windows-10-home": "/product-windows-11-pro.jpg",
  "windows-bootable-pendrive": "/product-windows-11-pro.jpg",

  // ── Learning ──
  "coursera-premium": "/product-coursera-premium.jpg",

  // ── LinkedIn / Career ──
  "linkedin-premium": "/product-linkedin-premium.jpg",
  "linkedin-career": "/product-linkedin-premium.jpg",
  "linkedin-business": "/product-linkedin-premium.jpg",
  "sales-navigator-core": "/product-linkedin-premium.jpg",
  "sales-navigator-advanced": "/product-linkedin-premium.jpg",
};

const CAT_IMAGES: Record<string, string> = {
  "design-tools": "/prod-design.jpg",
  "ai-tools": "/prod-ai.jpg",
  "streaming": "/prod-streaming.jpg",
  "productivity": "/prod-productivity.jpg",
  "security": "/prod-vpn.jpg",
  "developer": "/prod-gaming.jpg",
  "microsoft": "/prod-office.jpg",
  "learning": "/prod-ai.jpg",
  "combo-offers": "/prod-gaming.jpg",
};

/** Get the best image for a product — product-specific if available, otherwise category fallback */
export function getProductImage(slug: string, category: string): string {
  return PRODUCT_IMAGES[slug] || CAT_IMAGES[category] || "/prod-ai.jpg";
}

// ─── Categories ──────────────────────────────────────────────

export interface CategoryInfo {
  id: string;
  name: string;
  description: string;
  productCount: number;
  image: string;
}

const CAT_NAMES: Record<string, string> = {
  "design-tools": "Design Tools",
  "ai-tools": "AI Tools",
  streaming: "Streaming",
  productivity: "Productivity",
  security: "Security & VPN",
  developer: "Developer Tools",
  microsoft: "Microsoft Office",
  learning: "Learning",
  "combo-offers": "Combo Offers",
};

const CAT_DESCRIPTIONS: Record<string, string> = {
  "design-tools": "Professional design software subscriptions",
  "ai-tools": "AI-powered tools and services",
  streaming: "Premium streaming service access",
  productivity: "Boost your productivity with premium tools",
  security: "VPN and security software",
  developer: "Developer tools and IDEs",
  microsoft: "Microsoft Office and 365 subscriptions",
  learning: "Online learning platform access",
  "combo-offers": "Bundle deals and combo offers",
};

export function getCategories(): CategoryInfo[] {
  const cats = Object.keys(CAT_NAMES);
  return cats.map((id) => ({
    id,
    name: CAT_NAMES[id],
    description: CAT_DESCRIPTIONS[id] || "",
    productCount: PRODUCTS.filter((p) => p.category === id).length,
    image: CAT_IMAGES[id] || "/prod-ai.jpg",
  }));
}

export function getCategoryById(id: string): CategoryInfo | undefined {
  return getCategories().find((c) => c.id === id);
}

// ─── Coupons ─────────────────────────────────────────────────

export interface Coupon {
  code: string;
  type: "percentage" | "fixed";
  value: number;
  minOrder?: number;
  description: string;
}

const COUPONS: Coupon[] = [
  { code: "HERO20", type: "percentage", value: 20, minOrder: 10, description: "20% OFF orders above $10" },
  { code: "SAVE10", type: "percentage", value: 10, description: "10% OFF any order" },
  { code: "BUNDLE30", type: "percentage", value: 30, minOrder: 25, description: "30% OFF orders above $25" },
  { code: "WELCOME5", type: "fixed", value: 5, description: "$5 OFF your first order" },
  { code: "VIP40", type: "percentage", value: 40, minOrder: 50, description: "40% OFF orders above $50" },
];

export function validateCoupon(code: string, orderAmount: number) {
  const coupon = COUPONS.find(
    (c) => c.code.toLowerCase() === code.toLowerCase()
  );

  if (!coupon) {
    return { valid: false, message: "Invalid coupon code" };
  }

  if (coupon.minOrder && orderAmount < coupon.minOrder) {
    return {
      valid: false,
      message: `Minimum order amount is $${coupon.minOrder} for this coupon`,
    };
  }

  const discount =
    coupon.type === "percentage"
      ? (orderAmount * coupon.value) / 100
      : coupon.value;

  return {
    valid: true,
    code: coupon.code,
    type: coupon.type,
    value: coupon.value,
    discount: discount.toFixed(2),
    message: `Coupon applied! You save $${discount.toFixed(2)}`,
  };
}

// ─── Blog Posts ──────────────────────────────────────────────
// Re-export from blogData module
export type { BlogPost } from "./blogData";
export {
  getBlogPosts,
  getBlogPostBySlug,
  getBlogCategories,
  getRelatedBlogPosts,
} from "./blogData";

// ─── Testimonials ────────────────────────────────────────────

export interface Testimonial {
  name: string;
  location: string;
  text: string;
  rating: number;
  product: string;
}

export const TESTIMONIALS: Testimonial[] = [
  {
    name: "James Wilson",
    location: "London, UK",
    text: "Subscription Hero saved me over $500 on my annual software subscriptions. The delivery was instant and everything works perfectly.",
    rating: 5,
    product: "Adobe Creative Cloud",
  },
  {
    name: "Priya Sharma",
    location: "Mumbai, India",
    text: "Best marketplace for premium subscriptions. Bought Canva Pro for just $2 and ChatGPT Plus for $19. Genuine products, instant delivery!",
    rating: 5,
    product: "Canva Pro",
  },
  {
    name: "Marcus Chen",
    location: "Singapore",
    text: "I run a design agency and we've saved thousands buying Adobe Creative Cloud and other tools here. 24/7 support is incredibly responsive.",
    rating: 5,
    product: "Adobe Creative Cloud",
  },
  {
    name: "Elena Rodriguez",
    location: "Madrid, Spain",
    text: "Been buying from Subscription Hero for 6 months now. Never had a single issue. The WhatsApp support team is amazing!",
    rating: 5,
    product: "Netflix 4K",
  },
  {
    name: "David Kim",
    location: "Seoul, South Korea",
    text: "Purchased Netflix 4K and Spotify Premium. Both activated within minutes. The 24-hour refund guarantee gave me confidence to try.",
    rating: 5,
    product: "Spotify Premium",
  },
  {
    name: "Sarah Johnson",
    location: "New York, USA",
    text: "The combo offers are incredible. I got the Designer Pro Bundle with Canva, Adobe, and Figma for less than the price of one. Highly recommend!",
    rating: 5,
    product: "Designer Pro Bundle",
  },
];

// ─── FAQ ─────────────────────────────────────────────────────

export interface FaqItem {
  question: string;
  answer: string;
  category: string;
}

export const FAQS: FaqItem[] = [
  {
    question: "Are the subscriptions genuine and legal?",
    answer: "Yes. We provide 100% authentic subscriptions through official channels. All licenses are genuine with zero ban risk. We have served 10,000+ customers since 2023 with a 99.8% success rate.",
    category: "General",
  },
  {
    question: "How fast will I receive my subscription?",
    answer: "Instant delivery! Most orders are fulfilled within 2 to 10 minutes via WhatsApp or email. You will receive clear setup instructions and direct access credentials.",
    category: "Delivery",
  },
  {
    question: "What payment methods do you accept?",
    answer: "We accept UPI (Google Pay, PhonePe, Paytm), PayPal for international orders, and Cryptocurrency (Bitcoin, Ethereum, USDT). All payments are secure and encrypted.",
    category: "Payment",
  },
  {
    question: "Can I get a refund if something doesn't work?",
    answer: "Absolutely! We offer a 24-hour money-back guarantee. If we cannot resolve any issue within 24 hours, you get a full refund — no questions asked.",
    category: "Refunds",
  },
  {
    question: "Will my subscription work on multiple devices?",
    answer: "Yes, most subscriptions support multi-device access. After purchase, you will receive detailed instructions on how to activate on all your devices.",
    category: "General",
  },
  {
    question: "How do I contact customer support?",
    answer: "Our support team is available 24/7 via WhatsApp at +91 7038146526 or Telegram @mfatool. Average response time is under 5 minutes.",
    category: "Support",
  },
  {
    question: "Can I upgrade or change my subscription plan?",
    answer: "Yes, you can upgrade or change your plan at any time. Contact our support team via WhatsApp and they will help you with the transition.",
    category: "General",
  },
  {
    question: "Is my payment information secure?",
    answer: "Absolutely. We use industry-standard encryption for all transactions. We never store your payment details on our servers.",
    category: "Payment",
  },
];

// ─── Site Stats ──────────────────────────────────────────────

export const SITE_STATS = {
  customers: "10,000+",
  activationsThisMonth: "2,480+",
  usersViewingNow: 58,
  ordersThisWeek: "1,240+",
  avgDelivery: "<2min",
  successRate: "99.8%",
  products: PRODUCTS.length,
  countries: "50+",
};

// ─── Trust Badges ────────────────────────────────────────────

export const TRUST_BADGES = [
  { label: "81+ Products", sublabel: "Premium Tools" },
  { label: "96% Off Retail", sublabel: "Best Prices" },
  { label: "2-Min Delivery", sublabel: "Instant Access" },
  { label: "24H Refund", sublabel: "Money Back" },
  { label: "10,000+", sublabel: "Happy Customers" },
  { label: "99.8%", sublabel: "Success Rate" },
];
