<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>NodeKit</title>
    <link rel="shortcut icon" href="">

    <!-- NodeKit -->
    <script src="{{ js_path }}"></script>
    <link href="{{ css_path }}" rel="stylesheet">


    <script>
        function tryInferTurkContext() {
            if (typeof window === "undefined" || !window.location) {
                return null
            }

            const params = new URLSearchParams(window.location.search);

            // MTurk-style query params
            const assignmentId = params.get("assignmentId");
            const hitId = params.get("hitId");
            const workerId = params.get("workerId");
            const turkSubmitTo = params.get("turkSubmitTo");

            const looksLikeMTurk =
                assignmentId !== null ||
                hitId !== null ||
                workerId !== null ||
                turkSubmitTo !== null;

            if (!looksLikeMTurk) {
                return null
            }

            // Preview mode per MTurk docs: assignmentId is present and equals this sentinel.
            const PREVIEW_SENTINEL = "ASSIGNMENT_ID_NOT_AVAILABLE";
            const preview_mode = assignmentId === PREVIEW_SENTINEL;

            if (preview_mode) {
                return {
                    previewMode: true,
                    context: null,
                };
            }

            // Not previewing → require all fields
            if (!turkSubmitTo || !hitId || !assignmentId || !workerId) {
                const e = new Error("Missing required parameters in the query for MTurk platform.");
                e.name = "BadPlatformContextError";
                throw e;
            }

            return {
                previewMode: false,
                context: {
                    assignmentId: assignmentId,
                    turkSubmitTo: turkSubmitTo,
                    workerId: workerId,
                },
            };
        }
    </script>
    <script>
        function addPreviewSplash(){
            if (typeof window === "undefined" || !window.location) {
                return null
            }
            const div = document.createElement('div');
            div.textContent = 'Preview Mode. Accept the HIT to continue.';
            Object.assign(div.style, {
                position: 'fixed',
                top: '50%',
                left: '50%',
                transform: 'translate(-50%, -50%)',
                padding: '1.5rem 2rem',
                background: 'white',
                border: '2px solid #ccc',
                borderRadius: '8px',
                fontFamily: 'sans-serif',
                fontSize: '1.2rem',
                textAlign: 'center',
                boxShadow: '0 0 2px rgba(0,0,0,0.2)',
            });
            document.body.appendChild(div);
        }
    </script>

    <script>
        function submitToTurk(
            trace,
            assignmentId,
            turkSubmitTo,
        ){
            // Submission procedure for Mechanical Turk. See: https://docs.aws.amazon.com/AWSMechTurk/latest/AWSMechanicalTurkRequester/mturk-hits-defining-questions-html-javascript.html
            // Note the following undocumented gotcha: the form must have at least one input element other than assignmentId, otherwise
            // Mechanical Turk will not accept the submission. Here, we have the input element `sessionId`, which satisfies this requirement.

            // Get context variables:

            // create the form element and point it to the correct endpoint
            const form = document.createElement('form')
            form.action = (new URL('mturk/externalSubmit', turkSubmitTo)).href
            form.method = 'post'

            // attach the assignmentId
            const inputAssignmentId = document.createElement('input')
            inputAssignmentId.name = 'assignmentId'
            inputAssignmentId.value = assignmentId
            inputAssignmentId.hidden = true
            form.appendChild(inputAssignmentId)

            // attach a runId to allow for Experimenters to map HITs to Sessions
            const inputRunId = document.createElement('input')
            inputRunId.name = 'trace';
            inputRunId.value = JSON.stringify(trace);
            inputRunId.hidden = true;
            form.appendChild(inputRunId)

            // attach the form to the HTML document and trigger submission
            document.body.appendChild(form)

            // Submit the form
            form.submit()
        }
    </script>

    <script>
        const graph = {{ graph | tojson(indent=4) | indent(8, first=False) }};

        window.onload = async () => {
            // Infer the context:
            const turkContext = tryInferTurkContext()

            // Guard execution if in preview mode
            if (turkContext && turkContext.previewMode === true){
                // Add a simple, centered div in the middle of the page stating: "Preview Mode. Accept the HIT to continue."
                addPreviewSplash()
                return
            }

            // Play the Graph:
            const trace = await NodeKit.play(graph);

            // Handle close down procedures, based on the inferred context:
            if(turkContext && turkContext.previewMode === false){
                submitToTurk(
                    trace,
                    turkContext.context.assignmentId,
                    turkContext.context.turkSubmitTo,
                )
            }
        };
    </script>
</head>
<body></body>
</html>