import { useEffect, useState } from "react";
import { brandUrl, displayUrl } from "@/lib/utils";
import { canonicalUrl } from "@/lib/canonicalUrl";
import { buildBusinessProfileSeo } from "@/lib/seo";
import { useParams, Link } from "react-router-dom";
import { Helmet } from "react-helmet-async";
import SiteHeader from "@/components/SiteHeader";
import Footer from "@/components/Footer";
import LazyImage from "@/components/LazyImage";
import { supabase } from "@/integrations/supabase/client";
import BusinessRelatedLinks from "@/components/BusinessRelatedLinks";
import SearchAutocomplete from "@/components/SearchAutocomplete";

import StickyLeadCTA from "@/components/StickyLeadCTA";
import NewsSection from "@/components/NewsSection";
import EventsSection from "@/components/EventsSection";
import { CATEGORY_NEWS_KEYWORDS } from "@/hooks/useNews";
import ProfileAdSlot from "@/components/ProfileAdSlot";
import ListingEngagementButton from "@/components/ListingEngagementButton";
import ListingSaveButton from "@/components/ListingSaveButton";
import AffiliateAdSlot from "@/components/AffiliateAdSlot";
import { CalculatorIconRow, CalculatorSidebarCard } from "@/components/CalculatorEmbed";
import TrendingBusinesses from "@/components/TrendingBusinesses";
import BusinessServicesList from "@/components/BusinessServicesList";
import BusinessContactDialog from "@/components/BusinessContactDialog";
import VerificationBadgeStack from "@/components/VerificationBadgeStack";
import VerificationBadgeGuide from "@/components/VerificationBadgeGuide";
import ClaimListingModal from "@/components/ClaimListingModal";
import TrustIndicator from "@/components/TrustIndicator";
import PhoneLink from "@/components/PhoneLink";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Checkbox } from "@/components/ui/checkbox";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Skeleton } from "@/components/ui/skeleton";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { toast } from "sonner";
import {
  CheckCircle,
  ShieldCheck,
  Star,
  MapPin,
  Phone,
  Globe,
  Mail,
  Clock,
  ArrowLeft,
  ExternalLink,
  Facebook,
  Instagram,
  Linkedin,
  Twitter,
  Video,
  Calendar,
  Share2,
  AlertTriangle,
  Pencil,
  MessageSquare,
  Youtube,
  Music2,
  Image as ImageIcon,
} from "lucide-react";

interface BusinessData {
  id: string;
  business_name: string;
  slug: string;
  description: string | null;
  phone: string | null;
  email: string | null;
  website: string | null;
  street: string | null;
  street2: string | null;
  city_name: string | null;
  city_slug: string | null;
  region: string | null;
  zip: string | null;
  category_primary_name: string | null;
  category_primary_slug: string | null;
  verified_status: string;
  preferred_status: boolean;
  logo_url: string | null;
  banner_logo_url: string | null;
  latitude: number | null;
  longitude: number | null;
  business_hours: Record<string, string> | null;
  social_facebook: string | null;
  social_instagram: string | null;
  social_linkedin: string | null;
  social_twitter: string | null;
  social_tiktok: string | null;
  social_pinterest: string | null;
  social_youtube: string | null;
  video: string | null;
  booking_link: string | null;
  post_images: unknown[] | null;
  hide_street_address: boolean | null;
}


const DAYS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];

