'use client';

/**
 * MobileDealDetails — stateless mobile deal details block.
 *
 * Receives a `ctaRef` to attach to the CTA wrapper div so that the
 * IntersectionObserver in DealDetailInner can track CTA visibility.
 * The observer itself remains in the coordinator (DealDetailInner) because
 * its output (`mobileTopCtaHidden`) is also consumed by the mobile StickyCTA.
 *
 * Owns no state.
 */

import type { RefObject } from 'react';
import { Badge } from '@/components/ui/primitives/Badge';
import { Icon } from '@/components/ui/icons/Icon';
import { PriceDisplay } from '@/components/ui/domain/PriceDisplay';
import { CountdownTimer } from '@/components/ui/domain/CountdownTimer';
import { WishlistButton } from '@/components/ui/domain/WishlistButton';
import { ReportButton } from '@/components/ui/domain/ReportButton';
import { TagPills } from '@/components/ui/domain/TagPills';
import { ReportTranslationButton } from '@/components/ui/domain/translation/ReportTranslationButton/ReportTranslationButton';
import { useT } from '@/lib/i18n/react';
import { useAuthGateStore } from '@/lib/stores/auth-gate';
import { computeGroupProgress } from '@/lib/group-deal/progress';
import { DealCTA } from './DealCTA';
import type { DealCTAProps } from './DealCTA';
import type { GroupGroupProp } from '@/features/deal-detail';
import type { Locale } from '@/lib/i18n';
import { useDealStock } from '@/features/deals/useDealStock.js';

export interface MobileDealDetailsProps {
  dealId: string;
  dealSlug: string;
  dealTitle: string;
  dealDescription?: string | null;
  dealSpecialInstructions?: string | null;
  dealPickupAddress?: string | null;
  dealPickupStart?: string | null;
  dealPickupEnd?: string | null;
  dealWindowEnd?: string | null;
  originalPrice: number;
  discountedPrice: number;
  isSoldOut: boolean;
  isGuest: boolean;
  stockRemaining: number;
  quantityTotal: number;
  group: GroupGroupProp | null;
  categoryNameHe?: string | null;
  categoryNameEn?: string | null;
  tags?: Array<{ id: string; slug: string; nameHe: string; nameEn: string }> | null;
  selectedSkuQtyTiers: Array<{ minQty: number; discountPercent: number }>;
  qtyLadderText: string;
  ctaRef: RefObject<HTMLDivElement | null>;
  ctaProps: DealCTAProps;
  locale: Locale;
}

