{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "country-state-form",
  "title": "Country + State Form",
  "description": "Cascading Country and State dropdowns using registry-based loaders.",
  "registryDependencies": [
    "@buzzform/select",
    "card",
    "sonner"
  ],
  "files": [
    {
      "path": "registry/shadcn/examples/country-state-form.tsx",
      "content": "\"use client\";\n\nimport {\n  Card,\n  CardContent,\n  CardDescription,\n  CardHeader,\n  CardTitle,\n} from \"@/components/ui/card\";\nimport {\n  Form,\n  FormContent,\n  FormFields,\n  FormSubmit,\n} from \"@/registry/shadcn/form\";\nimport { toast } from \"sonner\";\nimport {\n  defineSchema,\n  defineOptionResolvers,\n  type InferType,\n} from \"@buildnbuzz/form-react\";\n\nconst API_BASE = \"https://countriesnow.space/api/v0.1\";\n\n/** Response shape for the countries endpoint. */\ninterface CountryEntry {\n  iso2: string;\n  country: string;\n}\n\n/** Response shape for the states endpoint. */\ninterface StateEntry {\n  name: string;\n  state_code: string;\n}\n\n/**\n * 1. Define Option Resolvers using the registry helper.\n *\n * Uses the CountriesNow API (free, no API key, CORS-friendly):\n * - Countries: GET /api/v0.1/countries\n * - States:    GET /api/v0.1/countries/states/q?country=X\n * - Cities:    GET /api/v0.1/countries/state/cities/q?country=X&state=Y\n */\nconst locationResolvers = defineOptionResolvers({\n  listCountries: async () => {\n    try {\n      const response = await fetch(`${API_BASE}/countries`);\n      if (!response.ok) {\n        toast.error(\"Could not fetch countries. Please try again later.\");\n        return [];\n      }\n\n      const json = await response.json();\n      const countries = json.data as CountryEntry[];\n\n      return countries\n        .map((c) => ({\n          label: c.country,\n          value: c.country,\n        }))\n        .filter(\n          (opt, i, arr) => arr.findIndex((o) => o.value === opt.value) === i,\n        )\n        .sort((a: { label: string }, b: { label: string }) =>\n          a.label.localeCompare(b.label),\n        );\n    } catch {\n      toast.error(\"Could not fetch countries. Check your network connection.\");\n      return [];\n    }\n  },\n\n  listStates: async ({ data }) => {\n    const country = data.country as string;\n    if (!country) return [];\n\n    const url = `${API_BASE}/countries/states/q?country=${encodeURIComponent(country)}`;\n    try {\n      const response = await fetch(url, { redirect: \"follow\" });\n      if (!response.ok) {\n        toast.error(`Could not fetch states for ${country}. Please try again.`);\n        return [];\n      }\n\n      const json = await response.json();\n      const states = json.data.states as StateEntry[];\n\n      return states\n        .map((s) => ({\n          label: s.name,\n          value: s.name,\n        }))\n        .filter(\n          (opt, i, arr) => arr.findIndex((o) => o.value === opt.value) === i,\n        );\n    } catch {\n      toast.error(\"Could not fetch states. Check your network connection.\");\n      return [];\n    }\n  },\n\n  listCities: async ({ data }) => {\n    const country = data.country as string;\n    const state = data.state as string;\n    if (!country || !state) return [];\n\n    const url = `${API_BASE}/countries/state/cities/q?country=${encodeURIComponent(country)}&state=${encodeURIComponent(state)}`;\n    try {\n      const response = await fetch(url);\n      if (!response.ok) {\n        toast.error(\n          `Could not fetch cities for ${state}, ${country}. Please try again.`,\n        );\n        return [];\n      }\n\n      const json = await response.json();\n      const cities = json.data as string[];\n\n      return cities\n        .map((city) => ({\n          label: city,\n          value: city,\n        }))\n        .filter(\n          (opt, i, arr) => arr.findIndex((o) => o.value === opt.value) === i,\n        );\n    } catch {\n      toast.error(\"Could not fetch cities. Check your network connection.\");\n      return [];\n    }\n  },\n});\n\n// 2. Define the Schema with various defaultValue patterns\nconst locationSchema = defineSchema({\n  fields: [\n    {\n      type: \"select\",\n      name: \"country\",\n      label: \"Country\",\n      defaultValue: \"United States\", // 1. Static literal default\n      placeholder: \"Search and select a country...\",\n      required: true,\n      options: { resolver: \"listCountries\" },\n    },\n    {\n      type: \"select\",\n      name: \"state\",\n      label: ({ data }) =>\n        data.country\n          ? ` State / Province in ${data.country}`\n          : \"State / Province\",\n      // 2. Inline function resolving from context\n      defaultValue: (ctx) => (ctx.context?.defaultState ? \"Florida\" : \"\"),\n      placeholder: ({ data }) =>\n        (data.country as string) || \"Choose country first\",\n      required: true,\n      options: { resolver: \"listStates\" },\n      dependencies: [\"/country\"],\n      disabled: { $data: \"/country\", not: true },\n      ui: {\n        emptyMessage: \"No states found for this country\",\n      },\n    },\n    {\n      type: \"select\",\n      name: \"city\",\n      label: {\n        $when: { $data: \"/state\" },\n        $then: { $text: \"City in ${/state}\" },\n        $else: \"City\",\n      },\n      placeholder: {\n        $when: { $data: \"/state\" },\n        $then: { $text: \"Choose city in ${/state}...\" },\n        $else: \"Choose state first\",\n      },\n      required: true,\n      options: { resolver: \"listCities\" },\n      dependencies: [\"/country\", \"/state\"],\n      disabled: { $data: \"/state\", not: true },\n      ui: {\n        emptyMessage: \"No cities found for this state\",\n      },\n    },\n    {\n      type: \"text\",\n      name: \"address_label\",\n      label: \"Mailing Label\",\n      // 4. Interpolated template string as default\n      defaultValue: { $text: \"Ship to ${/country}\" },\n      description: \"Auto-generated from your initial country selection.\",\n    },\n  ],\n});\n\ntype LocationData = InferType<typeof locationSchema.fields>;\n\n/**\n * Example demonstrating 3-level cascading dropdowns (Country → State → City)\n * using the Registry-based Options API with the CountriesNow REST API.\n */\nexport default function CountryStateForm() {\n  return (\n    <Card className=\"w-full max-w-md mx-auto\">\n      <CardHeader>\n        <CardTitle>Location Selector</CardTitle>\n        <CardDescription>\n          3-level cascading dropdowns powered by CountriesNow API\n        </CardDescription>\n      </CardHeader>\n      <CardContent>\n        <Form\n          schema={locationSchema}\n          registries={{ resolvers: locationResolvers }}\n          contextData={{ defaultState: \"California\" }}\n          onSubmit={async ({ value }) => {\n            const data = value as LocationData;\n            await new Promise((resolve) => setTimeout(resolve, 800));\n            toast(\"Location Saved!\", {\n              description: (\n                <pre className=\"mt-2 max-h-48 overflow-auto rounded-md bg-muted text-muted-foreground p-3 text-xs\">\n                  <code>{JSON.stringify(data, null, 2)}</code>\n                </pre>\n              ),\n            });\n          }}\n        >\n          <FormContent>\n            <FormFields className=\"space-y-4\" />\n            <div className=\"flex justify-end pt-4\">\n              <FormSubmit>Save Location</FormSubmit>\n            </div>\n          </FormContent>\n        </Form>\n      </CardContent>\n    </Card>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/buzzform/examples/country-state-form.tsx"
    }
  ],
  "type": "registry:block"
}