"use client";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useCallback, useRef, useState } from "react";
import { cn } from "@stigmer/theme";
import { getUserMessage } from "@stigmer/sdk";
import { useCreateOrganization } from "./useCreateOrganization";
import { generateSlug } from "../internal/slug";
// ---------------------------------------------------------------------------
// Slug validation (mirrors Organization proto CEL rules)
// ---------------------------------------------------------------------------
const SLUG_PATTERN = /^[a-z][a-z0-9-]*$/;
const SLUG_MIN = 2;
const SLUG_MAX = 15;
function validateSlug(slug) {
    if (slug.length === 0)
        return "Slug is required.";
    if (slug.length < SLUG_MIN || slug.length > SLUG_MAX)
        return `Must be between ${SLUG_MIN} and ${SLUG_MAX} characters.`;
    if (!/^[a-z]/.test(slug))
        return "Must start with a lowercase letter.";
    if (!SLUG_PATTERN.test(slug))
        return "Only lowercase letters, numbers, and hyphens are allowed.";
    return null;
}
/**
 * Compact form for creating a new {@link Organization} resource.
 *
 * Collects a name, auto-generates a URL-friendly slug, and accepts an
 * optional description. The slug is derived from the name by default
 * but can be manually overridden. It is sent to the server as both
 * `metadata.slug` and `metadata.org` (organizations are self-owning).
 *
 * All visual properties flow through `--stgm-*` design tokens.
 *
 * @example
 * ```tsx
 * <CreateOrganizationForm
 *   onCreated={(org) => console.log("Created:", org.metadata?.slug)}
 *   onCancel={() => setShowForm(false)}
 * />
 * ```
 */
export function CreateOrganizationForm({ onCreated, onCancel, className, }) {
    const { create, isCreating, error, clearError } = useCreateOrganization();
    const [name, setName] = useState("");
    const [slug, setSlug] = useState("");
    const [description, setDescription] = useState("");
    // Once the user manually edits the slug field, stop auto-deriving.
    const slugTouchedRef = useRef(false);
    const trimmedName = name.trim();
    const slugError = slug.length > 0 ? validateSlug(slug) : null;
    const canSubmit = trimmedName !== "" && slug.length > 0 && slugError === null && !isCreating;
    const handleNameChange = useCallback((value) => {
        setName(value);
        if (!slugTouchedRef.current) {
            setSlug(generateSlug(value.trim()));
        }
    }, []);
    const handleSlugChange = useCallback((value) => {
        slugTouchedRef.current = true;
        setSlug(value);
    }, []);
    const handleSubmit = useCallback(async (e) => {
        e.preventDefault();
        if (!canSubmit)
            return;
        clearError();
        try {
            const org = await create({
                name: trimmedName,
                slug,
                org: slug,
                description: description.trim() || undefined,
            });
            onCreated?.(org);
        }
        catch {
            // error state is managed by useCreateOrganization
        }
    }, [canSubmit, trimmedName, slug, description, create, clearError, onCreated]);
    return (_jsxs("form", { onSubmit: handleSubmit, className: cn("space-y-3", className), children: [_jsxs("div", { className: "space-y-2", children: [_jsxs("div", { className: "space-y-1", children: [_jsx("label", { htmlFor: "stgm-new-org-name", className: "text-xs font-medium text-foreground", children: "Name" }), _jsx("input", { id: "stgm-new-org-name", type: "text", value: name, onChange: (e) => handleNameChange(e.target.value), placeholder: "e.g. Acme Corp", disabled: isCreating, autoFocus: true, required: true, className: cn("w-full rounded-md border border-input bg-background px-2.5 py-1.5 text-xs text-foreground", "placeholder:text-muted-foreground", "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring", "disabled:pointer-events-none disabled:opacity-50") }), _jsx("p", { className: "text-[0.65rem] text-muted-foreground", children: "A human-readable display name for the organization." })] }), _jsxs("div", { className: "space-y-1", children: [_jsx("label", { htmlFor: "stgm-new-org-slug", className: "text-xs font-medium text-foreground", children: "Slug" }), _jsx("input", { id: "stgm-new-org-slug", type: "text", value: slug, onChange: (e) => handleSlugChange(e.target.value), placeholder: "e.g. acme-corp", disabled: isCreating, required: true, className: cn("w-full rounded-md border bg-background px-2.5 py-1.5 text-xs text-foreground font-mono", "placeholder:text-muted-foreground", "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring", "disabled:pointer-events-none disabled:opacity-50", slugError
                                    ? "border-destructive"
                                    : "border-input") }), slugError ? (_jsx("p", { className: "text-[0.65rem] text-destructive", role: "alert", children: slugError })) : (_jsxs("p", { className: "text-[0.65rem] text-muted-foreground", children: ["URL-friendly identifier used in resource references.", " ", SLUG_MIN, "\u2013", SLUG_MAX, " characters: lowercase letters, numbers, and hyphens."] }))] }), _jsxs("div", { className: "space-y-1", children: [_jsxs("label", { htmlFor: "stgm-new-org-desc", className: "text-xs font-medium text-muted-foreground", children: ["Description", " ", _jsx("span", { className: "text-muted-foreground-subtle", children: "(optional)" })] }), _jsx("input", { id: "stgm-new-org-desc", type: "text", value: description, onChange: (e) => setDescription(e.target.value), placeholder: "What is this organization for?", disabled: isCreating, className: cn("w-full rounded-md border border-input bg-background px-2.5 py-1.5 text-xs text-foreground", "placeholder:text-muted-foreground", "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring", "disabled:pointer-events-none disabled:opacity-50") })] })] }), error && (_jsx("p", { className: "text-destructive text-[0.65rem]", role: "alert", children: getUserMessage(error) })), _jsxs("div", { className: "flex items-center gap-2", children: [_jsxs("button", { type: "submit", disabled: !canSubmit, className: cn("inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium", "bg-primary text-primary-foreground hover:bg-primary-hover", "disabled:pointer-events-none disabled:opacity-40"), children: [isCreating && _jsx(SpinnerIcon, {}), "Create organization"] }), onCancel && (_jsx("button", { type: "button", onClick: onCancel, disabled: isCreating, className: cn("rounded-md px-3 py-1.5 text-xs", "text-muted-foreground hover:text-foreground hover:bg-accent-hover", "disabled:pointer-events-none disabled:opacity-50"), children: "Cancel" }))] })] }));
}
// ---------------------------------------------------------------------------
// Icons
// ---------------------------------------------------------------------------
function SpinnerIcon() {
    return (_jsx("svg", { width: "12", height: "12", viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", className: "animate-spin", "aria-hidden": "true", children: _jsx("path", { d: "M8 2a6 6 0 1 0 6 6" }) }));
}
//# sourceMappingURL=CreateOrganizationForm.js.map