export function MobileDealDetails({
  dealId,
  dealTitle,
  dealDescription,
  dealSpecialInstructions,
  dealPickupAddress,
  dealPickupStart,
  dealPickupEnd,
  dealWindowEnd,
  originalPrice,
  discountedPrice,
  isSoldOut,
  isGuest,
  stockRemaining: _stockRemaining,
  quantityTotal: _quantityTotal,
  group,
  categoryNameHe,
  categoryNameEn,
  tags,
  selectedSkuQtyTiers,
  qtyLadderText,
  ctaRef,
  ctaProps,
  locale,
}: MobileDealDetailsProps) {
  const t = useT('deal_detail');
  const tCard = useT('deal-card');
  const tg = useT('group_deal');
  const { triggerAuth } = useAuthGateStore();
  const stock = useDealStock(dealId);
  const liveSoldOut = stock.status === 'resolved' ? stock.soldOut : isSoldOut;
  const isGroupFull = group != null && group.currentReservationCount >= group.maxGroupSize;
  const displaySoldOut = liveSoldOut || isGroupFull;
  const stockPending = stock.status === 'loading' || stock.status === 'error';
  const displayRemaining =
    stock.status === 'resolved' && !stock.soldOut ? stock.stockRemaining : null;

  return (
    <>
      <div
        className="flex flex-col gap-4"
        data-deal-detail
        data-deal-id={dealId}
        data-stock-sold-out={displaySoldOut ? 'true' : undefined}
      >
        {((dealWindowEnd && !displaySoldOut) || group) && (
          <div className="flex items-center justify-center gap-2 md:justify-start">
            {dealWindowEnd && !displaySoldOut && (
              <>
                <Icon name="Clock" size="sm" color="muted" />
                <CountdownTimer endIso={dealWindowEnd} className="text-sm" />
              </>
            )}
            {group
              ? (() => {
                  const s = computeGroupProgress(group);
                  const tone =
                    s.kind === 'below_min' || s.kind === 'next_tier' ? 'brand' : 'success';
                  const label =
                    s.kind === 'full'
                      ? tg('group_full')
                      : s.kind === 'best_price'
                        ? tg('best_price_unlocked')
                        : s.kind === 'threshold_met'
                          ? tg('threshold_met')
                          : s.kind === 'next_tier'
                            ? tg('units_to_next_tier')
                                .replace('{{count}}', String(s.count))
                                .replace('{{percent}}', String(s.percent))
                            : tg('purchased_of')
                                .replace('{{current}}', String(s.current))
                                .replace('{{target}}', String(s.target));
                  return (
                    <>
                      {dealWindowEnd && !displaySoldOut && (
                        <span className="text-text-muted" aria-hidden>
                          ·
                        </span>
                      )}
                      <Badge tone={tone} size="sm" className="shrink-0">
                        {label}
                      </Badge>
                    </>
                  );
                })()
              : dealWindowEnd &&
                !displaySoldOut && (
                  <>
                    <span className="text-text-muted" aria-hidden>
                      ·
                    </span>
                    {stockPending ? (
                      <>
                        <Icon name="AlertCircle" size="sm" color="danger" />
                        <span
                          className="text-warning-600 text-sm font-medium"
                          aria-live="polite"
                          aria-busy={stockPending}
                        >
                          <span aria-label={tCard('loadingAvailability')}>
                            {tCard('loadingAvailability')}
                          </span>
                        </span>
                      </>
                    ) : displayRemaining != null && displayRemaining <= 9 ? (
                      <>
                        <Icon name="AlertCircle" size="sm" color="danger" />
                        <span className="text-warning-600 text-sm font-medium">
                          {t('stock_ok')} {displayRemaining}
                        </span>
                      </>
                    ) : (
                      <>
                        <Icon name="Check" size="sm" color="success" />
                        <span className="text-success-600 text-sm font-medium">
                          {t('stock_ok')}
                        </span>
                      </>
                    )}
                  </>
                )}
          </div>
        )}

        {liveSoldOut && (
          <p className="text-text-muted text-center text-sm font-medium md:text-start">
            {t('sold_out')}
          </p>
        )}

        <h1
          data-user-content
          className="text-text-primary text-[length:var(--font-size-display)] leading-tight font-[var(--font-weight-extrabold)] break-words"
        >
          {dealTitle}
        </h1>

        {/* Category + Tags */}
        {(categoryNameHe || (tags && tags.length > 0)) && (
          <div className="mt-2 flex flex-wrap items-center gap-2">
            {categoryNameHe && (
              <Badge tone="neutral" size="sm">
                {locale === 'he' ? categoryNameHe : categoryNameEn}
              </Badge>
            )}
            {tags && tags.length > 0 && <TagPills tags={tags} locale={locale} />}
          </div>
        )}

        {dealDescription && (
          <p data-user-content className="text-text-secondary text-base leading-normal">
            {dealDescription}
          </p>
        )}

        {dealSpecialInstructions && (
          <div className="bg-surface-inset border-border-default rounded-xl border px-4 py-3">
            <p className="text-text-secondary mb-1 text-xs font-semibold tracking-wide uppercase">
              {t('special_instructions')}
            </p>
            <p data-user-content className="text-text-secondary text-sm">
              {dealSpecialInstructions}
            </p>
          </div>
        )}

        {!isGuest && (
          <div className="flex justify-end">
            <ReportTranslationButton dealId={dealId} />
          </div>
        )}

        <PriceDisplay
          original={originalPrice}
          discounted={discountedPrice}
          size="lg"
          layout="inline"
        />

        {selectedSkuQtyTiers.length > 0 && (
          <p className="text-text-secondary text-xs">{qtyLadderText}</p>
        )}

        {dealPickupAddress && (
          <div className="flex items-start gap-2">
            <Icon name="MapPin" size="sm" color="muted" className="mt-0.5 shrink-0" />
            <div>
              <p className="text-text-muted text-xs font-medium">{t('pickup_address')}</p>
              <p data-user-content className="text-text-secondary text-sm">
                {dealPickupAddress}
              </p>
            </div>
          </div>
        )}

        {(dealPickupStart ?? dealPickupEnd) && (
          <div className="flex items-start gap-2">
            <Icon name="Clock" size="sm" color="muted" className="mt-0.5 shrink-0" />
            <div>
              <p className="text-text-muted text-xs font-medium">{t('pickup_hours')}</p>
              <p className="text-text-secondary text-sm" data-user-content>
                {dealPickupStart?.slice(0, 5)} - {dealPickupEnd?.slice(0, 5)}
              </p>
            </div>
          </div>
        )}

        <div ref={ctaRef}>
          <DealCTA {...ctaProps} isSoldOut={displaySoldOut} />
        </div>

        {/* Actions: Wishlist + Report.
          Share is intentionally omitted here — the mobile topBar (endExtra) already
          renders a ShareButton at mobile viewport. Rendering it again here would
          produce two accessible ShareButtons inside <main> at mobile, causing
          Playwright strict-mode violations on getByRole('button', { name: /share/ }). */}
        <div className="mt-4 flex items-center justify-center gap-1">
          <WishlistButton dealId={dealId} showLabel onAuthRequired={triggerAuth} />
          <ReportButton targetId={dealId} targetType="DEAL" showLabel />
        </div>
      </div>
    </>
  );
}
