// Extension points for add-ons (MadeCost Pro and others). An add-on registers a filter with @wordpress/hooks:
//
//   wp.hooks.addFilter('madecost.products.toolbar', 'my-addon', (items) => [...items, (ctx) => <MyButton ctx={ctx} />]);
//
// and the page calls every registered function while it renders. The add-on script must load after
// `wp-hooks` and before the page renders (a script printed in the footer is enough).
import { applyFilters } from "@wordpress/hooks";
import type { ReactNode } from "react";
import type { Material } from "./engine/cost";
import type { CostedProduct } from "./engine/costing";
import type { Notify } from "./components/App";
import type { Store } from "./store";

export interface ExtensionContext {
  store: Store;
  notify: Notify;
}


export type ToolbarExtension = (ctx: ExtensionContext) => ReactNode;
export type RowExtension = (row: CostedProduct, ctx: ExtensionContext) => ReactNode;
export type PanelExtension = (ctx: ExtensionContext & { productId: string }) => ReactNode;

// Buttons or panels above the products table (for example "Write all").
export function toolbarExtensions(): ToolbarExtension[] {
  return applyFilters("madecost.products.toolbar", []) as ToolbarExtension[];
}

// Extra actions at the end of each product row.
export function rowExtensions(): RowExtension[] {
  return applyFilters("madecost.products.rowActions", []) as RowExtension[];
}

// Extra tabs next to Products, Materials and Settings.
export interface TabExtension {
  id: string;
  label: string;
  render: (ctx: ExtensionContext) => ReactNode;
}

export function tabExtensions(): TabExtension[] {
  return applyFilters("madecost.tabs", []) as TabExtension[];
}

// Extra panels in the material dialog. `patch` holds the price, pack size and waste being typed once they are valid
// (null while the form has errors); `materialId` is null when a material is being added.
export type MaterialPanelExtension = (
  ctx: ExtensionContext & { materialId: string | null; patch: Partial<Pick<Material, "packPriceCents" | "packQuantity" | "wastePercent">> | null },
) => ReactNode;

export function materialPanelExtensions(): MaterialPanelExtension[] {
  return applyFilters("madecost.material.panels", []) as MaterialPanelExtension[];
}

// Extra panels under the cost preview of the recipe editor.
export function panelExtensions(): PanelExtension[] {
  return applyFilters("madecost.recipe.panels", []) as PanelExtension[];
}
