'use client'

import { create } from 'zustand'
import type { ApiMailSignature } from '@/lib/api/types'

type MailSignaturesState = {
  signatures: ApiMailSignature[]
  hydrated: boolean
}

type MailSignaturesActions = {
  hydrateFromApi: (signatures: ApiMailSignature[]) => void
  clear: () => void
}

export const useMailSignaturesStore = create<MailSignaturesState & MailSignaturesActions>()(
  (set) => ({
    signatures: [],
    hydrated: false,
    hydrateFromApi: (signatures) => set({ signatures, hydrated: true }),
    clear: () => set({ signatures: [], hydrated: false }),
  })
)

export function getMailSignatures(): ApiMailSignature[] {
  return useMailSignaturesStore.getState().signatures
}

export function getSignatureHtmlById(signatureId: string | null | undefined): string | null {
  if (!signatureId) return null
  const sig = getMailSignatures().find((s) => s.id === signatureId)
  return sig?.html?.trim() ? sig.html : null
}
