import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useError, useMaybeBody, useMaybeResult, useSubmitted } from "../data/index.js";
import { addFormMeta, setFormMeta, } from "../../../data/index.js";
import { ok } from "../../../is.js";
import { bugsUrl, commit, homepage, packageIdentifier, } from "../../../package.js";
import { CC0_URL, MIT_URL, NZCODE_URL } from "../../../static.js";
import { Octokit } from "@octokit/rest";
import { getOrigin } from "../../../listen/index.js";
import { isUnauthenticated } from "../../../authentication/index.js";
export const path = "/feedback";
export const anonymous = true;
function assertFeedback(value) {
    ok(value);
    ok(value.type === "feedback");
    ok(value.title?.trim().length, "Expected title");
    ok(value.message?.trim().length, "Expected message");
    ok(value.locatedInNewZealand, "We can only accept feedback from people located in New Zealand at this time");
    ok(value.storageConsent, "Feedback cannot be stored as no consent provided");
}
export async function submit(request) {
    const data = request.body;
    assertFeedback(data);
    let meta = await addFormMeta(data);
    const { GITHUB_TOKEN } = process.env;
    if (GITHUB_TOKEN) {
        const { pathname: repository, origin } = new URL(homepage);
        ok(origin.includes("github.com"), `Expected homepages origin to include github.com, got ${origin} for ${homepage}`);
        const split = repository.split("/").filter(Boolean);
        ok(split.length === 2, `Expected two parts to homepage pathname, got ${split.join(", ")}`);
        const [owner, repo] = split;
        const octokit = new Octokit({
            auth: GITHUB_TOKEN,
        });
        const result = await octokit.request("POST /repos/{owner}/{repo}/issues", {
            owner,
            repo,
            title: data.title,
            body: [
                data.message,
                [
                    `Origin: ${getOrigin()}`,
                    `Form Meta: ${meta.formMetaId}`,
                    `Package: ${packageIdentifier}`,
                    `Commit: ${commit}`,
                    isUnauthenticated() ? "Anonymous" : "Authenticated",
                    data.name ? `Name: ${data.name}` : "No name given",
                ]
                    .filter(Boolean)
                    .join("\n"),
            ].join("\n\n-------------\n\n"),
            assignees: [],
            labels: ["feedback"],
            headers: {
                "X-GitHub-Api-Version": "2022-11-28",
            },
        });
        if (result.data?.html_url) {
            meta = await setFormMeta({
                ...meta,
                externalIssueUrl: result.data.html_url,
            });
            console.log(result.data.html_url);
        }
    }
    return { success: true, meta };
}
const FORM_CLASS = `
mt-1
block
w-full
md:max-w-sm
rounded-md
border-gray-300
shadow-sm
focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50
disabled:bg-slate-300 disabled:cursor-not-allowed
`.trim();
const FORM_GROUP_CLASS = `block py-2`;
export function Feedback() {
    const body = useMaybeBody();
    const submitted = useSubmitted();
    const result = useMaybeResult();
    const error = useError();
    console.log(error);
    return (_jsxs("form", { name: "calculator", action: "/feedback#action-section", method: "post", children: [result ? (_jsx("script", { type: "application/json", id: "result-json", dangerouslySetInnerHTML: {
                    __html: JSON.stringify(result, undefined, "  "),
                } })) : undefined, _jsx("input", { type: "hidden", name: "type", value: "feedback" }), _jsxs("div", { className: "flex flex-col", children: [_jsxs("label", { className: FORM_GROUP_CLASS, children: [_jsx("span", { className: "text-gray-700", children: "Title" }), _jsx("input", { className: FORM_CLASS, type: "text", name: "title", placeholder: "Feedback Title", defaultValue: result?.success ? "" : body?.title || "" })] }), _jsxs("label", { className: FORM_GROUP_CLASS, children: [_jsx("span", { className: "text-gray-700", children: "Optional Name" }), _jsx("input", { className: FORM_CLASS, type: "text", name: "name", placeholder: "Optional Name", defaultValue: result?.success ? "" : body?.name || "" })] }), _jsxs("label", { className: FORM_GROUP_CLASS, children: [_jsx("span", { className: "text-gray-700", children: "Message" }), _jsx("textarea", { className: FORM_CLASS, name: "message", placeholder: "Feedback Message", defaultValue: result?.success ? "" : body?.message || "" })] })] }), _jsx("hr", { className: "my-8" }), _jsxs("label", { htmlFor: "locatedInNewZealand", className: "my-4 flex flex-row items-center", children: [_jsx("input", { name: "locatedInNewZealand", id: "locatedInNewZealand", type: "checkbox", className: "form-checkbox rounded m-1", defaultChecked: result?.success ? false : body?.locatedInNewZealand || false }), _jsxs("span", { className: "block ml-4", children: ["We adhere to the\u00A0", _jsx("a", { href: NZCODE_URL, target: "_blank", rel: "noreferrer", children: "New Zealand Code" }), "\u00A0licence. Because of this, we would like to acknowledge and understand if feedback or feature requests are by New Zealanders.", _jsx("br", {}), "By ticking this checkbox you are confirming you are located in New Zealand."] })] }), _jsxs("label", { htmlFor: "storageConsent", className: "my-4 flex flex-row items-center", children: [_jsx("input", { name: "storageConsent", id: "storageConsent", type: "checkbox", className: "form-checkbox rounded m-1", defaultChecked: result?.success ? false : body?.storageConsent || false }), _jsxs("ul", { className: "ml-4 list-none divide-y divide-dashed", children: [_jsx("li", { children: "I give consent for the provided information to be stored." }), _jsxs("li", { children: ["I give consent for the provided information to be published publicly, for example on sites like", " ", _jsx("a", { href: bugsUrl, target: "_blank", rel: "noreferrer", children: "GitHub" })] }), _jsxs("li", { children: ["I give consent for the feedback to be used to implement features potentially in more than one codebase, including code bases licenced using the", " ", _jsx("a", { href: MIT_URL, target: "_blank", rel: "noreferrer", children: "GitHub" }), " ", "licence or", " ", _jsx("a", { href: CC0_URL, target: "_blank", rel: "noreferrer", children: "GitHub" })] }), _jsx("li", { children: "I understand that the feedback will be taken into consideration and may or may not be included as a feature" })] })] }), _jsx("hr", { className: "my-8" }), _jsxs("div", { id: "action-section", children: [_jsx("button", { type: "submit", className: "bg-sky-500 hover:bg-sky-700 px-4 py-2.5 text-sm leading-5 rounded-md font-semibold text-white", children: "Submit Feedback" }), _jsxs("section", { id: "result-section", children: [error ? (_jsxs(_Fragment, { children: [_jsx("hr", { className: "my-8" }), _jsx("div", { className: "pointer-events-auto flex items-center justify-between gap-x-6 bg-red-400 px-6 py-2.5 sm:rounded-xl sm:py-3 sm:pl-4 sm:pr-3.5", children: _jsx("p", { className: "text-sm leading-6 text-white", children: error instanceof Error ? error.message : String(error) }) }), _jsx("hr", { className: "my-8" })] })) : undefined, submitted && result ? (_jsxs("div", { children: [_jsx("hr", { className: "my-8" }), result.success ? (_jsx("div", { className: "pointer-events-auto flex items-center justify-between gap-x-6 bg-emerald-500 px-6 py-2.5 sm:rounded-xl sm:py-3 sm:pl-4 sm:pr-3.5", children: _jsx("p", { className: "text-sm leading-6 text-white", children: "Feedback successfully submitted! Cheers" }) })) : undefined] })) : undefined] })] })] }));
}
export const Component = Feedback;
//# sourceMappingURL=feedback.js.map