<template>
  <teleport to="body">
    <transition-group
        name="toast"
        tag="div"
        class="toast-container"
    >
      <div
          v-for="toast in toasts"
          :key="toast.id"
          :class="['toast', `toast--${toast.variant}`]"
          @click="removeToast(toast.id)"
      >
        <div v-if="toast.icon" class="toast__icon">
          <component
              :is="toast.icon"
              weight="regular"
              size="24"
              class="icon-btn"
          />
        </div>
        <div class="toast__content">
          <div v-if="toast.title" class="toast__title">{{ toast.title }}</div>
          <div class="toast__message">{{ toast.message }}</div>
        </div>
        <div v-if="toast.count > 1" class="toast__badge">
          {{ toast.count }}
        </div>
      </div>
    </transition-group>
  </teleport>
</template>

<script>
import {PhCheck, PhFloppyDisk} from "@phosphor-icons/vue";

export default {
  name: 'Toast',
  components: {PhFloppyDisk, PhCheck},
  data() {
    return {
      toasts: [],
      nextId: 1
    }
  },
  methods: {
    /**
     * Add a new toast notification
     * @param {Object} options - Toast configuration
     * @param {string} options.message - Toast message (required)
     * @param {string} options.title - Toast title (optional)
     * @param {string} options.variant - Toast variant: 'success', 'error', 'warning', 'info'
     * @param {number} options.duration - Auto-dismiss duration in ms (0 = no auto-dismiss)
     * @param {string} options.icon - Icon name (optional)
     * @param {boolean} options.stack - Whether to stack identical toasts (default: true)
     */
    addToast(options = {}) {
      const shouldStack = options.stack !== undefined ? options.stack : true;

      // Check if an identical toast already exists
      if (shouldStack) {
        const existingToast = this.toasts.find(t =>
            t.message === options.message &&
            t.title === (options.title || null) &&
            t.variant === this.mapVariant(options.variant || 'primary')
        );

        if (existingToast) {
          // Increment count and reset timer
          existingToast.count = (existingToast.count || 1) + 1;

          // Clear existing timeout
          if (existingToast.timeoutId) {
            clearTimeout(existingToast.timeoutId);
          }

          // Set new timeout
          const duration = options.duration !== undefined ? options.duration : 5000;
          if (duration > 0) {
            existingToast.timeoutId = setTimeout(() => {
              this.removeToast(existingToast.id);
            }, duration);
          }

          return existingToast.id;
        }
      }

      const toast = {
        id: this.nextId++,
        message: options.message || 'Notification',
        title: options.title || null,
        variant: this.mapVariant(options.variant || 'primary' ),
        duration: options.duration !== undefined ? options.duration : 5000,
        icon: options.icon ? `Ph${options.icon.charAt(0).toUpperCase() + options.icon.slice(1)}` : null,
        count: 1,
        timeoutId: null
      };

      this.toasts.push(toast)

      // Auto-dismiss if duration is set
      if (toast.duration > 0) {
        toast.timeoutId = setTimeout(() => {
          this.removeToast(toast.id)
        }, toast.duration)
      }

      return toast.id
    },

    mapVariant(variant) {
      switch(variant) {
        case 'success':
          return 'primary'
        case 'warning':
          return 'secondary'
        case 'info':
          return 'primary'
        case 'error':
          return 'exception'
        default:
          return variant;
      }
    },

    /**
     * Remove a toast by ID
     * @param {number} id - Toast ID
     */
    removeToast(id) {
      const index = this.toasts.findIndex(toast => toast.id === id)
      if (index > -1) {
        // Clear timeout if exists
        if (this.toasts[index].timeoutId) {
          clearTimeout(this.toasts[index].timeoutId);
        }
        this.toasts.splice(index, 1)
      }
    },

    /**
     * Remove all toasts
     */
    clearToasts() {
      // Clear all timeouts
      this.toasts.forEach(toast => {
        if (toast.timeoutId) {
          clearTimeout(toast.timeoutId);
        }
      });
      this.toasts = []
    },

    // Convenience methods
    success(message, options = {}) {
      return this.addToast({ ...options, message, variant: 'primary' })
    },

    error(message, options = {}) {
      return this.addToast({ ...options, message, variant: 'exception' })
    },

    warning(message, options = {}) {
      return this.addToast({ ...options, message, variant: 'secondary' })
    },

    info(message, options = {}) {
      return this.addToast({ ...options, message, variant: 'secondary' })
    }
  }
}
</script>

<style scoped>
.toast-container {
  position: fixed;
  bottom: 20px;
  left:  50%;
  transform: translate(-50%, 0);
  z-index: 9999;
  pointer-events: none;
}

.toast {
  background-color: #5AF0B4;
  color: #002F54;
  min-width: 30rem;
  max-width: 40rem;
  margin-bottom: 1.2rem;
  padding: 1.6rem;
  border-radius: 0.8rem;
  box-shadow: 0 0.4rem 0.6rem -0.1rem rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
  gap: 1.6rem;
  cursor: pointer;
  pointer-events: auto;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
  position: relative;
}

.toast:hover {
  transform: translateY(-2px);
  box-shadow: 0 0.5rem 0.9rem rgba(0, 0, 0, 0.1);
}

.toast__icon {
  flex-shrink: 0;
  width: 3.6rem;
  height: 3.6rem;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 14px;
}

.toast__icon_sizing {
  width: 3.6rem;
  height: 3.6rem;
}

.toast__content {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  gap: 0.4rem;
  justify-content: center;
}

.toast__title {
  font-weight: 600;
  font-size: 1.6rem;
  margin-bottom: 0.2rem;
  line-height: 1.3;
}

.toast__message {
  font-size: 1.4rem;
  line-height: 1.4;
  word-break: break-word;
}

.toast__badge {
  flex-shrink: 0;
  width: 2.4rem;
  height: 2.4rem;
  border-radius: 50%;
  background-color: #002F54;
  color: #5AF0B4;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.2rem;
  font-weight: 700;
  margin-left: auto;
}

.toast-primary {
  background-color: #5AF0B4;
  color: #002F54;
}

.toast-primary .toast__badge {
  background-color: #002F54;
  color: #5AF0B4;
}

.toast--secondary {
  color: #002F54;
  background-color: #c3cfdf;
}

.toast--secondary .toast__badge {
  background-color: #002F54;
  color: #c3cfdf;
}

.toast--exception{
  background-color: #BC2B72;
  color: #ffffff;
}

.toast--exception .toast__badge {
  background-color: #ffffff;
  color: #BC2B72;
}

/* Transition animations */
.toast-enter-active {
  transition: all 0.3s ease;
}

.toast-leave-active {
  transition: all 0.3s ease;
}

.toast-enter-from {
  opacity: 0;
  transform: translateY(100%);
}

.toast-leave-to {
  opacity: 0;
  transform: translateY(100%);
}

.toast-move {
  transition: transform 0.3s ease;
}

/* Responsive design */
@media (max-width: 480px) {
  .toast-container {
    top: 10px;
    right: 10px;
    left: 10px;
  }

  .toast {
    min-width: auto;
    max-width: none;
  }
}
</style>