/**
 * Internet Service Configuration
 *
 * Centralized configuration for internet service tiers, offerings, and features.
 * This module eliminates duplication between InternetPlans.tsx and PublicInternetPlans.tsx.
 */

// ============================================================================
// Types
// ============================================================================

export type InternetTier = "Silver" | "Gold" | "Platinum";

export interface TierConfig {
  description: string;
  features: string[];
  pricingNote?: string | undefined;
  isRecommended?: boolean | undefined;
}

export interface OfferingConfig {
  offeringType: string;
  title: string;
  speedBadge: string;
  description: string;
  iconType: "home" | "apartment";
  isPremium: boolean;
  displayOrder: number;
  isAlternative?: boolean | undefined;
  alternativeNote?: string | undefined;
}

// ============================================================================
// Shared Feature Strings
// ============================================================================

const FEATURE_NTT_MODEM = "NTT modem + ISP connection";

// ============================================================================
// Tier Configuration
// ============================================================================

/**
 * Tier ordering for consistent display across all internet views
 */
export const TIER_ORDER: InternetTier[] = ["Silver", "Gold", "Platinum"];

/**
 * Tier order lookup for sorting operations
 */
export const TIER_ORDER_MAP: Record<string, number> = {
  Silver: 0,
  Gold: 1,
  Platinum: 2,
};

/**
 * Tier configurations with descriptions and features.
 * Used in both authenticated (InternetPlans) and public (PublicInternetPlans) views.
 */
export const TIER_CONFIGS: Record<InternetTier, TierConfig> = {
  Silver: {
    description: "Essential setup—bring your own router",
    features: [FEATURE_NTT_MODEM, "IPoE or PPPoE protocols", "Self-configuration"],
    isRecommended: false,
  },
  Gold: {
    description: "All-inclusive with router rental",
    features: [
      "Everything in Silver",
      "WiFi router included",
      "Auto-configured",
      "Range extender option",
    ],
    isRecommended: true,
  },
  Platinum: {
    description: "Tailored setup for larger homes",
    features: [
      "Netgear INSIGHT mesh routers",
      "Cloud-managed WiFi",
      "Remote support",
      "Custom setup",
    ],
    pricingNote: "+ equipment fees",
    isRecommended: false,
  },
};

/**
 * Public-facing tier descriptions (shorter, marketing-focused)
 */
export const PUBLIC_TIER_DESCRIPTIONS: Record<InternetTier, string> = {
  Silver: "Use your own router. Best for tech-savvy users.",
  Gold: "Includes WiFi router rental. Our most popular choice.",
  Platinum: "Premium equipment with mesh WiFi for larger homes.",
};

/**
 * Public-facing tier features (shorter list for marketing)
 */
export const PUBLIC_TIER_FEATURES: Record<InternetTier, string[]> = {
  Silver: [FEATURE_NTT_MODEM, "Use your own router", "Email/ticket support"],
  Gold: [FEATURE_NTT_MODEM, "WiFi router included", "Priority phone support"],
  Platinum: [FEATURE_NTT_MODEM, "Mesh WiFi system included", "Dedicated support line"],
};

// ============================================================================
// Offering Configuration
// ============================================================================

/**
 * Internet offering configurations by type.
 * Defines display properties for each offering type.
 */
export const OFFERING_CONFIGS: Record<string, Omit<OfferingConfig, "offeringType">> = {
  "Home 10G": {
    title: "Home 10Gbps",
    speedBadge: "10 Gbps",
    description: "Ultra-fast fiber with the highest speeds available in Japan.",
    iconType: "home",
    isPremium: true,
    displayOrder: 1,
  },
  "Home 1G": {
    title: "Home 1Gbps",
    speedBadge: "1 Gbps",
    description: "High-speed fiber. The most popular choice for home internet.",
    iconType: "home",
    isPremium: false,
    displayOrder: 2,
  },
  "Apartment 1G": {
    title: "Apartment 1Gbps",
    speedBadge: "1 Gbps",
    description: "High-speed fiber-to-the-unit for mansions and apartment buildings.",
    iconType: "apartment",
    isPremium: false,
    displayOrder: 1,
  },
  "Apartment 100M": {
    title: "Apartment 100Mbps",
    speedBadge: "100 Mbps",
    description: "Standard speed via VDSL or LAN for apartment buildings.",
    iconType: "apartment",
    isPremium: false,
    displayOrder: 2,
  },
  Apartment: {
    title: "Apartment",
    speedBadge: "Up to 1Gbps",
    description:
      "For mansions and apartment buildings. Speed depends on your building (up to 1Gbps).",
    iconType: "apartment",
    isPremium: false,
    displayOrder: 3,
  },
};

/**
 * Speed badge lookup by offering type
 */
export const SPEED_BADGES: Record<string, string> = {
  "Apartment 100M": "100Mbps",
  "Apartment 1G": "1Gbps",
  "Home 1G": "1Gbps",
  "Home 10G": "10Gbps",
};

// ============================================================================
// Helper Functions
// ============================================================================

/**
 * Get tier description for display
 */
export function getTierDescription(tier: string, usePublicVersion = false): string {
  const normalizedTier = tier as InternetTier;
  if (usePublicVersion) {
    return PUBLIC_TIER_DESCRIPTIONS[normalizedTier] ?? "";
  }
  return TIER_CONFIGS[normalizedTier]?.description ?? "";
}

/**
 * Get tier features for display
 */
