"use client"

import { useState, useMemo, useEffect, useCallback } from "react"
import Image from "next/image"
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Checkbox } from "@/components/ui/checkbox"
import { PublicInset, PublicSurface } from "@/components/public-surface"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import {
  Download,
  Search,
  Filter,
  X,
  Coffee,
  Utensils,
  Package,
  Droplet,
  Eye,
  ShoppingCart,
  LayoutGrid,
  List,
  ExternalLink,
  Loader2,
  AlertCircle,
} from "lucide-react"
import type { Manual, ManualGroup } from "@/lib/manuals-types"
import { getManualUrl, getThumbnailUrl } from "@/lib/manuals-types"
import {
  getMachineTypeInfo,
  getAllMachineTypeNames,
} from "@/lib/manuals-config"
import { ManualViewer } from "@/components/manual-viewer"
import { getManualsWithParts } from "@/lib/parts-lookup"
import { ebayClient } from "@/lib/ebay-api"

// Product Suggestion Component
interface ProductSuggestion {
  itemId: string
  title: string
  price: string
  currency: string
  imageUrl?: string
  viewItemUrl: string
  affiliateLink: string
  condition?: string
}

interface ProductSuggestionsProps {
  manual: Manual
  className?: string
}

function ProductSuggestions({
  manual,
  className = "",
}: ProductSuggestionsProps) {
  const [suggestions, setSuggestions] = useState<ProductSuggestion[]>([])
  const [isLoading, setIsLoading] = useState(ebayClient.isConfigured())
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    if (!ebayClient.isConfigured()) {
      setIsLoading(false)
      return
    }

    async function loadSuggestions() {
      setIsLoading(true)
      setError(null)

      try {
        // Generate search query from manual content
        const query = `${manual.manufacturer} ${manual.category} vending machine`
        const results = await ebayClient.searchItems({
          keywords: query,
          maxResults: 6,
          sortOrder: "BestMatch",
        })

        setSuggestions(results)
      } catch (err) {
        console.error("Error loading product suggestions:", err)
        setError("Could not load product suggestions")
      } finally {
        setIsLoading(false)
      }
    }

    if (manual) {
      loadSuggestions()
    }
  }, [manual])

  if (!ebayClient.isConfigured()) {
    return null
  }

  if (isLoading) {
    return (
      <div
        className={`bg-white/60 dark:bg-yellow-900/20 rounded border border-yellow-300/30 dark:border-yellow-700/30 p-4 ${className}`}
      >
        <div className="flex items-center justify-center h-32">
          <Loader2 className="h-5 w-5 text-yellow-700 dark:text-yellow-300 animate-spin" />
        </div>
      </div>
    )
  }

  if (error) {
    return (
      <div
        className={`bg-white/60 dark:bg-yellow-900/20 rounded border border-yellow-300/30 dark:border-yellow-700/30 p-4 ${className}`}
      >
        <div className="flex items-center justify-center h-32">
          <AlertCircle className="h-6 w-6 text-red-500" />
          <span className="ml-2 text-sm text-red-500">{error}</span>
        </div>
      </div>
    )
  }

  if (suggestions.length === 0) {
    return (
      <div
        className={`bg-white/60 dark:bg-yellow-900/20 rounded border border-yellow-300/30 dark:border-yellow-700/30 p-4 ${className}`}
      >
        <div className="flex items-center justify-center h-32">
          <AlertCircle className="h-6 w-6 text-yellow-500" />
          <span className="ml-2 text-sm text-yellow-600">
            No products found in sandbox environment
          </span>
        </div>
      </div>
    )
  }

  return (
    <div
      className={`bg-white/60 dark:bg-yellow-900/20 rounded border border-yellow-300/30 dark:border-yellow-700/30 p-4 ${className}`}
    >
      <div className="flex items-center gap-2 mb-4">
        <ShoppingCart className="h-4 w-4 text-yellow-700 dark:text-yellow-300" />
        <h3 className="text-sm font-semibold text-yellow-900 dark:text-yellow-100">
          Related Products
        </h3>
      </div>

      <div className="grid grid-cols-2 gap-3">
        {suggestions.map((product) => (
          <a
            key={product.itemId}
            href={product.affiliateLink}
            target="_blank"
            rel="noopener noreferrer"
            className="block group"
          >
            <div className="bg-white dark:bg-yellow-900/30 rounded border border-yellow-300/40 dark:border-yellow-700/40 p-2 hover:bg-yellow-50 dark:hover:bg-yellow-900/40 transition-colors">
              {/* Image */}
              {product.imageUrl && (
                <div className="mb-2 rounded overflow-hidden bg-yellow-100 dark:bg-yellow-900/50">
                  <img
                    src={product.imageUrl}
                    alt={product.title}
                    className="w-full h-16 object-cover"
                    onError={(e) => {
                      e.currentTarget.src = `https://via.placeholder.com/120x80/fbbf24/1f2937?text=${encodeURIComponent(product.title)}`
                    }}
                  />
                </div>
              )}
              {!product.imageUrl && (
                <div className="mb-2 rounded overflow-hidden bg-yellow-100 dark:bg-yellow-900/50 h-16 flex items-center justify-center">
                  <span className="text-[10px] text-yellow-700 dark:text-yellow-300">
                    No Image
                  </span>
                </div>
              )}

              {/* Product Details */}
              <div className="space-y-1">
                <div className="text-[11px] text-yellow-900 dark:text-yellow-100 line-clamp-2 min-h-[1.5rem]">
                  {product.title}
                </div>
                <div className="flex items-center justify-between">
                  <span className="text-xs font-semibold text-yellow-900 dark:text-yellow-100">
                    {product.price}
                  </span>
                  <ExternalLink className="h-3 w-3 text-yellow-700 dark:text-yellow-300 group-hover:text-yellow-900 dark:group-hover:text-yellow-100 transition-colors flex-shrink-0" />
                </div>
                {product.condition && (
                  <div className="text-[9px] text-yellow-700/80 dark:text-yellow-300/80">
                    {product.condition}
                  </div>
                )}
              </div>
            </div>
          </a>
        ))}
      </div>
    </div>
  )
}

