'use client';

/**
 * BusinessPage - React island for /business/[slug] (FDS §4.6).
 *
 * Composes:
 *  - BusinessHeader (blue block, name + hours, club badge, joined-via strip)
 *  - MapThumbnail (bottom-left of header area)
 *  - GalleryCarousel for vendor gallery
 *  - "Active deals" section with DealCard grid
 *  - Reviews section (stacked) + ReviewCard + TechnicalReviewCard
 *  - User gallery carousel
 *  - ReportButton and ShareButton in header
 *
 * JSON-LD is baked in by the Astro page via SeoHead.
 */

import { useMemo } from 'react';
import { israelWeekdayIndex } from '@/lib/datetime';
import { AppShell } from '@/components/ui/layout/AppShell';
import { HydratedIsland } from '@/components/HydratedIsland';
import { BottomNav } from '@/components/ui/layout/BottomNav';
import { SiteNav } from '@/components/ui/layout/SiteNav';
import { Container } from '@/components/ui/layout/Container';
import { Grid } from '@/components/ui/layout/Grid';
import { Breadcrumb } from '@/components/ui/layout/Breadcrumb';
import { Hero } from '@/components/ui/layout/Hero';
import { BusinessHeader } from '@/components/ui/domain/BusinessHeader';
import { GalleryCarousel } from '@/components/ui/domain/GalleryCarousel';
import { HeroCarousel } from '@/components/ui/domain/HeroCarousel';
import { MapThumbnail } from '@/components/ui/domain/MapThumbnail';
import { DealCard } from '@/components/ui/domain/DealCard';
import { ReviewCard } from '@/components/ui/domain/ReviewCard';
import { TechnicalReviewCard } from '@/components/ui/domain/TechnicalReviewCard';
import { ReportButton } from '@/components/ui/domain/ReportButton';
import { ShareButton } from '@/components/ui/domain/ShareButton';
import { FavoriteButton } from '@/components/ui/domain/FavoriteButton';
import { EmptyState } from '@/components/ui/feedback/EmptyState';
import { Icon } from '@/components/ui/icons/Icon';
import { GlobalCartDrawer } from '@/components/ui/domain/cart/GlobalCartDrawer';
import { AmbientDealCard } from '@/features/deals/AmbientDealCard';
import { CheckoutModal } from '@/features/checkout-modal/CheckoutModal';
import { useT } from '@/lib/i18n/react';
import { WishlistProvider } from '@/features/wishlist';
import { useAuthGateStore } from '@/lib/stores/auth-gate';
import { AuthGateModal } from '@/features/auth-flow/AuthGateModal';
import type { BusinessPageData } from './BusinessPageDataLoader';
import type { Locale } from '@/lib/i18n';
import type { BottomNavItem } from '@/components/ui/layout/BottomNav';
import type { DealCardDeal } from '@/components/ui/domain/DealCard';
import type { HeroCarouselSlide } from '@/components/ui/domain/HeroCarousel';

function showHeroImage(vendor: {
  heroImageUrl?: string | null;
  heroImageApprovalStatus?: string;
  tier?: string;
}): boolean {
  if (!vendor.heroImageUrl) return false;
  const status = vendor.heroImageApprovalStatus;
  const tier = vendor.tier;
  if (status === 'REJECTED') return false;
  if (status === 'APPROVED') return true;
  // PENDING: show for established vendors (VETERAN), hide for NEW
  return tier !== 'NEW';
}

export interface BusinessPageProps {
  data: BusinessPageData;
  locale: Locale;
  siteUrl: string;
  isGuest?: boolean;
  isAdmin?: boolean;
  isVendor?: boolean;
  isFavorited?: boolean;
}

function formatHours(hours: BusinessPageData['hours']): string {
  if (!hours) return '';
  const day = israelWeekdayIndex();

  const dayMap: Array<{ open: string | null; close: string | null; closed: boolean }> = [
    { open: hours.sundayOpen, close: hours.sundayClose, closed: hours.sundayClosed },
    { open: hours.mondayOpen, close: hours.mondayClose, closed: hours.mondayClosed },
    { open: hours.tuesdayOpen, close: hours.tuesdayClose, closed: hours.tuesdayClosed },
    { open: hours.wednesdayOpen, close: hours.wednesdayClose, closed: hours.wednesdayClosed },
    { open: hours.thursdayOpen, close: hours.thursdayClose, closed: hours.thursdayClosed },
    { open: hours.fridayOpen, close: hours.fridayClose, closed: hours.fridayClosed },
    { open: hours.saturdayOpen, close: hours.saturdayClose, closed: hours.saturdayClosed },
  ];

  const today = dayMap[day];
  if (!today || today.closed) return '';
  if (today.open && today.close) return `${today.open.slice(0, 5)}-${today.close.slice(0, 5)}`;
  return '';
}

