import { useEffect, useState, useRef, useCallback } from "react";
import { useParams, Link, useSearchParams } from "react-router-dom";
import { supabase } from "@/integrations/supabase/client";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Badge } from "@/components/ui/badge";
import { Checkbox } from "@/components/ui/checkbox";
import { ArrowLeft, MapPin, CalendarDays, FileText, Loader2, CheckCircle, Send, DollarSign } from "lucide-react";
import { L, circleDivIcon, addMapboxSatelliteLayer } from "@/lib/leafletMaps";
import { PublicPageThemeWrapper, type PublicPageThemeValues } from "@/components/public-content/PublicPageTheme";
import {
  format,
  isSameDay,
  parseISO,
  startOfMonth,
  endOfMonth,
  startOfWeek,
  endOfWeek,
  eachDayOfInterval,
  addMonths,
  subMonths,
  isBefore,
  startOfDay,
} from "date-fns";
import { ChevronLeft, ChevronRight } from "lucide-react";

// Interactive public map sub-component (Leaflet + OpenStreetMap, no API key needed)
function InteractivePublicMap({ pins, slug, accent, zoom, lockedView, onReservePin }: {
  pins: { id: string; label: string; lat: string; lng: string; status: string; linked_amenity_id?: string }[];
  slug: string;
  accent: string;
  zoom?: number;
  lockedView?: { lat: number; lng: number; zoom: number } | null;
  onReservePin?: (pin: any) => void;
}) {
  const cRef = useRef<HTMLDivElement>(null);
  const mapRef = useRef<L.Map | null>(null);

  useEffect(() => {
    if (!cRef.current || mapRef.current) return;
    const vp = pins.filter(p => !isNaN(parseFloat(p.lat)) && !isNaN(parseFloat(p.lng)));
    if (!vp.length) return;

    const savedZoom = lockedView?.zoom ?? zoom ?? 17;
    const center: [number, number] = lockedView
      ? [lockedView.lat, lockedView.lng]
      : [parseFloat(vp[0].lat), parseFloat(vp[0].lng)];

    const map = L.map(cRef.current, { center, zoom: savedZoom });
    void addMapboxSatelliteLayer(map);

    const bounds = L.latLngBounds([] as any);
    vp.forEach(pin => {
      const lat = parseFloat(pin.lat);
      const lng = parseFloat(pin.lng);
      bounds.extend([lat, lng]);
      const color = pin.status === "available" ? "#16a34a" : "#dc2626";
      const marker = L.marker([lat, lng], {
        title: pin.label || "Pin",
        // Smaller pins for the public-facing amenity view
        icon: circleDivIcon({ color, size: 18, label: pin.label || "", fontSize: "9px" }),
      }).addTo(map);

      const statusLabel = pin.status === "available" ? "Available" : pin.status === "rented" ? "Rented" : "Unavailable";
      const statusColor = pin.status === "available" ? "#16a34a" : "#dc2626";
      const reserveBtn = pin.status === "available"
        ? `<button id="reserve-btn-${pin.id}" style="display:inline-block;margin-top:8px;padding:8px 16px;background:${accent};color:#fff;border-radius:6px;border:none;font-size:13px;font-weight:600;cursor:pointer;">Reserve →</button>`
        : "";
      marker.bindPopup(
        `<div style="min-width:180px;padding:4px 0;font-family:Inter,system-ui,sans-serif;">
           <p style="font-weight:600;font-size:14px;margin:0 0 4px;">${pin.label || "Location"}</p>
           <span style="color:${statusColor};font-weight:600;">● ${statusLabel}</span>
           ${reserveBtn}
         </div>`
      );
      marker.on("popupopen", () => {
        if (pin.status !== "available") return;
        setTimeout(() => {
          const btn = document.getElementById(`reserve-btn-${pin.id}`);
          if (btn) btn.onclick = () => { map.closePopup(); onReservePin?.(pin); };
        }, 50);
      });
    });

    // Only auto-fit bounds when no locked view is configured.
    if (!lockedView && vp.length > 1) map.fitBounds(bounds, { padding: [40, 40] });
    mapRef.current = map;

    return () => {
      map.remove();
      mapRef.current = null;
    };
  }, [pins, slug, accent, zoom, lockedView, onReservePin]);

  return <div ref={cRef} className="w-full h-[400px] z-0" />;
}

interface FormField {
  id: string;
  label: string;
  type: "text" | "email" | "phone" | "textarea" | "select" | "signature" | "date" | "checkbox" | "paragraph";
  required: boolean;
  options?: string[];
  content?: string;
}

interface MapPinData {
  id: string;
  label: string;
  lat: string;
  lng: string;
  status: "available" | "unavailable" | "rented";
  linked_amenity_id?: string;
}

interface RentalFeeOption {
  id: string;
  label: string;
  amount: number;
}

