<?php
/**
 * Payout Drawer — Referrals Section
 *
 * One pattern: a card per referral, regardless of payout method. Row 1
 * always shows `#ID · amount · status badge`. Row 2 (transaction details)
 * renders only when the referral carries `item_transaction_id` — that's
 * genuine per-item state from PayPal / Stripe processors. Manual + Store
 * Credit payouts have no Row 2 content, so their cards collapse to
 * Row-1-only via the existing conditional border.
 *
 * The earlier chip-list mode for Manual / Store Credit was dropped: it
 * silently lost the amount + status badge to save vertical space, which
 * made the same referral look "demoted" when viewed via a Manual payout
 * versus the Stripe payout it was originally on. The conditional Row 2
 * already handles "no per-item details" cleanly without needing a second
 * presentation pattern.
 *
 * Expects the parent `x-data="{ drawer: $store.payoutDrawer }"` scope
 * (see drawer.php content_callback).
 *
 * @package     AffiliateWP
 * @subpackage  Admin/Payouts
 * @since       2.33.0
 */

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

?>

<template x-if="drawer.referrals && drawer.referrals.length > 0">
	<!--
		space-y-4 (16px) between heading and the warning block / first card —
		previously space-y-2 read as one grouped block, making the heading
		feel attached to the body content. 16px gives the heading its own
		visual breathing room consistent with the spacing between the
		Summary card and this section.
	-->
	<section class="space-y-4">

		<h3 class="text-sm font-semibold text-gray-900 mb-3" x-text="drawer.referralsHeading"></h3>

		<!--
			Hoisted warning summary. When multiple referrals hit the same
			PayPal failure mode we want one callout explaining what's
			happening, not a wall of yellow banners. Per-card badges still
			tell admins *which* rows are affected; this block tells them
			*what* is affected in aggregate.

			Suppressed when a Next Steps card is active: the Next Steps
			narration already says "PayPal returns these funds in N days
			if unclaimed" and offers the resolution affordance, which is
			the same message + action this banner carries. Showing both
			is the same diagnosis-twice redundancy we already retired
			between the Next Steps card and the old PayPal summary card.
			For statuses the Next Steps card doesn't cover yet (DENIED,
			REVERSED, BLOCKED, etc.), the banner still earns its keep.
		-->
		<template x-if="drawer.hasWarnings && ! ( drawer.payout && drawer.payout.next_steps )">
			<div class="space-y-2">
				<template x-for="group in drawer.warningGroups" :key="group.status">
					<div class="rounded-lg border border-orange-200 bg-orange-50 px-4 py-3 flex gap-3 items-start">
						<?php \AffiliateWP\Utils\Icons::render( 'circle-warning', '', [ 'class' => 'w-5 h-5 text-orange-500 shrink-0 mt-0.5' ] ); ?>
						<div class="min-w-0">
							<p class="text-sm font-medium text-orange-900 m-0"
								x-text="group.count + ' ' + (group.count === 1 ? 'referral' : 'referrals') + ' ' + drawer.humanizeItemStatus( group.status )"></p>
							<p class="text-xs text-orange-800 mt-1 m-0" x-text="group.message"></p>
						</div>
					</div>
				</template>
			</div>
		</template>

		<!-- Cards: always rendered for every method. Row 2 self-gates on transaction data. -->
		<div class="space-y-3">
			<template x-for="referral in drawer.referrals" :key="referral.referral_id">

					<!--
						Click target is the #ID link in the top-left
						corner, NOT the whole card. The earlier stretched-
						link experiment (Bootstrap pattern) was reverted
						because it competes with rich cards: PayPal /
						Stripe referrals carry transaction details meant
						for reading + copying (recipient email, txn ID,
						fee) plus an inline deep-link to the provider's
						dashboard. A whole-card-clickable surface turns
						the card into a giant button and interferes with
						selection + the inline txn-link affordance.

						When the Edit Referral destination becomes a
						drawer later, the #ID stays the trigger — drawer-
						over-list preserves queue context anyway, so the
						"bigger hit target for drawer-swap" argument
						doesn't hold up against the rich-card readability
						cost.
					-->
					<!--
						overflow-hidden is the standard policy for all drawer
						cards (see Next Steps, Supersession, Summary). Clips
						any future hoverable inner element against the card's
						border-radius — without it, hover backgrounds bleed
						past the rounded corners as a 90° edge artifact.
					-->
					<article class="affwp-card rounded-lg border border-gray-200 bg-white overflow-hidden">

						<!--
							Row 1: referral ID, amount, affiliate, per-item status pill.

							border-b is conditional on Row 2 actually rendering.
							Row 2 only appears for Stripe/PayPal referrals that
							carry transaction details (txn ID, recipient, fee).
							For Unpaid rows, manual payouts, store credit, or
							failed-before-transfer referrals, Row 2 doesn't
							render — and a static border-b on Row 1 leaves an
							orphaned divider stranded inside the card. The
							conditional class binding suppresses the border
							when there's nothing below it to separate from.
						-->
						<!--
							border-b is conditional on Row 2 actually rendering.
							With the per-referral affiliate name + recipient
							email + fee dropped from Row 2 (all of those were
							scope mismatches: same value across every row,
							belongs once in the header / Next Steps card /
							Details), Row 2 now only renders for referrals
							with a transaction ID. Other states collapse to a
							single-row card and the orphaned divider stays
							suppressed.
						-->
						<div class="px-4 py-3 flex items-center justify-between gap-3"
							:class="referral.item_transaction_id ? 'border-b border-gray-100' : ''">

							<div class="flex items-center gap-3 min-w-0">
								<!--
									Affiliate name dropped from per-referral row.
									Every referral on a single-payout drawer
									belongs to the same affiliate, established
									by the drawer header. Restating it four
									times was noise.
								-->
								<a :href="referral.edit_url"
									:aria-label="'Edit referral #' + referral.referral_id"
									class="font-medium text-affwp-link hover:text-affwp-link-hover shrink-0"
									x-text="'#' + referral.referral_id"></a>
								<span class="text-sm text-gray-900 shrink-0" x-text="referral.amount_formatted"></span>
							</div>

							<!--
								Two distinct facts, never conflated:

								Primary pill = the referral's AffiliateWP lifecycle
								status (Paid / Unpaid / Pending). This is what the
								Referrals list table shows and what the admin means
								by "the referral's status", so it always leads.

								Secondary chip = the payment processor's per-item
								state (PayPal UNCLAIMED, Stripe REVERSED, etc.),
								prefixed with the method name so it reads as provider
								context, not as the referral's own status. Shown only
								when it adds something beyond a plain success —
								otherwise a green "Success" chip sat next to an Unpaid
								referral and looked like the referral had been paid.

								On superseded payouts the primary pill carries a
								tooltip explaining the cross-payout linkage (the badge
								is correct — the referral got paid via the replacement
								— but the tooltip closes the interpretive gap).
							-->
							<div class="flex items-center gap-2 shrink-0">
								<span :class="drawer.badgeClass( drawer.badgeVariantForReferralStatus( referral.status ) ) + ' capitalize'"
									:title="drawer.isSuperseded && drawer.payout.superseded_by_payout_id && referral.status === 'paid' ? 'Paid via the replacement payout #' + drawer.payout.superseded_by_payout_id : ''"
									x-text="referral.status"></span>
								<template x-if="referral.item_status && referral.item_status !== 'SUCCESS'">
									<span :class="drawer.badgeClass( drawer.badgeVariantForItemStatus( referral.item_status ) )"
										x-text="drawer.payout.payout_method_label + ': ' + drawer.formatStatusLabel( referral.item_status )"></span>
								</template>
							</div>

						</div>

						<!--
							Row 2: transaction details. Method-neutral fields —
							PayPal populates item_transaction_id as its txn ID,
							Stripe populates it as the Transfer ID. The label
							flips per method ("Transaction" for PayPal, "Transfer"
							for Stripe) so the noun matches what the admin is
							actually looking at.
						-->
						<!--
							Row 2 now only renders for the transaction ID,
							which is genuinely per-referral data (each
							payment item has its own PayPal/Stripe txn).
							Recipient email + Fee dropped:
							- Recipient: same affiliate's PayPal email
							  across every row in a single-payout drawer.
							  Belongs once, somewhere with affiliate scope.
							- Fee: per-item but rarely consulted at the
							  row level during triage. Total surfaces in
							  the Details panel.
						-->
						<template x-if="referral.item_transaction_id">
							<div class="px-4 py-3 space-y-2 text-xs">

								<template x-if="referral.item_transaction_id">
									<div class="flex items-baseline justify-between gap-2">
										<span class="text-gray-500 shrink-0" x-text="referral.item_transaction_label"></span>
										<!--
											Links to the provider's dashboard when we have a
											deep-link URL (sandbox/live aware, built server-
											side). Falls back to plain text so the ID is
											never hidden. Same treatment as the per-method
											Summary card IDs.
										-->
										<template x-if="referral.item_transaction_url">
											<a :href="referral.item_transaction_url"
												target="_blank"
												rel="noopener noreferrer"
												class="inline-flex items-center gap-1.5 font-mono truncate text-affwp-link hover:text-affwp-link-hover"
												title="<?php echo esc_attr__( 'Open in provider dashboard (new tab)', 'affiliate-wp' ); ?>">
												<span class="truncate" x-text="referral.item_transaction_id"></span>
												<svg class="w-3.5 h-3.5 shrink-0" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true"><path d="M11 3a1 1 0 100 2h2.586l-6.293 6.293a1 1 0 101.414 1.414L15 6.414V9a1 1 0 102 0V4a1 1 0 00-1-1h-5z"/><path d="M5 5a2 2 0 00-2 2v8a2 2 0 002 2h8a2 2 0 002-2v-3a1 1 0 10-2 0v3H5V7h3a1 1 0 000-2H5z"/></svg>
											</a>
										</template>
										<template x-if="! referral.item_transaction_url">
											<span class="text-gray-900 font-mono truncate" x-text="referral.item_transaction_id"></span>
										</template>
									</div>
								</template>

							</div>
						</template>

					</article>

			</template>
		</div>

	</section>