function toActiveDealCard(
  deal: BusinessPageData['activeDeals'][number],
  vendorName: string,
): DealCardDeal {
  return {
    id: deal.id,
    title: deal.title,
    vendorName,
    city: '',
    originalPrice: deal.originalPrice,
    discountedPrice: deal.discountedPrice,
    imageSrc: deal.imageUrl ?? '',
    imageAlt: deal.title,
    windowEnd: deal.windowEnd ?? new Date(Date.now() + 86400000).toISOString(),
    stockRemaining: deal.quantityTotal - deal.quantitySold,
    stockTotal: deal.quantityTotal,
    dealType: deal.dealType,
    discountPercent: deal.discountPercent,
    heSlug: deal.heSlug ?? undefined,
  };
}

function BusinessPageInner({
  data,
  siteUrl,
  isGuest = true,
  isAdmin = false,
  isVendor = false,
}: Omit<BusinessPageProps, 'locale'>) {
  const { triggerAuth } = useAuthGateStore();
  const t = useT('business_page');
  const tNav = useT('nav');

  const { vendor } = data;

  const navItems: BottomNavItem[] = [
    { href: '/', icon: <Icon name="Check" size="sm" />, label: tNav('home') },
    { href: '/search', icon: <Icon name="Search" size="sm" />, label: tNav('search') },
    { href: '/purchases', icon: <Icon name="ShoppingBag" size="sm" />, label: tNav('purchases') },
    { href: '/profile', icon: <Icon name="User" size="sm" />, label: tNav('profile') },
  ];

  const hoursStr = formatHours(data.hours);

  const heroSlides = useMemo<HeroCarouselSlide[]>(() => {
    if (data.vendorGallery.length > 0) {
      return data.vendorGallery.slice(0, 5).map((img) => ({
        id: img.id,
        imageSrc: img.src,
        imageAlt: img.alt,
        label: vendor.displayName,
      }));
    }
    if (showHeroImage(vendor)) {
      return [
        {
          id: 'hero',
          imageSrc: vendor.heroImageUrl!,
          imageAlt: vendor.displayName,
          label: vendor.displayName,
          focalX: vendor.heroFocalX ?? 0.5,
          focalY: vendor.heroFocalY ?? 0.5,
        },
      ];
    }
    return [];
  }, [data.vendorGallery, vendor]);

  return (
    <AppShell
      mode="customer"
      desktopTopBar={
        <SiteNav
          variant="desktop"
          currentPath={`/business/${vendor.slug}`}
          isGuest={isGuest}
          isAdmin={isAdmin}
          isVendor={isVendor}
        />
      }
      topBar={
        <SiteNav
          variant="mobile"
          title=""
          currentPath={`/business/${vendor.slug}`}
          isGuest={isGuest}
          isAdmin={isAdmin}
          isVendor={isVendor}
          endExtra={
            <>
              <ReportButton
                targetId={vendor.id}
                targetType="VENDOR"
                showLabel
                className="text-text-inverse hover:text-text-inverse/70"
              />
              <ShareButton
                shareParams={{ targetUrl: `${siteUrl}/business/${vendor.slug}` }}
                title={vendor.displayName}
                showLabel
                className="text-text-inverse hover:text-text-inverse/70"
              />
              <FavoriteButton
                vendorId={vendor.id}
                onAuthRequired={triggerAuth}
                showLabel
                className="text-text-inverse hover:text-text-inverse/70"
              />
            </>
          }
        />
      }
      bottomNav={<BottomNav mode="customer" items={navItems} />}
      pageOverlays={<GlobalCartDrawer />}
    >
      <div>
        <Breadcrumb items={[{ label: tNav('home'), href: '/' }, { label: vendor.displayName }]} />
        {/* Desktop hero carousel */}
        {heroSlides.length > 0 && (
          <div className="hidden h-[28rem] lg:block">
            <Hero size="full" className="h-full">
              <HeroCarousel slides={heroSlides} mode="gallery" />
            </Hero>
          </div>
        )}

        {/* Mobile layout */}
        <div className="lg:hidden">
          {/* Business Header - h1 inside */}
          <BusinessHeader
            businessName={vendor.displayName}
            description={vendor.description || undefined}
            hours={hoursStr || undefined}
            joinedViaDeal={data.joinedViaDeal}
            isClubMember={data.isMember}
          />

          {/* Map thumbnail */}
          {vendor.lat !== undefined && vendor.lng !== undefined && vendor.address && (
            <div className="px-4 py-3">
              <MapThumbnail
                lat={vendor.lat}
                lng={vendor.lng}
                address={vendor.address}
                className="h-28 w-full"
              />
            </div>
          )}

          {/* Vendor gallery */}
          {data.vendorGallery.length > 0 && (
            <section aria-label={t('vendor_gallery')}>
              <GalleryCarousel images={data.vendorGallery} variant="vendor" />
            </section>
          )}

          {/* Active deals section */}
          <section aria-labelledby="active-deals-heading-mobile" className="px-4 py-4">
            <h2
              id="active-deals-heading-mobile"
              className="text-text-primary mb-3 text-2xl font-[var(--font-weight-extrabold)]"
            >
              {t('active_deals')}
            </h2>
            {data.activeDeals.length === 0 ? (
              <EmptyState title={t('active_deals')} />
            ) : (
              <Grid cols={3} gap="3">
                {data.activeDeals.map((deal) => (
                  <AmbientDealCard key={deal.id} imageSrc={deal.imageUrl}>
                    <DealCard deal={toActiveDealCard(deal, vendor.displayName)} variant="grid" />
                  </AmbientDealCard>
                ))}
              </Grid>
            )}
          </section>

          {/* Reviews section — stacked (no tabs) */}
          {data.reviews.length > 0 && (
            <section aria-labelledby="reviews-heading-mobile" className="py-2">
              <h2
                id="reviews-heading-mobile"
                className="text-text-primary px-4 py-2 text-2xl font-[var(--font-weight-extrabold)]"
              >
                {t('reviews_tab')}
                {vendor.reviewsCount > 0 && (
                  <span className="text-text-muted ms-2 text-sm font-normal">
                    ({vendor.reviewsScore.toFixed(1)} · {vendor.reviewsCount})
                  </span>
                )}
              </h2>
              <div className="flex flex-col gap-3 p-4">
                {data.reviews.map((r) => (
                  <ReviewCard
                    key={r.id}
                    reviewerName={r.reviewerName}
                    rating={r.rating ?? 0}
                    body={r.body}
                    date={r.date}
                    vendorReply={r.vendorReply ?? undefined}
                  />
                ))}
              </div>
            </section>
          )}

          {/* Technical reviews section — stacked */}
          {data.technicalReviews.length > 0 && (
            <section aria-labelledby="technical-heading-mobile" className="py-2">
              <h2
                id="technical-heading-mobile"
                className="text-text-primary px-4 py-2 text-2xl font-[var(--font-weight-extrabold)]"
              >
                {t('technical_tab')}
              </h2>
              <div className="flex flex-col gap-3 p-4">
                {data.technicalReviews.map((r) => (
                  <TechnicalReviewCard
                    key={r.id}
                    reviewerName={r.reviewerName}
                    body={r.body}
                    date={r.date}
                  />
                ))}
              </div>
            </section>
          )}

          {/* User gallery */}
          {data.userGallery.length > 0 && (
            <section aria-label={t('user_gallery')}>
              <h2 className="text-text-primary px-4 py-2 text-2xl font-[var(--font-weight-extrabold)]">
                {t('user_gallery')}
              </h2>
              <GalleryCarousel images={data.userGallery} variant="user" />
            </section>
          )}
        </div>

        {/* Desktop layout: two-column */}
        <div className="hidden lg:block">
          <Container maxWidth="4xl" px="8" className="py-8">
            <div className="flex items-start gap-10">
              {/* Left sidebar: BusinessHeader + map + actions */}
              <div className="sticky-below-topnav sticky flex w-80 shrink-0 flex-col gap-4">
                <BusinessHeader
                  businessName={vendor.displayName}
                  description={vendor.description || undefined}
                  hours={hoursStr || undefined}
                  joinedViaDeal={data.joinedViaDeal}
                  isClubMember={data.isMember}
                />
                {vendor.lat !== undefined && vendor.lng !== undefined && vendor.address && (
                  <MapThumbnail
                    lat={vendor.lat}
                    lng={vendor.lng}
                    address={vendor.address}
                    className="h-36 w-full"
                  />
                )}
                <div className="flex gap-2">
                  <FavoriteButton vendorId={vendor.id} onAuthRequired={triggerAuth} showLabel />
                  <ReportButton targetId={vendor.id} targetType="VENDOR" showLabel />
                  <ShareButton
                    shareParams={{ targetUrl: `${siteUrl}/business/${vendor.slug}` }}
                    title={vendor.displayName}
                    showLabel
                  />
                </div>
              </div>

              {/* Right: deals + offers + reviews + user gallery */}
              <div className="flex min-w-0 flex-1 flex-col gap-8">
                {/* Active deals */}
                <section aria-labelledby="active-deals-heading-desktop">
                  <h2
                    id="active-deals-heading-desktop"
                    className="text-text-primary mb-4 text-2xl font-[var(--font-weight-extrabold)]"
                  >
                    {t('active_deals')}
                  </h2>
                  {data.activeDeals.length === 0 ? (
                    <EmptyState title={t('active_deals')} />
                  ) : (
                    <Grid cols={3} lgCols={4} gap="3">
                      {data.activeDeals.map((deal) => (
                        <AmbientDealCard key={deal.id} imageSrc={deal.imageUrl}>
                          <DealCard
                            deal={toActiveDealCard(deal, vendor.displayName)}
                            variant="grid"
                          />
                        </AmbientDealCard>
                      ))}
                    </Grid>
                  )}
                </section>

                {/* Reviews — stacked (no tabs) */}
                {data.reviews.length > 0 && (
                  <section aria-labelledby="reviews-heading-desktop">
                    <h2
                      id="reviews-heading-desktop"
                      className="text-text-primary mb-4 text-2xl font-[var(--font-weight-extrabold)]"
                    >
                      {t('reviews_tab')}
                      {vendor.reviewsCount > 0 && (
                        <span className="text-text-muted ms-2 text-sm font-normal">
                          ({vendor.reviewsScore.toFixed(1)} · {vendor.reviewsCount})
                        </span>
                      )}
                    </h2>
                    <div className="flex flex-col gap-3">
                      {data.reviews.map((r) => (
                        <ReviewCard
                          key={r.id}
                          reviewerName={r.reviewerName}
                          rating={r.rating ?? 0}
                          body={r.body}
                          date={r.date}
                          vendorReply={r.vendorReply ?? undefined}
                        />
                      ))}
                    </div>
                  </section>
                )}

                {/* Technical reviews — stacked */}
                {data.technicalReviews.length > 0 && (
                  <section aria-labelledby="technical-heading-desktop">
                    <h2
                      id="technical-heading-desktop"
                      className="text-text-primary mb-4 text-2xl font-[var(--font-weight-extrabold)]"
                    >
                      {t('technical_tab')}
                    </h2>
                    <div className="flex flex-col gap-3">
                      {data.technicalReviews.map((r) => (
                        <TechnicalReviewCard
                          key={r.id}
                          reviewerName={r.reviewerName}
                          body={r.body}
                          date={r.date}
                        />
                      ))}
                    </div>
                  </section>
                )}

                {/* User gallery */}
                {data.userGallery.length > 0 && (
                  <section aria-label={t('user_gallery')}>
                    <h2 className="text-text-primary mb-4 text-2xl font-[var(--font-weight-extrabold)]">
                      {t('user_gallery')}
                    </h2>
                    <GalleryCarousel images={data.userGallery} variant="user" />
                  </section>
                )}
              </div>
            </div>
          </Container>
        </div>
      </div>
    </AppShell>
  );
}

export function BusinessPage({
  data,
  locale,
  siteUrl,
  isGuest,
  isAdmin,
  isVendor,
}: BusinessPageProps) {
  return (
    <HydratedIsland locale={locale}>
      <WishlistProvider
        initialVendorIds={data.isFavorited ? [data.vendor.id] : []}
        isAuthenticated={!isGuest}
      >
        <BusinessPageInner
          data={data}
          siteUrl={siteUrl}
          isGuest={isGuest}
          isAdmin={isAdmin}
          isVendor={isVendor}
        />
      </WishlistProvider>
      <AuthGateModal />
      <CheckoutModal />
    </HydratedIsland>
  );
}
