"use client";

import React, { useState, useMemo, useEffect } from "react";
import Link from "next/link";
import dynamic from "next/dynamic";
import {
  ShieldCheck,
  MapPin,
  Phone,
  Mail,
  ArrowRight,
  CheckCircle2,
  Calculator,
  Sparkles,
  Layers,
  Sprout,
  Compass,
  Award,
  Send,
  Download,
  ExternalLink,
  Lock,
} from "lucide-react";

const GeoTraceMap = dynamic(() => import("@/components/GeoTraceMap"), {
  ssr: false,
  loading: () => (
    <div className="h-[420px] w-full rounded-xl bg-slate-900 animate-pulse flex items-center justify-center text-honey-400 font-semibold">
      Loading Interactive Machakos GIS Map...
    </div>
  ),
});

export interface CatalogItemType {
  id: string;
  sku: string;
  category: string;
  name: string;
  unit: string;
  minPriceKes: number;
  maxPriceKes: number;
  originalPdfPrice?: string | null;
  notes: string;
}

interface PublicWebsiteClientProps {
  catalog: CatalogItemType[];
}

const DELIVERED_SITES_WAYPOINTS = [
  {
    latitude: -1.2844,
    longitude: 37.2411,
    caption: "Kamuthanga — 20-Hive Tree-Hung Canopy Apiary (Bee-Landing Level)",
    tagCategory: "Completed Apiary",
    imageUrl: "/images/kamuthanga-apiary.png",
    gpsSource: "GIS Surveyed",
    sequenceOrder: 1,
    includeInTrace: true,
  },
  {
    latitude: -1.2658,
    longitude: 37.3189,
    caption: "Tala Town HQ — Queen Grafting & Breeding Centre (A. m. scutellata)",
    tagCategory: "Headquarters & Breeding",
    imageUrl: "/images/langstroth-hives.png",
    gpsSource: "HQ Coordinates",
    sequenceOrder: 2,
    includeInTrace: true,
  },
  {
    latitude: -1.2245,
    longitude: 37.3115,
    caption: "Sengani — 50-Hive Commercial Pollination & Grafted Queen Programme",
    tagCategory: "Commercial Pollination",
    imageUrl: "/images/hero-bee.png",
    gpsSource: "GIS Surveyed",
    sequenceOrder: 3,
    includeInTrace: true,
  },
  {
    latitude: -1.298,
    longitude: 37.331,
    caption: "Matetani — Community Apiary & NBKI Partnered Training Hub",
    tagCategory: "Training & Apiary",
    imageUrl: "/images/kamuthanga-apiary.png",
    gpsSource: "GIS Surveyed",
    sequenceOrder: 4,
    includeInTrace: true,
  },
  {
    latitude: -1.3342,
    longitude: 37.3451,
    caption: "Kakuyuni — 60 Colonised Hives & 618m Conservation Bio-Fence Corridor",
    tagCategory: "Bio-Fencing & Apiary",
    imageUrl: "/images/langstroth-hives.png",
    gpsSource: "GIS Surveyed",
    sequenceOrder: 5,
    includeInTrace: true,
  },
  {
    latitude: -1.1325,
    longitude: 37.2485,
    caption: "Kilimambogo — Ecological Restoration & Wildlife Deterrent Bio-Fence",
    tagCategory: "Conservation Bio-Fence",
    imageUrl: "/images/kamuthanga-apiary.png",
    gpsSource: "GIS Surveyed",
    sequenceOrder: 6,
    includeInTrace: false,
  },
];

