"use client";

import { useMemo, useState } from "react";
import {
  ArrowRight,
  Sparkles,
  Wifi,
  Zap,
  Languages,
  FileText,
  Wrench,
  Globe,
  ChevronDown,
  ChevronUp,
  Home,
  Building,
} from "lucide-react";
import { usePublicInternetCatalog } from "@/features/services/hooks";
import type {
  InternetInstallationCatalogItem,
  InternetPlanCatalogItem,
} from "@customer-portal/domain/services";
import { Skeleton } from "@/components/atoms/loading-skeleton";
import { AlertBanner } from "@/components/molecules/AlertBanner/AlertBanner";
import { ServicesBackLink } from "@/features/services/components/base/ServicesBackLink";
import { useServicesBasePath } from "@/features/services/hooks/useServicesBasePath";
import { Button } from "@/components/atoms/button";
import type { TierInfo } from "@/features/services/components/internet/PublicOfferingCard";
import {
  ServiceHighlights,
  HighlightFeature,
} from "@/features/services/components/base/ServiceHighlights";
import { HowItWorksSection } from "@/features/services/components/internet/HowItWorksSection";
import { cn } from "@/shared/utils";

// Tier styling - matching the design with left border accents
const tierStyles = {
  Silver: {
    card: "border-gray-200 bg-white border-l-4 border-l-gray-400",
    accent: "text-gray-600",
    header: "Silver",
  },
  Gold: {
    card: "border-gray-200 bg-white border-l-4 border-l-amber-500",
    accent: "text-amber-600",
    header: "Gold",
  },
  Platinum: {
    card: "border-gray-200 bg-white border-l-4 border-l-primary",
    accent: "text-primary",
    header: "Platinum",
  },
} as const;

/**
 * Consolidated Internet Card - Single card showing all tiers with price ranges
 */
function ConsolidatedInternetCard({
  minPrice,
  maxPrice,
  setupFee,
  tiers,
  ctaPath,
  ctaLabel,
  onCtaClick,
}: {
  minPrice: number;
  maxPrice: number;
  setupFee: number;
  tiers: TierInfo[];
  ctaPath: string;
  ctaLabel: string;
  onCtaClick?: (e: React.MouseEvent) => void;
}) {
  return (
    <div className="rounded-xl border border-border bg-card shadow-[var(--cp-shadow-1)] overflow-hidden">
      {/* Header */}
      <div className="p-5 border-b border-border bg-muted/20">
        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
          <div className="space-y-1">
            <div className="flex items-center gap-3">
              <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-primary/10 text-primary">
                <Wifi className="h-5 w-5" />
              </div>
              <div>
                <h3 className="text-lg font-bold text-foreground">NTT Fiber Internet</h3>
                <p className="text-sm text-muted-foreground">Home & Apartment plans available</p>
              </div>
            </div>
          </div>
          <div className="text-left sm:text-right">
            <div className="flex items-baseline gap-1">
              <span className="text-2xl font-bold text-foreground">
                ¥{minPrice.toLocaleString()}~{maxPrice.toLocaleString()}
              </span>
              <span className="text-sm text-muted-foreground">/mo</span>
            </div>
            <p className="text-xs text-muted-foreground">Price varies by location & tier</p>
          </div>
        </div>
      </div>

      {/* Tier Cards */}
      <div className="p-5">
        <p className="text-sm font-medium text-foreground mb-2">Choose your service tier:</p>
        <p className="text-xs text-muted-foreground mb-4">
          Price varies based on your connection type: Home 10Gbps (select areas), Home 1Gbps, or
          Apartment (up to 1Gbps depending on building infrastructure). We&apos;ll confirm
          availability at your address.
        </p>
        <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 mb-6">
          {tiers.map(tier => (
            <div
              key={tier.tier}
              className={cn(
                "rounded-xl border p-4 transition-all duration-200 flex flex-col relative",
                tierStyles[tier.tier].card
              )}
            >
              {/* Popular Badge for Gold */}
              {tier.tier === "Gold" && (
                <div className="absolute -top-3 left-1/2 -translate-x-1/2">
                  <span className="inline-flex items-center gap-1 px-3 py-1 rounded-full bg-amber-500 text-white text-xs font-semibold shadow-sm">
                    <Sparkles className="h-3 w-3" />
                    Popular
                  </span>
                </div>
              )}

              {/* Tier Name */}
              <h4
                className={cn(
                  "font-bold text-lg mb-2",
                  tier.tier === "Gold" ? "mt-2" : "",
                  tierStyles[tier.tier].accent
                )}
              >
                {tier.tier}
              </h4>

              {/* Price Range */}
              <div className="mb-3">
                <div className="flex items-baseline gap-0.5 flex-wrap">
                  <span className="text-2xl font-bold text-foreground">
                    ¥{tier.monthlyPrice.toLocaleString()}
                    {tier.maxMonthlyPrice &&
                      tier.maxMonthlyPrice > tier.monthlyPrice &&
                      `~${tier.maxMonthlyPrice.toLocaleString()}`}
                  </span>
                  <span className="text-sm text-muted-foreground">/mo</span>
                </div>
                {tier.pricingNote && (
                  <span
                    className={`text-xs ${tier.tier === "Platinum" ? "text-primary" : "text-amber-600"}`}
                  >
                    {tier.pricingNote}
                  </span>
                )}
              </div>

              {/* Description */}
              <p className="text-sm text-muted-foreground mb-3">{tier.description}</p>

              {/* Features */}
              <ul className="space-y-2 flex-grow">
                {tier.features.map((feature, index) => (
                  <li key={index} className="flex items-start gap-2 text-sm">
                    <svg
                      className="h-4 w-4 text-gray-500 flex-shrink-0 mt-0.5"
                      viewBox="0 0 20 20"
                      fill="currentColor"
                    >
                      <path
                        fillRule="evenodd"
                        d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
                        clipRule="evenodd"
                      />
                    </svg>
                    <span className="text-muted-foreground">{feature}</span>
                  </li>
                ))}
              </ul>
            </div>
          ))}
        </div>

        {/* Footer with setup fee and CTA */}
        <div className="flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-4 pt-4 border-t border-border">
          <p className="text-sm text-muted-foreground">
            <span className="font-semibold text-foreground">
              + ¥{setupFee.toLocaleString()} one-time setup
            </span>{" "}
            (or 12/24-month installment)
          </p>
          {onCtaClick ? (
            <Button onClick={onCtaClick} size="lg" className="whitespace-nowrap">
              {ctaLabel}
            </Button>
          ) : (
            <Button as="a" href={ctaPath} size="lg" className="whitespace-nowrap">
              {ctaLabel}
            </Button>
          )}
        </div>
      </div>
    </div>
  );
}

