import type { Plugin } from "nuxt/app";

/**
 * Client-side Pinia persistence plugin.
 * Syncs the cart store to localStorage on every mutation and hydrates on load.
 */const STORAGE_KEY = "hms-cart";

export default defineNuxtPlugin(({ pinia }) => {
  // Hydrate from localStorage on plugin load
  if (import.meta.client) {
    try {
      const stored = localStorage.getItem(STORAGE_KEY);
      if (stored) {
        const parsed = JSON.parse(stored);
        if (parsed && Array.isArray(parsed.items)) {
          const cartStore = pinia._s.get("cart");
          if (cartStore) {
            cartStore.$patch({ items: parsed.items });
          }
        }
      }
    } catch (e) {
      console.warn("Failed to hydrate cart from localStorage:", e);
    }

    // Subscribe to cart store changes and persist
    const cartStore = pinia._s.get("cart");
    if (cartStore) {
      cartStore.$subscribe((_mutation, state) => {
        try {
          localStorage.setItem(
            STORAGE_KEY,
            JSON.stringify({ items: state.items }),
          );
        } catch (e) {
          console.warn("Failed to persist cart to localStorage:", e);
        }
      });
    }
  }
}) as Plugin;