</template>

<!--
	Empty state. Two flavors:

	  - The payout's `referrals` column points at IDs that don't exist
	    in the referrals table (deleted out from under the payout).
	    Surface the IDs so the admin sees "what was there got deleted"
	    rather than misreading the row as having never had referrals.
	    Common cause: an admin deletes a referral from the Referrals
	    list table after the payout was processed. The payout row stays
	    intact (it was Paid), the referral is gone.

	  - Genuinely no referrals on the payout row (created empty / all
	    cleared somehow). Fall back to the original copy.
-->
<template x-if="drawer.payout && drawer.referrals && drawer.referrals.length === 0">
	<section class="rounded-lg border border-dashed border-gray-200 bg-gray-50 px-5 py-6 text-center">
		<template x-if="drawer.payout.deleted_referral_ids && drawer.payout.deleted_referral_ids.length > 0">
			<div class="flex flex-col gap-1.5">
				<p class="text-sm font-medium text-gray-700 m-0">
					<span x-text="drawer.payout.deleted_referral_ids.length === 1 ? '<?php echo esc_js( __( 'Referral no longer exists', 'affiliate-wp' ) ); ?>' : '<?php echo esc_js( __( 'Referrals no longer exist', 'affiliate-wp' ) ); ?>'"></span>
				</p>
				<p class="text-xs text-gray-500 m-0">
					<span x-text="drawer.payout.deleted_referral_ids.map(function(id){return '#'+id}).join(', ')"></span>
					<span x-text="drawer.payout.deleted_referral_ids.length === 1 ? '<?php echo esc_js( __( 'was attached to this payout but has since been deleted.', 'affiliate-wp' ) ); ?>' : '<?php echo esc_js( __( 'were attached to this payout but have since been deleted.', 'affiliate-wp' ) ); ?>'"></span>
				</p>
			</div>
		</template>
		<template x-if="! drawer.payout.deleted_referral_ids || drawer.payout.deleted_referral_ids.length === 0">
			<p class="text-sm text-gray-500 m-0">
				<?php esc_html_e( 'No referrals are attached to this payout.', 'affiliate-wp' ); ?>
			</p>
		</template>
	</section>
</template>