export default function CommunityAmenityPage() {
  const { slug, amenityId } = useParams<{ slug: string; amenityId: string }>();
  const [searchParams] = useSearchParams();
  const db = supabase as any;
  // Maps now use Leaflet + OpenStreetMap (no API key required)

  const [loading, setLoading] = useState(true);
  const [notFound, setNotFound] = useState(false);
  const [amenity, setAmenity] = useState<any>(null);
  const [assocName, setAssocName] = useState("");
  const [accent, setAccent] = useState("#2563EB");
  const [theme, setTheme] = useState<PublicPageThemeValues | null>(null);

  // Booking form
  const [bookingForm, setBookingForm] = useState({ guest_name: "", guest_email: "", guest_phone: "", booking_date: "", start_time: "", notes: "" });
  const [bookingSubmitted, setBookingSubmitted] = useState(false);
  const [submitting, setSubmitting] = useState(false);

  // Custom form
  const [formData, setFormData] = useState<Record<string, string>>({});
  const [selectedRentalFeeId, setSelectedRentalFeeId] = useState("");
  const [formSubmitted, setFormSubmitted] = useState(false);
  const sigCanvasRefs = useRef<Record<string, HTMLCanvasElement | null>>({});
  const [sigDrawing, setSigDrawing] = useState<Record<string, boolean>>({});

  // Reservation form for map pins
  const [selectedPin, setSelectedPin] = useState<MapPinData | null>(null);
  const [reservationData, setReservationData] = useState<Record<string, string>>({});
  const [reservationCheckboxes, setReservationCheckboxes] = useState<Record<string, boolean>>({});
  const [reservationSubmitted, setReservationSubmitted] = useState(false);
  const [reservationSubmitting, setReservationSubmitting] = useState(false);
  const reservationSigRef = useRef<HTMLCanvasElement | null>(null);
  const [resSigDrawing, setResSigDrawing] = useState(false);
  const reservationFormRef = useRef<HTMLDivElement>(null);

  // Check for payment success
  const paymentSessionId = searchParams.get("session_id");
  const paymentBookingId = searchParams.get("booking_id");
  const paymentSuccess = paymentSessionId && paymentBookingId;
  const [paymentConfirmed, setPaymentConfirmed] = useState(false);

  // Booked dates calendar
  const [bookedDates, setBookedDates] = useState<{ booking_date: string; start_time: string | null; end_time: string | null; status: string; is_public_event?: boolean; event_title?: string | null }[]>([]);
  const [calendarMonth, setCalendarMonth] = useState<Date>(new Date());

  const loadBookedDates = useCallback(async () => {
    if (!amenityId) return;
    const { data } = await (supabase as any).rpc("get_public_amenity_booked_dates", { p_amenity_id: amenityId });
    setBookedDates(data || []);
  }, [amenityId]);

  useEffect(() => {
    if (amenity && ["booking", "rental_calendar", "meeting_calendar"].includes(amenity.amenity_type)) {
      loadBookedDates();
    }
  }, [amenity, loadBookedDates]);

  useEffect(() => {
    if (slug && amenityId) load();
  }, [slug, amenityId]);

  // Confirm payment and mark pin as rented on return from Stripe
  useEffect(() => {
    if (!paymentSuccess || paymentConfirmed) return;
    setPaymentConfirmed(true);
    fetch(
      `${import.meta.env.VITE_SUPABASE_URL}/functions/v1/confirm-reservation-payment`,
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          apikey: import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY,
        },
        body: JSON.stringify({
          booking_id: paymentBookingId,
          session_id: paymentSessionId,
        }),
      }
    ).then(() => {
      // Reload amenity to get updated pin statuses
      if (slug && amenityId) load();
    }).catch(console.error);
  }, [paymentSuccess]);

  const load = async () => {
    const { data: pageData } = await db
      .from("association_public_pages")
      .select("accent_color, bg_color, section_bg_color, text_color, heading_color, font_family, heading_font_family, associations(name)")
      .eq("slug", slug)
      .eq("is_published", true)
      .maybeSingle();

    if (!pageData) { setNotFound(true); setLoading(false); return; }
    setAccent(pageData.accent_color || "#2563EB");
    setTheme(pageData);
    setAssocName(pageData.associations?.name || "");

    const { data: amenityData, error } = await db
      .from("amenities")
      .select("*")
      .eq("id", amenityId)
      .eq("is_active", true)
      .maybeSingle();

    if (error || !amenityData || amenityData.amenity_type === "meeting_calendar") { setNotFound(true); setLoading(false); return; }
    setAmenity(amenityData);
    setLoading(false);
  };

  const handleReservePin = useCallback((pin: MapPinData) => {
    setSelectedPin(pin);
    setReservationData({});
    setReservationCheckboxes({});
    setReservationSubmitted(false);
    if (reservationSigRef.current) {
      const ctx = reservationSigRef.current.getContext("2d");
      if (ctx) ctx.clearRect(0, 0, reservationSigRef.current.width, reservationSigRef.current.height);
    }
    setTimeout(() => {
      reservationFormRef.current?.scrollIntoView({ behavior: "smooth", block: "start" });
    }, 100);
  }, []);

  const handleReservationSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedPin || !amenity) return;

    const mc = amenity.map_config || {};
    const fee = mc.reservation_fee ? parseFloat(mc.reservation_fee) : 0;
    const customFields: FormField[] = mc.reservation_form_fields || [];

    // Validate required checkboxes
    for (const field of customFields) {
      if (field.type === "checkbox" && field.required && !reservationCheckboxes[field.id]) {
        alert(`Please agree to: ${field.label}`);
        return;
      }
    }

    // Get signature data
    let sigData: string | null = null;
    if (reservationSigRef.current) {
      sigData = reservationSigRef.current.toDataURL();
    }

    // Build full form data for storage
    const fullFormData: Record<string, any> = {
      ...reservationData,
      ...Object.fromEntries(
        Object.entries(reservationCheckboxes).map(([k, v]) => [k, v ? "Yes" : "No"])
      ),
    };

    // Add custom field signature data
    for (const field of customFields) {
      if (field.type === "signature") {
        const canvas = sigCanvasRefs.current[`res-${field.id}`];
        if (canvas) fullFormData[field.id] = canvas.toDataURL();
      }
    }

    setReservationSubmitting(true);

    try {
      const currentUrl = window.location.href.split("?")[0];
      const response = await fetch(
        `${import.meta.env.VITE_SUPABASE_URL}/functions/v1/create-reservation-checkout`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            apikey: import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY,
          },
          body: JSON.stringify({
            association_id: amenity.association_id,
            amenity_id: amenity.id,
            pin_id: selectedPin.id,
            pin_label: selectedPin.label,
            guest_name: reservationData.guest_name || "",
            guest_email: reservationData.guest_email || null,
            guest_phone: reservationData.guest_phone || null,
            booking_date: reservationData.booking_date || new Date().toISOString().split("T")[0],
            signature_data: sigData,
            amount_cents: fee > 0 ? Math.round(fee * 100) : 0,
            success_url: currentUrl,
            cancel_url: currentUrl,
            form_data: fullFormData,
          }),
        }
      );

      const result = await response.json();

      if (!response.ok) {
        throw new Error(result.error || "Failed to create reservation");
      }

      if (result.checkout_url) {
        window.location.href = result.checkout_url;
        return;
      }

      setReservationSubmitted(true);
    } catch (err: any) {
      console.error("Reservation error:", err);
      alert(err.message || "Failed to submit reservation");
    } finally {
      setReservationSubmitting(false);
    }
  };

  const handleBookingSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!bookingForm.guest_name || !bookingForm.booking_date) return;
    setSubmitting(true);
    const fullData = { ...formData };
    (amenity.form_fields || []).forEach((f: FormField) => {
      if (f.type === "signature") {
        const canvas = sigCanvasRefs.current[`booking-${f.id}`];
        if (canvas) fullData[f.id] = canvas.toDataURL();
      }
    });
    const rentalFee = amenity.amenity_type === "rental_calendar" ? Number(amenity.booking_config?.rental_fee || 0) : 0;
    const securityDeposit = amenity.amenity_type === "rental_calendar" ? Number(amenity.booking_config?.security_deposit || 0) : 0;
    const feeOptions: RentalFeeOption[] = Array.isArray(amenity.booking_config?.fee_options) ? amenity.booking_config.fee_options : [];
    const selectedFee = feeOptions.find(option => option.id === selectedRentalFeeId);
    const selectedFeeAmount = selectedFee ? Number(selectedFee.amount || 0) : 0;
    const rentalTotal = rentalFee + securityDeposit + selectedFeeAmount;
    if (amenity.amenity_type === "rental_calendar" && feeOptions.length > 0 && !selectedRentalFeeId) {
      alert("Please select a rental fee option.");
      setSubmitting(false);
      return;
    }
    if (selectedFee) {
      fullData["__selected_fee"] = selectedFee.label;
      fullData["__selected_fee_amount"] = selectedFeeAmount.toFixed(2);
    }
    if (securityDeposit > 0) fullData["__security_deposit"] = securityDeposit.toFixed(2);
    if (amenity.amenity_type === "rental_calendar" && rentalTotal > 0) {
      const currentUrl = window.location.href.split("?")[0];
      const response = await fetch(`${import.meta.env.VITE_SUPABASE_URL}/functions/v1/create-reservation-checkout`, {
        method: "POST",
        headers: { "Content-Type": "application/json", apikey: import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY },
        body: JSON.stringify({
          association_id: amenity.association_id,
          amenity_id: amenityId,
          guest_name: bookingForm.guest_name,
          guest_email: bookingForm.guest_email || null,
          guest_phone: bookingForm.guest_phone || null,
          booking_date: bookingForm.booking_date,
          booking_type: "rental",
          title: "Rental Request",
          start_time: bookingForm.start_time || null,
          notes: bookingForm.notes || null,
          amount_cents: Math.round(rentalTotal * 100),
          success_url: currentUrl,
          cancel_url: currentUrl,
          form_data: fullData,
        }),
      });
      const result = await response.json();
      setSubmitting(false);
      if (!response.ok) {
        alert(result.error || "Failed to start checkout");
        return;
      }
      if (result.checkout_url) window.location.href = result.checkout_url;
      else setBookingSubmitted(true);
      return;
    }
    const { data: insertedBooking } = await db.from("amenity_bookings").insert({
      amenity_id: amenityId,
      association_id: amenity.association_id,
      booking_type: amenity.amenity_type === "meeting_calendar" ? "meeting" : "rental",
      title: amenity.amenity_type === "meeting_calendar" ? "Meeting Request" : "Rental Request",
      guest_name: bookingForm.guest_name,
      guest_email: bookingForm.guest_email || null,
      guest_phone: bookingForm.guest_phone || null,
      booking_date: bookingForm.booking_date,
      start_time: bookingForm.start_time || null,
      notes: bookingForm.notes || null,
      form_data: fullData,
      status: "pending_approval",
    }).select("id").single();

    // Send confirmation email if guest provided one
    if (insertedBooking?.id && bookingForm.guest_email) {
      try {
        const origin = window.location.origin;
        const formattedDate = bookingForm.booking_date
          ? format(parseISO(`${bookingForm.booking_date}T12:00:00`), "EEEE, MMMM d, yyyy")
          : "";
        await supabase.functions.invoke("send-transactional-email", {
          body: {
            templateName: "amenity-booking-confirmation",
            recipientEmail: bookingForm.guest_email,
            idempotencyKey: `amenity-booking-${insertedBooking.id}`,
            templateData: {
              guestName: bookingForm.guest_name,
              amenityName: amenity.name,
              associationName: assocName,
              bookingDate: formattedDate,
              startTime: bookingForm.start_time || "",
              status: "pending_approval",
              confirmationLink: `${origin}/booking/${insertedBooking.id}`,
            },
          },
        });
      } catch (err) {
        console.error("Failed to send confirmation email:", err);
      }
    }

    setSubmitting(false);
    setBookingSubmitted(true);
    loadBookedDates();
  };

  const handleFormSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    const fields: FormField[] = amenity.form_fields || [];
    const fullData = { ...formData };
    fields.forEach(f => {
      if (f.type === "signature") {
        const canvas = sigCanvasRefs.current[f.id];
        if (canvas) fullData[f.id] = canvas.toDataURL();
      }
    });
    setSubmitting(true);
    await db.from("amenity_form_submissions").insert({
      amenity_id: amenityId,
      association_id: amenity.association_id,
      submitter_name: fullData["__name"] || null,
      submitter_email: fullData["__email"] || null,
      form_data: fullData,
    });
    setSubmitting(false);
    setFormSubmitted(true);
  };

  // Signature pad helpers for custom forms
  const initSigCanvas = (fieldId: string, canvas: HTMLCanvasElement | null) => {
    sigCanvasRefs.current[fieldId] = canvas;
    if (!canvas) return;
    const ctx = canvas.getContext("2d");
    if (!ctx) return;
    ctx.lineWidth = 2; ctx.strokeStyle = "#000"; ctx.lineCap = "round";
  };

  const startDraw = (fieldId: string, e: React.MouseEvent | React.TouchEvent) => {
    setSigDrawing(p => ({ ...p, [fieldId]: true }));
    const canvas = sigCanvasRefs.current[fieldId];
    if (!canvas) return;
    const ctx = canvas.getContext("2d");
    if (!ctx) return;
    const rect = canvas.getBoundingClientRect();
    const x = ("touches" in e ? e.touches[0].clientX : e.clientX) - rect.left;
    const y = ("touches" in e ? e.touches[0].clientY : e.clientY) - rect.top;
    ctx.beginPath(); ctx.moveTo(x, y);
  };

  const draw = (fieldId: string, e: React.MouseEvent | React.TouchEvent) => {
    if (!sigDrawing[fieldId]) return;
    const canvas = sigCanvasRefs.current[fieldId];
    if (!canvas) return;
    const ctx = canvas.getContext("2d");
    if (!ctx) return;
    const rect = canvas.getBoundingClientRect();
    const x = ("touches" in e ? e.touches[0].clientX : e.clientX) - rect.left;
    const y = ("touches" in e ? e.touches[0].clientY : e.clientY) - rect.top;
    ctx.lineTo(x, y); ctx.stroke();
  };

  const stopDraw = (fieldId: string) => {
    setSigDrawing(p => ({ ...p, [fieldId]: false }));
  };

  const clearSig = (fieldId: string) => {
    const canvas = sigCanvasRefs.current[fieldId];
    if (!canvas) return;
    const ctx = canvas.getContext("2d");
    if (ctx) ctx.clearRect(0, 0, canvas.width, canvas.height);
  };

  // Reservation signature helpers
  const initResSig = (canvas: HTMLCanvasElement | null) => {
    reservationSigRef.current = canvas;
    if (!canvas) return;
    const ctx = canvas.getContext("2d");
    if (!ctx) return;
    ctx.lineWidth = 2; ctx.strokeStyle = "#000"; ctx.lineCap = "round";
  };

  const startResSigDraw = (e: React.MouseEvent | React.TouchEvent) => {
    setResSigDrawing(true);
    const canvas = reservationSigRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext("2d");
    if (!ctx) return;
    const rect = canvas.getBoundingClientRect();
    const x = ("touches" in e ? e.touches[0].clientX : e.clientX) - rect.left;
    const y = ("touches" in e ? e.touches[0].clientY : e.clientY) - rect.top;
    ctx.beginPath(); ctx.moveTo(x, y);
  };

  const drawResSig = (e: React.MouseEvent | React.TouchEvent) => {
    if (!resSigDrawing) return;
    const canvas = reservationSigRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext("2d");
    if (!ctx) return;
    const rect = canvas.getBoundingClientRect();
    const x = ("touches" in e ? e.touches[0].clientX : e.clientX) - rect.left;
    const y = ("touches" in e ? e.touches[0].clientY : e.clientY) - rect.top;
    ctx.lineTo(x, y); ctx.stroke();
  };

  const clearResSig = () => {
    const canvas = reservationSigRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext("2d");
    if (ctx) ctx.clearRect(0, 0, canvas.width, canvas.height);
  };

  // Render a custom form field
  const renderCustomField = (field: FormField, prefix: string) => {
    const fieldKey = `${prefix}${field.id}`;

    if (field.type === "paragraph") {
      return (
        <div key={field.id} className="space-y-1">
          {field.label && <h4 className="text-sm font-semibold text-foreground">{field.label}</h4>}
          {field.content && (
            <p className="text-sm text-muted-foreground whitespace-pre-wrap leading-relaxed">{field.content}</p>
          )}
        </div>
      );
    }

    if (field.type === "checkbox") {
      return (
        <div key={field.id} className="flex items-start gap-3 py-1">
          <Checkbox
            id={fieldKey}
            checked={reservationCheckboxes[field.id] || false}
            onCheckedChange={(v) => setReservationCheckboxes(p => ({ ...p, [field.id]: !!v }))}
            className="mt-0.5"
          />
          <label htmlFor={fieldKey} className="text-sm leading-snug cursor-pointer">
            {field.label} {field.required && <span className="text-destructive">*</span>}
          </label>
        </div>
      );
    }

    if (field.type === "signature") {
      const sigFieldId = `res-${field.id}`;
      return (
        <div key={field.id} className="space-y-2">
          <Label>{field.label} {field.required && <span className="text-destructive">*</span>}</Label>
          <canvas
            ref={el => initSigCanvas(sigFieldId, el)}
            width={500} height={150}
            className="w-full border rounded-lg bg-white cursor-crosshair touch-none"
            onMouseDown={e => startDraw(sigFieldId, e)}
            onMouseMove={e => draw(sigFieldId, e)}
            onMouseUp={() => stopDraw(sigFieldId)}
            onMouseLeave={() => stopDraw(sigFieldId)}
            onTouchStart={e => startDraw(sigFieldId, e)}
            onTouchMove={e => draw(sigFieldId, e)}
            onTouchEnd={() => stopDraw(sigFieldId)}
          />
          <Button type="button" variant="ghost" size="sm" className="text-xs" onClick={() => clearSig(sigFieldId)}>
            Clear
          </Button>
        </div>
      );
    }

    return (
      <div key={field.id} className="space-y-1.5">
        <Label>{field.label} {field.required && <span className="text-destructive">*</span>}</Label>
        {field.type === "textarea" ? (
          <Textarea
            value={reservationData[field.id] || ""}
            onChange={e => setReservationData(p => ({ ...p, [field.id]: e.target.value }))}
            required={field.required}
            rows={3}
          />
        ) : field.type === "select" ? (
          <select
            value={reservationData[field.id] || ""}
            onChange={e => setReservationData(p => ({ ...p, [field.id]: e.target.value }))}
            required={field.required}
            className="w-full px-3 py-2 text-sm border rounded-md bg-background"
          >
            <option value="">Select...</option>
            {(field.options || []).map(o => <option key={o} value={o}>{o}</option>)}
          </select>
        ) : (
          <Input
            type={field.type === "email" ? "email" : field.type === "phone" ? "tel" : field.type === "date" ? "date" : "text"}
            value={reservationData[field.id] || ""}
            onChange={e => setReservationData(p => ({ ...p, [field.id]: e.target.value }))}
            required={field.required}
          />
        )}
      </div>
    );
  };

  if (loading) return <div className="min-h-screen flex items-center justify-center"><Loader2 className="h-8 w-8 animate-spin text-muted-foreground" /></div>;
  if (notFound || !amenity) return (
    <div className="min-h-screen flex items-center justify-center">
      <div className="text-center">
        <h1 className="text-2xl font-bold mb-2">Not Found</h1>
        <p className="text-muted-foreground">This amenity doesn't exist or isn't available.</p>
      </div>
    </div>
  );

  const mc = amenity.map_config || {};
  const pins: MapPinData[] = Array.isArray(mc.pins)
    ? mc.pins
    : (mc.lat && mc.lng ? [{ id: "legacy", label: mc.label || amenity.name, lat: mc.lat.toString(), lng: mc.lng.toString(), status: "available" as const }] : []);
  const reservationFee = mc.reservation_fee ? parseFloat(mc.reservation_fee) : 0;
  const customReservationFields: FormField[] = mc.reservation_form_fields || [];
  const fields: FormField[] = amenity.form_fields || [];
  const rentalBaseFee = amenity.amenity_type === "rental_calendar" ? Number(amenity.booking_config?.rental_fee || 0) : 0;
  const rentalSecurityDeposit = amenity.amenity_type === "rental_calendar" ? Number(amenity.booking_config?.security_deposit || 0) : 0;
  const rentalFeeOptions: RentalFeeOption[] = Array.isArray(amenity.booking_config?.fee_options) ? amenity.booking_config.fee_options : [];
  const selectedRentalFee = rentalFeeOptions.find(option => option.id === selectedRentalFeeId);
  const rentalTotal = rentalBaseFee + rentalSecurityDeposit + Number(selectedRentalFee?.amount || 0);

  // Separate checkbox fields from regular fields for layout
  const regularCustomFields = customReservationFields.filter(f => f.type !== "checkbox" && f.type !== "signature");
  const checkboxFields = customReservationFields.filter(f => f.type === "checkbox");
  const customSigFields = customReservationFields.filter(f => f.type === "signature");

  return (
    <PublicPageThemeWrapper theme={theme} className="min-h-screen">
      <div className="w-full max-w-5xl mx-auto shadow-sm min-h-screen" style={{ backgroundColor: "var(--pp-section)" }}>
      {/* Header */}
      <div className="w-full border-b bg-white">
        <div className="max-w-3xl mx-auto px-4 py-4 flex items-center gap-3">
          <Link to={`/community/${slug}`} className="flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors">
            <ArrowLeft className="h-4 w-4" /> {assocName}
          </Link>
        </div>
      </div>

      {/* Cover image */}
      {amenity.cover_image_url && (
        <div className="w-full h-48 md:h-64" style={{ background: `url(${amenity.cover_image_url}) center/cover no-repeat` }} />
      )}

      <div className="max-w-3xl mx-auto px-4 py-8 space-y-6">
        <div>
          <h1 className="text-2xl font-bold">{amenity.name}</h1>
          {amenity.description && <p className="text-muted-foreground mt-1">{amenity.description}</p>}
        </div>

        {/* Payment success banner */}
        {paymentSuccess && (
          <Card className="border-green-200 bg-green-50">
            <CardContent className="py-6 text-center">
              <CheckCircle className="h-10 w-10 mx-auto mb-3 text-green-600" />
              <h3 className="text-lg font-semibold text-green-900">Payment Successful!</h3>
              <p className="text-sm text-green-700 mt-1">Your reservation has been confirmed and the spot has been marked as rented.</p>
            </CardContent>
          </Card>
        )}

        {/* MAP TYPE - Interactive Leaflet Map */}
        {amenity.amenity_type === "map" && pins.length > 0 && (
          <div className="space-y-4">
            <Card>
              <CardContent className="p-0 overflow-hidden rounded-lg">
                <InteractivePublicMap
                  pins={pins}
                  slug={slug || ""}
                  accent={accent}
                  zoom={mc.zoom}
                  lockedView={mc.locked_view && typeof mc.locked_view.lat === "number" && typeof mc.locked_view.lng === "number" ? mc.locked_view : null}
                  onReservePin={handleReservePin}
                />
              </CardContent>
            </Card>

            {/* Pin Legend */}
            <div className="grid sm:grid-cols-2 gap-3">
              {pins.map(pin => {
                const isRented = pin.status === "rented";
                const isUnavailable = pin.status === "unavailable" || isRented;
                return (
                  <Card key={pin.id} className={`border ${isUnavailable ? "opacity-60" : ""}`}>
                    <CardContent className="flex items-center gap-3 py-4">
                      <div
                        className="p-2 rounded-full shrink-0"
                        style={{
                          backgroundColor: !isUnavailable ? "#16a34a20" : "#dc262620",
                          color: !isUnavailable ? "#16a34a" : "#dc2626",
                        }}
                      >
                        <MapPin className="h-5 w-5" />
                      </div>
                      <div className="flex-1 min-w-0">
                        <p className="font-medium text-sm">{pin.label || "Unnamed Pin"}</p>
                      </div>
                      <div className="flex items-center gap-2">
                        {pin.status === "available" && (
                          <Button
                            variant="outline"
                            size="sm"
                            className="text-xs font-semibold"
                            style={{ color: accent, borderColor: accent }}
                            onClick={() => handleReservePin(pin)}
                          >
                            Reserve
                          </Button>
                        )}
                        <Badge
                          variant={pin.status === "available" ? "default" : "secondary"}
                          className="shrink-0 text-xs"
                          style={pin.status === "available" ? { backgroundColor: "#16a34a" } : {}}
                        >
                          {pin.status === "available" ? "Available" : isRented ? "Rented" : "Unavailable"}
                        </Badge>
                      </div>
                    </CardContent>
                  </Card>
                );
              })}
            </div>

            {/* Reservation Form */}
            {selectedPin && (
              <div ref={reservationFormRef}>
                <Card className="border-2" style={{ borderColor: `${accent}40` }}>
                  <CardHeader>
                    <CardTitle className="text-lg flex items-center gap-2" style={{ color: accent }}>
                      <CalendarDays className="h-5 w-5" /> Reserve: {selectedPin.label || "Location"}
                    </CardTitle>
                     {reservationFee > 0 && (
                      <div className="text-sm font-medium mt-1">
                        <div className="flex items-center gap-1.5">
                          <DollarSign className="h-4 w-4" />
                          Reservation Fee: ${reservationFee.toFixed(2)}
                        </div>
                        <p className="text-xs text-muted-foreground mt-0.5">+ processing fees applied at checkout</p>
                      </div>
                    )}
                  </CardHeader>
                  <CardContent>
                    {reservationSubmitted ? (
                      <div className="text-center py-8">
                        <CheckCircle className="h-12 w-12 mx-auto mb-3" style={{ color: accent }} />
                        <h3 className="text-lg font-semibold">Reservation Submitted!</h3>
                        <p className="text-muted-foreground text-sm mt-1">
                          Your reservation request has been received. Management will follow up with you shortly.
                        </p>
                      </div>
                    ) : (
                      <form onSubmit={handleReservationSubmit} className="space-y-5">
                        {/* Core fields: Name, Email, Date */}
                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                          <div className="space-y-1.5">
                            <Label>Full Name <span className="text-destructive">*</span></Label>
                            <Input
                              value={reservationData.guest_name || ""}
                              onChange={e => setReservationData(p => ({ ...p, guest_name: e.target.value }))}
                              required
                              placeholder="John Doe"
                            />
                          </div>
                          <div className="space-y-1.5">
                            <Label>Email <span className="text-destructive">*</span></Label>
                            <Input
                              type="email"
                              value={reservationData.guest_email || ""}
                              onChange={e => setReservationData(p => ({ ...p, guest_email: e.target.value }))}
                              required
                              placeholder="john@example.com"
                            />
                          </div>
                          <div className="space-y-1.5">
                            <Label>Phone</Label>
                            <Input
                              type="tel"
                              value={reservationData.guest_phone || ""}
                              onChange={e => setReservationData(p => ({ ...p, guest_phone: e.target.value }))}
                              placeholder="(555) 123-4567"
                            />
                          </div>
                          <div className="space-y-1.5">
                            <Label>Start Date <span className="text-destructive">*</span></Label>
                            <Input
                              type="date"
                              value={reservationData.booking_date || ""}
                              onChange={e => setReservationData(p => ({ ...p, booking_date: e.target.value }))}
                              required
                            />
                          </div>
                        </div>

                        {/* Custom regular fields */}
                        {regularCustomFields.length > 0 && (
                          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                            {regularCustomFields.map(f => renderCustomField(f, "res-"))}
                          </div>
                        )}

                        {/* Agreement checkboxes */}
                        {checkboxFields.length > 0 && (
                          <div className="space-y-3 p-4 rounded-lg border bg-muted/30">
                            <Label className="text-sm font-semibold">Agreements</Label>
                            {checkboxFields.map(f => renderCustomField(f, "res-"))}
                          </div>
                        )}

                        {/* Custom signature fields */}
                        {customSigFields.map(f => renderCustomField(f, "res-"))}

                        {/* Main Signature */}
                        <div className="space-y-2">
                          <Label>Signature <span className="text-destructive">*</span></Label>
                          <p className="text-xs text-muted-foreground">Sign below to agree to the reservation terms.</p>
                          <canvas
                            ref={initResSig}
                            width={500}
                            height={150}
                            className="w-full border rounded-lg bg-white cursor-crosshair touch-none"
                            onMouseDown={startResSigDraw}
                            onMouseMove={drawResSig}
                            onMouseUp={() => setResSigDrawing(false)}
                            onMouseLeave={() => setResSigDrawing(false)}
                            onTouchStart={startResSigDraw}
                            onTouchMove={drawResSig}
                            onTouchEnd={() => setResSigDrawing(false)}
                          />
                          <Button type="button" variant="ghost" size="sm" className="text-xs" onClick={clearResSig}>
                            Clear Signature
                          </Button>
                        </div>

                        {/* Fee display & Submit */}
                        <div className="flex items-center justify-between pt-2 border-t">
                          <div>
                            {reservationFee > 0 && (
                              <div>
                                <p className="text-sm font-semibold">
                                  Total: <span style={{ color: accent }}>${reservationFee.toFixed(2)}</span>
                                </p>
                                <p className="text-xs text-muted-foreground">+ processing fees</p>
                              </div>
                            )}
                          </div>
                          <Button
                            type="submit"
                            disabled={reservationSubmitting}
                            style={{ backgroundColor: accent }}
                            className="text-white gap-1.5 px-6"
                          >
                            {reservationSubmitting ? (
                              <Loader2 className="h-4 w-4 animate-spin" />
                            ) : reservationFee > 0 ? (
                              <DollarSign className="h-4 w-4" />
                            ) : (
                              <Send className="h-4 w-4" />
                            )}
                            {reservationFee > 0 ? "Pay & Reserve" : "Submit Reservation"}
                          </Button>
                        </div>
                      </form>
                    )}
                  </CardContent>
                </Card>
              </div>
            )}
          </div>
        )}

        {/* PUBLIC AVAILABILITY CALENDAR */}
        {["booking", "rental_calendar", "meeting_calendar"].includes(amenity.amenity_type) && (() => {
          const calendarDays = eachDayOfInterval({
            start: startOfWeek(startOfMonth(calendarMonth)),
            end: endOfWeek(endOfMonth(calendarMonth)),
          });
          const today = startOfDay(new Date());
          const bookedByDay = (day: Date) =>
            bookedDates.filter((b) => b.booking_date && isSameDay(parseISO(`${b.booking_date}T12:00:00`), day));
          return (
            <Card>
              <CardHeader>
                <div className="flex items-center justify-between">
                  <CardTitle className="text-lg flex items-center gap-2" style={{ color: accent }}>
                    <CalendarDays className="h-5 w-5" /> Availability
                  </CardTitle>
                  <div className="flex items-center gap-1">
                    <Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => setCalendarMonth((m) => subMonths(m, 1))}>
                      <ChevronLeft className="h-4 w-4" />
                    </Button>
                    <span className="text-sm font-medium px-2 min-w-[140px] text-center">{format(calendarMonth, "MMMM yyyy")}</span>
                    <Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => setCalendarMonth((m) => addMonths(m, 1))}>
                      <ChevronRight className="h-4 w-4" />
                    </Button>
                  </div>
                </div>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-7 rounded-md border overflow-hidden text-xs">
                  {["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"].map((d) => (
                    <div key={d} className="bg-muted/50 p-2 text-center font-semibold text-muted-foreground border-b">{d}</div>
                  ))}
                  {calendarDays.map((day) => {
                    const dayBookings = bookedByDay(day);
                    const isBooked = dayBookings.length > 0;
                    const isOtherMonth = day.getMonth() !== calendarMonth.getMonth();
                    const isPast = isBefore(day, today);
                    return (
                      <div
                        key={day.toISOString()}
                        className={`min-h-[64px] border-r border-b p-1.5 ${isOtherMonth ? "bg-muted/20" : ""} ${isPast ? "opacity-50" : ""}`}
                      >
                        <div className={`text-xs font-medium ${isOtherMonth ? "text-muted-foreground" : "text-foreground"}`}>{format(day, "d")}</div>
                        {isBooked && (() => {
                          const events = dayBookings.filter(b => b.is_public_event && b.event_title);
                          const nonEvents = dayBookings.filter(b => !(b.is_public_event && b.event_title));
                          const items: { label: string; isEvent: boolean }[] = [
                            ...events.map(e => ({ label: e.event_title as string, isEvent: true })),
                            ...nonEvents.map(() => ({ label: "Booked", isEvent: false })),
                          ];
                          const visible = items.slice(0, 3);
                          const extra = items.length - visible.length;
                          return (
                            <div className={`mt-1 space-y-0.5 ${isPast ? "opacity-60" : ""}`}>
                              {visible.map((item, idx) => (
                                <div
                                  key={idx}
                                  className="rounded px-1 py-0.5 text-[10px] font-semibold text-white text-center truncate"
                                  style={{ backgroundColor: item.isEvent ? accent : "#dc2626" }}
                                  title={item.label}
                                >
                                  {item.label}
                                </div>
                              ))}
                              {extra > 0 && (
                                <div className="text-[9px] text-muted-foreground text-center">+{extra} more</div>
                              )}
                            </div>
                          );
                        })()}
                      </div>
                    );
                  })}
                </div>
                <div className="mt-3 flex items-center gap-3 text-xs text-muted-foreground">
                  <div className="flex items-center gap-1.5"><span className="inline-block h-3 w-3 rounded" style={{ backgroundColor: "#dc2626" }} /> Booked</div>
                  <div className="flex items-center gap-1.5"><span className="inline-block h-3 w-3 rounded border" /> Available</div>
                </div>
              </CardContent>
            </Card>
          );
        })()}

        {/* BOOKING TYPE */}
        {["booking", "rental_calendar", "meeting_calendar"].includes(amenity.amenity_type) && (
          <Card>
            <CardHeader>
              <CardTitle className="text-lg flex items-center gap-2" style={{ color: accent }}>
                <CalendarDays className="h-5 w-5" /> Request a {amenity.amenity_type === "meeting_calendar" ? "Meeting" : "Rental"} Booking
              </CardTitle>
            </CardHeader>
            <CardContent>
              {bookingSubmitted ? (
                <div className="text-center py-8">
                  <CheckCircle className="h-12 w-12 mx-auto mb-3" style={{ color: accent }} />
                  <h3 className="text-lg font-semibold">Booking Request Submitted</h3>
                  <p className="text-muted-foreground text-sm mt-1">Management will review your request and get back to you.</p>
                </div>
              ) : (
                <form onSubmit={handleBookingSubmit} className="space-y-4">
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div className="space-y-1.5">
                      <Label>Your Name *</Label>
                      <Input value={bookingForm.guest_name} onChange={e => setBookingForm(p => ({ ...p, guest_name: e.target.value }))} required />
                    </div>
                    <div className="space-y-1.5">
                      <Label>Email</Label>
                      <Input type="email" value={bookingForm.guest_email} onChange={e => setBookingForm(p => ({ ...p, guest_email: e.target.value }))} />
                    </div>
                    <div className="space-y-1.5">
                      <Label>Phone</Label>
                      <Input type="tel" value={bookingForm.guest_phone} onChange={e => setBookingForm(p => ({ ...p, guest_phone: e.target.value }))} />
                    </div>
                    <div className="space-y-1.5">
                      <Label>Preferred Date *</Label>
                      <Input type="date" value={bookingForm.booking_date} onChange={e => setBookingForm(p => ({ ...p, booking_date: e.target.value }))} required />
                    </div>
                    <div className="space-y-1.5">
                      <Label>Preferred Time</Label>
                      <Input type="time" value={bookingForm.start_time} onChange={e => setBookingForm(p => ({ ...p, start_time: e.target.value }))} />
                    </div>
                  </div>
                  <div className="space-y-1.5">
                    <Label>Notes</Label>
                    <Textarea value={bookingForm.notes} onChange={e => setBookingForm(p => ({ ...p, notes: e.target.value }))} rows={3} placeholder="Any special requests..." />
                  </div>
                  {amenity.amenity_type === "rental_calendar" && rentalFeeOptions.length > 0 && (
                    <div className="space-y-1.5">
                      <Label>Rental Fee Option *</Label>
                      <select value={selectedRentalFeeId} onChange={e => setSelectedRentalFeeId(e.target.value)} required className="w-full px-3 py-2 text-sm border rounded-md bg-background">
                        <option value="">Select a fee...</option>
                        {rentalFeeOptions.map(option => <option key={option.id} value={option.id}>{option.label} — ${Number(option.amount || 0).toFixed(2)}</option>)}
                      </select>
                    </div>
                  )}
                  {amenity.amenity_type === "rental_calendar" && rentalTotal > 0 && (
                    <div className="rounded-md border bg-muted/30 p-3 text-sm space-y-1">
                      {rentalBaseFee > 0 && <div className="flex justify-between"><span>Rental fee</span><span>${rentalBaseFee.toFixed(2)}</span></div>}
                      {rentalSecurityDeposit > 0 && <div className="flex justify-between"><span>Security deposit</span><span>${rentalSecurityDeposit.toFixed(2)}</span></div>}
                      {selectedRentalFee && <div className="flex justify-between"><span>{selectedRentalFee.label}</span><span>${Number(selectedRentalFee.amount || 0).toFixed(2)}</span></div>}
                      <div className="flex justify-between border-t pt-2 font-semibold"><span>Total due</span><span>${rentalTotal.toFixed(2)}</span></div>
                      <p className="text-xs text-muted-foreground">Processing fees are added at checkout.</p>
                    </div>
                  )}
                  {fields.length > 0 && fields.map(field => (
                    field.type === "paragraph" ? (
                      <div key={field.id} className="space-y-1">
                        {field.label && <h4 className="text-sm font-semibold text-foreground">{field.label}</h4>}
                        {field.content && (
                          <p className="text-sm text-muted-foreground whitespace-pre-wrap leading-relaxed">{field.content}</p>
                        )}
                      </div>
                    ) : (
                    <div key={field.id} className="space-y-1.5">
                      <Label>{field.label} {field.required && <span className="text-destructive">*</span>}</Label>
                      {field.type === "textarea" ? (
                        <Textarea value={formData[field.id] || ""} onChange={e => setFormData(p => ({ ...p, [field.id]: e.target.value }))} rows={3} required={field.required} />
                      ) : field.type === "select" ? (
                        <select value={formData[field.id] || ""} onChange={e => setFormData(p => ({ ...p, [field.id]: e.target.value }))} required={field.required} className="w-full px-3 py-2 text-sm border rounded-md bg-background">
                          <option value="">Select...</option>
                          {(field.options || []).map(o => <option key={o} value={o}>{o}</option>)}
                        </select>
                      ) : field.type === "checkbox" ? (
                        <div className="flex items-center gap-2"><Checkbox checked={formData[field.id] === "Yes"} onCheckedChange={v => setFormData(p => ({ ...p, [field.id]: v ? "Yes" : "No" }))} /><span className="text-sm text-muted-foreground">{field.label}</span></div>
                      ) : field.type === "signature" ? (
                        <canvas ref={el => initSigCanvas(`booking-${field.id}`, el)} width={500} height={150} className="w-full border rounded-md bg-white cursor-crosshair touch-none" onMouseDown={e => startDraw(`booking-${field.id}`, e)} onMouseMove={e => draw(`booking-${field.id}`, e)} onMouseUp={() => stopDraw(`booking-${field.id}`)} onMouseLeave={() => stopDraw(`booking-${field.id}`)} onTouchStart={e => startDraw(`booking-${field.id}`, e)} onTouchMove={e => draw(`booking-${field.id}`, e)} onTouchEnd={() => stopDraw(`booking-${field.id}`)} />
                      ) : (
                        <Input type={field.type === "email" ? "email" : field.type === "phone" ? "tel" : field.type === "date" ? "date" : "text"} value={formData[field.id] || ""} onChange={e => setFormData(p => ({ ...p, [field.id]: e.target.value }))} required={field.required} />
                      )}
                    </div>
                    )
                  ))}
                  <Button type="submit" disabled={submitting} style={{ backgroundColor: accent }} className="text-white gap-1.5">
                    {submitting ? <Loader2 className="h-4 w-4 animate-spin" /> : <Send className="h-4 w-4" />}
                    Submit Booking Request
                  </Button>
                </form>
              )}
            </CardContent>
          </Card>
        )}

        {/* FORM TYPE */}
        {amenity.amenity_type === "form" && fields.length > 0 && (
          <Card>
            <CardHeader>
              <CardTitle className="text-lg flex items-center gap-2" style={{ color: accent }}>
                <FileText className="h-5 w-5" /> {amenity.name}
              </CardTitle>
            </CardHeader>
            <CardContent>
              {formSubmitted ? (
                <div className="text-center py-8">
                  <CheckCircle className="h-12 w-12 mx-auto mb-3" style={{ color: accent }} />
                  <h3 className="text-lg font-semibold">Form Submitted</h3>
                  <p className="text-muted-foreground text-sm mt-1">Thank you for your submission.</p>
                </div>
              ) : (
                <form onSubmit={handleFormSubmit} className="space-y-4">
                  {fields.map(field => (
                    field.type === "paragraph" ? (
                      <div key={field.id} className="space-y-1">
                        {field.label && <h4 className="text-sm font-semibold text-foreground">{field.label}</h4>}
                        {field.content && (
                          <p className="text-sm text-muted-foreground whitespace-pre-wrap leading-relaxed">{field.content}</p>
                        )}
                      </div>
                    ) : (
                    <div key={field.id} className="space-y-1.5">
                      <Label>
                        {field.label} {field.required && <span className="text-destructive">*</span>}
                      </Label>
                      {field.type === "text" && (
                        <Input value={formData[field.id] || ""} onChange={e => setFormData(p => ({ ...p, [field.id]: e.target.value }))} required={field.required} />
                      )}
                      {field.type === "email" && (
                        <Input type="email" value={formData[field.id] || ""} onChange={e => setFormData(p => ({ ...p, [field.id]: e.target.value, __email: e.target.value }))} required={field.required} />
                      )}
                      {field.type === "phone" && (
                        <Input type="tel" value={formData[field.id] || ""} onChange={e => setFormData(p => ({ ...p, [field.id]: e.target.value }))} required={field.required} />
                      )}
                      {field.type === "date" && (
                        <Input type="date" value={formData[field.id] || ""} onChange={e => setFormData(p => ({ ...p, [field.id]: e.target.value }))} required={field.required} />
                      )}
                      {field.type === "textarea" && (
                        <Textarea value={formData[field.id] || ""} onChange={e => setFormData(p => ({ ...p, [field.id]: e.target.value }))} rows={3} required={field.required} />
                      )}
                      {field.type === "select" && (
                        <select value={formData[field.id] || ""} onChange={e => setFormData(p => ({ ...p, [field.id]: e.target.value }))} required={field.required} className="w-full px-3 py-2 text-sm border rounded-md bg-background">
                          <option value="">Select...</option>
                          {(field.options || []).map(o => <option key={o} value={o}>{o}</option>)}
                        </select>
                      )}
                      {field.type === "signature" && (
                        <div>
                          <canvas
                            ref={el => initSigCanvas(field.id, el)}
                            width={500} height={150}
                            className="w-full border rounded-md bg-white cursor-crosshair touch-none"
                            onMouseDown={e => startDraw(field.id, e)}
                            onMouseMove={e => draw(field.id, e)}
                            onMouseUp={() => stopDraw(field.id)}
                            onMouseLeave={() => stopDraw(field.id)}
                            onTouchStart={e => startDraw(field.id, e)}
                            onTouchMove={e => draw(field.id, e)}
                            onTouchEnd={() => stopDraw(field.id)}
                          />
                          <Button type="button" variant="ghost" size="sm" className="text-xs mt-1" onClick={() => clearSig(field.id)}>
                            Clear Signature
                          </Button>
                        </div>
                      )}
                    </div>
                    )
                  ))}
                  <Button type="submit" disabled={submitting} style={{ backgroundColor: accent }} className="text-white gap-1.5">
                    {submitting ? <Loader2 className="h-4 w-4 animate-spin" /> : <Send className="h-4 w-4" />}
                    Submit
                  </Button>
                </form>
              )}
            </CardContent>
          </Card>
        )}
      </div>
      </div>
    </PublicPageThemeWrapper>
  );
}