/**
 * Offering type configuration for expandable plan cards
 */
interface OfferingTypeConfig {
  id: string;
  title: string;
  badge: string;
  badgeColor: string;
  description: string;
  icon: React.ReactNode;
}

const offeringTypeConfigs: OfferingTypeConfig[] = [
  {
    id: "home10g",
    title: "Home 10Gbps",
    badge: "10Gbps",
    badgeColor: "bg-primary text-white",
    description: "Ultra-fast fiber with the highest speeds available in Japan.",
    icon: <Home className="h-5 w-5 text-muted-foreground" />,
  },
  {
    id: "home1g",
    title: "Home 1Gbps",
    badge: "1Gbps",
    badgeColor: "bg-gray-200 text-gray-700",
    description: "High-speed fiber. The most popular choice for home internet.",
    icon: <Home className="h-5 w-5 text-muted-foreground" />,
  },
  {
    id: "apartment",
    title: "Apartment",
    badge: "Up to 1Gbps",
    badgeColor: "bg-gray-200 text-gray-700",
    description:
      "For mansions and apartment buildings. Speed depends on your building (up to 1Gbps).",
    icon: <Building className="h-5 w-5 text-muted-foreground" />,
  },
];

/**
 * Get offering type ID from plan's internetOfferingType field
 */
function getOfferingTypeId(offeringType: string | undefined): string {
  if (!offeringType) return "home1g";
  const type = offeringType.toLowerCase();
  if (type.includes("10g") || type.includes("10gbps")) return "home10g";
  if (type.includes("apartment") || type.includes("mansion")) return "apartment";
  if (type.includes("1g") || type.includes("1gbps") || type.includes("home")) return "home1g";
  return "home1g";
}

/**
 * Plan Card Header - Compact horizontal card for offering type
 */
