"use client";

import { create } from "zustand";
import type { NoteCover, NoteCoverCategory } from "@/lib/notes/note-covers";

interface NoteDesignRow {
  id: string;
  creator_id: string;
  name: string;
  category: string;
  tone: string;
  price_cents: number;
  background_css: string;
  editor_surface: string;
  text_color: string | null;
}

function rowToCover(row: NoteDesignRow): NoteCover {
  return {
    id: row.id,
    name: row.name,
    category: (row.category as NoteCoverCategory) || "custom",
    origin: "custom",
    price: row.price_cents,
    tone: row.tone === "light" ? "light" : "dark",
    style: { background: row.background_css },
    swatch: { background: row.background_css },
    creatorId: row.creator_id,
    editorSurface: row.editor_surface === "solid" ? "solid" : "glass",
    textColor: row.text_color || undefined,
  };
}

interface NoteDesignsState {
  customCovers: NoteCover[];
  loading: boolean;
  initialized: boolean;
  refetch: () => Promise<void>;
}

export const useNoteDesignsStore = create<NoteDesignsState>((set) => ({
  customCovers: [],
  loading: false,
  initialized: false,

  async refetch() {
    set({ loading: true });
    const { createClient } = await import("@/lib/supabase/client");
    const supabase = createClient();
    const { data } = await supabase
      .from("note_designs")
      .select("id, creator_id, name, category, tone, price_cents, background_css, editor_surface, text_color")
      .eq("is_published", true)
      .order("created_at", { ascending: false });
    set({
      customCovers: ((data || []) as NoteDesignRow[]).map(rowToCover),
      loading: false,
      initialized: true,
    });
  },
}));