export function getTierFeatures(tier: string, usePublicVersion = false): string[] {
  const normalizedTier = tier as InternetTier;
  if (usePublicVersion) {
    return PUBLIC_TIER_FEATURES[normalizedTier] ?? [];
  }
  return TIER_CONFIGS[normalizedTier]?.features ?? [];
}

/**
 * Get speed badge for offering type
 */
export function getSpeedBadge(offeringType: string): string {
  return SPEED_BADGES[offeringType] ?? "1Gbps";
}

/**
 * Get full tier config
 */
export function getTierConfig(tier: string): TierConfig | undefined {
  return TIER_CONFIGS[tier as InternetTier];
}

/**
 * Get offering config by type
 */
export function getOfferingConfig(
  offeringType: string
): Omit<OfferingConfig, "offeringType"> | undefined {
  return OFFERING_CONFIGS[offeringType];
}

/**
 * Check if a tier is the recommended tier
 */
export function isRecommendedTier(tier: string): boolean {
  return tier === "Gold";
}

/**
 * Sort tiers by the standard order
 */
export function sortTiers<T extends { internetPlanTier?: string }>(plans: T[]): T[] {
  return [...plans].sort(
    (a, b) =>
      (TIER_ORDER_MAP[a.internetPlanTier ?? ""] ?? 99) -
      (TIER_ORDER_MAP[b.internetPlanTier ?? ""] ?? 99)
  );
}

// ============================================================================
// Eligibility Display Configuration
// ============================================================================

export interface EligibilityDisplayInfo {
  residenceType: "home" | "apartment";
  speed: string;
  label: string;
  description: string;
}

/**
 * Eligibility display configuration by type
 */
const ELIGIBILITY_DISPLAY: Record<string, EligibilityDisplayInfo> = {
  "home 10g": {
    residenceType: "home",
    speed: "10 Gbps",
    label: "Standalone House (10Gbps available)",
    description:
      "Your address supports our fastest 10Gbps service. You can also choose 1Gbps for lower monthly cost.",
  },
  "home 1g": {
    residenceType: "home",
    speed: "1 Gbps",
    label: "Standalone House (1Gbps)",
    description: "Your address supports high-speed 1Gbps fiber connection.",
  },
  "apartment 1g": {
    residenceType: "apartment",
    speed: "1 Gbps",
    label: "Apartment/Mansion (1Gbps FTTH)",
    description: "Your building has fiber-to-the-unit infrastructure supporting 1Gbps speeds.",
  },
  "apartment 100m": {
    residenceType: "apartment",
    speed: "100 Mbps",
    label: "Apartment/Mansion (100Mbps)",
    description: "Your building uses VDSL or LAN infrastructure with up to 100Mbps speeds.",
  },
};

/**
 * Format eligibility string into display information
 */
export function formatEligibilityDisplay(eligibility: string): EligibilityDisplayInfo {
  const lower = eligibility.toLowerCase();

  // Check for known eligibility types
  for (const [key, info] of Object.entries(ELIGIBILITY_DISPLAY)) {
    if (lower.includes(key)) {
      return info;
    }
  }

  // Default fallback
  return {
    residenceType: "home",
    speed: eligibility,
    label: eligibility,
    description: "Service is available at your address.",
  };
}

type OfferingResult = OfferingConfig & { offeringType: string };

/**
 * Check if an offering type is available in the catalog plans
 */
function hasOfferingInCatalog<T extends { internetOfferingType?: string | undefined }>(
  plans: T[],
  offeringType: string
): boolean {
  return plans.some(p => p.internetOfferingType === offeringType);
}

/**
 * Add an offering to results if it exists in the config and catalog
 */
function addOfferingIfAvailable<T extends { internetOfferingType?: string | undefined }>(
  results: OfferingResult[],
  plans: T[],
  offeringType: string,
  overrides?: Partial<OfferingConfig>
): void {
  const config = OFFERING_CONFIGS[offeringType];
  if (!config || !hasOfferingInCatalog(plans, offeringType)) return;

  results.push({ offeringType, ...config, ...overrides });
}

/**
 * Determine primary offering type from eligibility string
 */
function getEligibilityOfferingType(eligibilityLower: string): string | null {
  if (eligibilityLower.includes("home 10g")) return "Home 10G";
  if (eligibilityLower.includes("home 1g")) return "Home 1G";
  if (eligibilityLower.includes("apartment 1g")) return "Apartment 1G";
  if (eligibilityLower.includes("apartment 100m")) return "Apartment 100M";
  return null;
}

/**
 * Get available offerings based on eligibility and catalog plans
 */
export function getAvailableOfferings<T extends { internetOfferingType?: string | undefined }>(
  eligibility: string | null,
  plans: T[]
): OfferingResult[] {
  if (!eligibility) return [];

  const results: OfferingResult[] = [];
  const eligibilityLower = eligibility.toLowerCase();
  const primaryOffering = getEligibilityOfferingType(eligibilityLower);

  if (!primaryOffering) return [];

  // Home 10G eligibility also allows Home 1G as alternative
  if (primaryOffering === "Home 10G") {
    addOfferingIfAvailable(results, plans, "Home 10G");
    addOfferingIfAvailable(results, plans, "Home 1G", {
      isAlternative: true,
      alternativeNote: "Lower monthly cost option",
    });
  } else {
    addOfferingIfAvailable(results, plans, primaryOffering);
  }

  return results.sort((a, b) => a.displayOrder - b.displayOrder);
}