interface ManualsPageClientProps {
  manuals: Manual[]
  groupedManuals: ManualGroup[]
  manufacturers: string[]
  categories: string[]
}

interface ManualCardProps {
  manual: Manual
  onView: (manual: { url: string; filename: string }) => void
  manualHasParts: (manual: Manual) => boolean
  getCategoryBadgeClass: (category: string) => string
  formatFileSize: (bytes?: number) => string
  showManufacturer?: boolean
}

function ManualCard({
  manual,
  onView,
  manualHasParts,
  getCategoryBadgeClass,
  formatFileSize,
  showManufacturer = false,
}: ManualCardProps) {
  const thumbnailUrl = getThumbnailUrl(manual)

  return (
    <Card className="overflow-hidden rounded-[1.75rem] border border-border/70 bg-background shadow-[0_18px_45px_rgba(15,23,42,0.08)] transition-all hover:-translate-y-0.5 hover:shadow-[0_24px_60px_rgba(15,23,42,0.12)]">
      {thumbnailUrl && (
        <div className="relative h-48 min-h-[192px] w-full overflow-hidden bg-[radial-gradient(circle_at_top_left,rgba(196,154,52,0.12),transparent_52%),linear-gradient(180deg,rgba(255,255,255,0.98),rgba(255,255,255,0.98))]">
          <Image
            src={thumbnailUrl}
            alt={manual.filename.replace(/\.pdf$/i, "")}
            fill
            className="object-contain"
            sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
          />
        </div>
      )}
      <CardHeader className="px-5 pt-5">
        <CardTitle className="line-clamp-2 text-base leading-snug">
          {manual.filename.replace(/\.pdf$/i, "")}
        </CardTitle>
        {manual.commonNames && manual.commonNames.length > 0 && (
          <div className="mt-2 flex flex-wrap gap-2">
            {manual.commonNames.map((name, index) => (
              <Badge
                key={index}
                variant="secondary"
                className="rounded-full border border-primary/15 bg-primary/[0.06] px-2.5 py-0.5 text-[11px] font-medium text-foreground"
              >
                {name}
              </Badge>
            ))}
          </div>
        )}
        {manual.searchTerms &&
          manual.searchTerms.length > 0 &&
          !manual.commonNames && (
            <div className="mt-2 flex flex-wrap gap-2">
              {manual.searchTerms.map((term, index) => (
                <Badge
                  key={index}
                  variant="secondary"
                  className="rounded-full border border-border/60 bg-muted/35 px-2.5 py-0.5 text-[11px] font-medium text-muted-foreground"
                >
                  {term}
                </Badge>
              ))}
            </div>
          )}
      </CardHeader>
      <CardContent className="space-y-4 px-5 pb-5">
        <div className="flex flex-wrap gap-2">
          <Badge
            variant="outline"
            className={`rounded-full px-2.5 py-0.5 text-xs font-medium ${getCategoryBadgeClass(
              manual.category
            )}`}
          >
            {manual.category}
          </Badge>
          {manualHasParts(manual) && (
            <Badge
              variant="outline"
              className="bg-yellow-50 text-yellow-800 border-yellow-300 dark:bg-yellow-950 dark:text-yellow-200 dark:border-yellow-700"
            >
              <ShoppingCart className="h-3 w-3 mr-1" />
              Has Parts
            </Badge>
          )}
        </div>
        <div className="text-sm text-muted-foreground space-y-1">
          {showManufacturer && (
            <p>
              <strong>Manufacturer:</strong> {manual.manufacturer}
            </p>
          )}
          {manual.size && (
            <p>
              <strong>Size:</strong> {formatFileSize(manual.size)}
            </p>
          )}
        </div>
        <div className="flex items-center gap-2">
          <Button
            variant="outline"
            size="sm"
            onClick={() =>
              onView({ url: getManualUrl(manual), filename: manual.filename })
            }
            className="flex-1 rounded-full border-border bg-background hover:border-primary/40 hover:text-primary"
          >
            <Eye className="h-4 w-4 mr-1" />
            View PDF
          </Button>
          <a
            href={getManualUrl(manual)}
            target="_blank"
            rel="noopener noreferrer"
            className="inline-flex items-center gap-2 text-sm font-medium hover:underline px-2"
          >
            <Download className="h-4 w-4" />
          </a>
        </div>
      </CardContent>
    </Card>
  )
}

