'use client';

/**
 * DealPurchaseCard — stateless desktop purchase card (sticky sidebar).
 *
 * Receives a `ctaRef` to attach to the CTA wrapper div so the
 * IntersectionObserver in DealDetailInner can track when the desktop CTA
 * scrolls out of view (showing the `StickyDesktopBar`).
 *
 * Owns no state.
 */

import type { RefObject } from 'react';
import { Icon } from '@/components/ui/icons/Icon';
import { WishlistButton } from '@/components/ui/domain/WishlistButton';
import { ShareButton } from '@/components/ui/domain/ShareButton';
import { ReportButton } from '@/components/ui/domain/ReportButton';
import { PriceDisplay } from '@/components/ui/domain/PriceDisplay';
import { CountdownTimer } from '@/components/ui/domain/CountdownTimer';
import { BusinessProfile } from '@/components/ui/domain/BusinessProfile';
import { GroupProgressBar } from '@/components/ui/domain/GroupProgressBar';
import { useT } from '@/lib/i18n/react';
import { useAuthGateStore } from '@/lib/stores/auth-gate';
import { computeGroupProgress, groupProgressBarMax } from '@/lib/group-deal/progress';
import { DealCTA } from './DealCTA';
import type { DealCTAProps } from './DealCTA';
import type { DealDetailData, GroupGroupProp } from './DealDetailDataLoader';
import { useDealStock } from '@/features/deals/useDealStock.js';

export interface DealPurchaseCardProps {
  deal: DealDetailData;
  dealSlug: string;
  siteUrl: string;
  savingsAmount: number;
  stockRemaining: number;
  stockFillPct: number;
  isSoldOut: boolean;
  group: GroupGroupProp | null;
  selectedSkuQtyTiers: Array<{ minQty: number; discountPercent: number }>;
  qtyLadderText: string;
  ctaRef: RefObject<HTMLDivElement | null>;
  ctaProps: DealCTAProps;
}

export function DealPurchaseCard({
  deal,
  dealSlug,
  siteUrl,
  savingsAmount,
  stockRemaining: _stockRemaining,
  stockFillPct,
  isSoldOut,
  group,
  selectedSkuQtyTiers,
  qtyLadderText,
  ctaRef,
  ctaProps,
}: DealPurchaseCardProps) {
  const t = useT('deal_detail');
  const tCard = useT('deal-card');
  const tg = useT('group_deal');
  const { triggerAuth } = useAuthGateStore();
  const stock = useDealStock(deal.id);
  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 (
    <>
      {/* Purchase card */}
      <div
        data-deal-detail
        data-deal-id={deal.id}
        data-stock-sold-out={displaySoldOut ? 'true' : undefined}
        className="bg-surface-elevated flex flex-col gap-3 rounded-2xl p-5 shadow-lg"
      >
        {/* Row: savings + price (start) | stock badge (center, 1-9 only) | countdown (end) */}
        <div className="flex items-start justify-between gap-3">
          <div className="flex flex-col gap-0.5">
            {savingsAmount > 0 && (
              <span className="text-success-700 text-sm font-semibold">
                {t('savings_badge').replace('{amount}', String(savingsAmount))}
              </span>
            )}
            <PriceDisplay
              original={deal.originalPrice}
              discounted={deal.discountedPrice}
              size="lg"
              layout="inline"
            />
            {selectedSkuQtyTiers.length > 0 && (
              <p className="text-text-secondary text-xs">{qtyLadderText}</p>
            )}
          </div>
          <div className="flex shrink-0 items-center gap-3">
            {deal.dealType === 'GROUP' && group
              ? (() => {
                  const s = computeGroupProgress(group);
                  const barMax = groupProgressBarMax(group, s);
                  const shownCount = Math.min(group.currentReservationCount, barMax);
                  const caption =
                    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 (
                    <GroupProgressBar
                      current={shownCount}
                      minTarget={group.minGroupSize}
                      maxTarget={barMax}
                      tiers={group.tiers.map((tier) => ({
                        minParticipants: tier.minParticipants,
                        pricePerUnit: tier.pricePerUnit,
                      }))}
                      caption={caption}
                      valueText={`${shownCount} / ${barMax}`}
                    />
                  );
                })()
              : !displaySoldOut && (
                  <div
                    className="flex items-center gap-1"
                    aria-live="polite"
                    aria-busy={stockPending}
                  >
                    <Icon name="AlertCircle" size="sm" color="danger" />
                    <span className="text-warning-800 inline-block min-w-[1.25rem] text-xs font-semibold tabular-nums">
                      {stockPending ? (
                        <span aria-label={tCard('loadingAvailability')}>
                          {tCard('loadingAvailability')}
                        </span>
                      ) : (
                        displayRemaining
                      )}
                    </span>
                  </div>
                )}
            {deal.windowEnd && !displaySoldOut && (
              <div className="flex items-center gap-1.5">
                <Icon name="Clock" size="sm" color="muted" />
                <CountdownTimer endIso={deal.windowEnd} className="text-sm font-medium" />
              </div>
            )}
          </div>
        </div>

        <div className="border-border-subtle border-t" />

        {/* Stock progress bar */}
        {!displaySoldOut && !(deal.dealType === 'GROUP' && group) && (
          <div
            className="bg-surface-inset h-2 w-full overflow-hidden rounded-full"
            role="progressbar"
            aria-label={t('stock_progress_label')}
            aria-valuenow={deal.quantitySold}
            aria-valuemin={0}
            aria-valuemax={deal.quantityTotal}
          >
            <div
              className="bg-brand-primary-500 h-full rounded-full transition-all"
              style={{ width: `${stockFillPct}%` }}
            />
          </div>
        )}

        {/* CTA */}
        <div ref={ctaRef} data-buy-section>
          <DealCTA {...ctaProps} isSoldOut={displaySoldOut} />
        </div>
      </div>

      {/* Actions: Wishlist + Favorite + Share + Report */}
      <div className="mt-4 flex items-center justify-center gap-1">
        <WishlistButton dealId={deal.id} showLabel onAuthRequired={triggerAuth} />
        <ShareButton
          shareParams={{ targetUrl: `${siteUrl}/deals/${dealSlug}`, dealId: deal.id }}
          title={deal.title}
          showLabel
        />
        <ReportButton targetId={deal.id} targetType="DEAL" showLabel />
      </div>

      {/* Store info card — BusinessProfile renders its own card shell */}
      <div className="mt-4">
        <BusinessProfile vendor={deal.vendor} />
      </div>
    </>
  );
}
