<section style="padding: 48px 0; max-width: 640px; margin: 0 auto; text-align: center;">
<% If isValid Then %>
  <span class="eyebrow">Order link verified</span>
  <h1>Your order link is valid.</h1>
  <p>Jurisdiction number: <strong><%= H(order("JurisdictionNumber")) %></strong></p>
<% Else %>
  <span class="eyebrow">Link problem</span>
  <h1>This link is invalid or has expired.</h1>
  <p>
    Please <a href="<%= H(Routes().AppURL & "request-order") %>">request a new order</a>
    to receive a fresh link.
  </p>
<% End If %>
</section>

<% If isValid Then
    Dim municipalityIsReadOnlyJs, municipalityDescription
    If Len(Trim(municipalityName)) > 0 Then
        municipalityIsReadOnlyJs = "true"
        municipalityDescription = "Matched automatically from your jurisdiction number."
    Else
        municipalityIsReadOnlyJs = "false"
        municipalityDescription = "We couldn't automatically match your jurisdiction number - please enter your municipality."
    End If
%>
<link href="https://cdn.jsdelivr.net/npm/survey-core@2.5.36/survey-core.min.css" rel="stylesheet">

<div style="max-width: 760px; margin: 0 auto; padding: 0 16px;">
  <div class="cf-turnstile" style="margin-bottom: 24px;"
       data-sitekey="<%= H(turnstileSiteKey) %>"
       data-callback="onTurnstileVerified"></div>
</div>

<div id="surveyContainer" style="max-width: 760px; margin: 0 auto 64px; padding: 0 16px;"></div>