function PlanCardHeader({
  config,
  minPrice,
  isExpanded,
  onToggle,
}: {
  config: OfferingTypeConfig;
  minPrice: number;
  isExpanded: boolean;
  onToggle: () => void;
}) {
  return (
    <div
      className={cn(
        "rounded-xl border-2 shadow-sm overflow-hidden h-full flex flex-col transition-all duration-200",
        isExpanded
          ? "border-primary bg-primary/5 shadow-md ring-1 ring-primary/20"
          : "border-border bg-card hover:border-primary/40"
      )}
    >
      {/* Header - Clickable to expand/collapse */}
      <button
        type="button"
        onClick={onToggle}
        className="w-full p-4 flex flex-col gap-3 hover:bg-muted/30 transition-colors text-left flex-grow"
      >
        <div className="flex items-start justify-between gap-2">
          <div
            className={cn(
              "flex h-10 w-10 items-center justify-center rounded-xl flex-shrink-0 transition-colors",
              isExpanded ? "bg-primary/10" : "bg-muted/50"
            )}
          >
            {config.icon}
          </div>
          <div
            className={cn(
              "flex items-center gap-1 transition-colors",
              isExpanded ? "text-primary" : "text-muted-foreground"
            )}
          >
            <span className="text-xs font-medium">{isExpanded ? "Hide tiers" : "Show tiers"}</span>
            {isExpanded ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
          </div>
        </div>
        <div>
          <div className="flex items-center gap-2 flex-wrap mb-1">
            <h3
              className={cn(
                "text-base font-bold transition-colors",
                isExpanded ? "text-primary" : "text-foreground"
              )}
            >
              {config.title}
            </h3>
            <span
              className={cn("text-xs font-semibold px-2 py-0.5 rounded-full", config.badgeColor)}
            >
              {config.badge}
            </span>
          </div>
          {config.id === "home10g" && (
            <span className="text-xs text-muted-foreground">(select areas)</span>
          )}
          <p className="text-sm text-muted-foreground mt-1">{config.description}</p>
          <p className="text-sm text-muted-foreground mt-2">
            From{" "}
            <span className="font-bold text-foreground text-lg">¥{minPrice.toLocaleString()}</span>{" "}
            /mo
          </p>
        </div>
      </button>
    </div>
  );
}

/**
 * Expanded Tier Details - Shows tier cards below the header cards
 */
function ExpandedTierDetails({
  config,
  tiers,
  setupFee,
}: {
  config: OfferingTypeConfig;
  tiers: TierInfo[];
  setupFee: number;
}) {
  return (
    <div className="rounded-xl border border-border bg-card shadow-sm overflow-hidden">
      {/* Header */}
      <div className="px-5 py-4 border-b border-border bg-muted/20">
        <div className="flex items-center gap-3">
          <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-muted/50">
            {config.icon}
          </div>
          <div>
            <div className="flex items-center gap-2 flex-wrap">
              <h3 className="text-lg font-bold text-foreground">{config.title}</h3>
              <span
                className={cn("text-xs font-semibold px-2 py-0.5 rounded-full", config.badgeColor)}
              >
                {config.badge}
              </span>
              {config.id === "home10g" && (
                <span className="text-xs text-muted-foreground">(select areas)</span>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* Tier Cards */}
      <div className="p-5">
        <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
          {tiers.map(tier => (
            <div
              key={tier.tier}
              className={cn(
                "rounded-xl border p-4 transition-all duration-200 flex flex-col relative bg-white",
                tierStyles[tier.tier].card
              )}
            >
              {/* Popular Badge for Gold */}
              {tier.tier === "Gold" && (
                <div className="absolute -top-3 left-1/2 -translate-x-1/2">
                  <span className="inline-flex items-center gap-1 px-3 py-1 rounded-full bg-amber-500 text-white text-xs font-semibold shadow-sm">
                    <Sparkles className="h-3 w-3" />
                    Popular
                  </span>
                </div>
              )}

              {/* Tier Name */}
              <h4
                className={cn(
                  "font-bold text-lg mb-2",
                  tier.tier === "Gold" ? "mt-2" : "",
                  tierStyles[tier.tier].accent
                )}
              >
                {tier.tier}
              </h4>

              {/* Price */}
              <div className="mb-3">
                <div className="flex items-baseline gap-0.5 flex-wrap">
                  <span className="text-2xl font-bold text-foreground">
                    ¥{tier.monthlyPrice.toLocaleString()}
                  </span>
                  <span className="text-sm text-muted-foreground">/mo</span>
                </div>
                {tier.pricingNote && (
                  <span
                    className={`text-xs ${tier.tier === "Platinum" ? "text-primary" : "text-amber-600"}`}
                  >
                    {tier.pricingNote}
                  </span>
                )}
              </div>

              {/* Description */}
              <p className="text-sm text-muted-foreground mb-3">{tier.description}</p>

              {/* Features */}
              <ul className="space-y-2 flex-grow">
                {tier.features.map((feature, index) => (
                  <li key={index} className="flex items-start gap-2 text-sm">
                    <svg
                      className="h-4 w-4 text-green-500 flex-shrink-0 mt-0.5"
                      viewBox="0 0 20 20"
                      fill="currentColor"
                    >
                      <path
                        fillRule="evenodd"
                        d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
                        clipRule="evenodd"
                      />
                    </svg>
                    <span className="text-muted-foreground">{feature}</span>
                  </li>
                ))}
              </ul>
            </div>
          ))}
        </div>

        {/* Footer with setup fee */}
        <div className="pt-5 mt-5 border-t border-border">
          <p className="text-sm text-muted-foreground">
            <span className="font-semibold text-foreground">
              + ¥{setupFee.toLocaleString()} one-time setup
            </span>{" "}
            (or 12/24-month installment)
          </p>
        </div>
      </div>
    </div>
  );
}

/**
 * Mobile Plan Card - Combined header + inline expandable details for mobile view
 */
function MobilePlanCard({
  config,
  minPrice,
  tiers,
  setupFee,
  isExpanded,
  onToggle,
}: {
  config: OfferingTypeConfig;
  minPrice: number;
  tiers: TierInfo[];
  setupFee: number;
  isExpanded: boolean;
  onToggle: () => void;
}) {
  return (
    <div
      className={cn(
        "rounded-xl border-2 shadow-sm overflow-hidden transition-all duration-300",
        isExpanded
          ? "border-primary bg-primary/5 shadow-md ring-1 ring-primary/20"
          : "border-border bg-card hover:border-primary/40"
      )}
    >
      {/* Header - Clickable to expand/collapse */}
      <button
        type="button"
        onClick={onToggle}
        className="w-full p-4 flex flex-col gap-3 hover:bg-muted/30 transition-colors text-left"
      >
        <div className="flex items-start justify-between gap-2">
          <div
            className={cn(
              "flex h-10 w-10 items-center justify-center rounded-xl flex-shrink-0 transition-colors",
              isExpanded ? "bg-primary/10" : "bg-muted/50"
            )}
          >
            {config.icon}
          </div>
          <div
            className={cn(
              "flex items-center gap-1 transition-colors",
              isExpanded ? "text-primary" : "text-muted-foreground"
            )}
          >
            <span className="text-xs font-medium">{isExpanded ? "Hide tiers" : "Show tiers"}</span>
            {isExpanded ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
          </div>
        </div>
        <div>
          <div className="flex items-center gap-2 flex-wrap mb-1">
            <h3
              className={cn(
                "text-base font-bold transition-colors",
                isExpanded ? "text-primary" : "text-foreground"
              )}
            >
              {config.title}
            </h3>
            <span
              className={cn("text-xs font-semibold px-2 py-0.5 rounded-full", config.badgeColor)}
            >
              {config.badge}
            </span>
          </div>
          {config.id === "home10g" && (
            <span className="text-xs text-muted-foreground">(select areas)</span>
          )}
          <p className="text-sm text-muted-foreground mt-1">{config.description}</p>
          <p className="text-sm text-muted-foreground mt-2">
            From{" "}
            <span className="font-bold text-foreground text-lg">¥{minPrice.toLocaleString()}</span>{" "}
            /mo
          </p>
        </div>
      </button>

      {/* Inline Expanded Content - slides down below header */}
      <div
        className={cn(
          "grid transition-all duration-300 ease-in-out",
          isExpanded ? "grid-rows-[1fr] opacity-100" : "grid-rows-[0fr] opacity-0"
        )}
      >
        <div className="overflow-hidden">
          <div className="border-t border-border/50 p-4 bg-muted/10">
            {/* Tier Cards - Stacked vertically on mobile */}
            <div className="space-y-3">
              {tiers.map(tier => (
                <div
                  key={tier.tier}
                  className={cn(
                    "rounded-xl border p-4 transition-all duration-200 flex flex-col relative bg-white",
                    tierStyles[tier.tier].card
                  )}
                >
                  {/* Popular Badge for Gold */}
                  {tier.tier === "Gold" && (
                    <div className="absolute -top-3 left-4">
                      <span className="inline-flex items-center gap-1 px-3 py-1 rounded-full bg-amber-500 text-white text-xs font-semibold shadow-sm">
                        <Sparkles className="h-3 w-3" />
                        Popular
                      </span>
                    </div>
                  )}

                  <div className="flex items-start justify-between gap-4">
                    <div className="flex-1">
                      {/* Tier Name */}
                      <h4
                        className={cn(
                          "font-bold text-lg mb-1",
                          tier.tier === "Gold" ? "mt-2" : "",
                          tierStyles[tier.tier].accent
                        )}
                      >
                        {tier.tier}
                      </h4>

                      {/* Description */}
                      <p className="text-sm text-muted-foreground">{tier.description}</p>
                    </div>

                    {/* Price - Right aligned */}
                    <div className="text-right flex-shrink-0">
                      <div className="flex items-baseline gap-0.5 justify-end">
                        <span className="text-xl font-bold text-foreground">
                          ¥{tier.monthlyPrice.toLocaleString()}
                        </span>
                        <span className="text-sm text-muted-foreground">/mo</span>
                      </div>
                      {tier.pricingNote && (
                        <span
                          className={`text-xs ${tier.tier === "Platinum" ? "text-primary" : "text-amber-600"}`}
                        >
                          {tier.pricingNote}
                        </span>
                      )}
                    </div>
                  </div>

                  {/* Features - Compact horizontal layout */}
                  <ul className="flex flex-wrap gap-x-4 gap-y-1 mt-3 pt-3 border-t border-border/30">
                    {tier.features.slice(0, 2).map((feature, index) => (
                      <li key={index} className="flex items-center gap-1.5 text-xs">
                        <svg
                          className="h-3 w-3 text-green-500 flex-shrink-0"
                          viewBox="0 0 20 20"
                          fill="currentColor"
                        >
                          <path
                            fillRule="evenodd"
                            d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
                            clipRule="evenodd"
                          />
                        </svg>
                        <span className="text-muted-foreground">{feature}</span>
                      </li>
                    ))}
                  </ul>
                </div>
              ))}
            </div>

            {/* Footer with setup fee */}
            <div className="pt-4 mt-4 border-t border-border/50">
              <p className="text-xs text-muted-foreground text-center">
                <span className="font-semibold text-foreground">
                  + ¥{setupFee.toLocaleString()} one-time setup
                </span>{" "}
                (or 12/24-month installment)
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

/**
 * Available Plans Section - Horizontal cards for each offering type with expandable details
 */
function AvailablePlansSection({
  plansByOffering,
  setupFee,
}: {
  plansByOffering: Record<string, { minPrice: number; tiers: TierInfo[] }>;
  setupFee: number;
}) {
  const [expandedCard, setExpandedCard] = useState<string | null>(null);

  const toggleCard = (id: string) => {
    setExpandedCard(prev => (prev === id ? null : id));
  };

  // Get configs that have data
  const availableConfigs = offeringTypeConfigs.filter(config => plansByOffering[config.id]);

  return (
    <section className="space-y-6 mt-8">
      <h2 className="text-2xl font-bold text-foreground text-center">Available Plans</h2>

      {/* Mobile view - Cards with inline expandable content */}
      <div className="md:hidden space-y-4">
        {availableConfigs.map(config => {
          const offeringData = plansByOffering[config.id];
          if (!offeringData) return null;

          return (
            <MobilePlanCard
              key={config.id}
              config={config}
              minPrice={offeringData.minPrice}
              tiers={offeringData.tiers}
              setupFee={setupFee}
              isExpanded={expandedCard === config.id}
              onToggle={() => toggleCard(config.id)}
            />
          );
        })}
      </div>

      {/* Desktop view - Horizontal card headers with separate expanded section */}
      <div className="hidden md:block">
        <div className="grid grid-cols-3 gap-4">
          {availableConfigs.map(config => {
            const offeringData = plansByOffering[config.id];
            if (!offeringData) return null;

            return (
              <PlanCardHeader
                key={config.id}
                config={config}
                minPrice={offeringData.minPrice}
                isExpanded={expandedCard === config.id}
                onToggle={() => toggleCard(config.id)}
              />
            );
          })}
        </div>

        {/* Expanded tier details - shown below the horizontal cards (desktop only) */}
        <div className="space-y-4 mt-4">
          {availableConfigs.map(config => {
            const offeringData = plansByOffering[config.id];
            if (!offeringData || expandedCard !== config.id) return null;

            return (
              <ExpandedTierDetails
                key={config.id}
                config={config}
                tiers={offeringData.tiers}
                setupFee={setupFee}
              />
            );
          })}
        </div>
      </div>
    </section>
  );
}

export interface PublicInternetPlansContentProps {
  onCtaClick?: (e: React.MouseEvent) => void;
  ctaPath?: string;
  ctaLabel?: string;
  heroTitle?: string;
  heroDescription?: string;
}

/**
 * Public Internet Plans Content - Reusable component
 */
export function PublicInternetPlansContent({
  onCtaClick,
  ctaPath: propCtaPath,
  ctaLabel = "Check Availability",
  heroTitle = "Internet for Expats in Japan",
  heroDescription = "Fast, reliable fiber internet with full English support. No Japanese required",
}: PublicInternetPlansContentProps) {
  const { data: servicesCatalog, error } = usePublicInternetCatalog();
  // Simple loading check: show skeleton until we have data or an error
  const isLoading = !servicesCatalog && !error;
  const servicesBasePath = useServicesBasePath();
  const defaultCtaPath = `${servicesBasePath}/internet/check-availability`;
  const ctaPath = propCtaPath ?? defaultCtaPath;

  const internetFeatures: HighlightFeature[] = [
    {
      icon: <Wifi className="h-6 w-6" />,
      title: "NTT Optical Fiber",
      description: "Japan's most reliable network with speeds up to 10Gbps",
      highlight: "99.9% uptime",
    },
    {
      icon: <Languages className="h-6 w-6" />,
      title: "No Japanese Required",
      description: "English contracts, English support, English installation coordination",
      highlight: "Fully bilingual",
    },
    {
      icon: <FileText className="h-6 w-6" />,
      title: "We Handle the Paperwork",
      description: "No need to navigate Japanese forms or phone calls",
      highlight: "Hassle-free setup",
    },
    {
      icon: <Zap className="h-6 w-6" />,
      title: "IPv6/IPoE Ready",
      description: "Next-gen protocol for congestion-free browsing",
      highlight: "No slowdowns",
    },
    {
      icon: <Wrench className="h-6 w-6" />,
      title: "English Onsite Support",
      description: "Our technicians speak English and can visit your home",
      highlight: "In-person help",
    },
    {
      icon: <Globe className="h-6 w-6" />,
      title: "Flexible Contracts",
      description: "Monthly billing, no long-term commitment required",
      highlight: "Cancel anytime",
    },
  ];

  // Consolidated internet plans data - one card with all tiers
  const consolidatedPlanData = useMemo(() => {
    if (!servicesCatalog?.plans) return null;

    // Get installation item for setup fee
    const installationItem = servicesCatalog.installations?.[0] as
      | InternetInstallationCatalogItem
      | undefined;
    const setupFee = installationItem?.oneTimePrice ?? 22800;

    // Get all prices across all plan types to show full range
    const allPrices = servicesCatalog.plans.map(p => p.monthlyPrice ?? 0).filter(p => p > 0);
    const minPrice = Math.min(...allPrices);
    const maxPrice = Math.max(...allPrices);

    // Get unique tiers with their price ranges across all offering types
    const tierOrder: Record<string, number> = { Silver: 0, Gold: 1, Platinum: 2 };
    const tierData: Record<
      string,
      { minPrice: number; maxPrice: number; plans: InternetPlanCatalogItem[] }
    > = {};

    for (const plan of servicesCatalog.plans) {
      const tier = plan.internetPlanTier ?? "Silver";
      if (!tierData[tier]) {
        tierData[tier] = { minPrice: Infinity, maxPrice: 0, plans: [] };
      }
      const price = plan.monthlyPrice ?? 0;
      tierData[tier].minPrice = Math.min(tierData[tier].minPrice, price);
      tierData[tier].maxPrice = Math.max(tierData[tier].maxPrice, price);
      tierData[tier].plans.push(plan);
    }

    // Build consolidated tier info with price ranges
    const tiers: TierInfo[] = Object.entries(tierData)
      .sort(([a], [b]) => (tierOrder[a] ?? 99) - (tierOrder[b] ?? 99))
      .map(([tier, data]) => ({
        tier: tier as TierInfo["tier"],
        monthlyPrice: data.minPrice,
        maxMonthlyPrice: data.maxPrice,
        description: getTierDescription(tier),
        features: getTierFeatures(tier),
        ...(tier === "Platinum" && { pricingNote: "+ equipment fees" }),
      }));

    return {
      minPrice,
      maxPrice,
      setupFee,
      tiers,
    };
  }, [servicesCatalog]);

  // Plans grouped by offering type (Home 10G, Home 1G, Apartment)
  const plansByOffering = useMemo(() => {
    // Default pricing for each offering type (used when catalog doesn't have specific data)
    const defaultOfferingPrices: Record<
      string,
      { silver: number; gold: number; platinum: number }
    > = {
      home10g: { silver: 8000, gold: 8500, platinum: 8500 },
      home1g: { silver: 6000, gold: 6500, platinum: 6500 },
      apartment: { silver: 4800, gold: 5300, platinum: 5300 },
    };

    const tierOrder: Record<string, number> = { Silver: 0, Gold: 1, Platinum: 2 };
    const offeringData: Record<
      string,
      {
        minPrice: number;
        tierData: Record<string, { price: number; plan?: InternetPlanCatalogItem }>;
      }
    > = {};

    // Process catalog plans if available
    if (servicesCatalog?.plans) {
      for (const plan of servicesCatalog.plans) {
        const offeringType = getOfferingTypeId(plan.internetOfferingType);
        const tier = plan.internetPlanTier ?? "Silver";
        const price = plan.monthlyPrice ?? 0;

        if (!offeringData[offeringType]) {
          offeringData[offeringType] = { minPrice: Infinity, tierData: {} };
        }

        offeringData[offeringType].minPrice = Math.min(offeringData[offeringType].minPrice, price);

        // Keep the price for this tier (use lowest if multiple plans for same tier)
        if (
          !offeringData[offeringType].tierData[tier] ||
          price < offeringData[offeringType].tierData[tier].price
        ) {
          offeringData[offeringType].tierData[tier] = { price, plan };
        }
      }
    }

    // Ensure all three offering types exist with default data
    for (const config of offeringTypeConfigs) {
      const defaults = defaultOfferingPrices[config.id];
      if (!defaults) continue;

      const existingData = offeringData[config.id];
      if (existingData) {
        // Fill in missing tiers with defaults
        if (!existingData.tierData["Silver"]) {
          existingData.tierData["Silver"] = { price: defaults.silver };
        }
        if (!existingData.tierData["Gold"]) {
          existingData.tierData["Gold"] = { price: defaults.gold };
        }
        if (!existingData.tierData["Platinum"]) {
          existingData.tierData["Platinum"] = { price: defaults.platinum };
        }
        // Recalculate min price
        const allPrices = Object.values(existingData.tierData).map(t => t.price);
        existingData.minPrice = Math.min(...allPrices);
      } else {
        offeringData[config.id] = {
          minPrice: defaults.silver,
          tierData: {
            Silver: { price: defaults.silver },
            Gold: { price: defaults.gold },
            Platinum: { price: defaults.platinum },
          },
        };
      }
    }

    // Convert to the format expected by AvailablePlansSection
    const result: Record<string, { minPrice: number; tiers: TierInfo[] }> = {};

    for (const [offeringType, data] of Object.entries(offeringData)) {
      const tiers: TierInfo[] = Object.entries(data.tierData)
        .sort(([a], [b]) => (tierOrder[a] ?? 99) - (tierOrder[b] ?? 99))
        .map(([tier, tierInfo]) => ({
          tier: tier as TierInfo["tier"],
          monthlyPrice: tierInfo.price,
          description: getTierDescription(tier),
          features: getTierFeatures(tier),
          ...(tier === "Platinum" && { pricingNote: "+ equipment fees" }),
        }));

      result[offeringType] = {
        minPrice: data.minPrice,
        tiers,
      };
    }

    return result;
  }, [servicesCatalog]);

  // Error state
  if (error) {
    return (
      <div className="space-y-6">
        <ServicesBackLink href={servicesBasePath} />
        <AlertBanner variant="error" title="Unable to load plans">
          We couldn&apos;t load internet plans. Please try again later.
        </AlertBanner>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Back link */}
      <ServicesBackLink href={servicesBasePath} />

      {/* Hero - Clean and impactful */}
      <div className="text-center py-4">
        <h1 className="text-3xl md:text-4xl font-bold text-foreground tracking-tight">
          {heroTitle}
        </h1>
        <p className="text-base text-muted-foreground mt-2 max-w-lg mx-auto">{heroDescription}</p>
      </div>

      {/* Service Highlights */}
      <ServiceHighlights features={internetFeatures} />

      {/* Consolidated Internet Plans Card */}
      <section className="space-y-3">
        {isLoading ? (
          <Skeleton className="h-64 w-full rounded-xl" />
        ) : consolidatedPlanData ? (
          <ConsolidatedInternetCard
            minPrice={consolidatedPlanData.minPrice}
            maxPrice={consolidatedPlanData.maxPrice}
            setupFee={consolidatedPlanData.setupFee}
            tiers={consolidatedPlanData.tiers}
            ctaPath={ctaPath}
            ctaLabel={ctaLabel}
            {...(onCtaClick && { onCtaClick })}
          />
        ) : null}
      </section>

      {/* Available Plans - Expandable cards by offering type */}
      {!isLoading && plansByOffering && consolidatedPlanData && (
        <AvailablePlansSection
          plansByOffering={plansByOffering}
          setupFee={consolidatedPlanData.setupFee}
        />
      )}

      {/* How It Works Section */}
      <HowItWorksSection />

      {/* FAQ Section */}
      <InternetFaqSection />

      {/* Final CTA - Polished */}
      <section className="text-center py-8 mt-4 rounded-2xl bg-gradient-to-br from-primary/5 via-transparent to-info/5 border border-border/50">
        <div className="inline-flex items-center gap-1.5 text-xs font-medium text-primary mb-3 px-3 py-1 rounded-full bg-primary/10">
          <Sparkles className="h-3.5 w-3.5" />
          Get started in minutes
        </div>
        <h2 className="text-xl font-bold text-foreground mb-2">Ready to get connected?</h2>
        <p className="text-sm text-muted-foreground mb-5 max-w-sm mx-auto">
          Enter your address to see what&apos;s available at your location
        </p>
        {onCtaClick ? (
          <Button onClick={onCtaClick} size="lg" rightIcon={<ArrowRight className="h-4 w-4" />}>
            {ctaLabel}
          </Button>
        ) : (
          <Button as="a" href={ctaPath} size="lg" rightIcon={<ArrowRight className="h-4 w-4" />}>
            {ctaLabel}
          </Button>
        )}
      </section>
    </div>
  );
}

/**
 * Public Internet Plans page - Marketing/Conversion focused
 * Clean, polished design optimized for conversion
 */
export function PublicInternetPlansView() {
  return <PublicInternetPlansContent />;
}

// Helper functions
function getTierDescription(tier: string): string {
  const descriptions: Record<string, 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.",
  };
  return descriptions[tier] ?? "";
}

function getTierFeatures(tier: string): string[] {
  const features: Record<string, string[]> = {
    Silver: [
      "NTT modem + ISP connection",
      "Two ISP connection protocols: IPoE (recommended) or PPPoE",
      "Self-configuration of router (you provide your own)",
    ],
    Gold: [
      "NTT modem + wireless router (rental)",
      "ISP (IPoE) configured automatically within 24 hours",
      "Basic wireless router included",
    ],
    Platinum: [
      "NTT modem + Netgear INSIGHT Wi-Fi routers",
      "Cloud management support for remote router management",
      "Automatic updates and quicker support",
    ],
  };
  return features[tier] ?? [];
}

// Internet FAQ data
const INTERNET_FAQ_ITEMS = [
  {
    question: "How can I check if the 10Gbps service is available in my apartment or home?",
    answer:
      "Service availability depends on your address and building's network infrastructure. Please contact us (info@asolutions.co.jp) with your full address (including apartment name and room number) so we can confirm if our 10Gbps plans can be installed at your location.",
  },
  {
    question:
      "My home requires multiple Wi-Fi routers for full residence coverage. Would you be able to assist with this?",
    answer:
      "Our tech consulting team will be able to make suggestions based on your residence layout and requirements. Please contact us at info@asolutions.co.jp for a free consultation.",
  },
  {
    question:
      "We already have an Internet contract with a different company. Would it be possible to transfer our current service over to Assist Solutions?",
    answer:
      "Depending on the service that you are currently subscribed to, you may be able to transfer the service without cancelling. Please contact us at info@asolutions.co.jp for more information.",
  },
  {
    question: "What is the service contract period?",
    answer:
      "We offer our home Internet service on a monthly basis and thus, you will not be bound by yearly contracts. A designated cancellation form will need to be submitted by the 25th to close the account at the end of the month. For example, cancellation requests will need to be sent in by May 25th, in order to cancel at the end of May.",
  },
  {
    question: "How are invoices sent every month?",
    answer:
      "E-statements (available only in English) will be sent to your primary Email address. The service fee will be charged automatically to your registered credit card on file. For corporate plans, please contact us with your requests.",
  },
  {
    question: "My Internet is not working as expected. What should I do?",
    answer:
      "Our Chatbot will be able to assist you 24/7 with the initial diagnosis and offer troubleshooting tips based on your situation. You are also welcome to contact us at info@asolutions.co.jp for tech support (our business hours are 10AM-6PM/Mon-Sat). When contacting us, please be sure to let us know of the account holder's name and residence address so that we would be able to locate your account quicker.",
  },
];

/**
 * Internet FAQ Section
 */
function InternetFaqSection() {
  return (
    <section className="mt-12 mb-8">
      <h2 className="text-2xl font-bold text-foreground mb-6 text-center">
        Frequently Asked Questions
      </h2>
      <div className="space-y-4 max-w-3xl mx-auto">
        {INTERNET_FAQ_ITEMS.map((item, index) => (
          <FaqItem key={index} question={item.question} answer={item.answer} />
        ))}
      </div>
    </section>
  );
}

/**
 * FAQ Item component with expand/collapse functionality
 */
function FaqItem({ question, answer }: { question: string; answer: string }) {
  const [isOpen, setIsOpen] = useState(false);

  return (
    <div className="border border-border rounded-xl overflow-hidden bg-card">
      <button
        type="button"
        onClick={() => setIsOpen(!isOpen)}
        className="w-full flex items-start justify-between gap-3 p-4 text-left hover:bg-muted/50 transition-colors"
      >
        <span className="font-medium text-foreground">{question}</span>
        <ChevronDown
          className={`w-5 h-5 text-muted-foreground flex-shrink-0 mt-0.5 transition-transform duration-200 ${isOpen ? "rotate-180" : ""}`}
        />
      </button>
      {isOpen && (
        <div className="px-4 pb-4 text-sm text-muted-foreground leading-relaxed">{answer}</div>
      )}
    </div>
  );
}