export default function PublicWebsiteClient({
  catalog,
}: PublicWebsiteClientProps) {
  const [sessionUser, setSessionUser] = useState<{
    name: string;
    role: "ADMIN" | "TECHNICIAN";
  } | null>(null);

  useEffect(() => {
    fetch("/api/auth/me")
      .then((r) => r.json())
      .then((d) => {
        if (d.user) setSessionUser(d.user);
      })
      .catch(() => {});
  }, []);

  // Interactive Quote Calculator state
  const [hiveCount, setHiveCount] = useState<number>(50);
  const [bioFenceMetres, setBioFenceMetres] = useState<number>(0);
  const [queenCount, setQueenCount] = useState<number>(10);
  const [includeInstallation, setIncludeInstallation] = useState<boolean>(true);
  const [includeMaintenance, setIncludeMaintenance] = useState<boolean>(true);

  // Quote submission form
  const [clientName, setClientName] = useState("");
  const [organization, setOrganization] = useState("");
  const [email, setEmail] = useState("");
  const [phone, setPhone] = useState("");
  const [location, setLocation] = useState("Machakos County");
  const [notes, setNotes] = useState("");
  const [submittingQuote, setSubmittingQuote] = useState(false);
  const [submittedQuoteCode, setSubmittedQuoteCode] = useState<string | null>(null);

  const groupedCatalog = useMemo(() => {
    const map = new Map<string, CatalogItemType[]>();
    for (const item of catalog) {
      const list = map.get(item.category) || [];
      list.push(item);
      map.set(item.category, list);
    }
    return Array.from(map.entries());
  }, [catalog]);

  // Calculate volume discount & estimated quote range using exact document KES figures
  const quoteCalculation = useMemo(() => {
    const discountPercent = hiveCount >= 200 ? 15 : hiveCount >= 50 ? 5 : 0;
    const discountMultiplier = (100 - discountPercent) / 100;

    let minTotal = 0;
    let maxTotal = 0;
    const selectedItems: Array<{ sku: string; name: string; qty: number; unit: string }> = [];

    if (hiveCount > 0) {
      // HB-01: 6,458 - 32,458 per hive (discounted by volume tier)
      minTotal += Math.round(hiveCount * 6458 * discountMultiplier);
      maxTotal += Math.round(hiveCount * 32458 * discountMultiplier);
      selectedItems.push({
        sku: "HB-01",
        name: `Per hive — standard Langstroth/other (${discountPercent > 0 ? `${discountPercent}% Volume Discount` : "Standard Rate"})`,
        qty: hiveCount,
        unit: "hives",
      });
    }

    if (includeInstallation && hiveCount > 0) {
      // AI-01 (645 - 3,245) + HB-03 (2,582 - 12,917)
      minTotal += 645 + 2582;
      maxTotal += 3245 + 12917;
      selectedItems.push({
        sku: "AI-01 + HB-03",
        name: "Site assessment, delivery and installation",
        qty: 1,
        unit: "site",
      });
    }

    if (includeMaintenance && hiveCount > 0) {
      // AM-01: 649 - 2,582 per hive/month
      minTotal += hiveCount * 649;
      maxTotal += hiveCount * 2582;
      selectedItems.push({
        sku: "AM-01",
        name: "Monthly maintenance (per hive)",
        qty: hiveCount,
        unit: "hive/month",
      });
    }

    if (queenCount > 0) {
      // QG-01: 645 - 2,582 per queen
      minTotal += queenCount * 645;
      maxTotal += queenCount * 2582;
      selectedItems.push({
        sku: "QG-01",
        name: "Grafted queen bee (A. m. scutellata)",
        qty: queenCount,
        unit: "queens",
      });
    }

    if (bioFenceMetres > 0) {
      // BF-01: 260 - 2,582 per metre
      minTotal += bioFenceMetres * 260;
      maxTotal += bioFenceMetres * 2582;
      selectedItems.push({
        sku: "BF-01",
        name: "Bio fencing, materials + installation",
        qty: bioFenceMetres,
        unit: "metres",
      });
    }

    return {
      discountPercent,
      minTotal,
      maxTotal,
      selectedItems,
    };
  }, [hiveCount, bioFenceMetres, queenCount, includeInstallation, includeMaintenance]);

  const formatPrice = (item: CatalogItemType) => {
    if (item.sku === "HB-02") {
      return "5% off at 50+ hives; 15% off at 200+";
    }
    if (item.originalPdfPrice) {
      return item.originalPdfPrice;
    }
    return `${item.minPriceKes.toLocaleString()} – ${item.maxPriceKes.toLocaleString()} ${item.unit}`;
  };

  const handleQuoteSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!clientName || !email || !phone) return;
    setSubmittingQuote(true);
    try {
      const res = await fetch("/api/quotes", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          clientName,
          organization,
          email,
          phone,
          location,
          hiveCount,
          discountPercent: quoteCalculation.discountPercent,
          estimatedMinKes: quoteCalculation.minTotal,
          estimatedMaxKes: quoteCalculation.maxTotal,
          items: quoteCalculation.selectedItems,
          notes,
        }),
      });
      const data = await res.json();
      if (data.quote?.quoteNumber) {
        setSubmittedQuoteCode(data.quote.quoteNumber);
      }
    } catch (err) {
      console.error("Quote submit failed:", err);
    } finally {
      setSubmittingQuote(false);
    }
  };

  return (
    <div className="min-h-screen flex flex-col bg-slate-50">
      {/* Top Corporate Bar */}
      <div className="bg-hive-950 text-slate-300 text-xs py-2 px-4 border-b border-slate-800">
        <div className="max-w-7xl mx-auto flex flex-wrap items-center justify-between gap-2">
          <div className="flex items-center gap-4 flex-wrap">
            <span className="flex items-center gap-1.5 text-honey-400 font-semibold">
              <MapPin className="w-3.5 h-3.5" /> Tala Town, Machakos County, Kenya
            </span>
            <span className="hidden sm:inline text-slate-600">|</span>
            <span className="hidden sm:inline">
              Reg No: <strong className="text-white">BN-79S6OBMR</strong>
            </span>
            <span className="hidden md:inline text-slate-600">|</span>
            <span className="hidden md:inline">
              M-Pesa Till No: <strong className="text-honey-400">1801420 (DAVALLY APICULTURE)</strong>
            </span>
          </div>
          <div className="flex items-center gap-4">
            <a href="tel:0708701569" className="hover:text-honey-400 flex items-center gap-1">
              <Phone className="w-3.5 h-3.5 text-honey-400" /> Mr. David: 0708 701 569
            </a>
            <a href="tel:0722260670" className="hover:text-honey-400 hidden sm:flex items-center gap-1">
              <Phone className="w-3.5 h-3.5 text-honey-400" /> Mr. Maveke: 0722 260 670
            </a>
          </div>
        </div>
      </div>

      {/* Main Sticky Header */}
      <header className="sticky top-0 z-40 bg-white/95 backdrop-blur-md border-b border-slate-200 shadow-sm">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 py-3 flex items-center justify-between gap-4">
          <Link href="/" className="flex items-center gap-3 group">
            <img
              src="/images/logo-icon.png"
              alt="Davally Apiculture Logo"
              className="w-11 h-11 object-contain"
            />
            <div>
              <div className="font-extrabold text-lg tracking-tight text-slate-900 leading-none">
                DAVALLY <span className="text-amber-600">APICULTURE</span>
              </div>
              <div className="text-[11px] font-medium text-slate-500 mt-0.5">
                Sustaining ecosystems, one queen at a time
              </div>
            </div>
          </Link>

          <nav className="hidden lg:flex items-center gap-6 text-sm font-semibold text-slate-700">
            <a href="#about" className="hover:text-amber-600 transition">
              About & Competencies
            </a>
            <a href="#hives" className="hover:text-amber-600 transition">
              Ready Hives
            </a>
            <a href="#catalogue" className="hover:text-amber-600 transition">
              Price Catalogue
            </a>
            <a href="#calculator" className="hover:text-amber-600 transition">
              Quote Calculator
            </a>
            <a href="#projects-map" className="hover:text-amber-600 transition">
              Where We Work (GIS)
            </a>
          </nav>

          <div className="flex items-center gap-2.5">
            {sessionUser ? (
              <>
                <Link
                  href="/erp/field-new"
                  className="hidden sm:inline-flex items-center gap-1.5 px-3.5 py-2 rounded-lg text-xs font-bold bg-amber-50 text-amber-900 border border-amber-300 hover:bg-amber-100 transition"
                >
                  <Compass className="w-3.5 h-3.5 text-amber-600" />
                  + Log Field Activity
                </Link>
                <Link
                  href="/erp"
                  className="inline-flex items-center gap-2 px-4 py-2.5 rounded-lg text-xs sm:text-sm font-bold bg-hive-900 text-honey-400 hover:bg-hive-800 border border-honey-500/40 shadow-sm transition"
                >
                  <span>
                    ERP ({sessionUser.name.split(" ")[0]} • {sessionUser.role})
                  </span>
                  <ArrowRight className="w-4 h-4" />
                </Link>
              </>
            ) : (
              <>
                <Link
                  href="/login?callbackUrl=/erp/field-new"
                  className="hidden sm:inline-flex items-center gap-1.5 px-3.5 py-2 rounded-lg text-xs font-bold bg-amber-50 text-amber-900 border border-amber-300 hover:bg-amber-100 transition"
                >
                  <Lock className="w-3.5 h-3.5 text-amber-600" />
                  Field Activity Login
                </Link>
                <Link
                  href="/login?callbackUrl=/erp"
                  className="inline-flex items-center gap-2 px-4 py-2.5 rounded-lg text-xs sm:text-sm font-bold bg-hive-900 text-honey-400 hover:bg-hive-800 border border-honey-500/40 shadow-sm transition"
                >
                  <Lock className="w-3.5 h-3.5" />
                  <span>Staff & ERP Login</span>
                  <ArrowRight className="w-4 h-4" />
                </Link>
              </>
            )}
          </div>
        </div>
      </header>

      {/* Hero Section */}
      <section className="relative bg-hive-950 text-white overflow-hidden border-b-4 border-honey-500">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 py-14 lg:py-20 grid lg:grid-cols-12 gap-10 items-center">
          <div className="lg:col-span-7 space-y-6">
            <div className="inline-flex items-center gap-2 px-3.5 py-1.5 rounded-full bg-honey-500/15 border border-honey-500/40 text-honey-300 text-xs font-bold uppercase tracking-wider">
              <Sparkles className="w-3.5 h-3.5" />
              Apis mellifera scutellata Specialists • Tala, Machakos
            </div>

            <h1 className="text-3xl sm:text-5xl font-black tracking-tight leading-tight">
              Sustaining Ecosystems,{" "}
              <span className="text-honey-400 underline decoration-honey-500/40">
                One Queen at a Time.
              </span>
            </h1>

            <p className="text-slate-300 text-base sm:text-lg leading-relaxed max-w-2xl">
              Davally Apiculture Limited is a Tala-based apiculture partner specialising in selective{" "}
              <strong className="text-white">queen bee grafting</strong> of the African honey bee (
              <em>Apis mellifera scutellata</em>), turnkey{" "}
              <strong className="text-white">apiary installation</strong>, ready-to-deploy{" "}
              <strong className="text-white">colonised beehives</strong>, and conservation{" "}
              <strong className="text-white">bio fencing</strong>—backed by GPS-verified field reporting.
            </p>

            {/* 4 Key Metadata Pills from Page 2 of PDF */}
            <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 pt-2">
              <div className="bg-white/5 border border-white/10 rounded-xl p-3">
                <div className="text-[10px] font-bold uppercase tracking-wider text-honey-400">
                  Headquarters
                </div>
                <div className="text-sm font-bold text-white mt-0.5">Tala, Machakos</div>
              </div>
              <div className="bg-white/5 border border-white/10 rounded-xl p-3">
                <div className="text-[10px] font-bold uppercase tracking-wider text-honey-400">
                  Service Area
                </div>
                <div className="text-sm font-bold text-white mt-0.5">National & Regional</div>
              </div>
              <div className="bg-white/5 border border-white/10 rounded-xl p-3">
                <div className="text-[10px] font-bold uppercase tracking-wider text-honey-400">
                  Specialty
                </div>
                <div className="text-sm font-bold text-white mt-0.5">Queen Bee Grafting</div>
              </div>
              <div className="bg-white/5 border border-white/10 rounded-xl p-3">
                <div className="text-[10px] font-bold uppercase tracking-wider text-honey-400">
                  Bee Species
                </div>
                <div className="text-sm font-bold italic text-white mt-0.5">A. m. scutellata</div>
              </div>
            </div>

            <div className="flex flex-wrap items-center gap-3 pt-2">
              <a
                href="#calculator"
                className="inline-flex items-center gap-2 px-6 py-3.5 rounded-xl bg-honey-500 text-hive-950 font-extrabold text-sm hover:bg-honey-400 transition shadow-lg shadow-honey-500/20"
              >
                <Calculator className="w-4 h-4" />
                Estimate Apiary / Bio-Fence Quote
              </a>
              <Link
                href="/reports/share/kamuthanga-2026-001"
                className="inline-flex items-center gap-2 px-5 py-3.5 rounded-xl bg-white/10 text-white font-bold text-sm hover:bg-white/20 border border-white/15 transition"
              >
                <Compass className="w-4 h-4 text-honey-400" />
                View Live Sample GIS Client Report
              </Link>
              <a
                href="/Davally_Apiculture_Company_Profile.pdf"
                target="_blank"
                rel="noreferrer"
                className="inline-flex items-center gap-1.5 px-4 py-3.5 rounded-xl text-slate-300 hover:text-white text-xs font-semibold"
              >
                <Download className="w-4 h-4 text-honey-400" />
                Download PDF Profile
              </a>
            </div>
          </div>

          {/* Right Hero Image Collage from PDF */}
          <div className="lg:col-span-5 space-y-4">
            <div className="bg-white rounded-2xl p-4 shadow-xl border-2 border-honey-500/60">
              <div className="flex items-center justify-center bg-white rounded-xl py-2 mb-3 border border-slate-100">
                <img
                  src="/images/logo-full.png"
                  alt="Davally Apiculture Full Logo"
                  className="h-28 object-contain"
                />
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div className="relative rounded-xl overflow-hidden group">
                  <img
                    src="/images/hero-bee.png"
                    alt="Apis mellifera scutellata"
                    className="w-full h-44 object-cover group-hover:scale-105 transition duration-500"
                  />
                  <div className="absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/80 via-black/40 to-transparent p-2.5">
                    <div className="text-[11px] font-bold text-honey-400">Selective Breeding</div>
                    <div className="text-xs text-white font-semibold">Grafted Queen Bees</div>
                  </div>
                </div>
                <div className="relative rounded-xl overflow-hidden group">
                  <img
                    src="/images/kamuthanga-apiary.png"
                    alt="Kamuthanga 20-Hive Canopy Apiary"
                    className="w-full h-44 object-cover group-hover:scale-105 transition duration-500"
                  />
                  <div className="absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/80 via-black/40 to-transparent p-2.5">
                    <div className="text-[11px] font-bold text-honey-400">Kamuthanga Site</div>
                    <div className="text-xs text-white font-semibold">Canopy Apiary Setup</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Core Competencies & Who We Serve */}
      <section id="about" className="py-16 max-w-7xl mx-auto px-4 sm:px-6">
        <div className="text-center max-w-3xl mx-auto mb-12">
          <div className="text-xs font-extrabold uppercase tracking-widest text-amber-600 mb-2">
            One Accountable Partner From Design to Execution
          </div>
          <h2 className="text-3xl font-black text-slate-900">
            Core Competencies & Turnkey Apiary Solutions
          </h2>
          <p className="text-slate-600 mt-3 text-sm sm:text-base">
            We help commercial farms, wildlife conservancies, research institutions, and NGOs build
            thriving bee populations that pollinate crops, restore habitat, and create sustainable
            livelihoods.
          </p>
        </div>

        <div className="grid md:grid-cols-2 lg:grid-cols-4 gap-6">
          {[
            {
              num: "01",
              title: "Queen Bee Grafting",
              icon: Sparkles,
              points: [
                "Selective breeding & larval grafting for robust, productive queens",
                "Genetic management suited to local ecology with disease-resistant traits",
                "Post-graft rearing support & nationwide queen shipping",
              ],
            },
            {
              num: "02",
              title: "Apiary Installation & Care",
              icon: Layers,
              points: [
                "Design and set-up tailored to land, climate, and seasonal forage",
                "Commissioning: hive placement, protective infrastructure, water & access",
                "Ongoing GPS-logged monitoring and seasonal hive management",
              ],
            },
            {
              num: "03",
              title: "Colonised Beehives",
              icon: ShieldCheck,
              points: [
                "Ready-to-use colonised hives for large-scale crop pollination",
                "Standard Langstroth and custom hive specifications",
                "Quality assurance, 90-day workmanship warranty & after-sales care",
              ],
            },
            {
              num: "04",
              title: "Conservation Bio Fencing",
              icon: Sprout,
              points: [
                "Fencing that supports biodiversity, pollinator corridors & conservancy goals",
                "Living barriers, reed & interlinked hive wildlife deterrent perimeters",
                "GIS-traced perimeter installation and annual maintenance packages",
              ],
            },
          ].map((comp) => {
            const Icon = comp.icon;
            return (
              <div
                key={comp.num}
                className="bg-white rounded-2xl p-6 border border-slate-200 shadow-sm hover:shadow-md hover:border-amber-400 transition flex flex-col justify-between"
              >
                <div>
                  <div className="flex items-center justify-between mb-4">
                    <span className="text-2xl font-black text-amber-500">{comp.num}</span>
                    <div className="w-10 h-10 rounded-xl bg-amber-50 flex items-center justify-center text-amber-600">
                      <Icon className="w-5 h-5" />
                    </div>
                  </div>
                  <h3 className="text-lg font-extrabold text-slate-900 mb-3">{comp.title}</h3>
                  <ul className="space-y-2.5 text-sm text-slate-600">
                    {comp.points.map((pt, i) => (
                      <li key={i} className="flex items-start gap-2">
                        <CheckCircle2 className="w-4 h-4 text-amber-500 shrink-0 mt-0.5" />
                        <span>{pt}</span>
                      </li>
                    ))}
                  </ul>
                </div>
              </div>
            );
          })}
        </div>

        {/* Who We Serve + NBKI Partnership Banner */}
        <div className="mt-10 bg-hive-900 text-white rounded-2xl p-6 sm:p-8 grid lg:grid-cols-12 gap-6 items-center border border-slate-800">
          <div className="lg:col-span-8 space-y-3">
            <div className="inline-flex items-center gap-2 text-honey-400 text-xs font-bold uppercase tracking-wider">
              <Award className="w-4 h-4" /> Strategic Partnership & Institutional Reach
            </div>
            <h3 className="text-xl sm:text-2xl font-bold">
              Partnered with the National Beekeeping Institute (NBKI)
            </h3>
            <p className="text-slate-300 text-sm leading-relaxed">
              We serve large-scale farmers and agribusinesses needing reliable pollination, wildlife
              conservancies protecting pollinator health, agricultural research institutions,
              beekeeping cooperatives, and government/NGO programmes across Kenya.
            </p>
          </div>
          <div className="lg:col-span-4 bg-white/5 rounded-xl p-4 border border-white/10 space-y-2 text-xs text-slate-200">
            <div className="font-bold text-honey-400 uppercase">Why Choose Davally</div>
            <div>• Enhanced crop pollination & biodiversity gains</div>
            <div>• Locally adapted Apis mellifera scutellata stock</div>
            <div>• Every field visit verified with GPS photos & GIS area trace</div>
            <div>• Flexible institutional terms (30 days net / 50-50 milestone)</div>
          </div>
        </div>
      </section>

      {/* Ready Hives Showcase */}
      <section id="hives" className="py-14 bg-amber-50/70 border-y border-amber-200/70">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 grid lg:grid-cols-12 gap-8 items-center">
          <div className="lg:col-span-5">
            <div className="rounded-2xl overflow-hidden shadow-lg border-4 border-white">
              <img
                src="/images/langstroth-hives.png"
                alt="Ready to Order Langstroth Beehives"
                className="w-full h-80 object-cover"
              />
            </div>
          </div>
          <div className="lg:col-span-7 space-y-4">
            <div className="inline-block px-3 py-1 rounded-full bg-amber-200/80 text-amber-950 text-xs font-extrabold uppercase">
              Ready Hives • Immediate Deployment
            </div>
            <h2 className="text-2xl sm:text-3xl font-black text-slate-900">
              Purpose-Built Colonised & Uncolonised Langstroth Hives
            </h2>
            <p className="text-slate-700 text-sm sm:text-base leading-relaxed">
              Finished to exacting standards and ready for placement. Supplied empty for you to
              colonise, or pre-colonised by our apiarists with vigorous, grafted{" "}
              <em>Apis mellifera scutellata</em> queens for immediate pollination service.
            </p>
            <div className="grid sm:grid-cols-3 gap-4 pt-2">
              <div className="bg-white p-4 rounded-xl border border-amber-200 shadow-sm">
                <div className="text-xs font-bold text-slate-500 uppercase">Per Hive (HB-01)</div>
                <div className="text-lg font-black text-slate-900 mt-1">KES 6,458 – 32,458</div>
                <div className="text-xs text-slate-500 mt-0.5">Based on hive type, size & age</div>
              </div>
              <div className="bg-white p-4 rounded-xl border-2 border-amber-400 shadow-sm">
                <div className="text-xs font-bold text-amber-700 uppercase">50+ Hives Order</div>
                <div className="text-2xl font-black text-amber-600 mt-1">5% OFF</div>
                <div className="text-xs text-slate-600 mt-0.5">Automatic volume discount</div>
              </div>
              <div className="bg-hive-900 text-white p-4 rounded-xl border border-hive-800 shadow-sm">
                <div className="text-xs font-bold text-honey-400 uppercase">200+ Hives Order</div>
                <div className="text-2xl font-black text-honey-400 mt-1">15% OFF</div>
                <div className="text-xs text-slate-300 mt-0.5">Commercial & conservancy scale</div>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Price Catalogue Section */}
      <section id="catalogue" className="py-16 max-w-7xl mx-auto px-4 sm:px-6">
        <div className="flex flex-col md:flex-row md:items-end justify-between gap-4 mb-8">
          <div>
            <div className="text-xs font-extrabold uppercase tracking-widest text-amber-600">
              Transparent Specifications & Service-Level Agreements
            </div>
            <h2 className="text-3xl font-black text-slate-900 mt-1">
              Price Catalogue (Kenyan Shillings — KES)
            </h2>
            <p className="text-sm text-slate-600 mt-1">
              Local price catalogue in Kenyan Shillings (KES), effective 29 April 2026. Exchange
              rate used: 1 USD = 129.10 KES.
            </p>
          </div>

          <div className="inline-flex items-center gap-2 bg-amber-50 border border-amber-200 px-4 py-2 rounded-xl text-xs font-extrabold text-amber-900 self-start">
            <span>Currency: Kenyan Shillings (KES)</span>
          </div>
        </div>

        <div className="space-y-8">
          {groupedCatalog.map(([categoryName, items]) => (
            <div
              key={categoryName}
              className="bg-white rounded-2xl border border-slate-200 shadow-sm overflow-hidden"
            >
              <div className="bg-hive-900 text-white px-5 py-3.5 flex items-center justify-between border-b-2 border-honey-500">
                <h3 className="font-extrabold text-sm sm:text-base text-honey-400">
                  {categoryName}
                </h3>
                <span className="text-xs text-slate-400">{items.length} SKUs</span>
              </div>
              <div className="overflow-x-auto">
                <table className="w-full text-left border-collapse">
                  <thead>
                    <tr className="bg-slate-50 border-b border-slate-200 text-[11px] font-bold uppercase text-slate-500">
                      <th className="py-3 px-4 w-24">SKU</th>
                      <th className="py-3 px-4">Description</th>
                      <th className="py-3 px-4 w-64">Price (KES)</th>
                      <th className="py-3 px-4">Notes</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-100 text-sm">
                    {items.map((item) => (
                      <tr key={item.sku} className="hover:bg-amber-50/40 transition">
                        <td className="py-3.5 px-4 font-mono font-bold text-amber-700 text-xs">
                          {item.sku}
                        </td>
                        <td className="py-3.5 px-4 font-bold text-slate-900">{item.name}</td>
                        <td className="py-3.5 px-4 font-extrabold text-slate-900">
                          {formatPrice(item)}
                        </td>
                        <td className="py-3.5 px-4 text-slate-600 text-xs leading-relaxed">
                          {item.notes}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          ))}
        </div>
      </section>

      {/* Interactive Quote Calculator & Lead Capture */}
      <section id="calculator" className="py-16 bg-hive-950 text-white border-y-4 border-honey-500">
        <div className="max-w-7xl mx-auto px-4 sm:px-6">
          <div className="grid lg:grid-cols-12 gap-10 items-start">
            {/* Left: Interactive Sliders */}
            <div className="lg:col-span-7 bg-hive-900 rounded-2xl p-6 sm:p-8 border border-slate-800 space-y-6">
              <div>
                <div className="text-xs font-bold uppercase tracking-wider text-honey-400">
                  Instant Project Estimator
                </div>
                <h2 className="text-2xl sm:text-3xl font-black mt-1">
                  Configure Your Apiary or Bio-Fencing Project
                </h2>
                <p className="text-slate-400 text-sm mt-1">
                  Adjust quantities below to calculate volume discounts and submit directly to our
                  ERP engineering team.
                </p>
              </div>

              {/* Hive Count Slider */}
              <div className="bg-white/5 p-5 rounded-xl border border-white/10 space-y-3">
                <div className="flex items-center justify-between">
                  <label className="text-sm font-bold text-white">
                    Number of Beehives (SKU HB-01)
                  </label>
                  <div className="flex items-center gap-2">
                    <input
                      type="number"
                      min={0}
                      max={1000}
                      value={hiveCount}
                      onChange={(e) => setHiveCount(Math.max(0, Number(e.target.value)))}
                      className="w-24 bg-hive-950 border border-slate-700 rounded-lg px-3 py-1.5 text-right font-extrabold text-honey-400"
                    />
                    <span className="text-xs text-slate-400">hives</span>
                  </div>
                </div>
                <input
                  type="range"
                  min={0}
                  max={300}
                  step={5}
                  value={Math.min(300, hiveCount)}
                  onChange={(e) => setHiveCount(Number(e.target.value))}
                  className="w-full accent-honey-500 cursor-pointer"
                />
                <div className="flex items-center justify-between text-xs text-slate-400">
                  <span>0 Hives</span>
                  <span className={hiveCount >= 50 && hiveCount < 200 ? "text-honey-400 font-bold" : ""}>
                    50+ Hives (5% Off)
                  </span>
                  <span className={hiveCount >= 200 ? "text-honey-400 font-bold" : ""}>
                    200+ Hives (15% Off)
                  </span>
                </div>
              </div>

              {/* Grafted Queens Slider */}
              <div className="bg-white/5 p-5 rounded-xl border border-white/10 space-y-3">
                <div className="flex items-center justify-between">
                  <label className="text-sm font-bold text-white">
                    Grafted Queen Bees — A. m. scutellata (SKU QG-01)
                  </label>
                  <div className="flex items-center gap-2">
                    <input
                      type="number"
                      min={0}
                      max={500}
                      value={queenCount}
                      onChange={(e) => setQueenCount(Math.max(0, Number(e.target.value)))}
                      className="w-24 bg-hive-950 border border-slate-700 rounded-lg px-3 py-1.5 text-right font-extrabold text-honey-400"
                    />
                    <span className="text-xs text-slate-400">queens</span>
                  </div>
                </div>
                <input
                  type="range"
                  min={0}
                  max={100}
                  step={5}
                  value={Math.min(100, queenCount)}
                  onChange={(e) => setQueenCount(Number(e.target.value))}
                  className="w-full accent-honey-500 cursor-pointer"
                />
              </div>

              {/* Bio-Fencing Metres Slider */}
              <div className="bg-white/5 p-5 rounded-xl border border-white/10 space-y-3">
                <div className="flex items-center justify-between">
                  <label className="text-sm font-bold text-white">
                    Conservation Bio Fencing Perimeter (SKU BF-01)
                  </label>
                  <div className="flex items-center gap-2">
                    <input
                      type="number"
                      min={0}
                      max={10000}
                      value={bioFenceMetres}
                      onChange={(e) => setBioFenceMetres(Math.max(0, Number(e.target.value)))}
                      className="w-24 bg-hive-950 border border-slate-700 rounded-lg px-3 py-1.5 text-right font-extrabold text-honey-400"
                    />
                    <span className="text-xs text-slate-400">metres</span>
                  </div>
                </div>
                <input
                  type="range"
                  min={0}
                  max={2000}
                  step={50}
                  value={Math.min(2000, bioFenceMetres)}
                  onChange={(e) => setBioFenceMetres(Number(e.target.value))}
                  className="w-full accent-honey-500 cursor-pointer"
                />
              </div>

              {/* Checkboxes */}
              <div className="grid sm:grid-cols-2 gap-3">
                <label className="flex items-center gap-3 p-3.5 rounded-xl bg-white/5 border border-white/10 cursor-pointer hover:border-honey-500/50">
                  <input
                    type="checkbox"
                    checked={includeInstallation}
                    onChange={(e) => setIncludeInstallation(e.target.checked)}
                    className="w-4 h-4 accent-honey-500"
                  />
                  <div>
                    <div className="text-xs font-bold text-white">
                      Include Site Assessment & Delivery
                    </div>
                    <div className="text-[11px] text-slate-400">SKUs AI-01 & HB-03</div>
                  </div>
                </label>

                <label className="flex items-center gap-3 p-3.5 rounded-xl bg-white/5 border border-white/10 cursor-pointer hover:border-honey-500/50">
                  <input
                    type="checkbox"
                    checked={includeMaintenance}
                    onChange={(e) => setIncludeMaintenance(e.target.checked)}
                    className="w-4 h-4 accent-honey-500"
                  />
                  <div>
                    <div className="text-xs font-bold text-white">
                      Include Monthly Maintenance Plan
                    </div>
                    <div className="text-[11px] text-slate-400">SKU AM-01 + GIS Email Reports</div>
                  </div>
                </label>
              </div>

              {/* Estimate Result Box */}
              <div className="bg-gradient-to-r from-honey-500/20 to-amber-600/10 border-2 border-honey-500 rounded-xl p-5 flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                <div>
                  <div className="text-xs font-bold uppercase text-honey-300">
                    Estimated Turnkey Investment Range (KES)
                  </div>
                  <div className="text-2xl sm:text-3xl font-black text-white mt-1">
                    KES {quoteCalculation.minTotal.toLocaleString()} –{" "}
                    {quoteCalculation.maxTotal.toLocaleString()}
                  </div>
                  <div className="text-xs text-slate-300 mt-1">
                    Currency: Kenyan Shillings (KES) • All prices exclude VAT where applicable
                  </div>
                </div>
                {quoteCalculation.discountPercent > 0 && (
                  <div className="bg-honey-500 text-hive-950 px-3.5 py-2 rounded-lg font-black text-xs uppercase self-start sm:self-center">
                    {quoteCalculation.discountPercent}% Volume Discount Applied
                  </div>
                )}
              </div>
            </div>

            {/* Right: Submit Quote to ERP */}
            <div className="lg:col-span-5 bg-white text-slate-900 rounded-2xl p-6 sm:p-8 shadow-xl">
              <h3 className="text-xl font-black text-slate-900">
                Request Official Quotation & Site Consult
              </h3>
              <p className="text-xs text-slate-500 mt-1 mb-5">
                Submits directly into the Davally Apiculture ERP for Mr. David & Mr. Maveke.
              </p>

              {submittedQuoteCode ? (
                <div className="bg-emerald-50 border border-emerald-200 rounded-xl p-6 text-center space-y-3">
                  <CheckCircle2 className="w-10 h-10 text-emerald-600 mx-auto" />
                  <h4 className="font-extrabold text-lg text-emerald-950">
                    Quote Logged in ERP: {submittedQuoteCode}
                  </h4>
                  <p className="text-xs text-emerald-800 leading-relaxed">
                    Thank you! Your project configuration has been received in the Davally ERP
                    backend. Our technical team will contact you shortly.
                  </p>
                  <div className="pt-2 flex justify-center gap-3">
                    <button
                      type="button"
                      onClick={() => setSubmittedQuoteCode(null)}
                      className="text-xs font-bold text-emerald-700 underline"
                    >
                      Configure Another Estimate
                    </button>
                    <Link
                      href="/erp"
                      className="text-xs font-bold bg-emerald-700 text-white px-3.5 py-1.5 rounded-lg"
                    >
                      View in ERP Inbox &rarr;
                    </Link>
                  </div>
                </div>
              ) : (
                <form onSubmit={handleQuoteSubmit} className="space-y-3.5">
                  <div>
                    <label className="block text-xs font-bold text-slate-700 mb-1">
                      Your Full Name *
                    </label>
                    <input
                      type="text"
                      required
                      value={clientName}
                      onChange={(e) => setClientName(e.target.value)}
                      placeholder="e.g. Eng. Joseph Mutiso"
                      className="w-full rounded-lg border border-slate-300 px-3.5 py-2 text-sm focus:border-amber-500 focus:outline-none"
                    />
                  </div>
                  <div className="grid grid-cols-2 gap-3">
                    <div>
                      <label className="block text-xs font-bold text-slate-700 mb-1">
                        Farm / Organization
                      </label>
                      <input
                        type="text"
                        value={organization}
                        onChange={(e) => setOrganization(e.target.value)}
                        placeholder="e.g. Makuyu Orchards Ltd"
                        className="w-full rounded-lg border border-slate-300 px-3.5 py-2 text-sm focus:border-amber-500 focus:outline-none"
                      />
                    </div>
                    <div>
                      <label className="block text-xs font-bold text-slate-700 mb-1">
                        Site Location / County *
                      </label>
                      <input
                        type="text"
                        required
                        value={location}
                        onChange={(e) => setLocation(e.target.value)}
                        placeholder="e.g. Kangundo, Machakos"
                        className="w-full rounded-lg border border-slate-300 px-3.5 py-2 text-sm focus:border-amber-500 focus:outline-none"
                      />
                    </div>
                  </div>
                  <div className="grid grid-cols-2 gap-3">
                    <div>
                      <label className="block text-xs font-bold text-slate-700 mb-1">
                        Email Address *
                      </label>
                      <input
                        type="email"
                        required
                        value={email}
                        onChange={(e) => setEmail(e.target.value)}
                        placeholder="you@company.co.ke"
                        className="w-full rounded-lg border border-slate-300 px-3.5 py-2 text-sm focus:border-amber-500 focus:outline-none"
                      />
                    </div>
                    <div>
                      <label className="block text-xs font-bold text-slate-700 mb-1">
                        Phone / WhatsApp *
                      </label>
                      <input
                        type="tel"
                        required
                        value={phone}
                        onChange={(e) => setPhone(e.target.value)}
                        placeholder="07XX XXX XXX"
                        className="w-full rounded-lg border border-slate-300 px-3.5 py-2 text-sm focus:border-amber-500 focus:outline-none"
                      />
                    </div>
                  </div>
                  <div>
                    <label className="block text-xs font-bold text-slate-700 mb-1">
                      Project Notes / Crop Type / Preferred Dates
                    </label>
                    <textarea
                      rows={2}
                      value={notes}
                      onChange={(e) => setNotes(e.target.value)}
                      placeholder="Tell us about your orchard, conservancy, or queen breeding goals..."
                      className="w-full rounded-lg border border-slate-300 px-3.5 py-2 text-sm focus:border-amber-500 focus:outline-none"
                    />
                  </div>
                  <button
                    type="submit"
                    disabled={submittingQuote}
                    className="w-full py-3 rounded-xl bg-hive-900 text-honey-400 font-extrabold text-sm hover:bg-hive-800 transition flex items-center justify-center gap-2 shadow"
                  >
                    <Send className="w-4 h-4" />
                    {submittingQuote ? "Submitting to ERP..." : "Submit Quote Request to Davally ERP"}
                  </button>
                </form>
              )}
            </div>
          </div>
        </div>
      </section>

      {/* Interactive "Where We Work" GIS Map Section */}
      <section id="projects-map" className="py-16 max-w-7xl mx-auto px-4 sm:px-6">
        <div className="grid lg:grid-cols-12 gap-8 items-center">
          <div className="lg:col-span-5 space-y-4">
            <div className="text-xs font-extrabold uppercase tracking-widest text-amber-600">
              Geo-Located Apiary & Bio-Fencing Footprint
            </div>
            <h2 className="text-3xl font-black text-slate-900">
              Where We Work Across Machakos & Beyond
            </h2>
            <p className="text-slate-600 text-sm leading-relaxed">
              Operating out of our headquarters in <strong>Tala Town</strong>, we have delivered
              high-performing apiary installations, queen grafting programmes, and conservation
              bio-fences across <strong>Kamuthanga, Kakuyuni, Sengani, Matetani, Kangundo, and Kilimambogo</strong>.
            </p>
            <div className="space-y-2.5 pt-1">
              {DELIVERED_SITES_WAYPOINTS.map((site) => (
                <div
                  key={site.sequenceOrder}
                  className="flex items-start gap-3 p-3 rounded-xl bg-white border border-slate-200 shadow-sm"
                >
                  <span className="w-6 h-6 rounded-full bg-honey-500 text-hive-950 font-black text-xs flex items-center justify-center shrink-0 mt-0.5">
                    {site.sequenceOrder}
                  </span>
                  <div>
                    <div className="text-xs font-bold text-slate-900">{site.caption}</div>
                    <div className="text-[11px] font-mono text-slate-500">
                      GPS: {site.latitude.toFixed(4)}, {site.longitude.toFixed(4)} • {site.tagCategory}
                    </div>
                  </div>
                </div>
              ))}
            </div>
            <div className="pt-2">
              <Link
                href="/erp/field-new"
                className="inline-flex items-center gap-2 text-xs font-extrabold text-amber-700 hover:text-amber-800"
              >
                Open Field Technician GPS Collector & Area Tracer <ExternalLink className="w-3.5 h-3.5" />
              </Link>
            </div>
          </div>

          <div className="lg:col-span-7">
            <GeoTraceMap
              waypoints={DELIVERED_SITES_WAYPOINTS}
              traceMode="POLYGON"
              editable={false}
              height="480px"
            />
          </div>
        </div>
      </section>

      {/* Footer with Official Registration & Payment Details */}
      <footer className="bg-hive-950 text-slate-400 border-t border-slate-800 mt-auto">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 py-12 grid md:grid-cols-3 gap-8">
          <div className="space-y-3">
            <div className="flex items-center gap-3">
              <img
                src="/images/logo-icon.png"
                alt="Davally Icon"
                className="w-10 h-10 rounded-lg bg-white p-1 object-contain"
              />
              <div>
                <div className="text-white font-black text-base">DAVALLY APICULTURE</div>
                <div className="text-xs text-honey-400">Sustaining ecosystems, one queen at a time</div>
              </div>
            </div>
            <p className="text-xs text-slate-400 leading-relaxed">
              Registered under the Registration of Business Names Act (Cap. 499), Republic of Kenya.
              Specialists in <em>Apis mellifera scutellata</em> queen grafting, colonised beehives,
              and GIS-monitored bio-fencing.
            </p>
          </div>

          <div className="space-y-2 text-xs">
            <div className="text-white font-bold uppercase tracking-wider mb-2">
              Corporate & Payment Verification
            </div>
            <div>
              Business Registration No: <strong className="text-white">BN-79S6OBMR</strong>
            </div>
            <div>
              Registered Owner: <strong className="text-white">David Mwangangi Kyalo</strong>
            </div>
            <div>
              M-Pesa Buy Goods Till No:{" "}
              <strong className="text-honey-400 text-sm">1801420 (DAVALLY APICULTURE)</strong>
            </div>
            <div>
              Payment Terms: 30 days net (approved institutions) | 50% upfront, 50% on completion
            </div>
            <div>Warranty: 90-day workmanship warranty from installation</div>
          </div>

          <div className="space-y-2 text-xs">
            <div className="text-white font-bold uppercase tracking-wider mb-2">
              Let&apos;s Build Your Apiary
            </div>
            <div className="flex items-center gap-2">
              <Mail className="w-4 h-4 text-honey-400" />
              <a href="mailto:david.kyalo@muajiri.com" className="text-white hover:text-honey-400">
                david.kyalo@muajiri.com
              </a>
            </div>
            <div className="flex items-center gap-2">
              <Phone className="w-4 h-4 text-honey-400" />
              <span className="text-white">Mr. Maveke: 0722 260 670</span>
            </div>
            <div className="flex items-center gap-2">
              <Phone className="w-4 h-4 text-honey-400" />
              <span className="text-white">Mr. David: 0708 701 569</span>
            </div>
            <div className="flex items-center gap-2">
              <MapPin className="w-4 h-4 text-honey-400" />
              <span>Tala Town, Machakos County, Kenya</span>
            </div>
            <div className="pt-3 flex gap-3">
              <Link
                href="/erp"
                className="px-3.5 py-2 rounded-lg bg-honey-500 text-hive-950 font-bold text-xs hover:bg-honey-400"
              >
                Staff ERP Portal
              </Link>
              <Link
                href="/erp/field-new"
                className="px-3.5 py-2 rounded-lg bg-slate-800 text-white font-bold text-xs hover:bg-slate-700"
              >
                Field Data Collector
              </Link>
            </div>
          </div>
        </div>
        <div className="border-t border-slate-900 py-4 text-center text-[11px] text-slate-500">
          &copy; {new Date().getFullYear()} Davally Apiculture Limited. All rights reserved.
        </div>
      </footer>
    </div>
  );
}
