/**
 * RewardAdCard — "Click N Ads to unlock M Hour(s) Ad-Free" UI.
 *
 * Drop into any sidebar / profile screen:
 *
 *   <RewardAdCard />                          // defaults: 3 ads → 1 hour
 *   <RewardAdCard adsToWatch={3} hoursPerUnlock={4} />
 *
 * Self-contained — uses `useAdFreeUnlock()` for state, fires the real
 * AdMob rewarded video on tap, and renders a different "Ad-free until
 * Xh Ym" state once the unlock is active.
 *
 * BUG-5 FEATURE (2026-05).
 * Iter-6 (2026-01): hardened click path — every tap now logs +
 * acknowledges immediately via toast so a missing AdMob unit ID can
 * never look like "the button is dead". Defaults moved to 3 ads / 1h.
 */
import { Gift, Clock, Loader2, Sparkles } from "lucide-react";
import { useAdFreeUnlock, formatRemaining } from "@/hooks/useAdFreeUnlock";
import { useEntitlement } from "@/hooks/useEntitlement";
import { useToast } from "@/hooks/use-toast";

interface Props {
  adsToWatch?: number;
  hoursPerUnlock?: number;
  className?: string;
  /** Hide the card entirely when the user is admin / premium / inside
   *  an active ad-free window AND `hideWhenAlreadyAdFree=true`. Defaults
   *  to false (we still show the "Ad-free for Xh Ym" state). */
  hideWhenAlreadyAdFree?: boolean;
}

const RewardAdCard = ({
  adsToWatch = 3,
  hoursPerUnlock = 1,
  className = "",
  hideWhenAlreadyAdFree = false,
}: Props) => {
  const { adsEnabled } = useEntitlement();
  const { clicks, unlocked, secondsRemaining, watchAd, loading } =
    useAdFreeUnlock({ adsToWatch, hoursPerUnlock });
  const { toast } = useToast();

  // Admin / native-premium users already have adsEnabled=false WITHOUT
  // a rewarded unlock — no reason to show this card to them.
  if (!adsEnabled && !unlocked) return null;
  if (unlocked && hideWhenAlreadyAdFree) return null;

  // BUG FIX (2026-01): defensive coercion. If for any reason `clicks`
  // ever lands as undefined / NaN (e.g. stale persistence layer, race
  // with the rewarded-event bus on cold start, or a future refactor
  // accidentally returning Number("")), the UI used to render
  // "(NaN/3)" which looks broken to the user. Force-fallback to 0 so
  // the counter is ALWAYS a finite integer and the progress bar is
  // ALWAYS a real percentage.
  const safeClicks = Number.isFinite(clicks) ? clicks : 0;
  const safeAdsToWatch =
    Number.isFinite(adsToWatch) && adsToWatch > 0 ? adsToWatch : 3;
  const progress = Math.min(1, safeClicks / safeAdsToWatch);
  const hourLabel = hoursPerUnlock === 1 ? "Hour" : "Hours";

  /** Iter-6 bulletproof click handler.
   *  Why so verbose for a tap? Users were reporting the button as
   *  "dead" because (a) it never reached the handler on certain
   *  themed devices, or (b) it reached `showRewarded()` which silently
   *  no-op'd when the admin hadn't configured a rewarded Ad Unit ID.
   *  Now every tap:
   *    1. Logs to the console so dev tools / adb logcat show activity.
   *    2. Stops event propagation so any parent overlay/portal can't
   *       swallow the gesture.
   *    3. Pops an immediate "Loading ad…" toast so the user sees
   *       feedback even before the SDK has a chance to fire.
   *  The actual reward / failure messaging is handled inside
   *  useAdFreeUnlock.watchAd(). */
  const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {
    e.preventDefault();
    e.stopPropagation();
    if (loading) return;
    console.log("[RewardAdCard] watch-ad button tapped");
    toast({
      title: "Loading ad…",
      description: "Please wait a moment.",
    });
    void watchAd();
  };

  return (
    <div
      className={`glass-card rounded-xl p-4 ${className}`}
      style={{ border: "1px solid hsla(40,80%,55%,0.28)" }}
      data-testid="reward-ad-card"
    >
      {unlocked ? (
        // ── Active ad-free window state ─────────────────────────────
        <div className="flex items-center gap-3">
          <div
            className="w-10 h-10 rounded-full flex items-center justify-center shrink-0"
            style={{ background: "hsla(140,60%,45%,0.18)" }}
          >
            <Sparkles className="w-5 h-5 text-emerald-400" />
          </div>
          <div className="flex-1 min-w-0">
            <p className="text-[10px] tracking-[0.3em] uppercase text-emerald-400 mb-1">
              Ad-Free Active
            </p>
            <p className="text-sm font-semibold text-foreground flex items-center gap-1">
              <Clock className="w-3.5 h-3.5 text-muted-foreground" />
              <span data-testid="ad-free-remaining">
                {formatRemaining(secondsRemaining)}
              </span>
              <span className="text-muted-foreground font-normal text-xs ml-1">remaining</span>
            </p>
          </div>
        </div>
      ) : (
        // ── Earn-progress state ─────────────────────────────────────
        <>
          <div className="flex items-start gap-3 mb-3">
            <div
              className="w-10 h-10 rounded-full flex items-center justify-center shrink-0"
              style={{ background: "hsla(40,80%,55%,0.18)" }}
            >
              <Gift className="w-5 h-5 text-primary" />
            </div>
            <div className="flex-1 min-w-0">
              <p className="text-[10px] tracking-[0.3em] uppercase text-primary mb-1">
                Reward
              </p>
              <p className="text-sm font-semibold text-foreground leading-snug">
                Click {adsToWatch} Ads to unlock {hoursPerUnlock} {hourLabel} Ad-Free
                <span className="text-muted-foreground font-normal ml-1">
                  ({safeClicks}/{safeAdsToWatch})
                </span>
              </p>
            </div>
          </div>

          {/* Progress bar */}
          <div
            className="h-1.5 rounded-full overflow-hidden mb-3"
            style={{ background: "hsla(0,0%,100%,0.06)" }}
          >
            <div
              className="h-full transition-all duration-500 ease-out"
              style={{
                width: `${progress * 100}%`,
                background:
                  "linear-gradient(90deg, hsl(40,80%,55%), hsl(45,90%,65%))",
              }}
              data-testid="reward-progress-fill"
            />
          </div>

          <button
            type="button"
            onClick={handleClick}
            aria-busy={loading || undefined}
            data-loading={loading || undefined}
            data-testid="reward-watch-btn"
            // Defensive z-index so any parent backdrop (drawer, sheet,
            // modal) can't trap the tap.
            style={{ position: "relative", zIndex: 1 }}
            className={`w-full py-2.5 rounded-full text-xs tracking-[0.25em] uppercase transition-colors flex items-center justify-center gap-2 ${
              loading
                ? "bg-muted/40 text-muted-foreground pointer-events-none cursor-wait"
                : "bg-primary text-primary-foreground hover:bg-primary/90 cursor-pointer"
            }`}
          >
            {loading ? (
              <>
                <Loader2 className="w-3.5 h-3.5 animate-spin" />
                Loading…
              </>
            ) : (
              <>Watch Ad ({safeClicks}/{safeAdsToWatch})</>
            )}
          </button>

          <p className="text-[10px] text-muted-foreground text-center mt-2">
            Tap the CTA inside each ad. Counter ticks on click or full watch.
          </p>
        </>
      )}
    </div>
  );
};

export default RewardAdCard;