export function ManualsPageClient({
  manuals,
  groupedManuals,
  manufacturers,
  categories,
}: ManualsPageClientProps) {
  const [searchTerm, setSearchTerm] = useState("")
  const [selectedManufacturer, setSelectedManufacturer] = useState<string>("")
  const [selectedCategory, setSelectedCategory] = useState<string>("")
  const [hasPartsOnly, setHasPartsOnly] = useState(false)
  const [viewMode, setViewMode] = useState<"grouped" | "list">("grouped")
  const [viewingManual, setViewingManual] = useState<{
    url: string
    filename: string
  } | null>(null)
  const [manualsWithParts, setManualsWithParts] = useState<Set<string>>(
    new Set()
  )
  const [partsLoading, setPartsLoading] = useState(true)

  // Load manuals with parts on mount
  useEffect(() => {
    getManualsWithParts()
      .then((set) => {
        setManualsWithParts(set)
        setPartsLoading(false)
      })
      .catch(() => {
        setPartsLoading(false)
      })
  }, [])

  // Helper function to check if a manual has parts
  const manualHasParts = useCallback(
    (manual: Manual): boolean => {
      if (manualsWithParts.size === 0) return false
      const filename = manual.filename
      return (
        manualsWithParts.has(filename) ||
        manualsWithParts.has(filename.toLowerCase()) ||
        manualsWithParts.has(filename.replace(/\.pdf$/i, "")) ||
        manualsWithParts.has(filename.replace(/\.pdf$/i, "").toLowerCase())
      )
    },
    [manualsWithParts]
  )

  // Filter manuals based on search and filters
  const filteredManuals = useMemo(() => {
    let filtered = manuals

    if (selectedManufacturer) {
      filtered = filtered.filter((m) => m.manufacturer === selectedManufacturer)
    }

    if (selectedCategory) {
      filtered = filtered.filter((m) => m.category === selectedCategory)
    }

    if (hasPartsOnly) {
      filtered = filtered.filter((m) => manualHasParts(m))
    }

    if (searchTerm) {
      const search = searchTerm.toLowerCase()
      filtered = filtered.filter(
        (m) =>
          m.filename.toLowerCase().includes(search) ||
          m.manufacturer.toLowerCase().includes(search) ||
          m.category.toLowerCase().includes(search) ||
          (m.commonNames &&
            m.commonNames.some((name) =>
              name.toLowerCase().includes(search)
            )) ||
          (m.searchTerms && m.searchTerms.some((term) => term.includes(search)))
      )
    }

    return filtered
  }, [
    manuals,
    searchTerm,
    selectedManufacturer,
    selectedCategory,
    hasPartsOnly,
    manualHasParts,
  ])

  // Get filtered categories based on selected manufacturer
  const filteredCategories = useMemo(() => {
    if (!selectedManufacturer) {
      return categories
    }

    const manufacturerManuals = manuals.filter(
      (m) => m.manufacturer === selectedManufacturer
    )
    const uniqueCategories = new Set(manufacturerManuals.map((m) => m.category))
    return Array.from(uniqueCategories)
  }, [manuals, selectedManufacturer, categories])

  // Filter grouped manuals
  const filteredGroupedManuals = useMemo(() => {
    if (
      !selectedManufacturer &&
      !selectedCategory &&
      !searchTerm &&
      !hasPartsOnly
    ) {
      return groupedManuals
    }

    return groupedManuals
      .filter((group) => {
        if (
          selectedManufacturer &&
          group.manufacturer !== selectedManufacturer
        ) {
          return false
        }
        return true
      })
      .map((group) => {
        const filteredCategories: { [key: string]: Manual[] } = {}
        for (const [category, categoryManuals] of Object.entries(
          group.categories
        )) {
          if (selectedCategory && category !== selectedCategory) {
            continue
          }
          const filtered = categoryManuals.filter((manual) => {
            if (hasPartsOnly && !manualHasParts(manual)) {
              return false
            }
            if (searchTerm) {
              const search = searchTerm.toLowerCase()
              return (
                manual.filename.toLowerCase().includes(search) ||
                manual.manufacturer.toLowerCase().includes(search) ||
                manual.category.toLowerCase().includes(search) ||
                (manual.commonNames &&
                  manual.commonNames.some((name) =>
                    name.toLowerCase().includes(search)
                  )) ||
                (manual.searchTerms &&
                  manual.searchTerms.some((term) => term.includes(search)))
              )
            }
            return true
          })
          if (filtered.length > 0) {
            filteredCategories[category] = filtered
          }
        }
        return {
          ...group,
          categories: filteredCategories,
        }
      })
      .filter((group) => Object.keys(group.categories).length > 0)
  }, [
    groupedManuals,
    selectedManufacturer,
    selectedCategory,
    searchTerm,
    hasPartsOnly,
    manualHasParts,
  ])

  const hasActiveFilters =
    selectedManufacturer || selectedCategory || searchTerm || hasPartsOnly

  const clearFilters = () => {
    setSearchTerm("")
    setSelectedManufacturer("")
    setSelectedCategory("")
    setHasPartsOnly(false)
  }

  const formatFileSize = (bytes?: number): string => {
    if (!bytes) return "Unknown size"
    if (bytes < 1024) return `${bytes} B`
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
    return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
  }

  // Organize categories by machine type first, then others
  const organizeCategories = (categories: { [key: string]: Manual[] }) => {
    const machineTypes = getAllMachineTypeNames()
    const machineTypeCategories: { [key: string]: Manual[] } = {}
    const otherCategories: { [key: string]: Manual[] } = {}

    for (const [category, manuals] of Object.entries(categories)) {
      if (machineTypes.includes(category)) {
        machineTypeCategories[category] = manuals
      } else {
        otherCategories[category] = manuals
      }
    }

    // Sort machine types by priority order
    const sortedMachineTypes = machineTypes
      .filter((type) => machineTypeCategories[type])
      .map((type) => [type, machineTypeCategories[type]] as [string, Manual[]])

    // Sort other categories alphabetically
    const sortedOthers = Object.entries(otherCategories).sort(([a], [b]) =>
      a.localeCompare(b)
    )

    return { machineTypes: sortedMachineTypes, others: sortedOthers }
  }

  // Get icon for machine type
  const getCategoryIcon = (category: string) => {
    const machineType = getMachineTypeInfo(category)
    if (!machineType) return null

    switch (category) {
      case "Coffee":
        return <Coffee className="h-4 w-4" />
      case "Food":
        return <Utensils className="h-4 w-4" />
      case "Beverage":
        return <Droplet className="h-4 w-4" />
      case "Snack":
        return <Package className="h-4 w-4" />
      default:
        return null
    }
  }

  // Get badge color for category
  const getCategoryBadgeClass = (category: string): string => {
    const machineType = getMachineTypeInfo(category)
    const categoryLower = category.toLowerCase()

    // Check for common category patterns
    if (categoryLower.includes("snack")) {
      return "bg-orange-100 text-orange-800 dark:bg-orange-900 dark:text-orange-200"
    }
    if (categoryLower.includes("beverage") || categoryLower.includes("drink")) {
      return "bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200"
    }
    if (categoryLower.includes("frozen")) {
      return "bg-indigo-100 text-indigo-800 dark:bg-indigo-900 dark:text-indigo-200"
    }
    if (categoryLower.includes("combo")) {
      return "bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200"
    }
    if (categoryLower.includes("coffee") || categoryLower.includes("hot")) {
      return "bg-amber-100 text-amber-800 dark:bg-amber-900 dark:text-amber-200"
    }
    if (categoryLower.includes("food")) {
      return "bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200"
    }
    if (categoryLower.includes("bulk")) {
      return "bg-pink-100 text-pink-800 dark:bg-pink-900 dark:text-pink-200"
    }
    if (categoryLower.includes("ice") || categoryLower.includes("cream")) {
      return "bg-cyan-100 text-cyan-800 dark:bg-cyan-900 dark:text-cyan-200"
    }
    if (categoryLower.includes("service") || categoryLower.includes("repair")) {
      return "bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200"
    }
    if (categoryLower.includes("parts")) {
      return "bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200"
    }
    if (categoryLower.includes("operator") || categoryLower.includes("user")) {
      return "bg-teal-100 text-teal-800 dark:bg-teal-900 dark:text-teal-200"
    }
    if (
      categoryLower.includes("installation") ||
      categoryLower.includes("setup")
    ) {
      return "bg-lime-100 text-lime-800 dark:bg-lime-900 dark:text-lime-200"
    }

    // Fallback for machine types
    if (machineType) {
      switch (category) {
        case "Snack":
          return "bg-orange-100 text-orange-800 dark:bg-orange-900 dark:text-orange-200"
        case "Beverage":
          return "bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200"
        case "Combo":
          return "bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200"
        case "Coffee":
          return "bg-amber-100 text-amber-800 dark:bg-amber-900 dark:text-amber-200"
        case "Food":
          return "bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200"
        case "Bulk":
          return "bg-pink-100 text-pink-800 dark:bg-pink-900 dark:text-pink-200"
        case "Ice Cream":
          return "bg-cyan-100 text-cyan-800 dark:bg-cyan-900 dark:text-cyan-200"
        default:
          return "bg-muted text-muted-foreground"
      }
    }

    return "bg-primary/[0.08] text-foreground"
  }

  return (
    <div className="space-y-6">
      {/* Search and Filter Controls */}
      <PublicSurface>
        <CardContent className="p-0">
          <div className="space-y-6">
            {/* Search Bar */}
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4" />
              <Input
                type="text"
                placeholder="Search manuals by name, manufacturer, or category..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="h-12 rounded-xl border-border/70 bg-white pl-10 shadow-sm"
              />
            </div>

            {/* Filters Row */}
            <div className="flex flex-col sm:flex-row flex-wrap gap-3 sm:gap-4 items-start sm:items-center">
              <div className="flex items-center gap-2 w-full sm:w-auto">
                <Filter className="h-4 w-4 text-muted-foreground flex-shrink-0" />
                <span className="text-sm font-medium">Filters:</span>
              </div>

              <div className="flex flex-col sm:flex-row gap-3 sm:gap-4 w-full sm:w-auto">
                <div className="relative">
                  <Select
                    value={selectedManufacturer || undefined}
                    onValueChange={(value) => {
                      setSelectedManufacturer(value ?? "")
                      // Clear category when manufacturer changes
                      if (
                        value &&
                        selectedCategory &&
                        !filteredCategories.includes(selectedCategory)
                      ) {
                        setSelectedCategory("")
                      }
                    }}
                  >
                    <SelectTrigger className="w-full rounded-xl border-border/70 bg-white shadow-sm sm:w-[200px]">
                      <SelectValue placeholder="All Manufacturers" />
                    </SelectTrigger>
                    <SelectContent>
                      {manufacturers.map((mfr) => (
                        <SelectItem key={mfr} value={mfr}>
                          {mfr}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  {selectedManufacturer && (
                    <Badge className="absolute -right-2 -top-2 rounded-full bg-primary text-[10px] text-white">
                      Applied
                    </Badge>
                  )}
                </div>

                <div className="relative">
                  <Select
                    value={selectedCategory || undefined}
                    onValueChange={(value) => {
                      setSelectedCategory(value ?? "")
                    }}
                    disabled={
                      !selectedManufacturer &&
                      filteredCategories.length === categories.length
                    }
                  >
                    <SelectTrigger className="w-full rounded-xl border-border/70 bg-white shadow-sm sm:w-[200px]">
                      <SelectValue placeholder="All Categories" />
                    </SelectTrigger>
                    <SelectContent>
                      {filteredCategories.map((cat) => (
                        <SelectItem key={cat} value={cat}>
                          {cat}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  {selectedCategory && (
                    <Badge className="absolute -right-2 -top-2 rounded-full bg-primary text-[10px] text-white">
                      Applied
                    </Badge>
                  )}
                </div>
              </div>

              <PublicInset className="flex w-full items-center gap-2 rounded-full px-4 py-2 shadow-none sm:w-auto">
                <Checkbox
                  id="has-parts"
                  checked={hasPartsOnly}
                  onCheckedChange={(checked) =>
                    setHasPartsOnly(checked === true)
                  }
                />
                <label
                  htmlFor="has-parts"
                  className="text-sm font-medium flex items-center gap-1.5 cursor-pointer"
                >
                  <ShoppingCart className="h-3.5 w-3.5" />
                  Has Parts Available
                </label>
                {hasPartsOnly && (
                  <Badge className="rounded-full bg-primary text-[10px] text-white">
                    Applied
                  </Badge>
                )}
              </PublicInset>

              {hasActiveFilters && (
                <Button
                  variant="outline"
                  size="sm"
                  onClick={clearFilters}
                  className="w-full rounded-full border-border bg-background sm:w-auto"
                >
                  <X className="h-4 w-4 mr-1" />
                  Clear Filters
                </Button>
              )}
            </div>

            {/* View Mode Toggle and Results Count */}
            <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 sm:gap-4">
              <div className="flex items-center gap-3 w-full sm:w-auto">
                <span className="text-sm text-muted-foreground flex-shrink-0">
                  View:
                </span>
                <div className="inline-flex flex-1 items-center rounded-full border border-border/70 bg-white p-1 shadow-sm sm:flex-initial">
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => setViewMode("grouped")}
                    className={`flex-1 rounded-full sm:flex-initial ${
                      viewMode === "grouped"
                        ? "bg-primary text-primary-foreground hover:bg-primary"
                        : "hover:bg-muted"
                    }`}
                    aria-label="Grouped view"
                  >
                    <LayoutGrid className="h-4 w-4 mr-1.5" />
                    <span className="hidden xs:inline">Grouped</span>
                  </Button>
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => setViewMode("list")}
                    className={`flex-1 rounded-full sm:flex-initial ${
                      viewMode === "list"
                        ? "bg-primary text-primary-foreground hover:bg-primary"
                        : "hover:bg-muted"
                    }`}
                    aria-label="List view"
                  >
                    <List className="h-4 w-4 mr-1.5" />
                    <span className="hidden xs:inline">List</span>
                  </Button>
                </div>
              </div>

              <div className="text-sm text-muted-foreground w-full sm:w-auto text-center sm:text-left">
                Showing <strong>{filteredManuals.length}</strong> of{" "}
                <strong>{manuals.length}</strong> manuals
              </div>
            </div>
          </div>
        </CardContent>
      </PublicSurface>

      {/* Manuals Display */}
      {filteredManuals.length === 0 ? (
        <PublicSurface>
          <CardContent className="py-16 text-center">
            <div className="space-y-2">
              <p className="text-lg font-medium text-foreground">
                No manuals found
              </p>
              <p className="text-sm text-muted-foreground">
                Try adjusting your search or filters to find what you're looking
                for.
              </p>
            </div>
          </CardContent>
        </PublicSurface>
      ) : viewMode === "grouped" ? (
        /* Grouped View */
        <div className="space-y-10">
          {filteredGroupedManuals.map((group) => {
            const organized = organizeCategories(group.categories)
            return (
              <PublicSurface key={group.manufacturer} className="space-y-6">
                <div className="border-b border-border/60 pb-3">
                  <h2 className="text-2xl font-bold tracking-tight">
                    {group.manufacturer}
                  </h2>
                </div>

                {/* Machine Type Categories First */}
                {organized.machineTypes.length > 0 && (
                  <div className="space-y-6">
                    {organized.machineTypes.map(
                      ([category, categoryManuals]) => {
                        const machineTypeInfo = getMachineTypeInfo(category)
                        const icon = getCategoryIcon(category)
                        return (
                          <div key={category} className="space-y-4">
                            <div className="flex items-center gap-3 flex-wrap">
                              {icon && (
                                <span className="text-muted-foreground">
                                  {icon}
                                </span>
                              )}
                              <h3 className="text-lg font-semibold">
                                {category}
                              </h3>
                              <Badge
                                variant="outline"
                                className={`rounded-full px-2.5 py-0.5 text-xs font-medium ${getCategoryBadgeClass(
                                  category
                                )}`}
                              >
                                {categoryManuals.length}{" "}
                                {categoryManuals.length === 1
                                  ? "manual"
                                  : "manuals"}
                              </Badge>
                              {machineTypeInfo && (
                                <span className="text-sm text-muted-foreground hidden sm:inline">
                                  {machineTypeInfo.description}
                                </span>
                              )}
                            </div>
                            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
                              {categoryManuals.map((manual) => (
                                <ManualCard
                                  key={manual.path}
                                  manual={manual}
                                  onView={setViewingManual}
                                  manualHasParts={manualHasParts}
                                  getCategoryBadgeClass={getCategoryBadgeClass}
                                  formatFileSize={formatFileSize}
                                />
                              ))}
                            </div>
                          </div>
                        )
                      }
                    )}
                  </div>
                )}

                {/* Other Categories (Model Numbers, Document Types, etc.) */}
                {organized.others.length > 0 && (
                  <div className="space-y-6">
                    {organized.machineTypes.length > 0 && (
                      <div className="border-t border-border/60 pt-6">
                        <h3 className="text-lg font-semibold text-muted-foreground mb-4">
                          Models & Other Documents
                        </h3>
                      </div>
                    )}
                    {organized.others.map(([category, categoryManuals]) => (
                      <div key={category} className="space-y-4">
                        <div className="flex items-center gap-2">
                          <h4 className="text-base font-semibold text-muted-foreground">
                            {category}
                          </h4>
                          <span className="text-xs text-muted-foreground">
                            ({categoryManuals.length}{" "}
                            {categoryManuals.length === 1
                              ? "manual"
                              : "manuals"}
                            )
                          </span>
                        </div>
                        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
                          {categoryManuals.map((manual) => (
                            <ManualCard
                              key={manual.path}
                              manual={manual}
                              onView={setViewingManual}
                              manualHasParts={manualHasParts}
                              getCategoryBadgeClass={getCategoryBadgeClass}
                              formatFileSize={formatFileSize}
                            />
                          ))}
                        </div>
                      </div>
                    ))}
                  </div>
                )}

                {/* Product Suggestions Section */}
                {filteredManuals.length > 0 && (
                  <div className="space-y-6 mt-8">
                    <div className="border-t border-border/60 pt-6">
                      <h3 className="text-lg font-semibold text-muted-foreground mb-4">
                        Related Products
                      </h3>
                    </div>
                    <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
                      {filteredManuals.slice(0, 3).map((manual) => (
                        <ProductSuggestions key={manual.path} manual={manual} />
                      ))}
                    </div>
                  </div>
                )}
              </PublicSurface>
            )
          })}
        </div>
      ) : (
        /* List View */
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
          {filteredManuals.map((manual) => (
            <ManualCard
              key={manual.path}
              manual={manual}
              onView={setViewingManual}
              manualHasParts={manualHasParts}
              getCategoryBadgeClass={getCategoryBadgeClass}
              formatFileSize={formatFileSize}
              showManufacturer={true}
            />
          ))}
        </div>
      )}

      {/* PDF Viewer Modal */}
      {viewingManual && (
        <ManualViewer
          manualUrl={viewingManual.url}
          filename={viewingManual.filename}
          isOpen={!!viewingManual}
          onClose={() => setViewingManual(null)}
        />
      )}
    </div>
  )
}
