import { Button } from "@/components/ui/button";
import { createBreadcrumbSchema, createFAQSchema, updateMetaTags, createStructuredData } from "@/lib/seo";
import { trackWorkshopView, trackBookingCTAClick } from "@/lib/ga";
import { trpc } from "@/lib/trpc";
import { useLocation, useParams } from "wouter";
import { useState, useRef, useEffect, lazy, Suspense } from "react";
import {
  ChevronLeft, ChevronRight, Clock, Users, AlertCircle,
  CheckCircle2, ChevronDown, ArrowLeft, Star, Eye, EyeOff,
  Heart, Shield, ZoomIn, X, Sparkles, MapPin, Lock, Home
} from "lucide-react";
import type { BookingFormData } from "@/components/BookingModal";
const BookingModal = lazy(() => import("@/components/BookingModal"));
import { Navbar } from "@/components/Navbar";
import { ShareButton } from "@/components/ShareButton";
import { Footer } from "@/components/Footer";
import { Breadcrumb } from "@/components/Breadcrumb";
import { ProgressiveImage } from "@/components/ProgressiveImage";
import { useLanguage } from "@/contexts/LanguageContext";
import { WorkshopDetailSkeleton } from "@/components/HydrationSkeletons";
import { useHydrationTransition } from "@/hooks/useHydrationTransition";

function difficultyLabel(d?: string, lang?: string) {
  if (lang === 'en') {
    if (d === "beginner") return "Beginner-Friendly";
    if (d === "intermediate") return "Intermediate";
    return "Advanced";
  }
  if (d === "beginner") return "初學友好";
  if (d === "intermediate") return "中級";
  return "進階";
}
function difficultyColor(d?: string) {
  if (d === "beginner") return "bg-emerald-50 text-emerald-700 border-emerald-200";
  if (d === "intermediate") return "bg-amber-50 text-amber-700 border-amber-200";
  return "bg-rose-50 text-rose-700 border-rose-200";
}

function BookingCard({
  workshopId, price, duration, maxParticipants, difficulty, onBook, onContact,
  variants: variantsProp, monthlyCount: monthlyCountProp,
}: {
  workshopId: number; price: number; duration: number; maxParticipants: number; difficulty?: string;
  onBook: () => void; onContact: () => void;
  variants?: { price: number }[] | null;
  monthlyCount?: number | null;
}) {
  const { t, language } = useLanguage();
  const isEn = language === 'en';
  const monthlyCount = monthlyCountProp;
  const variants = variantsProp;
  const hasVariants = variants && variants.length > 0;
  const minPrice = hasVariants ? Math.min(...variants!.map(v => v.price)) : price;
  const maxPrice = hasVariants ? Math.max(...variants!.map(v => v.price)) : price;
  const priceDisplay = hasVariants && minPrice !== maxPrice
    ? `HK$${(minPrice / 100).toFixed(0)} – ${(maxPrice / 100).toFixed(0)}`
    : `HK$${(minPrice / 100).toFixed(0)}`;
  return (
    <div className="rounded-2xl overflow-hidden shadow-xl border border-[#e8e8e8]">
      {/* Price header */}
      <div className="bg-[#0a0a0a] text-white px-6 py-6">
        <p className="text-[11px] text-white/40 mb-1 tracking-widest uppercase">{isEn ? 'Couple Exclusive Price' : '情侶專屬價格'}</p>
        <div className="flex items-baseline gap-1">
          <p className="text-4xl font-bold tracking-tight" style={{color:'#e6e6e6'}}>{priceDisplay}</p>
          <span className="text-white/50 text-sm">{t('workshopDetail.perPerson')}</span>
        </div>
        {hasVariants && (
          <p className="text-[11px] text-white/50 mt-1">{isEn ? 'Price varies by size option' : '價格根據規格選項而异'}</p>
        )}
        <div className="mt-3 flex items-center gap-1.5 bg-white/10 rounded-full px-3 py-1.5 w-fit">
          <Heart className="w-3 h-3 text-rose-400 fill-rose-400" />
          <span className="text-[11px] text-white/80 font-medium">{isEn ? '1 couple per session — fully private' : '每時段僅限 1 對情侶，全程私人包場'}</span>
        </div>
      </div>

      {/* Stats row */}
      <div className="grid grid-cols-3 divide-x divide-[#f0f0f0] border-b border-[#f0f0f0] bg-white">
        <div className="flex flex-col items-center py-4 px-2">
          <Clock className="w-4 h-4 text-[#9a9a9a] mb-1" />
          <p className="text-[10px] text-[#9a9a9a] uppercase tracking-wide">{t('workshopDetail.duration')}</p>
          <p className="text-sm font-bold text-[#1a1a1a] mt-0.5">{Math.round(duration / 60)}h</p>
        </div>
        <div className="flex flex-col items-center py-4 px-2">
          <Users className="w-4 h-4 text-[#9a9a9a] mb-1" />
          <p className="text-[10px] text-[#9a9a9a] uppercase tracking-wide">{t('workshopDetail.participants')}</p>
          <p className="text-sm font-bold text-[#1a1a1a] mt-0.5">{isEn ? '2 ppl' : '2 人'}</p>
        </div>
        <div className="flex flex-col items-center py-4 px-2">
          <Star className="w-4 h-4 text-amber-400 mb-1" />
          <p className="text-[10px] text-[#9a9a9a] uppercase tracking-wide">{isEn ? 'Rating' : '評分'}</p>
          <p className="text-sm font-bold text-[#1a1a1a] mt-0.5">4.9</p>
        </div>
      </div>

      {/* Inclusions checklist */}
      <div className="bg-[#fafafa] px-5 py-4 border-b border-[#f0f0f0] space-y-2.5">
        {(isEn ? [
          "All materials included",
          "1-on-1 instructor guidance",
          "Take your artwork home same day",
          "Private studio space",
        ] : [
          "全程材料費用已包含",
          "專業導師一對一指導",
          "完成品即日帶走",
          "私人專屬工作室空間",
        ]).map((t) => (
          <div key={t} className="flex items-center gap-2.5 text-sm text-[#3d3d3d]">
            <div className="w-4 h-4 rounded-full bg-[#0a0a0a] flex items-center justify-center shrink-0">
              <CheckCircle2 className="w-2.5 h-2.5 text-white" />
            </div>
            {t}
          </div>
        ))}
      </div>

      {/* CTA buttons */}
      <div className="px-5 pt-5 pb-3 space-y-3 bg-white">
        <Button
          className="w-full bg-[#0a0a0a] text-white hover:bg-[#0a0a0a]/85 h-13 text-base font-semibold rounded-xl shadow-lg shadow-black/10 active:scale-[0.98] transition-transform"
          onClick={onBook}
        >
          <Heart className="w-4 h-4 mr-2 fill-white" />
          {t('workshopDetail.bookingCTA')}
        </Button>
        <Button
          variant="outline"
          className="w-full border-[#e0e0e0] text-[#3d3d3d] hover:bg-[#f5f5f5] hover:border-[#c0c0c0] h-11 rounded-xl"
          onClick={onContact}
        >
          {isEn ? 'Ask a Question' : '詢問更多資訊'}
        </Button>
      </div>

      {/* Trust signal */}
      <div className="px-5 pb-3 bg-white">
        <div className="flex items-center justify-center gap-1.5 text-[11px] text-[#9a9a9a]">
          <Lock className="w-3 h-3" />
          <span>{t('workshopDetail.trustBadge')}</span>
        </div>
      </div>

      {/* Social proof */}
      <div className="px-5 pb-5 bg-white">
        <div className="flex items-center gap-2.5 bg-[#f5f5f5] rounded-xl px-4 py-3">
          <Shield className="w-4 h-4 text-[#9a9a9a] shrink-0" />
          <p className="text-[12px] text-[#7a7a7a] leading-snug">
            {isEn ? <><strong className="text-[#1a1a1a]">{monthlyCount ?? 42} couples</strong> booked this month</> : <>本月已有 <strong className="text-[#1a1a1a]">{monthlyCount ?? 42} 對情侶</strong> 完成預約</>}
          </p>
        </div>
      </div>

      {/* Difficulty badge */}
      <div className="px-5 pb-5 bg-white border-t border-[#f0f0f0] pt-4">
        <span className={`inline-flex items-center gap-1.5 text-xs font-semibold px-3 py-1.5 rounded-full border ${difficultyColor(difficulty)}`}>
          <Sparkles className="w-3 h-3" />
          {isEn ? 'Level' : '難度'}：{difficultyLabel(difficulty, language)}
        </span>
      </div>
    </div>
  );
}

