// ╔══════════════════════════════════════════════════════════════════╗
// ║  animations.jsx — Lottie celebration popups                        ║
// ║  • SuccessPopup       one-shot ✓ (payment success). Waits for the  ║
// ║                       animation's `complete` event before closing. ║
// ║  • WelcomeTokensPopup gift + "free tokens on us" + button. Plays   ║
// ║                       once (no loop).                              ║
// ║  Both .lottie files are PRELOADED at load so they're cached and    ║
// ║  render instantly (fixes the "empty popup flash").                 ║
// ╚══════════════════════════════════════════════════════════════════╝
(function () {
  const { useEffect, useRef } = React;

  const SUCCESS_LOTTIE = "https://lottie.host/23d90682-ff38-4286-8a53-b4678a4b725e/88Caz63KNq.lottie";
  const WELCOME_LOTTIE = "https://lottie.host/4e16f801-6b8c-4b0a-9802-44718d841f72/KSNPftTkPR.lottie";

  // Warm the browser cache immediately so the web component renders instantly later.
  [SUCCESS_LOTTIE, WELCOME_LOTTIE].forEach((u) => {
    try { fetch(u, { cache: "force-cache", mode: "cors" }).catch(() => {}); } catch (e) {}
  });

  function SuccessAnimation({ size = 200 }) {
    return (
      <dotlottie-wc src={SUCCESS_LOTTIE} style={{ width: size + "px", height: size + "px" }} autoplay />
    );
  }

  // Centered popup: plays the success animation once, dismisses when it COMPLETES
  // (with a safety timeout so it never gets stuck if the file fails to load).
  // open = null | { message }
  function SuccessPopup({ open, onClose }) {
    const ref = useRef(null);
    useEffect(() => {
      if (!open) return;
      let done = false;
      const finish = () => { if (!done) { done = true; onClose && onClose(); } };
      const el = ref.current;
      const onComplete = () => finish();
      if (el && el.addEventListener) el.addEventListener("complete", onComplete);
      // Safety net: never linger past 5s (covers a failed/slow load or a missing event).
      const t = setTimeout(finish, 5000);
      return () => {
        clearTimeout(t);
        if (el && el.removeEventListener) el.removeEventListener("complete", onComplete);
      };
    }, [open]);
    if (!open) return null;
    return (
      <div className="swfx-overlay" onClick={onClose} role="status" aria-live="polite">
        <div className="swfx-card swfx-card--success" onClick={(e) => e.stopPropagation()}>
          <dotlottie-wc ref={ref} src={SUCCESS_LOTTIE} style={{ width: "210px", height: "210px" }} autoplay />
          {open.message && <div className="swfx-msg">{open.message}</div>}
        </div>
      </div>
    );
  }

  // "Free tokens on us" welcome — plays ONCE (no loop) + close button.
  // open = null | { tokens }
  function WelcomeTokensPopup({ open, onClose }) {
    if (!open) return null;
    const n = window.formatTokens ? window.formatTokens(open.tokens) : open.tokens;
    const isBonus = open.kind === "bonus";
    const title = isBonus ? `${n} bonus tokens 🎉` : `${n} tokens, on us 🎉`;
    const sub = isBonus
      ? "Thank you for being an early Sweepify customer — these tokens are on us. Spend them on any scan."
      : "Welcome to Sweepify — these free credits are on the house to get you started. Spend them on any scan.";
    return (
      <div className="swfx-overlay" role="dialog" aria-modal="true" aria-label="Token gift">
        <div className="swfx-card swfx-card--welcome" onClick={(e) => e.stopPropagation()}>
          <dotlottie-wc src={WELCOME_LOTTIE} style={{ width: "230px", height: "230px" }} autoplay />
          <div className="swfx-title">{title}</div>
          <div className="swfx-sub">{sub}</div>
          <button className="sw-btn sw-btn--lg swfx-btn" onClick={onClose}>Start exploring</button>
        </div>
      </div>
    );
  }

  if (!document.getElementById("swfx-styles")) {
    const s = document.createElement("style");
    s.id = "swfx-styles";
    s.textContent = `
      .swfx-overlay{position:fixed;inset:0;z-index:300;display:flex;align-items:center;justify-content:center;
        background:rgba(15,23,42,.5);backdrop-filter:blur(5px);-webkit-backdrop-filter:blur(5px);
        animation:swfx-in 180ms ease;padding:20px;}
      .swfx-card{background:#fff;border-radius:24px;box-shadow:0 30px 80px rgba(15,23,42,.34);
        display:flex;flex-direction:column;align-items:center;text-align:center;
        padding:24px 28px 30px;max-width:380px;width:100%;
        animation:swfx-pop 280ms cubic-bezier(.18,.89,.32,1.28);}
      .swfx-card--success{padding:20px 26px 24px;max-width:340px;}
      .swfx-msg{margin-top:2px;font-weight:800;font-size:18px;color:#0F172A;letter-spacing:-.01em;}
      .swfx-card--welcome dotlottie-wc{margin-top:-6px;}
      .swfx-title{font-size:25px;font-weight:900;color:#0F172A;letter-spacing:-.02em;margin-top:4px;}
      .swfx-sub{color:#475569;font-size:14px;line-height:1.55;margin:10px 4px 22px;}
      .swfx-btn{width:100%;}
      @keyframes swfx-in{from{opacity:0}to{opacity:1}}
      @keyframes swfx-pop{from{opacity:0;transform:translateY(12px) scale(.95)}to{opacity:1;transform:none}}
    `;
    document.head.appendChild(s);
  }

  Object.assign(window, { SuccessAnimation, SuccessPopup, WelcomeTokensPopup });
})();