<div id="colorPickerOverlay" style="display:none; position:fixed; inset:0; background:rgba(36,16,58,0.55); z-index:1000; align-items:center; justify-content:center; padding:16px;">
  <div style="background:#fff; border-radius:14px; max-width:640px; width:100%; max-height:85vh; display:flex; flex-direction:column; overflow:hidden; box-shadow:0 12px 40px rgba(36,16,58,0.35);">
    <div style="display:flex; align-items:center; justify-content:space-between; padding:20px 24px; border-bottom:1px solid #f0e7f8;">
      <h3 style="margin:0; color:#201a27; font-size:18px;">Choose your colors</h3>
      <button type="button" id="colorPickerCloseBtn" aria-label="Close" style="background:none; border:none; font-size:22px; line-height:1; color:#6d6574; cursor:pointer; padding:4px 8px;">&times;</button>
    </div>
    <div id="colorPickerGrid" style="overflow-y:auto; padding:20px 24px; display:grid; grid-template-columns:repeat(auto-fill, minmax(150px, 1fr)); gap:12px;"></div>
    <div style="display:flex; justify-content:flex-end; gap:10px; padding:16px 24px; border-top:1px solid #f0e7f8;">
      <button type="button" id="colorPickerCancelBtn" class="button button-secondary">Cancel</button>
      <button type="button" id="colorPickerApplyBtn" class="button button-primary">Apply</button>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/survey-core@2.5.36/survey.core.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/survey-js-ui@2.5.36/survey-js-ui.min.js"></script>
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>
<script>
(function () {
  "use strict";

  var submitUrl = "<%= H(Routes().AppURL & "order/submit?token=" & Server.URLEncode(token)) %>";
  var csrfToken = "<%= H(csrfToken) %>";
  var turnstileToken = "";
  window.onTurnstileVerified = function (token) {
    turnstileToken = token;
  };

  // Election-materials order form. Field (name) values match the OrderDetails table
  // columns 1:1 - see db/migrations/20260728145000_create_order_details_table.asp and
  // db/migrations/20260804153857_revise_order_details_columns.asp.
  // Content and branching sourced from docs/lucid/*.pdf (the "(1)" files are the current
  // revision - see docs/lucid for both the original and revised versions).
  var surveyJson = {
    showProgressBar: "top",
    showQuestionNumbers: "off",
    completeText: "Submit Order",
    checkErrorsMode: "onNextPage",
    clearInvisibleValues: "onHidden",
    completedHtml: "<h3>Thank you for submitting your order.</h3>",
    pages: [
      {
        name: "contact",
        title: "1. Contact Information",
        elements: [
          { type: "text", name: "ContactName", title: "Contact Name", isRequired: true },
          {
            type: "text", name: "Municipality", title: "Municipality", isRequired: true,
            defaultValue: "<%= H(municipalityName) %>",
            readOnly: <%= municipalityIsReadOnlyJs %>,
            description: "<%= H(municipalityDescription) %>"
          },
          { type: "text", name: "Phone", title: "Phone Number", inputType: "tel", isRequired: true }
        ]
      },
      {
        name: "purpleEnvelope",
        title: "2. Purple Ballot Envelope Order Form",
        elements: [
          {
            type: "boolean", name: "PurpleWantsQuote", labelTrue: "Yes", labelFalse: "No",
            title: "Would you like for KCI to print your purple AV envelopes?",
            isRequired: true
          },
          {
            type: "text", name: "PurplePermanentBallotListCount",
            title: "How many are on your permanent ballot list?",
            inputType: "number", min: 0,
            visibleIf: "{PurpleWantsQuote} = true",
            isRequired: true
          },
          {
            type: "radiogroup", name: "PurpleEnvelopeStock",
            title: "Are you planning to use KCI's purple envelopes or from your own stock?",
            visibleIf: "{PurpleWantsQuote} = true",
            isRequired: true,
            choices: [
              { value: "KCIStock", text: "KCI's stock" },
              { value: "OwnStock", text: "My own stock" }
            ]
          },
          {
            type: "radiogroup", name: "PurplePrintOption",
            title: "Would you like KCI to print voter addresses on your purple envelopes or state of Michigan permit only?",
            visibleIf: "{PurpleWantsQuote} = true",
            isRequired: true,
            choices: [
              { value: "AddressesAndPermit", text: "Voter Addresses and state of Michigan permit" },
              { value: "PermitOnly", text: "State of Michigan permit only" }
            ]
          },
          {
            type: "radiogroup", name: "PurplePrintStyle",
            title: "Would you like your envelopes printed with color coding or black ink only?",
            visibleIf: "{PurplePrintOption} = 'AddressesAndPermit'",
            isRequired: true,
            choices: [
              { value: "ColorCoding", text: "Color Coding" },
              { value: "BlackOnly", text: "Black Ink Only" }
            ]
          },
          {
            type: "radiogroup", name: "PurpleColorCodingBy",
            title: "Color coding by precinct or by election?",
            visibleIf: "{PurplePrintStyle} = 'ColorCoding'",
            isRequired: true,
            choices: [
              { value: "Precinct", text: "Precinct" },
              { value: "Election", text: "Election" }
            ]
          },
          {
            type: "text", name: "PurplePrecinctCount", title: "How many precincts?",
            inputType: "number", min: 0,
            visibleIf: "{PurpleColorCodingBy} = 'Precinct'",
            isRequired: true
          },
          {
            type: "html",
            visibleIf: "{PurplePrintStyle} = 'ColorCoding'",
            html: "<button type=\"button\" id=\"openColorPickerBtn\" class=\"button button-secondary\">Choose Colors&hellip;</button>"
          },
          {
            type: "text", name: "PurpleColorNames", readOnly: true,
            title: "Which colors would you like to use?",
            description: "Use the \"Choose Colors…\" button above to pick from KCI's available envelope colors.",
            visibleIf: "{PurplePrintStyle} = 'ColorCoding'",
            isRequired: true
          },
          {
            type: "boolean", name: "PurpleTrackMIBallot", labelTrue: "Yes", labelFalse: "No",
            title: "Would you like to track ballots using TrackMI Ballot?",
            visibleIf: "{PurplePrintOption} = 'AddressesAndPermit'",
            isRequired: true
          },
          {
            type: "text", name: "PurpleExtraEnvelopeQty",
            title: "How many extra purple envelopes would you like? (If none, please put zero)",
            inputType: "number", min: 0,
            visibleIf: "{PurplePrintOption} = 'AddressesAndPermit'",
            isRequired: true
          },
          {
            type: "html",
            visibleIf: "{PurpleWantsQuote} = true",
            html: "<p>Purple envelopes are usually delivered or shipped 3 to 5 days after proof is approved.</p>"
          }
        ]
      },
      {
        name: "blueEnvelope",
        title: "3. Blue AV Envelope Order Form",
        elements: [
          {
            type: "boolean", name: "BlueWantsQuote", labelTrue: "Yes", labelFalse: "No",
            title: "Would you like to purchase blue AV envelopes from KCI?",
            isRequired: true
          },
          {
            type: "radiogroup", name: "BlueWantsOfficeCopies",
            title: "Would you like additional office copies when ordering KCI envelopes?",
            visibleIf: "{BlueWantsQuote} = true",
            isRequired: true,
            choices: [
              { value: "Yes", text: "Yes" },
              { value: "No", text: "No" }
            ]
          },
          {
            type: "text", name: "BlueOfficeCopiesQty",
            title: "How many additional office copies would you like?",
            inputType: "number", min: 0,
            visibleIf: "{BlueWantsOfficeCopies} = 'Yes'",
            isRequired: true
          },
          {
            type: "radiogroup", name: "PurpleBlueProvider",
            title: "Who is your blue envelope provider?",
            visibleIf: "{BlueWantsQuote} = false",
            isRequired: true,
            choices: [
              { value: "ElectionSource", text: "ElectionSource" },
              { value: "PSI", text: "PSI" },
              { value: "Spectrum", text: "Spectrum" },
              { value: "Other", text: "Other" }
            ]
          },
          {
            type: "text", name: "PurpleBlueProviderOther",
            title: "Please specify your blue envelope provider",
            visibleIf: "{PurpleBlueProvider} = 'Other'",
            isRequired: true
          },
          {
            type: "boolean", name: "BluePrintPermit", labelTrue: "Yes", labelFalse: "No",
            title: "Would you like KCI to print a permit on your blue envelope?",
            isRequired: true
          },
          {
            type: "radiogroup", name: "BluePermitOwnership",
            title: "Will you be using KCI's permit or your own?",
            visibleIf: "{BluePrintPermit} = true",
            isRequired: true,
            choices: [
              { value: "KCIPermit", text: "KCI permit" },
              { value: "OwnPermit", text: "My organization's permit" }
            ]
          },
          {
            type: "html",
            visibleIf: "{BluePermitOwnership} = 'KCIPermit'",
            html: "<p><strong>Please note, envelopes with KCI's permit MUST be mailed from KCI.</strong></p>"
          },
          {
            type: "radiogroup", name: "BlueHasNonprofitStatus",
            title: "Does your organization have confirmed nonprofit status with USPS?",
            visibleIf: "{BluePrintPermit} = true",
            isRequired: true,
            choices: [
              { value: "Yes", text: "Yes" },
              { value: "No", text: "No" },
              { value: "Unsure", text: "Unsure (That's okay, we can help you!)" }
            ]
          },
          {
            type: "text", name: "BluePermitCity", title: "City of permit holder",
            description: "A permit lookup can't be done from the authorization code alone, so please also provide the following information.",
            visibleIf: "{BluePermitOwnership} = 'OwnPermit'",
            isRequired: true
          },
          {
            type: "text", name: "BluePermitNumber", title: "Permit Number",
            visibleIf: "{BluePermitOwnership} = 'OwnPermit'",
            isRequired: true
          }
        ]
      },
      {
        name: "mailingService",
        title: "4. Ballot Mailing Service",
        elements: [
          {
            type: "boolean", name: "MailingWantsService", labelTrue: "Yes", labelFalse: "No",
            title: "Would you like to save postage and have KCI mail your ballots?",
            isRequired: true
          },
          {
            type: "radiogroup", name: "MailingPostageOption",
            title: "Would you like KCI to apply postage?",
            visibleIf: "{MailingWantsService} = true",
            isRequired: true,
            choices: [
              { value: "FirstClass", text: "Yes, at First Class Rate ($0.721/pc.)" },
              { value: "NonprofitRate", text: "Yes, at Nonprofit Rate ($0.263/pc.)" },
              { value: "PresortStandard", text: "Yes, at Presort Standard Rate ($0.473/pc.)" },
              { value: "No", text: "No" }
            ]
          },
          {
            type: "radiogroup", name: "MailingHasNonprofitStatus",
            title: "Do you have Nonprofit Status with the USPS?",
            visibleIf: "{MailingPostageOption} = 'NonprofitRate'",
            isRequired: true,
            choices: [
              { value: "Yes", text: "Yes" },
              { value: "No", text: "No" },
              { value: "NotSure", text: "I'm not sure (that's okay, we can help you!)" }
            ]
          },
          {
            type: "text", name: "MailingNonprofitAuthCode",
            title: "Please provide your nonprofit authorization code.",
            visibleIf: "{MailingHasNonprofitStatus} = 'Yes' and {MailingNonprofitAuthCodeUnknown} <> true",
            isRequired: true
          },
          {
            type: "boolean", name: "MailingNonprofitAuthCodeUnknown",
            title: "I don't know my authorization code",
            renderAs: "checkbox",
            visibleIf: "{MailingHasNonprofitStatus} = 'Yes'",
            defaultValue: false
          },
          {
            type: "text", name: "MailingEstimatedQuantity",
            title: "Please provide your estimated quantity.",
            inputType: "number", min: 0,
            visibleIf: "{MailingWantsService} = true",
            isRequired: true
          },
          {
            type: "dropdown", name: "MailingPickupDate",
            title: "What is your preferred (first) pickup date?",
            visibleIf: "{MailingWantsService} = true",
            isRequired: true,
            choices: [
              { value: "2026-09-21", text: "September 21, 2026" },
              { value: "2026-09-22", text: "September 22, 2026" },
              { value: "2026-09-23", text: "September 23, 2026" },
              { value: "2026-09-24", text: "September 24, 2026" },
              { value: "2026-09-25", text: "September 25, 2026" },
              { value: "2026-09-28", text: "September 28, 2026" },
              { value: "2026-09-29", text: "September 29, 2026" },
              { value: "2026-09-30", text: "September 30, 2026" },
              { value: "2026-10-01", text: "October 1, 2026" },
              { value: "2026-10-02", text: "October 2, 2026" }
            ]
          }
        ]
      },
      {
        name: "additionalItems",
        title: "5. Additional Election Items Request",
        elements: [
          {
            type: "text", name: "SecrecySleevesQty", title: "Secrecy Sleeves (quantity)",
            inputType: "number", min: 0, defaultValue: 0,
            isRequired: true
          },
          {
            type: "text", name: "IVotedStickerRolls", title: "\"I Voted\" Stickers - number of rolls (rolls of 250)",
            inputType: "number", min: 0, defaultValue: 0,
            isRequired: true
          },
          {
            type: "text", name: "FutureVoterStickerRolls", title: "\"Future Voter\" Stickers - number of rolls (rolls of 500)",
            inputType: "number", min: 0, defaultValue: 0,
            isRequired: true
          },
          {
            type: "comment", name: "SpecialRequests",
            title: "We will send you a copy of your price quote upon completion of this order form. If you have any special requests for any of your orders, please let us know here."
          }
        ]
      }
    ]
  };

  var survey = new Survey.Model(surveyJson);

  // Color picker modal for the "Which colors would you like to use?" question. Swatches are
  // the pre-converted PNGs in public/images/purple-envelope-colors/ (converted from the
  // original public/images/Purple_ballot_envelopes colors/*.bmp - those BMPs were ~400KB
  // each; PNG compresses these flat-color swatches down to ~1-4KB each).
  (function () {
    var COLOR_FILES = [
      "Aqua", "Black", "Blue", "Brown", "BurlyWood", "Chocolate", "Clay", "Coral",
      "CornflowerBlue", "Crimson", "DarkOrange", "DeepPink", "DeepSkyBlue", "DimGray",
      "DodgerBlue", "FireBrick", "ForestGreen", "Fuchsia", "Gold", "Goldenrod", "Green",
      "HotPink", "Indigo", "LightSeaGreen", "Lime", "LimeGreen", "LtGreen", "MediumOrchid",
      "MediumPurple", "MediumTurquoise", "MintGreen", "Navy", "Olive", "OliveDrab", "Orange",
      "OrangeRed", "Orchid", "PastelBlue", "PastelPink", "PastelPurple", "PastelYellow",
      "Peru", "Pink", "Purple", "Red", "RoyalBlue", "SaddleBrown", "SeaGreen", "Sienna",
      "Silver", "SkyBlue", "SteelBlue", "Tan", "Teal", "Tomato", "Turquoise", "Violet",
      "White", "Yellow"
    ];
    var colorImageBaseUrl = "<%= H(Routes().AppURL & "images/purple-envelope-colors/") %>";
    var overlay = document.getElementById("colorPickerOverlay");
    var grid = document.getElementById("colorPickerGrid");

    function colorLabel(fileName) {
      return fileName.replace(/([a-z])([A-Z])/g, "$1 $2");
    }

    COLOR_FILES.forEach(function (fileName) {
      var label = colorLabel(fileName);
      var item = document.createElement("label");
      item.style.cssText = "display:flex; flex-direction:column; gap:6px; border:1px solid #f0e7f8; border-radius:8px; padding:8px; cursor:pointer;";
      item.innerHTML =
        '<img src="' + colorImageBaseUrl + encodeURIComponent(fileName) + '.png" alt="" ' +
        'style="width:100%; height:36px; border-radius:4px; object-fit:cover; border:1px solid #e5d9f2;" />' +
        '<span style="display:flex; align-items:center; gap:6px; font-size:13px; color:#201a27;">' +
        '<input type="checkbox" class="color-picker-checkbox" value="' + label.replace(/"/g, "&quot;") + '" /> ' +
        label + "</span>";
      grid.appendChild(item);
    });

    function openColorPicker() {
      var current = (survey.getValue("PurpleColorNames") || "")
        .split(",")
        .map(function (s) { return s.trim(); })
        .filter(Boolean);
      var currentSet = {};
      current.forEach(function (c) { currentSet[c] = true; });
      var checkboxes = grid.querySelectorAll(".color-picker-checkbox");
      checkboxes.forEach(function (cb) { cb.checked = !!currentSet[cb.value]; });
      overlay.style.display = "flex";
    }

    function closeColorPicker() {
      overlay.style.display = "none";
    }

    function applyColorPicker() {
      var checked = grid.querySelectorAll(".color-picker-checkbox:checked");
      var selected = Array.prototype.map.call(checked, function (cb) { return cb.value; });
      survey.setValue("PurpleColorNames", selected.join(", "));
      closeColorPicker();
    }

    document.getElementById("colorPickerCloseBtn").addEventListener("click", closeColorPicker);
    document.getElementById("colorPickerCancelBtn").addEventListener("click", closeColorPicker);
    document.getElementById("colorPickerApplyBtn").addEventListener("click", applyColorPicker);
    overlay.addEventListener("click", function (event) {
      if (event.target === overlay) closeColorPicker();
    });

    // The "Choose Colors..." button is rendered by SurveyJS as an html question, so it
    // doesn't exist in the DOM until that page is shown - delegate from a stable ancestor.
    document.addEventListener("click", function (event) {
      if (event.target && event.target.id === "openColorPickerBtn") {
        event.preventDefault();
        openColorPicker();
      }
    });
  })();

  survey.onCompleting.add(function (sender, options) {
    if (!turnstileToken) {
      options.allowComplete = false;
      alert("Please complete the verification challenge above before submitting.");
    }
  });

  survey.onComplete.add(function (sender) {
    fetch(submitUrl, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "X-CSRF-Token": csrfToken,
        "X-Turnstile-Token": turnstileToken
      },
      body: JSON.stringify(sender.data)
    })
      .then(function (res) {
        return res.json().catch(function () { return {}; }).then(function (body) {
          return { ok: res.ok, body: body };
        });
      })
      .then(function (result) {
        if (result.ok && result.body && result.body.success) {
          window.location.href = "<%= H(Routes().AppURL) %>";
        } else {
          alert((result.body && result.body.error) || "Something went wrong submitting your order. Please try again.");
        }
      })
      .catch(function () {
        alert("Something went wrong submitting your order. Please check your connection and try again.");
      });
  });

  survey.render(document.getElementById("surveyContainer"));
})();
</script>
<% End If %>
