'use client';

import { createContext, useCallback, useContext, useMemo, type ReactNode } from 'react';
import { Content, type RawEntry } from '@/app/lib/content/content';
import { getClientContent, setClientContent } from '@/app/lib/content/client';
import type { ClientKey } from '@/app/lib/content/seed-client';
import type { TemplateVars } from '@/app/lib/content/template';

const ContentContext = createContext<Content<ClientKey> | null>(null);

/**
 * Gives the page its wording: the text, labels and messages the server read from the database for this request.
 * Rendered by the root layout, so the page arrives with the right wording already in it (no flash of other text).
 */
export function ContentProvider({ entries, children }: { entries: Record<string, RawEntry>; children: ReactNode }) {
  const content = useMemo(() => {
    const c = new Content<ClientKey>(entries as Record<ClientKey, RawEntry>);
    setClientContent(c); // for code that is not a component (API helpers)
    return c;
  }, [entries]);
  return <ContentContext.Provider value={content}>{children}</ContentContext.Provider>;
}

/** The page's content. Without a provider (tests, isolated components) it is the seeded wording. */
export function useContent(): Content<ClientKey> {
  return useContext(ContentContext) ?? getClientContent();
}

/** `t('copy.signIn')`, or `t('copy.welcomeBody', { company })` for text with {{blanks}}. */
export function useT(): (key: ClientKey, vars?: TemplateVars) => string {
  const content = useContent();
  return useCallback((key, vars) => content.render(key, vars), [content]);
}