const BusinessProfile = () => {
  const { categorySlug, citySlug, businessSlug } = useParams();
  const [biz, setBiz] = useState<BusinessData | null>(null);
  const [loading, setLoading] = useState(true);
  const [businessType, setBusinessType] = useState<string>("place");
  const [claimForm, setClaimForm] = useState({ name: "", email: "", phone: "", relationship: "", smsConsent: false });
  const [submitting, setSubmitting] = useState(false);
  const [claimed, setClaimed] = useState(false);
  const [claimModalOpen, setClaimModalOpen] = useState(false);

  // Suggest an Edit state
  const [showSuggestForm, setShowSuggestForm] = useState(false);
  const [suggestForm, setSuggestForm] = useState({ name: "", email: "", field: "", value: "", notes: "" });
  const [suggestSubmitting, setSuggestSubmitting] = useState(false);
  const [cityCoords, setCityCoords] = useState<{ lat: number; lng: number } | null>(null);


  useEffect(() => {
    const fetchBiz = async () => {
      setLoading(true);
      // Try exact match first (category + city + slug)
      let { data, error } = await supabase
        .from("locations")
        .select("*")
        .eq("slug", businessSlug ?? "")
        .eq("category_primary_slug", categorySlug ?? "")
        .eq("city_slug", citySlug ?? "")
        .eq("is_published", true)
        .single();

      // Fallback: slug-only lookup if exact match fails (handles null/mismatched category or city)
      if (error || !data) {
        const fallback = await supabase
          .from("locations")
          .select("*")
          .eq("slug", businessSlug ?? "")
          .eq("is_published", true)
          .single();
        if (!fallback.error && fallback.data) {
          data = fallback.data;
          error = null;
        }
      }

      if (!error && data) {
        setBiz(data as unknown as BusinessData);
        // Record page view for trending
        supabase.from("page_views").insert({ location_id: data.id }).then(() => {});

        // Fetch category business_type
        if (data.category_primary_slug) {
          supabase
            .from("categories")
            .select("business_type")
            .eq("slug", data.category_primary_slug)
            .maybeSingle()
            .then(({ data: cat }) => {
              if (cat?.business_type) setBusinessType(cat.business_type as string);
            });
        }

        // Fetch city coordinates for the city-only map fallback (used when address is hidden)
        if (data.city_slug) {
          supabase
            .from("cities")
            .select("latitude, longitude")
            .eq("slug", data.city_slug)
            .maybeSingle()
            .then(({ data: city }) => {
              if (city?.latitude && city?.longitude) {
                setCityCoords({ lat: city.latitude, lng: city.longitude });
              }
            });
        }
      }
      setLoading(false);
    };
    fetchBiz();
  }, [businessSlug, categorySlug, citySlug]);

  const isUnclaimed = biz?.verified_status !== "verified";
  const pageUrl = canonicalUrl();

  // --- Handlers ---
  const handleClaim = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!biz) return;
    setSubmitting(true);
    const { error } = await supabase.from("claims").insert({
      location_id: biz.id,
      claimant_name: claimForm.name,
      claimant_email: claimForm.email,
      claimant_phone: claimForm.phone,
      relationship: claimForm.relationship,
    });
    if (error) {
      toast.error("Failed to submit claim. Please try again.");
    } else {
      toast.success("Claim submitted! We'll review and get back to you.");
      setClaimed(true);
    }
    setSubmitting(false);
  };

  const shareMessage = `Hey! I found ${biz?.business_name} listed on BestofUtah.com. You can claim your free listing and update your business info here: ${pageUrl}`;

  const trackOutreach = (channel: "sms" | "email") => {
    if (biz?.id) {
      const visitorId = localStorage.getItem("bou_vid") || "";
      supabase.from("claim_outreach_events").insert({
        location_id: biz.id,
        channel,
        visitor_id: visitorId,
      }).then(() => {});
    }
  };

  const handleShareText = () => {
    trackOutreach("sms");
    const phoneNum = biz?.phone?.replace(/\D/g, "") || "";
    window.open(`sms:${phoneNum}?body=${encodeURIComponent(shareMessage)}`, "_blank");
  };
  const handleShareEmail = () => {
    trackOutreach("email");
    const to = (biz?.email || "").trim();
    const subject = encodeURIComponent(`Claim ${biz?.business_name} on BestofUtah.com`);
    const body = encodeURIComponent(shareMessage);
    // Do NOT encodeURIComponent the address — Apple Mail won't parse %40 as @
    const href = `mailto:${to}?subject=${subject}&body=${body}`;
    // Use location.href so the OS mail handler reliably picks up the To: field
    window.location.href = href;
  };

  const handleSuggestEdit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!biz) return;
    setSuggestSubmitting(true);
    const { error } = await supabase.from("suggestions").insert({
      location_id: biz.id,
      submitter_name: suggestForm.name,
      submitter_email: suggestForm.email,
      field_name: suggestForm.field,
      suggested_value: suggestForm.value,
      notes: suggestForm.notes,
    });
    if (error) {
      toast.error("Failed to submit suggestion. Please try again.");
    } else {
      toast.success("Thanks! Your suggestion has been submitted for review.");
      setShowSuggestForm(false);
      setSuggestForm({ name: "", email: "", field: "", value: "", notes: "" });
    }
    setSuggestSubmitting(false);
  };


  // --- Computed ---
  const addressHidden = !!biz?.hide_street_address;

  const fullAddress = biz
    ? addressHidden
      ? [biz.city_name, biz.region].filter(Boolean).join(", ")
      : [biz.street, biz.street2, biz.city_name, biz.region, biz.zip].filter(Boolean).join(", ")
    : "";

  // Pick coordinates: exact business coords unless owner hid the address — then use the city center.
  const mapLat = addressHidden ? cityCoords?.lat ?? null : biz?.latitude ?? null;
  const mapLng = addressHidden ? cityCoords?.lng ?? null : biz?.longitude ?? null;
  const mapDelta = addressHidden ? 0.05 : 0.01;
  const mapSrc = mapLat && mapLng
    ? `https://www.openstreetmap.org/export/embed.html?bbox=${mapLng - mapDelta}%2C${mapLat - mapDelta}%2C${mapLng + mapDelta}%2C${mapLat + mapDelta}&layer=mapnik&marker=${mapLat}%2C${mapLng}`
    : null;

  const ensureAbsoluteUrl = (url: string | null): string | null => {
    if (!url || !url.trim()) return null;
    const trimmed = url.trim();
    if (trimmed.startsWith('http://') || trimmed.startsWith('https://')) return trimmed;
    return `https://${trimmed}`;
  };

  const socialLinks = biz ? [
    { url: ensureAbsoluteUrl(biz.social_facebook), icon: Facebook, label: "Facebook" },
    { url: ensureAbsoluteUrl(biz.social_instagram), icon: Instagram, label: "Instagram" },
    { url: ensureAbsoluteUrl(biz.social_linkedin), icon: Linkedin, label: "LinkedIn" },
    { url: ensureAbsoluteUrl(biz.social_twitter), icon: Twitter, label: "Twitter" },
    { url: ensureAbsoluteUrl(biz.social_tiktok), icon: Music2, label: "TikTok" },
    { url: ensureAbsoluteUrl(biz.social_pinterest), icon: ImageIcon, label: "Pinterest" },
    { url: ensureAbsoluteUrl(biz.social_youtube), icon: Youtube, label: "YouTube" },
  ].filter(s => s.url) : [];

  const hours = biz?.business_hours as Record<string, string> | null;

  if (loading) {
    return (
      <div className="min-h-screen bg-background">
        <SiteHeader />
        <div className="container mx-auto px-4 py-8 space-y-6">
          <Skeleton className="h-8 w-64" />
          <Skeleton className="h-48 w-full rounded-xl" />
          <Skeleton className="h-64 w-full rounded-xl" />
        </div>
      </div>
    );
  }

  if (!biz) {
    const guessedQuery = (businessSlug ?? "")
      .replace(/-\d+$/, "")
      .replace(/-/g, " ")
      .trim();
    return (
      <div className="min-h-screen bg-background flex flex-col">
        <SiteHeader />
        <main className="flex-1 container mx-auto px-4 py-16">
          <div className="mx-auto max-w-2xl text-center">
            <h1 className="text-2xl font-bold mb-2">Business Not Found</h1>
            <p className="text-muted-foreground mb-8">
              This listing may have been removed or is no longer published.
            </p>
            <div className="mb-6 text-left">
              <label className="mb-2 block text-sm font-medium text-foreground">
                Search for a business
              </label>
              <SearchAutocomplete
                initialValue={guessedQuery}
                placeholder="Search businesses, categories, or cities..."
                size="lg"
              />
            </div>
            <div className="flex flex-wrap items-center justify-center gap-3">
              {citySlug && (
                <Link to={`/city/${citySlug}`}>
                  <Button variant="outline">Browse {citySlug.replace(/-/g, " ")}</Button>
                </Link>
              )}
              {categorySlug && (
                <Link to={`/${categorySlug}`}>
                  <Button variant="outline">Browse category</Button>
                </Link>
              )}
              <Link to="/"><Button>Back to Home</Button></Link>
            </div>
          </div>
        </main>
        <Footer />
      </div>
    );
  }

  const isPlaceholder = biz.description?.includes("Looking for more info on this Utah business");
  const displayDesc = isPlaceholder || !biz.description?.trim()
    ? `${biz.business_name} is a ${biz.category_primary_name || "local"} business in ${biz.city_name || "Utah"}. This listing hasn't been claimed yet — if you're the owner or know them, let them know they can claim and customize their profile for free!`
    : biz.description;

  const seo = buildBusinessProfileSeo({
    categorySlug: biz.category_primary_slug ?? "",
    citySlug: biz.city_slug ?? "",
    businessSlug: biz.slug,
    businessName: biz.business_name,
    categoryName: biz.category_primary_name ?? "",
    cityName: biz.city_name ?? "",
    logoUrl: biz.logo_url,
  });

  return (
    <div className="min-h-screen bg-background">
      {/* JSON-LD Structured Data */}
      <Helmet>
        <title>{seo.title}</title>
        <meta name="description" content={seo.description} />
        <link rel="canonical" href={seo.canonical} />
        <meta property="og:title" content={seo.ogTitle} />
        <meta property="og:description" content={seo.ogDescription} />
        <meta property="og:url" content={seo.ogUrl} />
        <meta property="og:type" content={seo.ogType} />
        <meta property="og:image" content={seo.ogImage} />
        <meta name="twitter:card" content={seo.twitterCard} />
        <script type="application/ld+json">
          {JSON.stringify({
            "@context": "https://schema.org",
            "@type": "LocalBusiness",
            name: biz.business_name,
            description: displayDesc?.slice(0, 300),
            url: `https://bestofutah.com/${biz.category_primary_slug}/${biz.city_slug}/${biz.slug}`,
            ...(biz.logo_url && biz.logo_url !== "none" && biz.logo_url !== "" && { image: biz.logo_url }),
            ...(biz.phone && { telephone: biz.phone }),
            ...(biz.email && { email: biz.email }),
            ...((biz.website || socialLinks.length > 0) && {
              sameAs: [
                ...(biz.website ? [biz.website] : []),
                ...socialLinks.map(s => s.url).filter(Boolean),
              ],
            }),
            ...(fullAddress && {
              address: {
                "@type": "PostalAddress",
                ...(addressHidden ? {} : { streetAddress: [biz.street, biz.street2].filter(Boolean).join(", ") }),
                addressLocality: biz.city_name,
                addressRegion: biz.region || "UT",
                ...(addressHidden ? {} : { postalCode: biz.zip }),
                addressCountry: "US",
              },
            }),
            ...(biz.latitude && biz.longitude && {
              geo: {
                "@type": "GeoCoordinates",
                latitude: biz.latitude,
                longitude: biz.longitude,
              },
            }),
            ...(hours && Object.keys(hours).length > 0 && {
              openingHoursSpecification: DAYS
                .filter(day => hours[day] && hours[day] !== "Closed" && hours[day] !== "")
                .map(day => {
                  const parts = hours[day]?.split("-").map(s => s.trim()) || [];
                  return {
                    "@type": "OpeningHoursSpecification",
                    dayOfWeek: day,
                    ...(parts.length === 2 && { opens: parts[0], closes: parts[1] }),
                  };
                }),
            }),
          })}
        </script>
        <script type="application/ld+json">
          {JSON.stringify({
            "@context": "https://schema.org",
            "@type": "BreadcrumbList",
            itemListElement: [
              { "@type": "ListItem", position: 1, name: "Home", item: "https://bestofutah.com/" },
              ...(biz.category_primary_name && biz.category_primary_slug ? [{ "@type": "ListItem", position: 2, name: biz.category_primary_name, item: `https://bestofutah.com/${biz.category_primary_slug}` }] : []),
              ...(biz.city_name && biz.category_primary_slug && biz.city_slug ? [{ "@type": "ListItem", position: 3, name: `${biz.category_primary_name} in ${biz.city_name}`, item: `https://bestofutah.com/${biz.category_primary_slug}/${biz.city_slug}` }] : []),
              { "@type": "ListItem", position: 4, name: biz.business_name, item: `https://bestofutah.com/${biz.category_primary_slug}/${biz.city_slug}/${biz.slug}` },
            ],
          })}
        </script>
      </Helmet>
      <SiteHeader />
      <TrendingBusinesses citySlug={biz?.city_slug ?? undefined} cityName={biz?.city_name ?? undefined} label={biz?.city_name ? `Buzzing in ${biz.city_name}` : "Buzzing Now"} />

      <main className="container mx-auto px-4 py-8">
        {/* Unclaimed Banner */}
        {isUnclaimed && (
          <div className="mb-6 rounded-xl border border-amber-500/30 bg-amber-500/5 p-4 flex flex-col sm:flex-row items-start sm:items-center gap-3">
            <div className="flex items-center gap-2 text-amber-600 dark:text-amber-400 shrink-0">
              <AlertTriangle className="h-5 w-5" />
              <span className="font-semibold text-sm">Unclaimed Listing</span>
            </div>
            <p className="text-sm text-muted-foreground flex-1">
              This business hasn't been claimed yet. Know the owner? Help them get found on BestofUtah.com!
            </p>
            <div className="flex gap-2 shrink-0">
              <Button size="sm" variant="outline" onClick={handleShareText} className="gap-1.5">
                <MessageSquare className="h-3.5 w-3.5" /> Text
              </Button>
              <BusinessContactDialog
                locationId={biz.id}
                businessName={biz.business_name}
                trigger={
                  <Button size="sm" variant="outline" className="gap-1.5">
                    <Mail className="h-3.5 w-3.5" /> Email
                  </Button>
                }
              />
              <Button size="sm" className="gap-1.5" onClick={() => setClaimModalOpen(true)}>
                <CheckCircle className="h-3.5 w-3.5" /> Claim Listing
              </Button>
            </div>
          </div>
        )}

        {/* Breadcrumb */}
        <div className="mb-6 flex flex-wrap items-center gap-1 text-sm text-muted-foreground">
          <Link to="/" className="hover:text-foreground">Home</Link>
          {biz.category_primary_name && biz.category_primary_slug && biz.category_primary_slug !== "uncategorized" && (
            <>
              <span>/</span>
              <Link to={`/${biz.category_primary_slug}`} className="hover:text-foreground">
                {biz.category_primary_name}
              </Link>
            </>
          )}
          {biz.city_name && biz.city_slug && (
            <>
              <span>/</span>
              <Link to={`/city/${biz.city_slug}`} className="hover:text-foreground">
                {biz.city_name}
              </Link>
            </>
          )}
          <span>/</span>
          <span className="text-foreground">{biz.business_name}</span>
        </div>

        {/* Profile Ad Slot — hidden for Preferred Partners */}
        <ProfileAdSlot
          locationId={biz.id}
          categorySlug={biz.category_primary_slug || ""}
          citySlug={biz.city_slug || ""}
          isPreferred={biz.preferred_status}
        />

        <div className="grid gap-8 lg:grid-cols-3">
          {/* Main Column */}
          <div className="lg:col-span-2 space-y-6">
            {/* Hero Card */}
            <Card className="border-border bg-card overflow-hidden">
              {biz.banner_logo_url && (
                <div className="aspect-[3/1] w-full bg-muted/40 flex items-center justify-center border-b border-border">
                  <img
                    src={biz.banner_logo_url}
                    alt={`${biz.business_name} banner`}
                    className="h-full w-full object-contain"
                    loading="eager"
                  />
                </div>
              )}
              <CardContent className="p-6 md:p-8">
                <div className="flex items-start gap-5">
                  <LazyImage
                    src={biz.logo_url}
                    alt={biz.business_name}
                    fallbackChar={biz.business_name.charAt(0).toUpperCase()}
                    containerClassName="flex h-20 w-20 shrink-0 items-center justify-center rounded-xl bg-muted text-3xl font-bold text-muted-foreground relative overflow-hidden"
                    className="h-full w-full rounded-xl object-cover"
                  />
                  <div className="min-w-0 flex-1">
                    <div className="flex flex-wrap items-center gap-2 mb-2">
                      <h1 className="text-2xl font-bold md:text-3xl">{biz.business_name}</h1>
                      {biz.preferred_status && (
                        <Badge className="bg-primary/15 text-primary border-primary/30">
                          <ShieldCheck className="mr-1 h-3 w-3" /> Preferred Verified Business
                        </Badge>
                      )}
                      {biz.verified_status === "verified" && (
                        <Badge variant="outline" className="border-success/50 text-success">
                          <CheckCircle className="mr-1 h-3 w-3" /> Verified Owner
                        </Badge>
                      )}
                    </div>
                    <div className="flex flex-wrap items-center gap-2">
                      <p className="text-sm text-muted-foreground">{biz.category_primary_name} · {biz.city_name}</p>
                      <CalculatorIconRow categorySlug={biz.category_primary_slug} />
                    </div>
                    <div className="mt-3 flex flex-wrap items-center gap-2">
                      <TrustIndicator businessId={biz.id} size="md" hideIfEmpty={false} showProgress />
                    </div>
                  </div>
                </div>

                <p className="mt-5 text-muted-foreground leading-relaxed">{displayDesc}</p>

                {/* Action Buttons */}
                <div className="mt-6 flex flex-wrap gap-3">
                  {biz.phone && (
                    <PhoneLink phone={biz.phone}>
                      <Button variant="secondary" size="sm"><Phone className="mr-1 h-4 w-4" /> Call</Button>
                    </PhoneLink>
                  )}
                  {biz.website && (
                    <a href={brandUrl(biz.website)} target="_blank" rel="noopener noreferrer">
                      <Button variant="secondary" size="sm"><Globe className="mr-1 h-4 w-4" /> Website <ExternalLink className="ml-1 h-3 w-3" /></Button>
                    </a>
                  )}
                  <BusinessContactDialog
                    locationId={biz.id}
                    businessName={biz.business_name}
                    cityId={(biz as any).city_id ?? null}
                    categoryId={(biz as any).category_primary_id ?? null}
                    trigger={
                      <Button variant="secondary" size="sm">
                        <Mail className="mr-1 h-4 w-4" /> Contact
                      </Button>
                    }
                  />
                  {biz.booking_link && (
                    <a href={biz.booking_link} target="_blank" rel="noopener noreferrer">
                      <Button size="sm"><Calendar className="mr-1 h-4 w-4" /> Book Now</Button>
                    </a>
                  )}
                  {isUnclaimed && (
                    <>
                      <Button variant="outline" size="sm" onClick={() => setShowSuggestForm(!showSuggestForm)} className="gap-1.5">
                        <Pencil className="h-3.5 w-3.5" /> Suggest an Edit
                      </Button>
                      <Button variant="outline" size="sm" onClick={handleShareEmail} className="gap-1.5">
                        <Mail className="h-3.5 w-3.5" /> Share with Owner
                      </Button>
                    </>
                  )}
                  <ListingEngagementButton locationId={biz.id} businessType={businessType} />
                  <ListingSaveButton locationId={biz.id} />
                </div>
              </CardContent>
            </Card>

            {/* Suggest an Edit Form */}
            {showSuggestForm && (
              <Card className="border-border bg-card">
                <CardHeader>
                  <CardTitle className="text-base flex items-center gap-2">
                    <Pencil className="h-4 w-4 text-primary" /> Suggest an Edit
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <p className="text-sm text-muted-foreground mb-4">
                    See something wrong? Help us keep BestofUtah.com accurate by suggesting a correction.
                  </p>
                  <form onSubmit={handleSuggestEdit} className="space-y-3">
                    <div className="grid gap-3 sm:grid-cols-2">
                      <Input
                        placeholder="Your name"
                        required
                        value={suggestForm.name}
                        onChange={e => setSuggestForm(f => ({ ...f, name: e.target.value }))}
                        className="bg-muted border-border"
                      />
                      <Input
                        placeholder="Your email"
                        type="email"
                        required
                        value={suggestForm.email}
                        onChange={e => setSuggestForm(f => ({ ...f, email: e.target.value }))}
                        className="bg-muted border-border"
                      />
                    </div>
                    <Select value={suggestForm.field} onValueChange={val => setSuggestForm(f => ({ ...f, field: val }))}>
                      <SelectTrigger className="bg-muted border-border">
                        <SelectValue placeholder="What needs updating?" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="phone">Phone Number</SelectItem>
                        <SelectItem value="address">Address</SelectItem>
                        <SelectItem value="hours">Business Hours</SelectItem>
                        <SelectItem value="website">Website</SelectItem>
                        <SelectItem value="name">Business Name</SelectItem>
                        <SelectItem value="closed">Business is Closed</SelectItem>
                        <SelectItem value="other">Other</SelectItem>
                      </SelectContent>
                    </Select>
                    <Input
                      placeholder="Correct information"
                      required
                      value={suggestForm.value}
                      onChange={e => setSuggestForm(f => ({ ...f, value: e.target.value }))}
                      className="bg-muted border-border"
                    />
                    <Textarea
                      placeholder="Additional notes (optional)"
                      rows={2}
                      value={suggestForm.notes}
                      onChange={e => setSuggestForm(f => ({ ...f, notes: e.target.value }))}
                      className="bg-muted border-border"
                    />
                    <div className="flex gap-2">
                      <Button type="submit" size="sm" disabled={suggestSubmitting}>
                        {suggestSubmitting ? "Submitting..." : "Submit Suggestion"}
                      </Button>
                      <Button type="button" variant="ghost" size="sm" onClick={() => setShowSuggestForm(false)}>
                        Cancel
                      </Button>
                    </div>
                  </form>
                </CardContent>
              </Card>
            )}

            {/* Services List */}
            <BusinessServicesList
              locationId={biz.id}
              primaryCategoryName={biz.category_primary_name}
              primaryCategorySlug={biz.category_primary_slug}
              citySlug={biz.city_slug}
            />

            {/* Media Showcase — Preferred Partners only */}
            {biz.preferred_status && biz.video ? (
              <Card className="border-border bg-card overflow-hidden">
                <CardHeader>
                  <CardTitle className="text-base flex items-center gap-2">
                    <Video className="h-4 w-4 text-primary" /> Video Showcase
                  </CardTitle>
                </CardHeader>
                <CardContent className="p-0">
                  <div className="aspect-video w-full">
                    <iframe
                      src={biz.video.replace("watch?v=", "embed/").split("&")[0]}
                      title={`${biz.business_name} video`}
                      className="h-full w-full border-0"
                      allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                      allowFullScreen
                      loading="lazy"
                    />
                  </div>
                </CardContent>
              </Card>
            ) : !biz.preferred_status ? (
              <Card className="border-dashed border-2 border-primary/20 bg-primary/[0.02]">
                <CardContent className="p-6 text-center">
                  <div className="flex flex-col items-center gap-3">
                    <div className="flex items-center gap-4 text-muted-foreground/50">
                      <Video className="h-8 w-8" />
                      <span className="text-2xl font-light text-muted-foreground/30">+</span>
                      <svg xmlns="http://www.w3.org/2000/svg" className="h-8 w-8" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/></svg>
                    </div>
                    <div>
                      <p className="text-sm font-semibold text-foreground">Video & Photo Gallery</p>
                      <p className="text-xs text-muted-foreground mt-1 max-w-sm mx-auto">
                        Preferred Partners can showcase a YouTube video and photo gallery to make their listing stand out.
                      </p>
                    </div>
                    <Badge className="bg-primary/15 text-primary border-primary/30 text-xs">
                      <Star className="mr-1 h-3 w-3" /> Preferred Partner Feature
                    </Badge>
                  </div>
                </CardContent>
              </Card>
            ) : null}

            {/* Photo Gallery — Preferred Partners only */}
            {biz.preferred_status && biz.post_images && Array.isArray(biz.post_images) && (biz.post_images as string[]).length > 0 && (
              <Card className="border-border bg-card overflow-hidden">
                <CardHeader>
                  <CardTitle className="text-base flex items-center gap-2">
                    <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 text-primary" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/></svg>
                    Photo Gallery
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="grid grid-cols-2 md:grid-cols-3 gap-3">
                    {(biz.post_images as string[]).slice(0, 6).map((img, i) => (
                      <div key={i} className="aspect-square rounded-lg overflow-hidden bg-muted">
                        <img src={img as string} alt={`${biz.business_name} photo ${i + 1}`} className="h-full w-full object-cover" loading="lazy" />
                      </div>
                    ))}
                  </div>
                </CardContent>
              </Card>
            )}


            {/* Map */}
            {mapSrc && (
              <Card className="border-border bg-card overflow-hidden">
                <CardHeader className="pb-0">
                  <CardTitle className="text-base flex items-center gap-2">
                    <MapPin className="h-4 w-4 text-primary" />
                    {addressHidden ? "Service Area" : "Location"}
                  </CardTitle>
                </CardHeader>
                <CardContent className="p-0 mt-4">
                  <iframe title="Business location" src={mapSrc} className="h-64 w-full border-0" loading="lazy" />
                  <div className="px-6 py-3 text-sm text-muted-foreground">
                    {addressHidden ? (
                      <span>🌐 Online business serving <strong className="text-foreground">{biz.city_name}, Utah</strong> and surrounding areas. Exact address not shown.</span>
                    ) : (
                      fullAddress
                    )}
                  </div>
                </CardContent>
              </Card>
            )}

            {/* Business Hours */}
            {hours && Object.keys(hours).length > 0 && (() => {
              const is24x7 = (h: string | undefined) => {
                if (!h) return false;
                const v = h.replace(/\s+/g, "").toLowerCase();
                return v === "00:00-23:59" || v === "00:00-24:00" || v === "0:00-23:59" || v === "24hours" || v === "24/7" || v === "open24hours";
              };
              const allDays247 = DAYS.every((d) => is24x7(hours[d]));
              return (
                <Card className="border-border bg-card">
                  <CardHeader>
                    <CardTitle className="text-base flex items-center gap-2">
                      <Clock className="h-4 w-4 text-primary" /> Business Hours
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    {allDays247 ? (
                      <p className="text-sm font-medium text-success">Open 24 hours · 7 days a week</p>
                    ) : (
                      <div className="space-y-2">
                        {DAYS.map((day) => (
                          <div key={day} className="flex justify-between text-sm">
                            <span className="font-medium">{day}</span>
                            <span className="text-muted-foreground">
                              {is24x7(hours[day]) ? "Open 24 hours" : hours[day] || "Closed"}
                            </span>
                          </div>
                        ))}
                      </div>
                    )}
                  </CardContent>
                </Card>
              );
            })()}
          </div>

          {/* Sidebar */}
          <div className="space-y-6">
            <CalculatorSidebarCard categorySlug={biz.category_primary_slug} />
            {/* Contact Info */}
            <Card className="border-border bg-card">
              <CardHeader>
                <CardTitle className="text-base">{biz.business_name}</CardTitle>
              </CardHeader>
              <CardContent className="space-y-3 text-sm">
                {fullAddress && (
                  <div className="flex items-start gap-2">
                    <MapPin className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
                    <span>
                      {addressHidden && <span className="mr-1">🌐</span>}
                      {fullAddress}
                      {addressHidden && <span className="block text-xs italic mt-0.5">Online business — exact address not public</span>}
                    </span>
                  </div>
                )}
                {biz.phone && (
                  <div className="flex items-center gap-2">
                    <Phone className="h-4 w-4 text-muted-foreground" />
                    <PhoneLink phone={biz.phone} className="hover:text-primary">{biz.phone}</PhoneLink>
                  </div>
                )}
                <div className="flex items-center gap-2">
                  <Mail className="h-4 w-4 text-muted-foreground" />
                  <BusinessContactDialog
                    locationId={biz.id}
                    businessName={biz.business_name}
                    cityId={(biz as any).city_id ?? null}
                    categoryId={(biz as any).category_primary_id ?? null}
                    trigger={
                      <button type="button" className="hover:text-primary text-left">
                        Send a message
                      </button>
                    }
                  />
                </div>
                {biz.website && (
                  <div className="flex items-center gap-2">
                    <Globe className="h-4 w-4 text-muted-foreground" />
                    <a href={brandUrl(biz.website)} target="_blank" rel="noopener noreferrer" className="hover:text-primary truncate">
                      {displayUrl(biz.website)}
                    </a>
                  </div>
                )}
                {socialLinks.length > 0 && (
                  <div className="flex gap-3 pt-1">
                    {socialLinks.map(({ url, icon: Icon, label }) => (
                      <a
                        key={label}
                        href={url!}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="flex h-8 w-8 items-center justify-center rounded-lg bg-muted text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
                        aria-label={label}
                      >
                        <Icon className="h-4 w-4" />
                      </a>
                    ))}
                  </div>
                )}
              </CardContent>
            </Card>


            {/* Lead capture for unclaimed listings moved to floating bubble (LeadCaptureBubble) */}

            {/* Share with Owner CTA (sidebar) */}
            {isUnclaimed && (
              <Card className="border-amber-500/30 bg-amber-500/5">
                <CardContent className="p-5">
                  <div className="flex items-center gap-2 mb-3">
                    <Share2 className="h-5 w-5 text-amber-600 dark:text-amber-400" />
                    <h3 className="font-semibold text-sm">Know the owner?</h3>
                  </div>
                  <p className="text-sm text-muted-foreground mb-3">
                    Help {biz.business_name} get found! Share this listing so they can claim their free profile on BestofUtah.com.
                  </p>
                  <div className="flex flex-col gap-2">
                    <Button size="sm" variant="outline" onClick={handleShareText} className="w-full gap-1.5">
                      <MessageSquare className="h-3.5 w-3.5" /> Send a Text
                    </Button>
                    <Button size="sm" variant="outline" onClick={handleShareEmail} className="w-full gap-1.5">
                      <Mail className="h-3.5 w-3.5" /> Send an Email
                    </Button>
                  </div>
                </CardContent>
              </Card>
            )}

            {/* Affiliate Offers — hidden for Preferred Partners */}
            {!biz.preferred_status && (
              <AffiliateAdSlot
                placements={[biz.category_primary_slug || "global", "profile-sidebar", "global"]}
                limit={3}
                className="mt-2"
              />
            )}

            {/* Verification Badge Guide (verified only; unclaimed uses modal via header CTA) */}
            {biz.verified_status === "verified" && (
              <div id="claim-section">
                <VerificationBadgeGuide businessId={biz.id} />
              </div>
            )}
          </div>
        </div>

        {/* What's Happening Nearby */}
        {biz.city_slug && (
          <NewsSection
            title="What's Happening Nearby"
            citySlug={biz.city_slug}
            categoryTags={biz.category_primary_slug ? [biz.category_primary_slug] : undefined}
            limit={3}
            maxAgeHours={120}
            className="mb-8"
          />
        )}

        {/* Events Nearby */}
        <EventsSection
          title={`Events in ${biz.city_name || "Utah"}`}
          cityName={biz.city_name || undefined}
          keywords={biz.category_primary_slug ? (CATEGORY_NEWS_KEYWORDS[biz.category_primary_slug] || [biz.category_primary_name?.toLowerCase() || ""]) : undefined}
          statewide={!biz.category_primary_slug}
        />

        {/* Related Links & Service Area */}
        {biz.category_primary_slug && biz.city_slug && (
          <BusinessRelatedLinks
            categorySlug={biz.category_primary_slug}
            categoryName={biz.category_primary_name || ""}
            citySlug={biz.city_slug}
            cityName={biz.city_name || ""}
            businessId={biz.id}
          />
        )}
      </main>

      {biz && (
        <ClaimListingModal
          open={claimModalOpen}
          onOpenChange={setClaimModalOpen}
          locationId={biz.id}
          businessName={biz.business_name}
        />
      )}

      <Footer />
      {isUnclaimed && (
        <StickyLeadCTA headline={`Need a verified ${biz.category_primary_name?.toLowerCase() || "local"} in ${biz.city_name || "Utah"}?`} />
      )}
    </div>
  );
};

export default BusinessProfile;
