

(function () {
  const STYLE_ID = 'shaste-hub-toast-style';
  const EVENT_NAME = 'shaste:level-up';
  const TOAST_DURATION_MS = 4000;

  function ensureStyles() {
    if (document.getElementById(STYLE_ID)) return;
    const style = document.createElement('style');
    style.id = STYLE_ID;
    style.textContent = ''
      + '.shaste-levelup-layer{position:fixed;inset:0;z-index:99998;pointer-events:none;overflow:hidden;}'
      + '.shaste-levelup-toast{position:fixed;left:50%;top:20px;transform:translateX(-50%);z-index:99999;'
      + 'max-width:min(92vw,700px);padding:14px 18px;border-radius:12px;'
      + 'background:rgba(12,14,20,.92);border:1px solid rgba(255,255,255,.18);color:#fff;'
      + 'font:600 16px/1.3 Inter,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;'
      + 'box-shadow:0 12px 30px rgba(0,0,0,.35);text-align:center;}'
      + '.shaste-confetti-piece{position:absolute;top:-10vh;width:10px;height:16px;opacity:.95;'
      + 'animation:shaste-fall linear forwards;}'
      + '@keyframes shaste-fall{to{transform:translate3d(var(--x,0),115vh,0) rotate(var(--r,540deg));opacity:1;}}';
    document.head.appendChild(style);
  }

  function extractStreakPayload(value) {
    if (!value || typeof value !== 'object') return null;
    if (value.streak_toast && typeof value.streak_toast === 'object') {
      return value.streak_toast;
    }
    if (Array.isArray(value)) {
      for (let i = 0; i < value.length; i += 1) {
        const found = extractStreakPayload(value[i]);
        if (found) return found;
      }
      return null;
    }
    const keys = Object.keys(value);
    for (let i = 0; i < keys.length; i += 1) {
      const found = extractStreakPayload(value[keys[i]]);
      if (found) return found;
    }
    return null;
  }

  function showConfettiToast(message, eventDetail) {
    if (!message || !document.body) return;
    ensureStyles();

    const layer = document.createElement('div');
    layer.className = 'shaste-levelup-layer';

    const toast = document.createElement('div');
    toast.className = 'shaste-levelup-toast';
    toast.textContent = message;
    document.body.appendChild(toast);
    document.body.appendChild(layer);

    try {
      window.dispatchEvent(new CustomEvent(EVENT_NAME, { detail: eventDetail || {} }));
    } catch (e) {}

    const colors = ['#ff4f9a', '#f59e0b', '#2dd4bf', '#60a5fa', '#f5f6fa', '#a78bfa'];
    for (let i = 0; i < 140; i += 1) {
      const piece = document.createElement('span');
      piece.className = 'shaste-confetti-piece';
      piece.style.left = `${Math.random() * 100}vw`;
      piece.style.background = colors[Math.floor(Math.random() * colors.length)];
      piece.style.animationDuration = `${(2.7 + Math.random() * 1.6).toFixed(2)}s`;
      piece.style.animationDelay = `${(Math.random() * 0.3).toFixed(2)}s`;
      piece.style.setProperty('--x', `${(Math.random() * 40 - 20).toFixed(1)}vw`);
      piece.style.setProperty('--r', `${(Math.random() * 1080 - 540).toFixed(0)}deg`);
      layer.appendChild(piece);
    }

    window.setTimeout(() => {
      toast.remove();
      layer.remove();
    }, TOAST_DURATION_MS);
  }

  function attachStreakToast(payload) {
    const streak = extractStreakPayload(payload);
    if (streak && streak.message) {
      showConfettiToast(streak.message, {
        leveled_up: false,
        streak_toast: streak,
      });
      return true;
    }
    return false;
  }

  function showClaimSuccess(days) {
    const safeDays = Number.isFinite(days) && days > 0 ? days : null;
    const message = safeDays
      ? `🔥 Daily login claimed! Streak: ${safeDays} day${safeDays === 1 ? '' : 's'}.`
      : '🔥 Daily login claimed!';
    showConfettiToast(message, {
      leveled_up: false,
      source: 'daily-claim',
      streak_days: safeDays,
    });
  }

  window.SHASTE_HUB_TOASTS = {
    attachStreakToast,
    showClaimSuccess,
  };
})();