export default function WorkshopDetail() {
  const { slug } = useParams<{ slug: string }>();
  const [, navigate] = useLocation();
  const { t, language } = useLanguage();
  const isEn = language === 'en';
  const [currentImageIndex, setCurrentImageIndex] = useState(0);
  const [expandedFaq, setExpandedFaq] = useState<number | null>(null);
  const [showIncludedDesc, setShowIncludedDesc] = useState(true);
  const [isBookingModalOpen, setIsBookingModalOpen] = useState(false);

  const createBookingMutation = trpc.bookings.create.useMutation({
    onSuccess: () => {
      setIsBookingModalOpen(false);
    },
  });
  const handleBookingSubmit = (data: BookingFormData) => {
    createBookingMutation.mutate({
      workshopId: data.workshopId,
      customerName: data.customerName,
      customerEmail: data.customerEmail,
      customerPhone: data.customerPhone,
      customerWhatsApp: data.customerWhatsApp,
      participantCount: data.participantCount,
      participantNames: data.participantNames,
      bookingDate: new Date(data.bookingDate),
      bookingTime: data.bookingTime || undefined,
      specialRequests: data.specialRequests || undefined,
      totalPrice: (workshop?.price ?? 0) * data.participantCount,
    });
  };
  const [heroLoaded, setHeroLoaded] = useState(false);
  const touchStartX = useRef<number | null>(null);
  const bookingCardRef = useRef<HTMLElement | null>(null);
  const [lightboxIndex, setLightboxIndex] = useState<number | null>(null);

  const handleBookClick = () => {
    trackBookingCTAClick(workshop?.title);
    const isDesktop = window.innerWidth >= 1024;
    if (isDesktop && bookingCardRef.current) {
      bookingCardRef.current.scrollIntoView({ behavior: 'smooth', block: 'center' });
    } else {
      setIsBookingModalOpen(true);
    }
  };

  const { initialData } = useHydrationTransition();
  // SSR pre-populates workshop detail — no loading state on first render
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const ssrDetailData: any = (initialData?.page === "workshopDetail" && initialData.workshop?.slug === slug) ? {
    workshop: initialData.workshop,
    variants: initialData.variants ?? [],
    gallery: initialData.workshopGallery ?? [],
    monthlyCount: initialData.monthlyCount ?? null,
  } : undefined;

  // Single batch query: replaces getBySlug + getVariants (×2) + workshopGallery.list + urgency.monthlyCount
  // Eliminates the waterfall (getBySlug → wait → getVariants + gallery) and the duplicate getVariants call.
  const detailQuery = trpc.workshopDetail.bySlug.useQuery(
    { slug: slug || "" },
    {
      staleTime: 5 * 60 * 1000, // 5 min cache — workshop data changes infrequently
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      initialData: ssrDetailData,
      initialDataUpdatedAt: ssrDetailData ? Date.now() - 30_000 : undefined,
    }
  );
  const workshop = detailQuery.data?.workshop;
  const galleryImages = detailQuery.data?.gallery;
  const pageVariants = detailQuery.data?.variants;
  const detailMonthlyCount = detailQuery.data?.monthlyCount;
  const hasPageVariants = pageVariants && pageVariants.length > 0;
  const workshopQuery = detailQuery; // keep alias for isLoading/isError checks below

  // Track workshop view once data is loaded
  useEffect(() => {
    if (workshop) {
      trackWorkshopView(workshop.title, workshop.slug ?? String(workshop.id));
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [workshop?.id]);

  // Auto-open booking modal when ?book=1 is present in the URL.
  // Waits until workshop data is loaded so the modal has the correct workshop info.
  // Removes the query param after opening to keep the address bar clean.
  useEffect(() => {
    if (!workshop) return;
    const params = new URLSearchParams(window.location.search);
    if (params.get('book') === '1') {
      setIsBookingModalOpen(true);
      // Strip the query param without triggering a navigation / re-render
      window.history.replaceState({}, '', window.location.pathname);
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [workshop?.id]);

  // Safe JSON parser: returns fallback if value is plain text or invalid JSON
  function safeParseJson<T>(val: string | null | undefined, fallback: T): T {
    if (!val) return fallback;
    try {
      return JSON.parse(val) as T;
    } catch {
      return [val] as unknown as T;
    }
  }

  const heroImages: string[] = safeParseJson<string[]>(workshop?.heroImages, []);

  const nextImage = () => setCurrentImageIndex((p) => (p + 1) % (heroImages.length || 1));
  const prevImage = () => setCurrentImageIndex((p) => (p - 1 + (heroImages.length || 1)) % (heroImages.length || 1));

  useEffect(() => {
    const handler = (e: KeyboardEvent) => {
      if (!heroImages.length) return;
      if (e.key === "ArrowLeft") prevImage();
      if (e.key === "ArrowRight") nextImage();
    };
    window.addEventListener("keydown", handler);
    return () => window.removeEventListener("keydown", handler);
  });

  const handleTouchStart = (e: React.TouchEvent) => { touchStartX.current = e.touches[0].clientX; };
  const handleTouchEnd = (e: React.TouchEvent) => {
    if (touchStartX.current === null) return;
    const diff = touchStartX.current - e.changedTouches[0].clientX;
    if (Math.abs(diff) > 40) diff > 0 ? nextImage() : prevImage();
    touchStartX.current = null;
  };

  // ── SEO variables (computed before early returns to satisfy Rules of Hooks) ──
  // All variables use optional chaining so they are safe when workshop is null/undefined.
  const whatYouMake_seo: string[] = safeParseJson<string[]>(workshop?.whatYouMake, []);
  const rawIncluded_seo: (string | { label: string; description?: string })[] = safeParseJson<(string | { label: string; description?: string })[]>(workshop?.whatIncluded, []);
  const whatIncluded_seo: { label: string; description?: string }[] = rawIncluded_seo.map((item) =>
    typeof item === 'string' ? { label: item } : item
  );
  const classFlow_seo: { text: string; imageUrl?: string }[] = safeParseJson<(string | { text: string; imageUrl?: string })[]>(workshop?.classFlow, []).map(
    (item) => typeof item === 'string' ? { text: item } : { text: item.text ?? '', imageUrl: item.imageUrl }
  );
  const faqData_seo: { question: string; answer: string }[] = safeParseJson<{ question: string; answer: string }[]>(workshop?.faq, []);

  const isTufting_seo = !!(workshop?.slug?.toLowerCase().includes('tufting') ||
    workshop?.title?.toLowerCase().includes('tufting') ||
    workshop?.category?.toLowerCase().includes('tufting'));
  const isSilver_seo = !!(workshop?.slug?.toLowerCase().includes('ring') ||
    workshop?.slug?.toLowerCase().includes('silver') ||
    workshop?.title?.toLowerCase().includes('銀') ||
    workshop?.title?.toLowerCase().includes('戒'));

  const pageTitle_seo = isEn
    ? isTufting_seo
      ? `Tufting Workshop HK — Couple Private Session | Zoneout`
       : isSilver_seo
       ? `Couple Silver Ring Workshop Hong Kong — Anniversary Date Idea | Zoneout Studio`
       : `${workshop?.title ?? ''} | Zoneout Studio Hong Kong Couple Handcraft Workshop`
     : isTufting_seo
     ? `Tufting 工作坊香港 — 情侶私人包場首選 | Zoneout Studio`
    : isSilver_seo
    ? `情侶銀戒指製作 香港 — 拍拖好去處 · 紀念日首選 | Zoneout Studio`
    : `${workshop?.title ?? ''} | Zoneout Studio 香港情侶手作工作坊 · 拍拖好去處`;

  const priceHKD_seo = ((workshop?.price ?? 0) / 100).toFixed(0);

  const pageDescription_seo = isEn
    ? isTufting_seo
       ? `Hong Kong Tufting DIY Workshop in San Po Kong — top couple date idea, birthday gift & creative experience. Make your own tufted rug with Tufting Gun, fully private session (no strangers), instructor-guided, take it home same day. From HK$${priceHKD_seo}. Book now at Zoneout Studio.`
      : isSilver_seo
      ? `Hong Kong couple silver ring workshop — top date idea. Craft a unique sterling silver ring for each other, fully private session, instructor-guided, take home same day. From HK$${priceHKD_seo}.`
      : workshop?.description
        ? `${workshop.description.slice(0, 155)}…`
        : `Experience ${workshop?.title ?? ''} at Zoneout Studio — Hong Kong's private couple handcraft workshop. Fully instructor-guided, all materials included, take your creation home same day.`
    : isTufting_seo
     ? `香港 Tufting DIY Workshop | 新蒲崗 Zoneout Studio — 情侶好去處、拍拖好去處首選。使用 Tufting Gun 親手製作簇絨地毯，全程私人包場（不與陌生人同場），導師手把手指導，完成品即日帶走。HK$${priceHKD_seo} 起，立即預約。`
    : isSilver_seo
    ? `香港情侶銀戒指製作工作坊，拍拖好去處首選。親手為對方打造獨一無二的純銀戒指，全程私人包場，導師手把手指導，完成品即日帶走。HK$${priceHKD_seo} 起。`
    : workshop?.description
      ? `${workshop.description.slice(0, 155)}…`
      : `在 Zoneout Studio 體驗 ${workshop?.title ?? ''}，香港私人情侶手作工作坊，拍拖好去處首選，全程導師指導，材料費用全包，完成品即日帶走。`;

   // SSR keywords (max 8)
   const pageKeywords_seo = isTufting_seo
     ? `tufting hk, tufting 工作坊, 情侶工作坊, 拍拖好去處, 私人包場, 簇絨工作坊, 香港手作, Zoneout Studio`
    : isSilver_seo
    ? `情侶銀戒指, 銀戒指工作坊, 拍拖好去處, 情侶工作坊, 私人包場, 香港手作, 紀念日禮物, Zoneout Studio`
    : `${workshop?.title ?? ''}, 香港手作工作坊, 情侶工作坊, 拍拖好去處, 私人包場, Zoneout Studio, 新蒲崗手作`;

  const pageUrl_seo = `https://zoneout-workshop.com/workshops/${workshop?.slug ?? ''}`;
  const SITE_ORIGIN_seo = "https://zoneout-workshop.com";
  const rawOgImage_seo = heroImages[0] ?? workshop?.imageUrl ?? null;
  const ogImage_seo = rawOgImage_seo
    ? rawOgImage_seo.startsWith('http') ? rawOgImage_seo : `${SITE_ORIGIN_seo}${rawOgImage_seo}`
    : `${SITE_ORIGIN_seo}/og-default.jpg`;
  const ogImageAlt_seo = isEn ? `${workshop?.title ?? ''} — Zoneout Studio Hong Kong Handcraft Workshop` : `${workshop?.title ?? ''} — Zoneout Studio 香港手作工作坊`;

  const studioAddress_seo = {
    "@type": "PostalAddress",
    streetAddress: "同德工業大廈 8 樓",
    addressLocality: "新蒲崗",
    addressRegion: "香港",
    addressCountry: "HK",
    postalCode: "000000",
  };

  const studioOrganization_seo = {
    "@type": "LocalBusiness",
    "@id": "https://zoneout-workshop.com/#organization",
    name: "Zoneout Studio",
    alternateName: "Zoneout 香港手作工作室",
    description: "香港拍拖好去處首選 — 情侶手作工作坊，提供 Tufting、銀飾、陶藝等私人包場體驗",
    url: "https://zoneout-workshop.com",
    logo: "https://zoneout-workshop.com/manus-storage/zoneout-logo_3b4efa7e.webp",
    image: heroImages.length > 0 ? heroImages[0] : ogImage_seo,
    telephone: "+852-9554-8808",
    email: "info@zoneout-workshop.com",
    priceRange: "$$",
    currenciesAccepted: "HKD",
    paymentAccepted: "Cash, Credit Card, PayMe, FPS",
    address: studioAddress_seo,
    geo: { "@type": "GeoCoordinates", latitude: "22.3358", longitude: "114.2003" },
    hasMap: "https://maps.google.com/?q=22.3358,114.2003",
    openingHoursSpecification: [
      { "@type": "OpeningHoursSpecification", dayOfWeek: ["Monday","Tuesday","Wednesday","Thursday","Friday"], opens: "12:00", closes: "21:00" },
      { "@type": "OpeningHoursSpecification", dayOfWeek: ["Saturday","Sunday"], opens: "10:00", closes: "21:00" },
    ],
    amenityFeature: [
      { "@type": "LocationFeatureSpecification", name: "私人包場工作室", value: true },
      { "@type": "LocationFeatureSpecification", name: "全程導師指導", value: true },
      { "@type": "LocationFeatureSpecification", name: "材料費用全包", value: true },
      { "@type": "LocationFeatureSpecification", name: "完成品即日帶走", value: true },
    ],
    aggregateRating: { "@type": "AggregateRating", ratingValue: "4.9", reviewCount: "50", bestRating: "5", worstRating: "1" },
    sameAs: ["https://www.instagram.com/zoneout_hk", "https://www.facebook.com/zohkstudio"],
  };

  const productJsonLd_seo = {
    "@context": "https://schema.org",
    "@type": "Product",
    "@id": `${pageUrl_seo}#product`,
    name: workshop?.title ?? '',
    description: pageDescription_seo,
    url: pageUrl_seo,
    image: heroImages.length > 0 ? heroImages : [ogImage_seo],
    keywords: pageKeywords_seo,
    sku: `ZO-${workshop?.id ?? 0}-${workshop?.slug ?? ''}`,
    category: isTufting_seo ? "Tufting 工作坊" : isSilver_seo ? "銀飾工作坊" : "手作工作坊",
    brand: { "@type": "Brand", name: "Zoneout Studio" },
    additionalProperty: [
      { "@type": "PropertyValue", name: "時長", value: `${Math.round((workshop?.duration ?? 0) / 60)} 小時` },
      { "@type": "PropertyValue", name: "人數", value: `最多 ${workshop?.maxParticipants ?? 0} 人` },
      { "@type": "PropertyValue", name: "難度", value: workshop?.difficulty === 'beginner' ? '初學友好' : workshop?.difficulty === 'intermediate' ? '中級' : '進階' },
      { "@type": "PropertyValue", name: "地點", value: "香港新蒲崗" },
      { "@type": "PropertyValue", name: "包場形式", value: "私人專屬包場" },
    ],
    offers: {
      "@type": "Offer",
      priceCurrency: "HKD",
      price: priceHKD_seo,
      availability: "https://schema.org/InStock",
      url: pageUrl_seo,
      validFrom: "2025-01-01",
      priceValidUntil: "2026-12-31",
      seller: studioOrganization_seo,
    },
    aggregateRating: { "@type": "AggregateRating", ratingValue: "4.9", reviewCount: "50", bestRating: "5", worstRating: "1" },
    review: [
      {
        "@type": "Review",
        reviewRating: { "@type": "Rating", ratingValue: "5", bestRating: "5" },
        author: { "@type": "Person", name: "Mandy & Jason" },
        reviewBody: isTufting_seo
           ? "超好玩！第一次試 Tufting 工作坊，完全零基礎都做到！導師很耐心，全程私人包場好温馨。完成的 Tufting 簇絨地毯超漂亮，係香港最值得試的拍拖好去處！送禮都超有心意！"
          : isSilver_seo
          ? "一起打造對方的戒指，有意義過任何禮物！導師很專業，成品超精美。紀念日首選！"
          : `在 Zoneout Studio 體驗 ${workshop?.title ?? ''}，導師耐心指導，全程私人包場非常温馨。強列推薦！`,
        datePublished: "2025-12-01",
      },
      {
        "@type": "Review",
        reviewRating: { "@type": "Rating", ratingValue: "5", bestRating: "5" },
        author: { "@type": "Person", name: "Chloe & Ken" },
        reviewBody: isTufting_seo
           ? "第一次嚟 Zoneout Studio 試 Tufting 工作坊，完全唔識都做到！導師好專業，私人包場超有氣氛。買來當生日禮物送男友，佢超感動！強烈推薦香港 Tufting 工作坊！"
          : isSilver_seo
          ? "銀戒指超精美！全程導師指導，即使零基礎也能完成。私人包場就是好！"
          : `${workshop?.title ?? ''}體驗非常好！全程私人包場，導師很耐心。強列推薦給所有情侶！`,
        datePublished: "2026-01-15",
      },
    ],
  };

  const courseJsonLd_seo = {
    "@context": "https://schema.org",
    "@type": "Course",
    "@id": `${pageUrl_seo}#course`,
    name: workshop?.title ?? '',
    description: pageDescription_seo,
    url: pageUrl_seo,
    image: heroImages.length > 0 ? heroImages[0] : ogImage_seo,
    provider: studioOrganization_seo,
    educationalLevel: workshop?.difficulty === 'beginner' ? '初學者' : workshop?.difficulty === 'intermediate' ? '中級' : '進階',
    teaches: isTufting_seo
       ? "Tufting Gun 操作技巧、簇絨地毯設計與製作、毛線顏色配搭、後期修剪與整理"
      : isSilver_seo
      ? "純銀戒指設計與鑄造技巧"
      : `${workshop?.title ?? ''}手作技巧`,
    inLanguage: "zh-HK",
    availableLanguage: ["zh-HK", "en"],
    offers: { "@type": "Offer", price: priceHKD_seo, priceCurrency: "HKD", availability: "https://schema.org/InStock", url: pageUrl_seo },
    hasCourseInstance: {
      "@type": "CourseInstance",
      courseMode: "onsite",
      location: { "@type": "Place", name: "Zoneout Studio", address: studioAddress_seo },
      courseSchedule: {
        "@type": "Schedule",
        repeatFrequency: "P1D",
        repeatCount: 365,
        byDay: ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],
        startTime: "10:00:00",
        endTime: "21:00:00",
      },
      ...(workshop?.instructor ? {
        instructor: {
          "@type": "Person",
          name: workshop.instructor,
          ...(workshop.instructorBio ? { description: workshop.instructorBio } : {}),
          worksFor: { "@type": "Organization", name: "Zoneout Studio" },
        },
      } : {}),
      offers: { "@type": "Offer", price: priceHKD_seo, priceCurrency: "HKD", availability: "https://schema.org/InStock", url: pageUrl_seo },
    },
    aggregateRating: { "@type": "AggregateRating", ratingValue: "4.9", reviewCount: "50", bestRating: "5" },
  };

  const eventJsonLd_seo = {
    "@context": "https://schema.org",
    "@type": "Event",
    "@id": `${pageUrl_seo}#event`,
    name: workshop?.title ?? '',
    description: pageDescription_seo,
    url: pageUrl_seo,
    image: heroImages.length > 0 ? heroImages : [ogImage_seo],
    eventStatus: "https://schema.org/EventScheduled",
    eventAttendanceMode: "https://schema.org/OfflineEventAttendanceMode",
    typicalAgeRange: "18-45",
    maximumAttendeeCapacity: workshop?.maxParticipants ?? 0,
    isAccessibleForFree: false,
    inLanguage: "zh-HK",
    location: {
      "@type": "Place",
      name: "Zoneout Studio",
      address: studioAddress_seo,
      geo: { "@type": "GeoCoordinates", latitude: "22.3358", longitude: "114.2003" },
    },
    organizer: studioOrganization_seo,
    performer: workshop?.instructor ? {
      "@type": "Person",
      name: workshop.instructor,
      description: workshop.instructorBio ?? undefined,
    } : studioOrganization_seo,
    audience: { "@type": "Audience", audienceType: "情侶 / 拍拖 / 團體" },
    startDate: "2026-01-01T10:00:00+08:00",
    endDate: "2027-12-31T21:00:00+08:00",
    offers: {
      "@type": "Offer",
      price: priceHKD_seo,
      priceCurrency: "HKD",
      availability: "https://schema.org/InStock",
      url: pageUrl_seo,
      validFrom: "2026-01-01",
    },
  };

  const howToJsonLd_seo = classFlow_seo.length > 0 ? {
    "@context": "https://schema.org",
    "@type": "HowTo",
    "@id": `${pageUrl_seo}#howto`,
    name: isTufting_seo
      ? `如何製作 Tufting 掛毯 — ${workshop?.title ?? ''}課程流程`
      : isSilver_seo
      ? `如何製作純銀戒指 — ${workshop?.title ?? ''}課程流程`
      : `${workshop?.title ?? ''} 課程流程指南`,
    description: pageDescription_seo,
    image: heroImages.length > 0 ? heroImages[0] : ogImage_seo,
    totalTime: `PT${workshop?.duration ?? 0}M`,
    estimatedCost: { "@type": "MonetaryAmount", currency: "HKD", value: priceHKD_seo },
    supply: (whatIncluded_seo.length > 0 ? whatIncluded_seo : [
      { label: isTufting_seo ? "Tufting Gun" : isSilver_seo ? "純銀材料" : "全部材料" },
      { label: "導師指導" },
    ]).map(item => ({ "@type": "HowToSupply", name: item.label })),
    tool: [{ "@type": "HowToTool", name: isTufting_seo ? "Tufting Gun" : isSilver_seo ? "銀工工具組" : "工具組" }],
    step: classFlow_seo.map((step, idx) => ({
      "@type": "HowToStep",
      position: idx + 1,
      name: `步驟 ${idx + 1}`,
      text: step.text,
      ...(step.imageUrl ? { image: { "@type": "ImageObject", url: step.imageUrl } } : {}),
      url: `${pageUrl_seo}#step-${idx + 1}`,
    })),
  } : null;

  const defaultFaq_seo = faqData_seo.length > 0 ? faqData_seo : isTufting_seo ? [
    { question: "簇絨工作坊係咩？適合情侶參加嗎？", answer: "Tufting（簇絨）是用 Tufting Gun 將毛線刺入布料製作地毯或掛毯的手作工藝。Zoneout Studio 採用全程私人包場，每個時段只屬於你們兩人，無需任何手作經驗，導師全程指導，完成品即日帶走。" },
    { question: "可以預約工作坊作為禮物嗎？", answer: `可以！一份親手製作簇絨掛毯的體驗，比任何現成禮物更有心意。無論是生日、情人節、週年紀念，都是獨特的創意禮物。費用 HK$${priceHKD_seo} / 人，可為對方預約指定日期。` },
    { question: "工作坊需要多少時間？", answer: `Zoneout Studio 的簇絨工作坊時長約 ${Math.round((workshop?.duration ?? 0) / 60)} 小時，包括設計圖案、製作、修剪及整理。全程由導師指導，初學者也能完成一件精美作品。` },
    { question: "費用包含哪些項目？", answer: `工作坊費用為 HK$${priceHKD_seo} / 人，已包含所有材料、工具使用及導師指導費。完成品即日帶走，無需額外費用。` },
    { question: "香港有什麼情侶好去處推薦？", answer: "除了餐廳和電影院，一起動手製作獨一無二的作品是更有紀念價值的選擇。Zoneout Studio 採用私人包場形式，不與陌生人同場，是近年最受情侶歡迎的拍拖好去處。" },
    { question: "工作室在哪裡？交通方便嗎？", answer: "Zoneout Studio 位於九龍新蒲崗，鑽石山港鐵站 C2 出口步行約 3 分鐘，來自港島、九龍、新界均方便到達。" },
  ] : isSilver_seo ? [
    { question: "情侶銀戒指工作坊係咩體驗？", answer: "Zoneout Studio 的情侶銀戒指製作工作坊讓你們親手為對方打造一枚獨一無二的純銀戒指。全程私人包場，導師手把手指導，即使是零手作經驗的情侶也能完成。是香港最受歡迎的拍拖好去處之一，完成品即日帶走。" },
    { question: "製作銀戒指需要幾多時間？", answer: `Zoneout Studio 的情侶銀戒指工作坊時長約 ${Math.round((workshop?.duration ?? 0) / 60)} 小時，包括設計、鑄造、打磨及拋光。全程由導師指導，確保每枚戒指都達到精緻水準。` },
    { question: "銀戒指工作坊費用係幾多？", answer: `Zoneout Studio 情侶銀戒指工作坊費用為 HK$${priceHKD_seo} / 人，費用已包含所有純銀材料、工具使用及導師指導費。完成品即日帶走，是最有紀念價值的情侶禮物。` },
    { question: "香港有咩拍拖好去處推薦？", answer: "除了傳統的餐廳、電影院，Zoneout Studio 的手作工作坊是近年最受情侶歡迎的拍拖好去處。銀戒指工作坊讓你們親手製作一件承載愛意的作品，留下比相片更有紀念價值的回憶。私人包場、無外人打擾，是情侶好去處的首選。" },
    { question: "情侶好去處除咗食飯仲有咩選擇？", answer: "手作工作坊是近年香港最受歡迎的情侶好去處新選擇！Zoneout Studio 提供 Tufting、銀飾等多種工作坊，全部採用私人包場形式，一起動手製作一件作品更能增進感情、留下獨特回憶。" },
  ] : [
    { question: `${workshop?.title ?? ''}適合情侶參加嗎？`, answer: `${workshop?.title ?? ''}採用全程私人包場形式，每個時段只屬於你們，是香港拍拖好去處的優質選擇。無需任何手作經驗，導師會全程指導，完成品即日帶走。` },
    { question: "香港有咩拍拖好去處推薦？", answer: `除了傳統的餐廳、電影院，Zoneout Studio 的手作工作坊是近年最受情侶歡迎的拍拖好去處。${workshop?.title ?? ''}讓你們親手製作一件獨一無二的作品，留下比相片更有紀念價值的回憶。` },
    { question: `${workshop?.title ?? ''}費用係幾多？`, answer: `Zoneout Studio ${workshop?.title ?? ''}費用為 HK$${priceHKD_seo} / 人，費用已包含所有材料、工具使用及導師指導費。完成品即日帶走，無需額外費用。` },
    { question: "情侶好去處除咗食飯仲有咩選擇？", answer: "手作工作坊是近年香港最受歡迎的情侶好去處新選擇！Zoneout Studio 提供多種工作坊，全部採用私人包場形式，一起動手製作一件作品更能增進感情、留下獨特回憶。" },
  ];

  const faqJsonLdData_seo = defaultFaq_seo.length > 0 ? createFAQSchema(defaultFaq_seo) : null;

  // ── SEO useEffect (MUST be before early returns to satisfy Rules of Hooks) ──
  useEffect(() => {
    if (!workshop) return;
    updateMetaTags({
      title: pageTitle_seo,
      description: pageDescription_seo,
      image: ogImage_seo,
      url: pageUrl_seo,
      type: 'website',
    });
    let kwMeta = document.querySelector<HTMLMetaElement>('meta[name="keywords"]');
    if (!kwMeta) {
      kwMeta = document.createElement('meta');
      kwMeta.setAttribute('name', 'keywords');
      document.head.appendChild(kwMeta);
    }
    kwMeta.setAttribute('content', pageKeywords_seo);
    const setOG = (prop: string, val: string) => {
      let el = document.querySelector<HTMLMetaElement>(`meta[property="${prop}"]`);
      if (!el) { el = document.createElement('meta'); el.setAttribute('property', prop); document.head.appendChild(el); }
      el.setAttribute('content', val);
    };
    const setTW = (name: string, val: string) => {
      let el = document.querySelector<HTMLMetaElement>(`meta[name="${name}"]`);
      if (!el) { el = document.createElement('meta'); el.setAttribute('name', name); document.head.appendChild(el); }
      el.setAttribute('content', val);
    };
    setOG('og:image:secure_url', ogImage_seo);
    setOG('og:image:type', 'image/webp');
    setOG('og:image:width', '1200');
    setOG('og:image:height', '630');
    setOG('og:image:alt', ogImageAlt_seo);
    setOG('og:site_name', 'Zoneout Studio');
    setOG('og:locale', isEn ? 'en_HK' : 'zh_HK');
    setOG('og:locale:alternate', isEn ? 'zh_HK' : 'en_HK');
    setTW('twitter:card', 'summary_large_image');
    setTW('twitter:image:alt', ogImageAlt_seo);
    setTW('twitter:site', '@zoneout_hk');
    setTW('twitter:creator', '@zoneout_hk');
    createStructuredData(productJsonLd_seo, 'schema-workshop-product');
    createStructuredData(courseJsonLd_seo, 'schema-workshop-course');
    createStructuredData(eventJsonLd_seo, 'schema-workshop-event');
    createStructuredData({ '@context': 'https://schema.org', ...studioOrganization_seo }, 'schema-workshop-org');
    if (faqJsonLdData_seo) createStructuredData(faqJsonLdData_seo, 'schema-workshop-faq');
    if (howToJsonLd_seo) createStructuredData(howToJsonLd_seo, 'schema-workshop-howto');
  }, [workshop, pageTitle_seo, pageDescription_seo, pageKeywords_seo, pageUrl_seo, ogImage_seo, ogImageAlt_seo, isEn,
      productJsonLd_seo, courseJsonLd_seo, eventJsonLd_seo, studioOrganization_seo, faqJsonLdData_seo, howToJsonLd_seo]);

  if (workshopQuery.isLoading) {
    return (
      <div className="min-h-screen bg-white">
        <Navbar />
        <WorkshopDetailSkeleton />
      </div>
    );
  }

  if (!workshop) {
    // If the query errored (DB temporarily unavailable), show a meaningful fallback
    // instead of a blank "not found" page that Google would classify as Soft 404.
    if (workshopQuery.isError || (!workshopQuery.isLoading && workshopQuery.fetchStatus !== 'idle')) {
      // Static fallback content keyed by slug for known workshops
      const STATIC_FALLBACK: Record<string, { title: string; titleEn: string; desc: string; descEn: string; price: string }> = {
        'couple-ring-workshop': {
          title: '香港情侶銀戒指工作坊',
          titleEn: 'Couples Silver Ring Workshop Hong Kong',
          desc: '親手為對方打造獨一無二的 999 純銀戒指，免費刻字服務，全程私人包場。新蒲崗 Zoneout Studio。',
          descEn: 'Craft a unique 999 sterling silver ring for each other. Free engraving, fully private session. Zoneout Studio, San Po Kong.',
          price: 'HK$880 / 人',
        },
        'tufting-workshop': {
          title: 'Tufting 地毯工作坊香港',
          titleEn: 'Tufting Workshop Hong Kong',
          desc: '使用 Tufting Gun 親手製作簇絨地毯，全程私人包場，導師指導，新蒲崗 Zoneout Studio。',
          descEn: 'Make your own tufted rug with a Tufting Gun. Private session, instructor-guided. Zoneout Studio, San Po Kong.',
          price: 'HK$580 起 / 人',
        },
      };
      const fb = slug ? STATIC_FALLBACK[slug] : undefined;
      return (
        <div className="min-h-screen bg-white">
          <Navbar />
          <div className="max-w-2xl mx-auto px-6 py-20 text-center">
            {fb ? (
              <>
                <h1 className="text-2xl font-semibold text-[#0a0a0a] mb-4">{isEn ? fb.titleEn : fb.title}</h1>
                <p className="text-[#5a5a5a] mb-3">{isEn ? fb.descEn : fb.desc}</p>
                <p className="text-[#0a0a0a] font-medium mb-8">{fb.price}</p>
                <p className="text-sm text-[#9a9a9a] mb-6">{isEn ? 'Page is temporarily loading. Please try again.' : '頁面暫時載入中，請稍後再試。'}</p>
              </>
            ) : (
              <p className="text-[#5a5a5a] mb-6 text-lg">{isEn ? 'Workshop not found' : '找不到此工作坊'}</p>
            )}
            <div className="flex gap-3 justify-center">
              <Button variant="outline" className="rounded-xl px-6" onClick={() => window.location.reload()}>
                {isEn ? 'Retry' : '重新載入'}
              </Button>
              <Button className="bg-[#0a0a0a] text-white hover:bg-[#0a0a0a]/85 rounded-xl px-6" onClick={() => navigate("/workshops")}>
                <ArrowLeft className="w-4 h-4 mr-2" />
                {isEn ? 'Back to Workshops' : '返回工作坊列表'}
              </Button>
            </div>
          </div>
        </div>
      );
    }
    // True not-found (query succeeded but returned null)
    return (
      <div className="min-h-screen bg-white">
        <Navbar />
        <div className="flex items-center justify-center min-h-[60vh]">
          <div className="text-center">
            <p className="text-[#5a5a5a] mb-6 text-lg">{isEn ? 'Workshop not found' : '找不到此工作坊'}</p>
            <Button className="bg-[#0a0a0a] text-white hover:bg-[#0a0a0a]/85 rounded-xl px-6" onClick={() => navigate("/workshops")}>
              <ArrowLeft className="w-4 h-4 mr-2" />
              {isEn ? 'Back to Workshops' : '返回工作坊列表'}
            </Button>
          </div>
        </div>
      </div>
    );
  }

  const whatYouMake: string[] = safeParseJson<string[]>(workshop.whatYouMake, []);
  const rawIncluded: (string | { label: string; description?: string })[] = safeParseJson<(string | { label: string; description?: string })[]>(workshop.whatIncluded, []);
  const whatIncluded: { label: string; description?: string }[] = rawIncluded.map((item) =>
    typeof item === 'string' ? { label: item } : item
  );
  const classFlow: { text: string; imageUrl?: string }[] = safeParseJson<(string | { text: string; imageUrl?: string })[]>(workshop.classFlow, []).map(
    (item) => typeof item === 'string' ? { text: item } : { text: item.text ?? '', imageUrl: item.imageUrl }
  );
  const faqData: { question: string; answer: string }[] = safeParseJson<{ question: string; answer: string }[]>(workshop.faq, []);

  // Check if whatYouMake items are URLs (images) or text descriptions
  const isImageUrl = (s: string) => s.startsWith('http') || s.startsWith('/');

  // ── SEO helpers ──
  const isTufting = workshop.slug?.toLowerCase().includes('tufting') ||
    workshop.title?.toLowerCase().includes('tufting') ||
    workshop.category?.toLowerCase().includes('tufting');
  const isSilver = workshop.slug?.toLowerCase().includes('ring') ||
    workshop.slug?.toLowerCase().includes('silver') ||
    workshop.title?.toLowerCase().includes('銀') ||
    workshop.title?.toLowerCase().includes('戒');

  // Dynamic SEO title
  const pageTitle = isEn
    ? isTufting
       ? `Tufting Workshop HK — Couple Private Session | Zoneout`
       : isSilver
       ? `Couple Silver Ring Workshop Hong Kong — Anniversary Date Idea | Zoneout Studio`
       : `${workshop.title} | Zoneout Studio Hong Kong Couple Handcraft Workshop`
     : isTufting
     ? `Tufting 工作坊香港 — 情侶私人包場首選 | Zoneout Studio`
    : isSilver
    ? `情侶銀戒指製作 香港 — 拍拖好去處 · 紀念日首選 | Zoneout Studio`
    : `${workshop.title} | Zoneout Studio 香港情侶手作工作坊 · 拍拖好去處`;

  // Dynamic SEO description
  const pageDescription = isEn
    ? isTufting
       ? `Hong Kong Tufting DIY Workshop in San Po Kong — top couple date idea, birthday gift & creative experience. Make your own tufted rug with Tufting Gun, fully private session (no strangers), instructor-guided, take it home same day. From HK$${(workshop.price / 100).toFixed(0)}. Book now at Zoneout Studio.`
      : isSilver
      ? `Hong Kong couple silver ring workshop — top date idea. Craft a unique sterling silver ring for each other, fully private session, instructor-guided, take home same day. From HK$${(workshop.price / 100).toFixed(0)}.`
      : workshop.description
        ? `${workshop.description.slice(0, 155)}…`
        : `Experience ${workshop.title} at Zoneout Studio — Hong Kong’s private couple handcraft workshop. Fully instructor-guided, all materials included, take your creation home same day.`
    : isTufting
     ? `香港 Tufting DIY Workshop | 新蒲崗 Zoneout Studio — 情侶好去處、拍拖好去處首選。使用 Tufting Gun 親手製作簇絨地毯，全程私人包場（不與陌生人同場），導師手把手指導，完成品即日帶走。HK\$${(workshop.price / 100).toFixed(0)} 起，立即預約。`
    : isSilver
    ? `香港情侶銀戒指製作工作坊，拍拖好去處首選。親手為對方打造獨一無二的純銀戒指，全程私人包場，導師手把手指導，完成品即日帶走。HK\$${(workshop.price / 100).toFixed(0)} 起。`
    : workshop.description
      ? `${workshop.description.slice(0, 155)}…`
      : `在 Zoneout Studio 體驗 ${workshop.title}，香港私人情侶手作工作坊，拍拖好去處首選，全程導師指導，材料費用全包，完成品即日帶走。`;

  // Dynamic SEO keywords (max 8 per SEO best practice)
  const pageKeywords = isTufting
     ? `tufting hk, tufting 工作坊, 情侶工作坊, 拍拖好去處, 私人包場, 簇絨工作坊, 香港手作, Zoneout Studio`
     : isSilver
    ? `情侶銀戒指, 銀戒指工作坊, 拍拖好去處, 情侶工作坊, 私人包場, 香港手作, 紀念日禮物, Zoneout Studio`
    : `${workshop.title}, 香港手作工作坊, 情侶工作坊, 拍拖好去處, 私人包場, Zoneout Studio, 新蒲崗手作`;

  const pageUrl = `https://zoneout-workshop.com/workshops/${workshop.slug}`;
  const SITE_ORIGIN = "https://zoneout-workshop.com";
  const rawOgImage = heroImages[0] ?? workshop.imageUrl ?? null;
  const ogImage = rawOgImage
    ? rawOgImage.startsWith('http') ? rawOgImage : `${SITE_ORIGIN}${rawOgImage}`
    : `${SITE_ORIGIN}/og-default.jpg`;
  const ogImageAlt = isEn ? `${workshop.title} — Zoneout Studio Hong Kong Handcraft Workshop` : `${workshop.title} — Zoneout Studio 香港手作工作坊`;
  const priceHKD = (workshop.price / 100).toFixed(0);

  // ── Shared address / organization objects (reused across schemas) ──
  const studioAddress = {
    "@type": "PostalAddress",
    streetAddress: "同德工業大廈 8 樓",
    addressLocality: "新蒲崗",
    addressRegion: "香港",
    addressCountry: "HK",
    postalCode: "000000",
  };

  const studioOrganization = {
    "@type": "LocalBusiness",
    "@id": "https://zoneout-workshop.com/#organization",
    name: "Zoneout Studio",
    alternateName: "Zoneout 香港手作工作室",
    description: "香港拍拖好去處首選 — 情侶手作工作坊，提供 Tufting、銀飾、陶藝等私人包場體驗",
    url: "https://zoneout-workshop.com",
    logo: "https://zoneout-workshop.com/manus-storage/zoneout-logo_3b4efa7e.webp",
    image: heroImages.length > 0 ? heroImages[0] : ogImage,
    telephone: "+852-9554-8808",
    email: "info@zoneout-workshop.com",
    priceRange: "$$",
    currenciesAccepted: "HKD",
    paymentAccepted: "Cash, Credit Card, PayMe, FPS",
    address: studioAddress,
    geo: {
      "@type": "GeoCoordinates",
      latitude: "22.3358",
      longitude: "114.2003",
    },
    hasMap: "https://maps.google.com/?q=22.3358,114.2003",
    openingHoursSpecification: [
      {
        "@type": "OpeningHoursSpecification",
        dayOfWeek: ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"],
        opens: "12:00",
        closes: "21:00",
      },
      {
        "@type": "OpeningHoursSpecification",
        dayOfWeek: ["Saturday", "Sunday"],
        opens: "10:00",
        closes: "21:00",
      },
    ],
    amenityFeature: [
      { "@type": "LocationFeatureSpecification", name: "私人包場工作室", value: true },
      { "@type": "LocationFeatureSpecification", name: "全程導師指導", value: true },
      { "@type": "LocationFeatureSpecification", name: "材料費用全包", value: true },
      { "@type": "LocationFeatureSpecification", name: "完成品即日帶走", value: true },
    ],
    aggregateRating: {
      "@type": "AggregateRating",
      ratingValue: "4.9",
      reviewCount: "50",
      bestRating: "5",
      worstRating: "1",
    },
    sameAs: [
      "https://www.instagram.com/zoneout_hk",
      "https://www.facebook.com/zohkstudio",
    ],
  };

  // Product JSON-LD (enhanced with sku, category, additionalProperty)
  const productJsonLd = {
    "@context": "https://schema.org",
    "@type": "Product",
    "@id": `${pageUrl}#product`,
    name: workshop.title,
    description: pageDescription,
    url: pageUrl,
    image: heroImages.length > 0 ? heroImages : [ogImage],
    keywords: pageKeywords,
    sku: `ZO-${workshop.id}-${workshop.slug}`,
    category: isTufting ? "Tufting 工作坊" : isSilver ? "銀飾工作坊" : "手作工作坊",
    brand: { "@type": "Brand", name: "Zoneout Studio" },
    additionalProperty: [
      { "@type": "PropertyValue", name: "時長", value: `${Math.round(workshop.duration / 60)} 小時` },
      { "@type": "PropertyValue", name: "人數", value: `最多 ${workshop.maxParticipants} 人` },
      { "@type": "PropertyValue", name: "難度", value: workshop.difficulty === 'beginner' ? '初學友好' : workshop.difficulty === 'intermediate' ? '中級' : '進階' },
      { "@type": "PropertyValue", name: "地點", value: "香港新蒲崗" },
      { "@type": "PropertyValue", name: "包場形式", value: "私人專屬包場" },
    ],
    offers: {
      "@type": "Offer",
      priceCurrency: "HKD",
      price: priceHKD,
      availability: "https://schema.org/InStock",
      url: pageUrl,
      validFrom: "2025-01-01",
      priceValidUntil: "2026-12-31",
      seller: studioOrganization,
    },
    aggregateRating: {
      "@type": "AggregateRating",
      ratingValue: "4.9",
      reviewCount: "50",
      bestRating: "5",
      worstRating: "1",
    },
    review: [
      {
        "@type": "Review",
        reviewRating: { "@type": "Rating", ratingValue: "5", bestRating: "5" },
        author: { "@type": "Person", name: "Mandy & Jason" },
        reviewBody: isTufting
          ? "超好玩！導師很耐心，全程私人包場好温馨。最終製作的 Tufting 掛毯超漂亮，拍拖好去處首選！送禮都超有心意！"
          : isSilver
          ? "一起打造對方的戒指，有意義過任何禮物！導師很專業，成品超精美。紀念日首選！"
          : `在 Zoneout Studio 體驗 ${workshop.title}，導師耐心指導，全程私人包場非常温馨。強列推薦！`,
        datePublished: "2025-12-01",
      },
      {
        "@type": "Review",
        reviewRating: { "@type": "Rating", ratingValue: "5", bestRating: "5" },
        author: { "@type": "Person", name: "Chloe & Ken" },
        reviewBody: isTufting
          ? "首次試 Tufting，原來都會！Zoneout Studio 導師很專業，私人包場超有氣氛。買來當生日禮物送男友，佢超感動！"
          : isSilver
          ? "銀戒指超精美！全程導師指導，即使零基礎也能完成。私人包場就是好！"
          : `${workshop.title}體驗非常好！全程私人包場，導師很耐心。強列推薦給所有情侶！`,
        datePublished: "2026-01-15",
      },
    ],
  };

  // Course JSON-LD — helps Google show workshop as a structured course
  const courseJsonLd = {
    "@context": "https://schema.org",
    "@type": "Course",
    "@id": `${pageUrl}#course`,
    name: workshop.title,
    description: pageDescription,
    url: pageUrl,
    image: heroImages.length > 0 ? heroImages[0] : ogImage,
    provider: studioOrganization,
    educationalLevel: workshop.difficulty === 'beginner' ? '初學者' : workshop.difficulty === 'intermediate' ? '中級' : '進階',
    teaches: isTufting
      ? "Tufting Gun 操作技巧、簇絨地毯設計與製作、毛線顏色配搭、後期修剪與整理"
      : isSilver
      ? "純銀戒指設計、鑄造、打磨及拋光技巧"
      : `${workshop.title}手作技巧`,
    inLanguage: "zh-HK",
    availableLanguage: ["zh-HK", "en"],
    offers: { "@type": "Offer", price: priceHKD, priceCurrency: "HKD", availability: "https://schema.org/InStock", url: pageUrl },
    hasCourseInstance: {
      "@type": "CourseInstance",
      courseMode: "onsite",
      location: {
        "@type": "Place",
        name: "Zoneout Studio",
        address: studioAddress,
      },
      courseSchedule: {
        "@type": "Schedule",
        repeatFrequency: "P1D",
        repeatCount: 365,
        byDay: ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
        startTime: "10:00:00",
        endTime: "21:00:00",
      },
      ...(workshop.instructor ? {
        instructor: {
          "@type": "Person",
          name: workshop.instructor,
          ...(workshop.instructorBio ? { description: workshop.instructorBio } : {}),
          worksFor: { "@type": "Organization", name: "Zoneout Studio" },
        },
      } : {}),
      offers: {
        "@type": "Offer",
        price: priceHKD,
        priceCurrency: "HKD",
        availability: "https://schema.org/InStock",
        url: pageUrl,
      },
    },
    keywords: pageKeywords,
    about: isTufting
      ? { "@type": "Thing", name: "Tufting 手工藝 — 使用 Tufting Gun 製作簇絨地毯" }
      : isSilver
      ? { "@type": "Thing", name: "純銀首飾製作工藝" }
      : { "@type": "Thing", name: `${workshop.title} 手作工藝` },
    coursePrerequisites: "無需任何手作經驗，適合初學者",
    aggregateRating: {
      "@type": "AggregateRating",
      ratingValue: "4.9",
      reviewCount: "50",
      bestRating: "5",
    },
  };

  // Event JSON-LD (enhanced with typicalAgeRange, performer, audience)
  const eventJsonLd = {
    "@context": "https://schema.org",
    "@type": "Event",
    "@id": `${pageUrl}#event`,
    name: workshop.title,
    description: pageDescription,
    url: pageUrl,
    image: heroImages.length > 0 ? heroImages : [ogImage],
    eventStatus: "https://schema.org/EventScheduled",
    eventAttendanceMode: "https://schema.org/OfflineEventAttendanceMode",
    typicalAgeRange: "18-45",
    maximumAttendeeCapacity: workshop.maxParticipants,
    isAccessibleForFree: false,
    inLanguage: "zh-HK",
    location: {
      "@type": "Place",
      name: "Zoneout Studio",
      address: studioAddress,
      geo: { "@type": "GeoCoordinates", latitude: "22.3358", longitude: "114.2003" },
    },
    organizer: studioOrganization,
    performer: workshop.instructor ? {
      "@type": "Person",
      name: workshop.instructor,
      description: workshop.instructorBio ?? undefined,
    } : studioOrganization,
    audience: {
      "@type": "Audience",
      audienceType: "情侶 / 拍拖 / 團體",
    },
    startDate: "2026-01-01T10:00:00+08:00",
    endDate: "2027-12-31T21:00:00+08:00",
    duration: `PT${workshop.duration}M`,
    keywords: pageKeywords,
    about: isTufting
      ? { "@type": "Thing", name: "Tufting 手工藝" }
      : isSilver
      ? { "@type": "Thing", name: "純銀首飾製作" }
      : { "@type": "Thing", name: workshop.title },
    offers: {
      "@type": "Offer",
      price: priceHKD,
      priceCurrency: "HKD",
      availability: "https://schema.org/InStock",
      url: pageUrl,
      validFrom: "2026-01-01",
      validThrough: "2027-12-31",
    },
  };

  // HowTo JSON-LD — built from classFlow steps (helps Google show step-by-step rich results)
  const howToJsonLd = classFlow.length > 0 ? {
    "@context": "https://schema.org",
    "@type": "HowTo",
    "@id": `${pageUrl}#howto`,
    name: isTufting
      ? `如何製作 Tufting 掛毯 — ${workshop.title}課程流程`
      : isSilver
      ? `如何製作純銀戒指 — ${workshop.title}課程流程`
      : `${workshop.title} 課程流程指南`,
    description: pageDescription,
    image: heroImages.length > 0 ? heroImages[0] : ogImage,
    totalTime: `PT${workshop.duration}M`,
    estimatedCost: {
      "@type": "MonetaryAmount",
      currency: "HKD",
      value: priceHKD,
    },
    supply: (whatIncluded.length > 0 ? whatIncluded : [
      { label: isTufting ? "Tufting Gun" : isSilver ? "純銀材料" : "全部材料" },
      { label: "導師指導" },
    ]).map(item => ({
      "@type": "HowToSupply",
      name: item.label,
    })),
    tool: [{
      "@type": "HowToTool",
      name: isTufting ? "Tufting Gun" : isSilver ? "銀工工具組" : "工具組",
    }],
    step: classFlow.map((step, idx) => ({
      "@type": "HowToStep",
      position: idx + 1,
      name: `步驟 ${idx + 1}`,
      text: step.text,
      ...(step.imageUrl ? { image: { "@type": "ImageObject", url: step.imageUrl } } : {}),
      url: `${pageUrl}#step-${idx + 1}`,
    })),
  } : null;

  // Default FAQ for SEO — generated dynamically based on workshop type
  const defaultFaq = faqData.length > 0 ? faqData : isTufting ? [
    { question: "Tufting 係咩？零基礎可以參加嗎？", answer: "Tufting（簇絨）是用 Tufting Gun 將毛線刺入底布，製作地毯或掛毯的手作工藝。完全適合零基礎，導師會全程手把手指導，確保每位學員都能完成屬於自己的作品。" },
    { question: "工作坊費用係幾多？包含咩？", answer: `費用為 HK$${priceHKD} / 人，已包含所有材料、Tufting Gun 使用費及導師指導費。情侶兩人合計 HK$${(workshop.price / 100 * 2).toFixed(0)}，完成品即日帶走，無需額外費用。` },
    { question: "工作坊需要幾多時間？", answer: `時長約 ${Math.round(workshop.duration / 60)} 小時，包括選色、描繪圖案、Tufting 製作、修剪及整理。全程私人包場，節奏由你們掌控，不用趕時間。` },
    { question: "咩係私人包場？同其他工作坊有咩分別？", answer: "私人包場即每個時段只屬於你們兩人，不與陌生人同場。香港大部分工作坊都是多人共用，Zoneout Studio 是少數提供全程私人體驗的工作坊，讓你們可以放鬆創作，更有二人世界的感覺。" },
    { question: "可以自訂圖案嗎？", answer: "可以！預約時可提供自訂圖案，導師會協助描繪到底布上。也可以當場選擇工作室提供的圖案範本，超過 50 種毛線顏色任意配搭。" },
  ] : isSilver ? [
    { question: "情侶銀戒指工作坊係咩體驗？", answer: "Zoneout Studio 的情侶銀戒指製作工作坊讓你們親手為對方打造一枚獨一無二的純銀戒指。全程私人包場，導師手把手指導，即使是零手作經驗的情侶也能完成。是香港最受歡迎的拍拖好去處之一，完成品即日帶走。" },
    { question: "製作銀戒指需要幾多時間？", answer: `Zoneout Studio 的情侶銀戒指工作坊時長約 ${Math.round(workshop.duration / 60)} 小時，包括設計、鑄造、打磨及拋光。全程由導師指導，確保每枚戒指都達到精緻水準。` },
    { question: "銀戒指工作坊費用係幾多？", answer: `Zoneout Studio 情侶銀戒指工作坊費用為 HK$${priceHKD} / 人，費用已包含所有純銀材料、工具使用及導師指導費。完成品即日帶走，是最有紀念價值的情侶禮物。` },
    { question: "香港有咩拍拖好去處推薦？", answer: "除了傳統的餐廳、電影院，Zoneout Studio 的手作工作坊是近年最受情侶歡迎的拍拖好去處。銀戒指工作坊讓你們親手製作一件承載愛意的作品，留下比相片更有紀念價值的回憶。私人包場、無外人打擾，是情侶好去處的首選。" },
    { question: "情侶好去處除咗食飯仲有咩選擇？", answer: "手作工作坊是近年香港最受歡迎的情侶好去處新選擇！Zoneout Studio 提供 Tufting、銀飾等多種工作坊，全部採用私人包場形式，一起動手製作一件作品更能增進感情、留下獨特回憶。" },
  ] : [
    { question: `${workshop.title}適合情侶參加嗎？`, answer: `${workshop.title}採用全程私人包場形式，每個時段只屬於你們，是香港拍拖好去處的優質選擇。無需任何手作經驗，導師會全程指導，完成品即日帶走。` },
    { question: "香港有咩拍拖好去處推薦？", answer: `除了傳統的餐廳、電影院，Zoneout Studio 的手作工作坊是近年最受情侶歡迎的拍拖好去處。${workshop.title}讓你們親手製作一件獨一無二的作品，留下比相片更有紀念價值的回憶。` },
    { question: `${workshop.title}費用係幾多？`, answer: `Zoneout Studio ${workshop.title}費用為 HK$${priceHKD} / 人，費用已包含所有材料、工具使用及導師指導費。完成品即日帶走，無需額外費用。` },
    { question: "情侶好去處除咗食飯仲有咩選擇？", answer: "手作工作坊是近年香港最受歡迎的情侶好去處新選擇！Zoneout Studio 提供多種工作坊，全部採用私人包場形式，一起動手製作一件作品更能增進感情、留下獨特回憶。" },
  ];

  const effectiveFaq = defaultFaq;
  const faqJsonLdData = effectiveFaq.length > 0 ? createFAQSchema(effectiveFaq) : null;

  // Breadcrumb JSON-LD
  const breadcrumbMidLabel = isTufting
    ? "Tufting 工作坊 · 拍拖好去處"
    : isSilver
    ? "情侶銀戒指 · 拍拖好去處"
    : "工作坊 · 情侶好去處";
  const breadcrumbJsonLd = createBreadcrumbSchema([
    { name: "首頁", url: "https://zoneout-workshop.com/" },
    { name: breadcrumbMidLabel, url: "https://zoneout-workshop.com/workshops" },
    { name: workshop.title, url: pageUrl },
  ]);

  return (
    <div className="min-h-screen bg-white">
      {/*
        ── Structured Data (JSON-LD) ──
        IMPORTANT: productJsonLd is intentionally NOT inlined here.
        It is injected once via useEffect → createStructuredData('schema-workshop-product').
        Inlining it here would create a second Product schema with a duplicate 'brand' field,
        which Google Search Console flags as "Duplicate field 'brand'" in Merchant Listings.
        Course, Event, HowTo, FAQ and Breadcrumb are safe to inline as they have no
        conflicting fields with the useEffect-injected schemas.
      ── */}
      <script type="application/ld+json" id="schema-workshop-course-inline" dangerouslySetInnerHTML={{ __html: JSON.stringify(courseJsonLd) }} />
      <script type="application/ld+json" id="schema-workshop-event-inline" dangerouslySetInnerHTML={{ __html: JSON.stringify(eventJsonLd) }} />
      {howToJsonLd && <script type="application/ld+json" id="schema-workshop-howto-inline" dangerouslySetInnerHTML={{ __html: JSON.stringify(howToJsonLd) }} />}
      {faqJsonLdData && <script type="application/ld+json" id="schema-workshop-faq-inline" dangerouslySetInnerHTML={{ __html: JSON.stringify(faqJsonLdData) }} />}
      <script type="application/ld+json" id="schema-workshop-breadcrumb" dangerouslySetInnerHTML={{ __html: JSON.stringify(breadcrumbJsonLd) }} />
      <Navbar />

      {/* ── Hero ── */}
      <section
        className="relative mt-[60px] sm:mt-[64px] overflow-hidden bg-[#0a0a0a]"
        style={{ height: "clamp(260px, 55vw, 680px)" }}
        onTouchStart={handleTouchStart}
        onTouchEnd={handleTouchEnd}
      >
        {heroImages.length > 0 ? (
          <>
            {heroImages.map((src: string, i: number) => (
              <img
                key={i}
                src={src}
                alt={i === currentImageIndex ? `${workshop.title} - 圖片 ${i + 1}` : ""}
                aria-hidden={i !== currentImageIndex}
                loading={i === 0 ? "eager" : "lazy"}
                decoding="async"
                fetchPriority={i === 0 ? "high" : "auto"}
                width="1920"
                height="680"
                className={`absolute inset-0 w-full h-full object-cover transition-opacity duration-700 ${i === currentImageIndex ? "opacity-100" : "opacity-0"} ${heroLoaded ? "" : "blur-sm scale-105"}`}
                onLoad={() => i === 0 && setHeroLoaded(true)}
              />
            ))}
            {/* Multi-layer gradient overlay */}
            <div className="absolute inset-0 bg-gradient-to-t from-black/80 via-black/20 to-black/30 pointer-events-none" />
            <div className="absolute inset-0 bg-gradient-to-r from-black/40 to-transparent pointer-events-none" style={{ width: "60%" }} />

            {/* Top bar */}
            <div className="absolute top-5 left-5 right-5 flex items-center justify-between z-20">
              <button
                onClick={() => navigate("/workshops")}
                aria-label={isEn ? 'Back to Workshops' : '返回工作坊列表'}
                className="flex items-center gap-2 bg-black/40 hover:bg-black/60 backdrop-blur-md text-white text-xs font-medium px-4 py-2.5 rounded-full transition-all duration-200 active:scale-95 border border-white/10"
              >
                <ArrowLeft className="w-3.5 h-3.5" />
                {isEn ? 'Workshops' : '工作坊列表'}
              </button>
              <ShareButton title={workshop.title} description={workshop.description ?? undefined} url={typeof window !== "undefined" ? window.location.href : ""} size="sm" />
            </div>

            {/* Bottom title overlay — always visible */}
            <div className="absolute bottom-0 left-0 right-0 p-6 sm:p-10 z-10">
              {/* Badges */}
              <div className="flex flex-wrap gap-2 mb-4">
                {workshop.badge && (
                  <span className="text-[11px] font-bold px-3 py-1 rounded-full bg-white text-[#0a0a0a] flex items-center gap-1">
                    <Sparkles className="w-3 h-3" />
                    {workshop.badge}
                  </span>
                )}
                <span className={`text-[11px] font-semibold px-3 py-1 rounded-full border backdrop-blur-sm ${difficultyColor(workshop.difficulty ?? undefined)}`}>
                  {difficultyLabel(workshop.difficulty ?? undefined)}
                </span>
              </div>
              {/* Title */}
              <h1 className="text-2xl sm:text-3xl md:text-4xl lg:text-5xl font-serif font-bold text-white leading-tight drop-shadow-xl max-w-2xl">
                {isTufting
                  ? (isEn ? `Tufting HK · ${workshop.title} — Couple Date Idea & Birthday Gift` : `Tufting HK｜${workshop.title}：情侶私人包場 · 生日禮物首選`)
                  : isSilver
                  ? (isEn ? `${workshop.title} — Couple Ring DIY Hong Kong` : `${workshop.title}：香港情侶對戒 DIY · 紀念日首選`)
                  : workshop.title}
              </h1>
              {/* Stats strip */}
              <div className="mt-3 sm:mt-5 flex flex-wrap items-center gap-3 sm:gap-4 lg:gap-6">
                <div className="flex items-center gap-1.5 text-white/80 text-sm">
                  <Clock className="w-4 h-4 text-white/60" />
                  <span>{workshop.duration} {isEn ? 'mins' : '分鐘'}</span>
                </div>
                <div className="w-px h-4 bg-white/20" />
                <div className="flex items-center gap-1.5 text-white/80 text-sm">
                  <Users className="w-4 h-4 text-white/60" />
                  <span>{isEn ? `Up to ${workshop.maxParticipants} ppl` : `最多 ${workshop.maxParticipants} 人`}</span>
                </div>
                <div className="w-px h-4 bg-white/20" />
                <div className="flex items-center gap-1.5 text-white/80 text-sm">
                  <Star className="w-4 h-4 text-amber-400 fill-amber-400" />
                  <span>4.9 {isEn ? '· 50+ reviews' : '分 · 50+ 好評'}</span>
                </div>
                <div className="w-px h-4 bg-white/20" />
                <div className="flex items-center gap-1.5 text-white/80 text-sm">
                  <MapPin className="w-4 h-4 text-white/60" />
                  <span>{isEn ? 'San Po Kong, Diamond Hill' : '新蒲崗鑽石山站'}</span>
                </div>
              </div>
            </div>

            {/* Carousel controls */}
            {heroImages.length > 1 && (
              <>
                <button onClick={prevImage} aria-label={isEn ? 'Previous image' : '上一張'} className="absolute left-4 top-1/2 -translate-y-1/2 z-20 w-11 h-11 bg-black/40 hover:bg-black/70 backdrop-blur-sm text-white rounded-full flex items-center justify-center transition-all duration-150 active:scale-90 border border-white/10">
                  <ChevronLeft className="w-5 h-5" />
                </button>
                <button onClick={nextImage} aria-label={isEn ? 'Next image' : '下一張'} className="absolute right-4 top-1/2 -translate-y-1/2 z-20 w-11 h-11 bg-black/40 hover:bg-black/70 backdrop-blur-sm text-white rounded-full flex items-center justify-center transition-all duration-150 active:scale-90 border border-white/10">
                  <ChevronRight className="w-5 h-5" />
                </button>
                <div className="absolute bottom-6 right-6 z-20 flex gap-1.5">
                  {heroImages.map((_: string, idx: number) => (
                    <button key={idx} onClick={() => setCurrentImageIndex(idx)} aria-label={`切換到第 ${idx + 1} 張`} className={`h-1.5 rounded-full transition-all duration-300 ${idx === currentImageIndex ? "bg-white w-6" : "bg-white/40 w-1.5 hover:bg-white/70"}`} />
                  ))}
                </div>
              </>
            )}
          </>
        ) : (
          /* Fallback: no hero image — show imageUrl as single image */
          workshop.imageUrl ? (
            <>
              <img src={workshop.imageUrl} alt={workshop.title} loading="eager" fetchPriority="high" decoding="async" width="1920" height="680" className="absolute inset-0 w-full h-full object-cover" />
              <div className="absolute inset-0 bg-gradient-to-t from-black/80 via-black/20 to-black/30 pointer-events-none" />
              <div className="absolute bottom-0 left-0 right-0 p-6 sm:p-10 z-10">
                <h1 className="text-3xl sm:text-4xl md:text-5xl font-serif font-bold text-white leading-tight drop-shadow-xl max-w-2xl">{workshop.title}</h1>
              </div>
            </>
          ) : (
            <div className="w-full h-full flex items-center justify-center bg-[#1a1a1a]">
              <p className="text-white/30">暫無圖片</p>
            </div>
          )
        )}
      </section>

      {/* ── Main Content ── */}
      <div className="container max-w-6xl py-8 sm:py-12 md:py-16 pb-28 sm:pb-32 lg:pb-20">

        {/* ── Breadcrumb (visual + JSON-LD) ── */}
        <Breadcrumb
          withJsonLd
          className="mb-8"
          items={[
            { label: isEn ? 'Workshops' : '工作坊', href: "/workshops", canonicalUrl: "https://zoneout-workshop.com/workshops" },
            { label: workshop.title, canonicalUrl: pageUrl },
          ]}
        />

        <div className="grid grid-cols-1 lg:grid-cols-[1fr_340px] gap-12 lg:gap-16 items-start">

          {/* ── Left: Article ── */}
          <article className="space-y-14">

            {/* Description */}
            {workshop.description && (
              <section>
                <div className="mb-6">
                  <div className="flex items-center gap-2 mb-3">
                    <div className="w-5 h-px bg-[#0a0a0a]/30" />
                    <p className="text-[10px] font-bold tracking-[0.25em] uppercase text-black/40">About This Workshop</p>
                  </div>
                  <h2 className="text-2xl sm:text-3xl font-serif font-bold text-[#1a1a1a]">{isEn ? 'About This Workshop' : '工作坊介紹'}</h2>
                </div>
                <p className="text-[#4a4a4a] leading-[1.95] text-base sm:text-[1.0625rem] whitespace-pre-wrap">{workshop.description}</p>
                {/* Keyword pills — dynamic for all workshops */}
                {(() => {                   const pills: { label: string; href: string }[] = isTufting ? [
                    { label: "Tufting HK", href: "/workshops" },
                    { label: "Tufting 工作坊 香港", href: "/workshops" },
                    { label: "Tufting Gun 體驗", href: "/workshops" },
                    { label: "簇絨地毯工作坊", href: "/workshops" },
                    { label: "情侶私人包場", href: "/contact" },
                    { label: "情侶好去處", href: "/workshops" },
                    { label: "拍拖好去處", href: "/workshops" },
                    { label: "生日禮物首選", href: "/workshops" },
                    { label: "情侶禮物", href: "/workshops" },
                    { label: "新蒲崗工作坊", href: "/about" },
                  ] : isSilver ? [
                    { label: "情侶銀戒指工作坊", href: "/workshops" },
                    { label: "香港對戒 DIY", href: "/workshops" },
                    { label: "拍拖好去處", href: "/workshops" },
                    { label: "銀飾工作坊 香港", href: "/workshops" },
                    { label: "999 純銀戒指", href: "/workshops" },
                    { label: "免費刻字", href: "/workshops" },
                    { label: "私人包場", href: "/contact" },
                    { label: "紀念日禮物首選", href: "/gallery" },
                    { label: "情侶禮物香港", href: "/gallery" },
                    { label: "新蒲崗工作坊", href: "/about" },
                  ] : [
                    { label: workshop.title, href: "/workshops" },
                    { label: "拍拖好去處", href: "/workshops" },
                    { label: "情侶好去處", href: "/workshops" },
                    { label: "私人包場", href: "/contact" },
                    { label: "香港手作體驗", href: "/gallery" },
                  ];
                  return (
                    <div className="mt-4 flex flex-wrap gap-2">
                      {pills.map(({ label, href }) => (
                        <a
                          key={label}
                          href={href}
                          className="inline-block text-[11px] font-semibold text-[#5a5a5a] bg-[#f5f5f5] border border-[#e8e8e8] rounded-full px-3 py-1 hover:bg-[#0a0a0a] hover:text-white hover:border-[#0a0a0a] transition-all duration-150"
                        >
                          {label}
                        </a>
                      ))}
                    </div>
                  );
                })()}
              </section>
            )}

            {/* Instructor */}
            {workshop.instructor && (
              <section>
                <div className="mb-6">
                  <div className="flex items-center gap-2 mb-3">
                    <div className="w-5 h-px bg-[#0a0a0a]/30" />
                    <p className="text-[10px] font-bold tracking-[0.25em] uppercase text-black/40">Your Guide</p>
                  </div>
                  <h2 className="text-2xl sm:text-3xl font-serif font-bold text-[#1a1a1a]">{t('workshopDetail.instructor')}</h2>
                </div>
                <div className="flex items-start gap-5 p-6 rounded-2xl bg-[#fafafa] border border-[#efefef]">
                  <div className="relative shrink-0">
                    <div className="w-14 h-14 rounded-full bg-gradient-to-br from-[#2a2a2a] to-[#0a0a0a] flex items-center justify-center text-2xl font-bold text-white shadow-md ring-2 ring-[#e8e8e8]">
                      {workshop.instructor.charAt(0)}
                    </div>
                    <div className="absolute -bottom-0.5 -right-0.5 w-5 h-5 rounded-full bg-emerald-500 border-2 border-white flex items-center justify-center">
                      <CheckCircle2 className="w-2.5 h-2.5 text-white" />
                    </div>
                  </div>
                  <div>
                    <p className="font-bold text-[#1a1a1a] text-lg mb-0.5">{workshop.instructor}</p>
                    <p className="text-[11px] text-emerald-600 font-semibold mb-2 uppercase tracking-wide">{t('workshopDetail.certifiedInstructor')}</p>
                    {workshop.instructorBio && <p className="text-sm text-[#5a5a5a] leading-relaxed">{workshop.instructorBio}</p>}
                  </div>
                </div>
              </section>
            )}

            {/* What You'll Make */}
            {whatYouMake.length > 0 && (
              <section>
                <div className="mb-6">
                  <div className="flex items-center gap-2 mb-3">
                    <div className="w-5 h-px bg-[#0a0a0a]/30" />
                    <p className="text-[10px] font-bold tracking-[0.25em] uppercase text-black/40">Your Creation</p>
                  </div>
                  <h2 className="text-2xl sm:text-3xl font-serif font-bold text-[#1a1a1a]">{t('workshopDetail.whatYouMake')}</h2>
                </div>
                {isImageUrl(whatYouMake[0]) ? (
                  <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
                    {whatYouMake.map((src: string, idx: number) => (
                      <ProgressiveImage
                        key={idx}
                        src={src}
                        alt={isTufting ? `Tufting 掛毯作品 ${idx + 1} — Zoneout Studio 香港 Tufting 工作坊禮物` : `作品 ${idx + 1} — ${workshop.title}`}
                        aspectRatio="1/1"
                        wrapperClassName="rounded-xl group"
                        className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"
                        loading="lazy"
                        width={400}
                        height={400}
                      />
                    ))}
                  </div>
                ) : (
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                    {whatYouMake.map((item: string, idx: number) => (
                      <div key={idx} className="flex items-center gap-4 p-5 rounded-2xl bg-[#fafafa] border border-[#efefef] hover:border-[#d0d0d0] hover:bg-white transition-colors duration-150">
                        <div className="w-10 h-10 rounded-full bg-[#0a0a0a] text-white flex items-center justify-center shrink-0 text-sm font-bold">
                          {String(idx + 1).padStart(2, '0')}
                        </div>
                        <p className="text-sm font-semibold text-[#1a1a1a] leading-snug">{item}</p>
                      </div>
                    ))}
                  </div>
                )}
              </section>
            )}

            {/* What's Included */}
            {whatIncluded.length > 0 && (
              <section>
                <div className="flex items-end justify-between mb-6">
                  <div>
                    <div className="flex items-center gap-2 mb-3">
                      <div className="w-5 h-px bg-[#0a0a0a]/30" />
                      <p className="text-[10px] font-bold tracking-[0.25em] uppercase text-black/40">What's Included</p>
                    </div>
                    <h2 className="text-2xl sm:text-3xl font-serif font-bold text-[#1a1a1a]">{t('workshopDetail.whatIncluded')}</h2>
                  </div>
                  <button
                    onClick={() => setShowIncludedDesc((v) => !v)}
                    className="flex items-center gap-1.5 px-3 py-1.5 rounded-full border border-[#e0e0e0] text-xs font-medium text-[#5a5a5a] hover:border-[#0a0a0a] hover:text-[#0a0a0a] transition-all duration-150 shrink-0 mb-1"
                  >
                    {showIncludedDesc ? <><EyeOff className="w-3.5 h-3.5" />{t('workshopDetail.hideDesc')}</> : <><Eye className="w-3.5 h-3.5" />{t('workshopDetail.showDesc')}</>}
                  </button>
                </div>
                <ul className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                  {whatIncluded.map((item, idx: number) => (
                    <li key={idx} className="flex items-start gap-3 p-4 rounded-xl bg-[#fafafa] border border-[#efefef] hover:border-[#d8d8d8] hover:bg-white transition-colors duration-150">
                      <div className="w-6 h-6 rounded-full bg-[#1a1a1a] flex items-center justify-center shrink-0 mt-0.5">
                        <CheckCircle2 className="w-3.5 h-3.5 text-white" />
                      </div>
                      <div className="min-w-0">
                        <p className="text-sm font-semibold text-[#1a1a1a] leading-snug">{item.label}</p>
                        {item.description && (
                          <div
                            className="overflow-hidden transition-all duration-300 ease-in-out"
                            style={{ maxHeight: showIncludedDesc ? '20rem' : '0px', opacity: showIncludedDesc ? 1 : 0 }}
                          >
                            <p className="text-xs text-[#7a7a7a] leading-relaxed mt-1">{item.description}</p>
                          </div>
                        )}
                      </div>
                    </li>
                  ))}
                </ul>
              </section>
            )}

            {/* ── Product Variations ── */}
            {hasPageVariants && (
              <section>
                <div className="mb-6">
                  <div className="flex items-center gap-2 mb-3">
                    <div className="w-5 h-px bg-[#0a0a0a]/30" />
                    <p className="text-[10px] font-bold tracking-[0.25em] uppercase text-black/40">Choose Your Size</p>
                  </div>
                  <h2 className="text-2xl sm:text-3xl font-serif font-bold text-[#1a1a1a]">{isEn ? 'Available Options' : '作品規格選項'}</h2>
                  <p className="text-sm text-[#6a6a6a] mt-2">{isEn ? 'Select your preferred size or style when booking.' : '預約時可選擇心儀的尺寸或款式，價格因規格而異。'}</p>
                </div>

                {/* Image-card grid when any variant has an image */}
                {pageVariants!.some(v => v.imageUrl) ? (
                  <div className="grid grid-cols-2 sm:grid-cols-3 gap-4">
                    {pageVariants!.map((v) => (
                      <div
                        key={v.id}
                        className="group rounded-2xl overflow-hidden border border-[#efefef] bg-white hover:border-[#d0d0d0] hover:shadow-md transition-all duration-200"
                      >
                        {/* Image */}
                        <div className="w-full aspect-[4/3] bg-[#f5f5f5] overflow-hidden">
                          {v.imageUrl ? (
                            <img
                              src={v.imageUrl}
                              alt={`${v.name} — ${workshop.title}`}
                              className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"
                              loading="lazy"
                              decoding="async"
                              width="400"
                              height="300"
                            />
                          ) : (
                            <div className="w-full h-full flex items-center justify-center">
                              <span className="text-3xl text-[#d0d0d0]">🖼</span>
                            </div>
                          )}
                        </div>
                        {/* Info */}
                        <div className="px-4 py-3">
                          <p className="text-sm font-bold text-[#1a1a1a] leading-tight">{v.name}</p>
                          {v.description && (
                            <p className="text-xs text-[#7a7a7a] mt-0.5 leading-snug">{v.description}</p>
                          )}
                          <p className="text-base font-bold text-[#1a1a1a] mt-2">
                            {'HK$'}{(v.price / 100).toFixed(0)}
                            <span className="text-xs font-normal text-[#9a9a9a] ml-1">{isEn ? '/person' : '/位'}</span>
                          </p>
                        </div>
                      </div>
                    ))}
                  </div>
                ) : (
                  /* Text-only list when no images */
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                    {pageVariants!.map((v) => (
                      <div
                        key={v.id}
                        className="flex items-center justify-between px-5 py-4 rounded-xl bg-[#fafafa] border border-[#efefef] hover:border-[#d0d0d0] hover:bg-white transition-colors duration-150"
                      >
                        <div className="min-w-0">
                          <p className="text-sm font-bold text-[#1a1a1a]">{v.name}</p>
                          {v.description && (
                            <p className="text-xs text-[#7a7a7a] mt-0.5">{v.description}</p>
                          )}
                        </div>
                        <div className="shrink-0 ml-4 text-right">
                          <p className="text-base font-bold text-[#1a1a1a]">{'HK$'}{(v.price / 100).toFixed(0)}</p>
                          <p className="text-[11px] text-[#9a9a9a]">{isEn ? '/person' : '/位'}</p>
                        </div>
                      </div>
                    ))}
                  </div>
                )}

                {/* CTA */}
                <div className="mt-5 flex items-center gap-3 p-4 rounded-xl bg-[#0a0a0a]/[0.03] border border-[#0a0a0a]/[0.06]">
                  <div className="w-8 h-8 rounded-full bg-[#0a0a0a] flex items-center justify-center shrink-0">
                    <svg className="w-4 h-4 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                      <path strokeLinecap="round" strokeLinejoin="round" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                  </div>
                  <p className="text-xs text-[#5a5a5a] leading-relaxed">
                    {isEn
                      ? 'You can select your preferred option during booking. Price will be updated accordingly.'
                      : '預約時可在規格選項中選擇，總金額將根據所選規格及人數自動計算。'
                    }
                  </p>
                </div>
              </section>
            )}

            {/* Class Flow */}
            {classFlow.length > 0 && (
              <section>
                <div className="mb-6">
                  <div className="flex items-center gap-2 mb-3">
                    <div className="w-5 h-px bg-[#0a0a0a]/30" />
                    <p className="text-[10px] font-bold tracking-[0.25em] uppercase text-black/40">Workshop Flow</p>
                  </div>
                  <h2 className="text-2xl sm:text-3xl font-serif font-bold text-[#1a1a1a]">{t('workshopDetail.classFlow')}</h2>
                </div>
                <ol className="relative space-y-0">
                  {classFlow.map((step, idx: number) => (
                    <li key={idx} className="flex gap-5 pb-7 last:pb-0">
                      <div className="flex flex-col items-center">
                        <div className="w-9 h-9 rounded-full bg-[#0a0a0a] text-white text-sm font-bold flex items-center justify-center shrink-0 z-10 shadow-md ring-4 ring-[#f5f5f5]">
                          {idx + 1}
                        </div>
                        {idx < classFlow.length - 1 && (
                          <div className="w-px flex-1 mt-2" style={{ background: 'repeating-linear-gradient(to bottom, #d0d0d0 0px, #d0d0d0 4px, transparent 4px, transparent 8px)' }} />
                        )}
                      </div>
                      <div className="pt-1.5 pb-2 flex-1">
                        <div className="rounded-xl bg-[#fafafa] border border-[#efefef] hover:border-[#d8d8d8] hover:bg-white transition-colors duration-150 overflow-hidden">
                          {step.imageUrl && (
                            <ProgressiveImage
                              src={step.imageUrl}
                              alt={isTufting ? `Tufting 工作坊步驟 ${idx + 1} — Zoneout Studio` : `${workshop.title} 步驟 ${idx + 1}`}
                              loading="lazy"
                              width={600}
                              height={208}
                              className="w-full h-44 sm:h-52 object-cover"
                              wrapperClassName="w-full h-44 sm:h-52"
                            />
                          )}
                          <div className="p-4">
                            <p className="text-[#3d3d3d] leading-relaxed text-sm sm:text-base">{step.text}</p>
                          </div>
                        </div>
                      </div>
                    </li>
                  ))}
                </ol>
              </section>
            )}

            {/* Requirements */}
            {workshop.requirements && (
              <section>
                <div className="flex gap-4 p-5 sm:p-6 rounded-2xl bg-[#fafafa] border border-[#e0e0e0]">
                  <div className="w-8 h-8 rounded-full bg-[#0a0a0a] flex items-center justify-center shrink-0 mt-0.5">
                    <AlertCircle className="w-4 h-4 text-white" />
                  </div>
                  <div>
                    <p className="font-bold text-[#1a1a1a] mb-2 text-sm uppercase tracking-wide">{t('workshopDetail.requirements')}</p>
                    <p className="text-[#5a5a5a] text-sm leading-relaxed whitespace-pre-wrap">{workshop.requirements}</p>
                  </div>
                </div>
              </section>
            )}

            {/* Gift Section — Tufting only */}
            {isTufting && (
              <section>
                <div className="mb-6">
                  <div className="flex items-center gap-2 mb-3">
                    <div className="w-5 h-px bg-[#0a0a0a]/30" />
                    <p className="text-[10px] font-bold tracking-[0.25em] uppercase text-black/40">Gift Ideas</p>
                  </div>
                  <h2 className="text-2xl sm:text-3xl font-serif font-bold text-[#1a1a1a]">{isEn ? 'Perfect Gift — A Unique Hong Kong Experience' : '送禮首選 — 獨一無二的香港禮物體驗'}</h2>
                </div>
                <p className="text-[#4a4a4a] leading-[1.95] text-base sm:text-[1.0625rem] mb-6">
                   {isEn ? "Looking for a unique gift in Hong Kong? A Zoneout Studio Tufting Workshop experience is the most creative gift choice. Unlike ordinary presents, creating a tufted rug together with a Tufting Gun is more memorable and meaningful — perfect for birthdays, anniversaries, or couple gifts." : '找不到獨特禮物？一份 Zoneout Studio Tufting 工作坊體驗，是香港最有創意的禮物選擇。使用 Tufting Gun 親手製作獨一無二的簇絨地毯，比任何普通禮物更有紀念價值、更難忘。無論是生日禮物、情侶禮物、紀念日禮物，Tufting 工作坊都是最有心意的選擇。'}
                </p>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  {(isEn ? [
                    { icon: "🎂", title: "Birthday Gift", desc: "A unique experience gift — more memorable than any physical present" },
                    { icon: "❤️", title: "Couple Gift", desc: "Create something together — deepen your bond and make lasting memories" },
                    { icon: "🎉", title: "Anniversary Gift", desc: "Perfect for anniversaries, Valentine's Day, Mother's Day" },
                    { icon: "🌟", title: "Friend Gift", desc: "A special experience gift for your best friend" },
                  ] : [
                    { icon: "🎂", title: "生日禮物", desc: "送一個 Tufting 工作坊體驗，比任何實物更獨特難忘，親手製作的簇絨地毯更有心意" },
                    { icon: "❤️", title: "情侶禮物 / 拍拖好去處", desc: "一起用 Tufting Gun 創作，增進感情、留下屬於你們的獨特手作回憶" },
                    { icon: "🎉", title: "紀念日禮物", desc: "週年紀念、情人節、母親節首選 — 一件親手製作的 Tufting 地毯勝過千言萬語" },
                    { icon: "🌟", title: "朋友 / 閨蜜禮物", desc: "香港最特別的創意體驗禮物，一起玩 Tufting 留下美好回憶" },
                  ]).map(({ icon, title, desc }) => (
                    <div key={title} className="flex items-start gap-4 p-5 rounded-2xl bg-[#fafafa] border border-[#efefef] hover:border-[#d0d0d0] hover:bg-white transition-colors duration-150">
                      <span className="text-2xl shrink-0">{icon}</span>
                      <div>
                        <p className="font-bold text-[#1a1a1a] mb-1">{title}</p>
                        <p className="text-sm text-[#5a5a5a] leading-relaxed">{desc}</p>
                      </div>
                    </div>
                  ))}
                </div>
                <div className="mt-6 p-5 rounded-2xl bg-[#0a0a0a] text-white" style={{color: '#ff8585'}}>                  <p className="font-bold mb-1" style={{color: '#ff8585'}}>🎁 {isEn ? 'Gift Tip' : '送禮小貼士'}</p>
                  <p className="text-sm text-white/75 leading-relaxed">{isEn ? `Book a session for your loved one on a specific date — they'll discover the surprise when they arrive. Fully private, instructor-guided, take home same day. HK$${priceHKD} / person, all materials included.` : `可為對方預約指定日期，當天到工作室就會知道這是一份獨特禮物。全程私人包場，導師手把手指導，完成品即日帶走。費用 HK$${priceHKD} / 人，包含所有材料及導師費。`}</p>
                </div>
              </section>
            )}

            {/* Tufting HK SEO Guide Section */}
            {isTufting && (
              <section>
                <div className="mb-6">
                  <div className="flex items-center gap-2 mb-3">
                    <div className="w-5 h-px bg-[#0a0a0a]/30" />
                    <p className="text-[10px] font-bold tracking-[0.25em] uppercase text-black/40">{isEn ? 'Tufting HK Guide' : 'Tufting HK 完整指南'}</p>
                  </div>
                  <h2 className="text-2xl sm:text-3xl font-serif font-bold text-[#1a1a1a]">
                    {isEn ? 'Tufting HK — Everything You Need to Know' : 'Tufting HK 完整指南 — 香港簇絨地毯工作坊全攻略'}
                  </h2>
                </div>
                <div className="space-y-6 text-[#4a4a4a] leading-[1.95] text-base sm:text-[1.0625rem]">
                  <div>
                    <h3 className="text-lg font-bold text-[#1a1a1a] mb-2">{isEn ? 'What is Tufting?' : '什麼是 Tufting（簇絨）？'}</h3>
                    <p>{isEn
                      ? 'Tufting is a textile craft where yarn is punched through a backing fabric using a Tufting Gun to create a fluffy, textured rug or wall art. It originated from traditional rug-making, but Hong Kong workshops have made it accessible to complete beginners — no experience needed.'
                      : 'Tufting（簇絨）是一種紡織手工藝，使用 Tufting Gun（簇絨槍）將毛線穿入底布，製作出蓬鬆、有立體感的地毯或掛毯。近年在香港大受歡迎，零基礎也能輕鬆上手，親手製作屬於自己的簇絨作品。'}
                    </p>
                  </div>
                  <div>
                    <h3 className="text-lg font-bold text-[#1a1a1a] mb-2">{isEn ? 'Why Choose Zoneout Studio?' : '為什麼選擇 Zoneout Studio？'}</h3>
                    <p>{isEn
                      ? 'Unlike group tufting workshops in Hong Kong where you share the space with strangers, Zoneout Studio offers fully private sessions — each time slot is exclusively for you and your partner. Our San Po Kong studio is equipped with professional Tufting Guns, a wide selection of yarn colours, and an experienced instructor who guides you through every step.'
                      : '與香港其他工作坊不同，Zoneout Studio 採用全程私人包場形式 — 每個時段只屬於你們兩人，不與陌生人同場。新蒲崗工作室配備專業 Tufting Gun、豐富毛線顏色選擇，以及經驗豐富的導師全程手把手指導。'}
                    </p>
                  </div>
                  <div>
                    <h3 className="text-lg font-bold text-[#1a1a1a] mb-2">{isEn ? 'Location & Getting There' : '工作室地點及交通'}</h3>
                    <p>{isEn
                      ? 'Zoneout Studio is located in San Po Kong, Kowloon — a 3-minute walk from Diamond Hill MTR Station (Exit C2). Easily accessible from all parts of Hong Kong.'
                      : 'Zoneout Studio 位於九龍新蒲崗，鑽石山港鐵站 C2 出口步行約 3 分鐘即達，無論來自港島、九龍還是新界都能輕鬆到達。'}
                    </p>
                    <div className="mt-3 flex flex-wrap gap-2">
                      {(isEn ? ['San Po Kong', 'Diamond Hill MTR', '3 min walk', 'Kowloon', 'Easily accessible'] : ['新蒲崗', '鑽石山港鐵站', '步行 3 分鐘', '九龍', '交通方便']).map(tag => (
                        <span key={tag} className="text-[11px] font-medium text-[#5a5a5a] bg-[#f0f0f0] rounded-full px-3 py-1">{tag}</span>
                      ))}
                    </div>
                  </div>
                </div>
              </section>
            )}
            {/* Gift Section — Silver Ring */}
            {isSilver && (
              <section>
                <div className="mb-6">
                  <div className="flex items-center gap-2 mb-3">
                    <div className="w-5 h-px bg-[#0a0a0a]/30" />
                    <p className="text-[10px] font-bold tracking-[0.25em] uppercase text-black/40">Gift Ideas</p>
                  </div>
                  <h2 className="text-2xl sm:text-3xl font-serif font-bold text-[#1a1a1a]">{isEn ? 'Perfect Couple Gift — Handcrafted Silver Ring' : '情侶禮物首選 — 親手打造純銀對戒'}</h2>
                </div>
                <p className="text-[#4a4a4a] leading-[1.95] text-base sm:text-[1.0625rem] mb-6">
                  {isEn
                    ? 'Looking for a meaningful couple gift in Hong Kong? A handcrafted sterling silver ring is the most heartfelt choice. Unlike buying off-the-shelf jewellery, crafting a ring together at Zoneout Studio creates a lasting memory and a wearable symbol of your love — engraved with names or dates, taken home the same day.'
                    : '想找一份有意義的情侶禮物？一枚親手打造的純銀戒指，是比任何現成首飾更有心意的選擇。在 Zoneout Studio 一起製作，刻上名字或紀念日，完成品即日帶走，是最有紀念價值的情侶禮物、生日禮物及紀念日禮物。'}
                </p>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  {(isEn ? [
                    { icon: "💍", title: "Anniversary Gift", desc: "Engrave your anniversary date — a wearable reminder of your love story" },
                    { icon: "❤️", title: "Couple Gift", desc: "Craft matching rings together — the most romantic couple date idea in Hong Kong" },
                    { icon: "🎂", title: "Birthday Gift", desc: "A unique experience gift — more meaningful than any physical present" },
                    { icon: "💝", title: "Valentine's Day", desc: "Skip the flowers — give a sterling silver ring you made yourself" },
                  ] : [
                    { icon: "💍", title: "週年紀念禮物", desc: "刻上紀念日日期，每次戴上都是對愛情的提醒，是最有意義的週年禮物" },
                    { icon: "❤️", title: "情侶禮物 / 拍拖好去處", desc: "一起親手製作配對銀戒指，是香港最浪漫的情侶好去處體驗" },
                    { icon: "🎂", title: "生日禮物", desc: "送一個親手製作銀戒指的體驗，比任何現成禮物更獨特難忘" },
                    { icon: "💝", title: "情人節 / 求婚禮物", desc: "親手打造的純銀戒指，是最有心意的情人節或求婚前禮物" },
                  ]).map(({ icon, title, desc }) => (
                    <div key={title} className="flex items-start gap-4 p-5 rounded-2xl bg-[#fafafa] border border-[#efefef] hover:border-[#d0d0d0] hover:bg-white transition-colors duration-150">
                      <span className="text-2xl shrink-0">{icon}</span>
                      <div>
                        <p className="font-bold text-[#1a1a1a] mb-1">{title}</p>
                        <p className="text-sm text-[#5a5a5a] leading-relaxed">{desc}</p>
                      </div>
                    </div>
                  ))}
                </div>
                <div className="mt-6 p-5 rounded-2xl bg-[#0a0a0a] text-white">
                  <p className="font-bold mb-1" style={{color: '#ff8585'}}>🎁 {isEn ? 'Gift Tip' : '送禮小貼士'}</p>
                  <p className="text-sm text-white/75 leading-relaxed">{isEn ? `Book a session for your loved one on a specific date — they'll discover the surprise when they arrive. Fully private, instructor-guided, free engraving included. HK$${priceHKD} / person, all 999 sterling silver materials included.` : `可為對方預約指定日期，當天到工作室就會知道這是一份獨特驚喜。全程私人包場，導師手把手指導，免費刻字服務，完成品即日帶走。費用 HK$${priceHKD} / 人，包含所有 999 純銀材料及導師費。`}</p>
                </div>
              </section>
            )}

            {/* Silver Ring — Pricing */}
            {isSilver && (
              <section>
                <div className="mb-6">
                  <div className="flex items-center gap-2 mb-3">
                    <div className="w-5 h-px bg-[#0a0a0a]/30" />
                    <p className="text-[10px] font-bold tracking-[0.25em] uppercase text-black/40">{isEn ? 'Pricing' : '費用'}</p>
                  </div>
                  <h2 className="text-2xl sm:text-3xl font-serif font-bold text-[#1a1a1a]">{isEn ? 'Workshop Pricing' : '工作坊費用'}</h2>
                </div>
                {/* Pricing Table */}
                <div className="mt-0">
                  <div className="rounded-2xl border border-[#efefef] overflow-hidden">
                    <div className="grid grid-cols-3 bg-[#0a0a0a] text-white text-xs font-bold uppercase tracking-wider px-5 py-3">
                      <span>{isEn ? 'Package' : '方案'}</span>
                      <span className="text-center">{isEn ? 'Per Person' : '每人'}</span>
                      <span className="text-right">{isEn ? 'Couple Total' : '情侶合計'}</span>
                    </div>
                    <div className="grid grid-cols-3 px-5 py-4 border-b border-[#f0f0f0] bg-white">
                      <div>
                        <p className="font-semibold text-[#1a1a1a] text-sm">{isEn ? 'Silver Ring' : '純銀戒指'}</p>
                        <p className="text-xs text-[#9a9a9a] mt-0.5">{isEn ? '3 hrs · 2 rings' : '3 小時 · 2 枚戒指'}</p>
                      </div>
                      <p className="text-center font-bold text-[#1a1a1a]">HK${priceHKD}</p>
                      <p className="text-right font-bold text-[#1a1a1a]">HK${(workshop.price / 100 * 2).toFixed(0)}</p>
                    </div>
                    <div className="px-5 py-3 bg-[#fafafa] text-xs text-[#5a5a5a]">
                      {isEn
                        ? '✓ All 999 sterling silver materials  ✓ Tools & equipment  ✓ Instructor guidance  ✓ Free engraving  ✓ Take home same day'
                        : '✓ 所有 999 純銀材料  ✓ 工具及設備  ✓ 導師全程指導  ✓ 免費刻字  ✓ 完成品即日帶走'}
                    </div>
                  </div>
                </div>
              </section>
            )}

            {/* Workshop Gallery */}
            {galleryImages && galleryImages.length > 0 && (
              <section>
                <div className="mb-6">
                  <div className="flex items-center gap-2 mb-3">
                    <div className="w-5 h-px bg-[#0a0a0a]/30" />
                    <p className="text-[10px] font-bold tracking-[0.25em] uppercase text-black/40">Student Work</p>
                  </div>
                  <h2 className="text-2xl sm:text-3xl font-serif font-bold text-[#1a1a1a]">{t('workshopDetail.gallery')}</h2>
                </div>
                <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
                  {galleryImages.map((img, idx) => (
                    <button
                      key={img.id}
                      onClick={() => setLightboxIndex(idx)}
                      className="group aspect-square rounded-xl overflow-hidden bg-[#f0f0f0] relative focus:outline-none focus:ring-2 focus:ring-[#0a0a0a] focus:ring-offset-2"
                      aria-label={img.caption ?? `作品圖片 ${idx + 1}`}
                    >
                      <ProgressiveImage
                        src={img.imageUrl}
                        alt={img.caption ?? (isTufting ? `Tufting 掛毯學員作品 ${idx + 1} — Zoneout Studio 香港 Tufting 工作坊` : `${workshop.title} 學員作品 ${idx + 1}`)}
                        className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"
                        wrapperClassName="w-full h-full"
                        loading="lazy"
                        width={400}
                        height={400}
                      />
                      <div className="absolute inset-0 bg-black/0 group-hover:bg-black/25 transition-colors duration-200 flex items-center justify-center pointer-events-none">
                        <ZoomIn className="w-6 h-6 text-white opacity-0 group-hover:opacity-100 transition-opacity duration-200" />
                      </div>
                      {img.caption && (
                        <div className="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/70 to-transparent p-3 opacity-0 group-hover:opacity-100 transition-opacity duration-200">
                          <p className="text-xs text-white truncate">{img.caption}</p>
                        </div>
                      )}
                    </button>
                  ))}
                </div>
              </section>
            )}

            {/* FAQ */}
            {effectiveFaq.length > 0 && (
              <section>
                <div className="mb-6">
                  <div className="flex items-center gap-2 mb-3">
                    <div className="w-5 h-px bg-[#0a0a0a]/30" />
                    <p className="text-[10px] font-bold tracking-[0.25em] uppercase text-black/40">FAQ</p>
                  </div>
                  <h2 className="text-2xl sm:text-3xl font-serif font-bold text-[#1a1a1a]">{t('workshopDetail.faq')}</h2>
                </div>
                <div className="divide-y divide-[#f0f0f0] border border-[#efefef] rounded-2xl overflow-hidden">
                  {effectiveFaq.map((item, idx: number) => (
                    <div key={idx}>
                      <button
                        onClick={() => setExpandedFaq(expandedFaq === idx ? null : idx)}
                        aria-expanded={expandedFaq === idx}
                        className="w-full flex items-center justify-between gap-4 px-5 sm:px-6 py-5 text-left hover:bg-[#fafafa] transition-colors duration-150 focus-visible:outline-none"
                      >
                        <span className="font-semibold text-[#1a1a1a] text-sm sm:text-base leading-snug">{item.question}</span>
                        <ChevronDown className={`w-4 h-4 text-[#9a9a9a] shrink-0 transition-transform duration-300 ${expandedFaq === idx ? "rotate-180" : ""}`} />
                      </button>
                      <div className={`overflow-hidden transition-all duration-300 ${expandedFaq === idx ? "max-h-96" : "max-h-0"}`}>
                        <p className="px-5 sm:px-6 pb-5 pt-1 text-sm text-[#5a5a5a] leading-relaxed bg-[#fafafa]">{item.answer}</p>
                      </div>
                    </div>
                  ))}
                </div>
                {/* Internal nav cards — shown below FAQ for all workshops */}
                {(() => {
                  const navCards: { href: string; icon: string; title: string; desc: string }[] = isTufting ? [
                    { href: "/workshops", icon: "🎨", title: isEn ? 'All Workshops' : '全部工作坊', desc: isEn ? 'Browse Tufting, Silver, Pottery & more' : '瀏覽 Tufting、銀飾、陶藝等情侶好去處' },
                    { href: "/gallery", icon: "📸", title: isEn ? 'Student Gallery' : '學員作品集', desc: isEn ? "See other couples' tufting works" : '看看其他情侶的 Tufting 作品' },
                    { href: "/about", icon: "🏠", title: isEn ? 'About the Studio' : '關於工作室', desc: isEn ? 'Discover Zoneout Studio San Po Kong' : '了解 Zoneout Studio 全新工作室空間' },
                  ] : isSilver ? [
                    { href: "/workshops", icon: "🎨", title: isEn ? 'All Workshops' : '全部工作坊', desc: isEn ? 'Browse Tufting, Silver & more' : '瀏覽 Tufting、銀飾等情侶好去處' },
                    { href: "/workshops/tufting-workshop", icon: "🧶", title: 'Tufting Workshop', desc: isEn ? 'Another popular couple experience — make a rug together' : '另一熱門情侶手作體驗，親手製作掟毯' },
                    { href: "/gallery", icon: "📸", title: isEn ? 'Student Gallery' : '學員作品集', desc: isEn ? "See other couples' silver works" : '看看其他情侶的銀飾作品' },
                  ] : [
                    { href: "/workshops", icon: "🎨", title: isEn ? 'All Workshops' : '全部工作坊', desc: isEn ? 'Browse more Hong Kong couple date ideas' : '瀏覽更多香港情侶手作好去處' },
                    { href: "/gallery", icon: "📸", title: isEn ? 'Student Gallery' : '學員作品集', desc: isEn ? 'See other students\' amazing works' : '看看其他學員的精彩作品' },
                    { href: "/about", icon: "🏠", title: isEn ? 'About the Studio' : '關於工作室', desc: isEn ? 'Discover Zoneout Studio' : '了解 Zoneout Studio 工作室空間' },
                  ];
                  return (
                    <nav aria-label={isEn ? 'Related pages' : '相關頁面'} className="mt-8 border-t border-[#f0f0f0] pt-7">
                      <p className="text-[10px] font-bold tracking-[0.25em] uppercase text-black/40 mb-4">{isEn ? 'Explore More Date Ideas' : '探索更多拍拖好去處'}</p>
                      <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
                        {navCards.map(({ href, icon, title, desc }) => (
                          <a
                            key={href}
                            href={href}
                            className="group flex items-start gap-3 p-4 rounded-xl border border-[#efefef] bg-[#fafafa] hover:border-[#0a0a0a] hover:bg-white transition-all duration-200"
                          >
                            <span className="text-xl shrink-0 mt-0.5">{icon}</span>
                            <div>
                              <p className="text-sm font-semibold text-[#1a1a1a] group-hover:text-[#0a0a0a]">{title}</p>
                              <p className="text-xs text-[#8a8a8a] mt-0.5 leading-snug">{desc}</p>
                            </div>
                            <ChevronRight className="w-4 h-4 text-[#c0c0c0] group-hover:text-[#0a0a0a] shrink-0 ml-auto mt-0.5 transition-colors" />
                          </a>
                        ))}
                      </div>
                    </nav>
                  );
                })()}
              </section>
            )}

          </article>

          {/* ── Right: Sticky Booking Card ── */}
          <aside ref={bookingCardRef} className="hidden lg:block lg:sticky lg:top-28">
            <BookingCard
              workshopId={workshop.id}
              price={workshop.price}
              duration={workshop.duration}
              maxParticipants={workshop.maxParticipants}
              difficulty={workshop.difficulty ?? undefined}
              variants={pageVariants}
              monthlyCount={detailMonthlyCount}
              onBook={() => { trackBookingCTAClick(workshop.title); setIsBookingModalOpen(true); }}
              onContact={() => navigate("/contact")}
            />
            {/* Related links below booking card — desktop only, all workshops */}
            {(() => {
                  const asideLinks: { href: string; label: string }[] = isTufting ? [
                { href: "/workshops", label: isEn ? 'All Workshops · Date Ideas' : '所有工作坊 · 情侶好去處' },
                { href: "/gallery", label: isEn ? 'Student Tufting Gallery' : '學員 Tufting 作品集' },
                { href: "/about", label: isEn ? 'About Zoneout Studio' : '關於 Zoneout Studio' },
                { href: "/contact", label: isEn ? 'Corporate / Group Enquiry' : '機構包場 / 團體詢問' },
              ] : isSilver ? [
                { href: "/workshops", label: isEn ? 'All Workshops · Date Ideas' : '所有工作坊 · 情侶好去處' },
                { href: "/workshops/tufting-workshop", label: isEn ? 'Tufting Rug Workshop' : 'Tufting 地毯工作坊' },
                { href: "/gallery", label: isEn ? 'Student Silver Gallery' : '學員銀飾作品集' },
                { href: "/contact", label: isEn ? 'Corporate / Group Enquiry' : '機構包場 / 團體詢問' },
              ] : [
                { href: "/workshops", label: isEn ? 'All Workshops · Date Ideas' : '所有工作坊 · 情侶好去處' },
                { href: "/gallery", label: isEn ? 'Student Gallery' : '學員作品集' },
                { href: "/about", label: isEn ? 'About Zoneout Studio' : '關於 Zoneout Studio' },
                { href: "/contact", label: isEn ? 'Corporate / Group Enquiry' : '機構包場 / 團體詢問' },
              ];
              return (
                <nav aria-label={isEn ? 'Related links' : '相關連結'} className="mt-5 space-y-2">
                  <p className="text-[10px] font-bold tracking-[0.2em] uppercase text-[#b0b0b0] mb-3">{isEn ? 'Related Pages' : '相關頁面'}</p>
                  {asideLinks.map(({ href, label }) => (
                    <a
                      key={href}
                      href={href}
                      className="flex items-center justify-between px-4 py-2.5 rounded-lg border border-[#efefef] text-sm text-[#5a5a5a] hover:border-[#0a0a0a] hover:text-[#0a0a0a] hover:bg-[#fafafa] transition-all duration-150 group"
                    >
                      <span>{label}</span>
                      <ChevronRight className="w-3.5 h-3.5 text-[#c8c8c8] group-hover:text-[#0a0a0a] transition-colors" />
                    </a>
                  ))}
                </nav>
              );
            })()}
            {/* Social share strip — desktop aside */}
            <div className="mt-5 pt-4 border-t border-[#f0f0f0]">
              <ShareButton
                title={workshop.title}
                description={workshop.description ?? undefined}
                url={pageUrl}
                variant="inline"
              />
            </div>
          </aside>
        </div>
      </div>

      <Footer />

      {/* ── Mobile Sticky Bottom Bar ── */}
      <div className="lg:hidden fixed bottom-0 left-0 right-0 z-40 bg-white/95 backdrop-blur-md border-t border-[#e8e8e8] px-4 py-3 flex items-center gap-2 shadow-[0_-4px_24px_rgba(0,0,0,0.08)]">
        <div className="flex-1 min-w-0">
          <p className="text-[10px] text-[#9a9a9a] uppercase tracking-wide">{isEn ? 'Per Person' : '每人費用'}</p>
          <p className="text-2xl font-bold text-[#0a0a0a] leading-tight">{'HK$'}{(workshop.price / 100).toFixed(0)}</p>
        </div>
        {/* Share button — mobile */}
        <ShareButton
          title={workshop.title}
          description={workshop.description ?? undefined}
          url={pageUrl}
          size="sm"
        />
        <Button className="bg-[#0a0a0a] text-white hover:bg-[#0a0a0a]/85 px-6 h-12 rounded-xl text-base font-semibold shrink-0" onClick={handleBookClick}>
          <Heart className="w-4 h-4 mr-2 fill-white" />
          {isEn ? 'Book Now' : '立即預約'}
        </Button>
      </div>

      {/* ── Gallery Lightbox ── */}
      {galleryImages && lightboxIndex !== null && (
        <div
          className="fixed inset-0 z-50 bg-black/95 flex items-center justify-center"
          onClick={() => setLightboxIndex(null)}
          role="dialog"
          aria-modal="true"
        >
          <button
            className="absolute top-5 right-5 z-10 p-2.5 rounded-full bg-white/10 hover:bg-white/20 text-white transition-colors"
            onClick={() => setLightboxIndex(null)}
            aria-label={isEn ? 'Close' : '關閉'}
          >
            <X className="w-5 h-5" />
          </button>
          {lightboxIndex > 0 && (
            <button
              className="absolute left-4 top-1/2 -translate-y-1/2 z-10 p-3 rounded-full bg-white/10 hover:bg-white/20 text-white transition-colors"
              onClick={(e) => { e.stopPropagation(); setLightboxIndex(lightboxIndex - 1); }}
              aria-label={isEn ? 'Previous' : '上一張'}
            >
              <ChevronLeft className="w-6 h-6" />
            </button>
          )}
          {lightboxIndex < galleryImages.length - 1 && (
            <button
              className="absolute right-4 top-1/2 -translate-y-1/2 z-10 p-3 rounded-full bg-white/10 hover:bg-white/20 text-white transition-colors"
              onClick={(e) => { e.stopPropagation(); setLightboxIndex(lightboxIndex + 1); }}
              aria-label={isEn ? 'Next' : '下一張'}
            >
              <ChevronRight className="w-6 h-6" />
            </button>
          )}
          <div className="max-w-3xl max-h-[85vh] px-16" onClick={(e) => e.stopPropagation()}>
            <img
              src={galleryImages[lightboxIndex].imageUrl}
              alt={galleryImages[lightboxIndex].caption ?? (isTufting ? `Tufting 掛毯作品 — Zoneout Studio 香港 Tufting 工作坊` : `${workshop.title} 學員作品`)}
              loading="eager"
              decoding="async"
              width="1200"
              height="900"
              className="max-w-full max-h-[80vh] object-contain rounded-xl shadow-2xl"
            />
            {galleryImages[lightboxIndex].caption && (
              <p className="text-center text-white/70 text-sm mt-3">{galleryImages[lightboxIndex].caption}</p>
            )}
            <p className="text-center text-white/40 text-xs mt-1">{lightboxIndex + 1} / {galleryImages.length}</p>
          </div>
        </div>
      )}

      {/* ── Booking Modal (lazy-loaded — only fetched when user opens it) ── */}
      {workshop && isBookingModalOpen && (
        <Suspense fallback={null}>
          <BookingModal
            workshopId={workshop.id}
            workshopTitle={workshop.title}
            workshopPrice={workshop.price}
            isOpen={isBookingModalOpen}
            onClose={() => setIsBookingModalOpen(false)}
            onSubmit={handleBookingSubmit}
          />
        </Suspense>
      )}
    </div>
  );
}
