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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
// Change.org offline clone - local-only interactions. No remote requests.
(function () {
  "use strict";

  var homePetitionForm = document.querySelector("[data-home-petition-form]");
  if (homePetitionForm) {
    var homePetitionQuestion = homePetitionForm.querySelector(
      "[data-home-petition-question]"
    );
    homePetitionForm.addEventListener("submit", function (event) {
      var value = homePetitionQuestion
        ? homePetitionQuestion.value.trim()
        : "";
      if (!value) {
        event.preventDefault();
        if (homePetitionQuestion) {
          homePetitionQuestion.setAttribute("aria-invalid", "true");
          homePetitionQuestion.focus();
        }
        return;
      }
      window.sessionStorage.setItem("change:start-flow:issue", value);
      window.sessionStorage.removeItem("change:start-flow:title");
      window.sessionStorage.removeItem("change:start-flow:body");
    });
    if (homePetitionQuestion) {
      homePetitionQuestion.addEventListener("input", function () {
        homePetitionQuestion.removeAttribute("aria-invalid");
      });
    }
  }

  // The captured source returned a 301 document transition to /intro and
  // subsequently exposed started_flow=true as browser history state. Keep
  // those two observations separate instead of inventing a 302-with-query.
  if (
    window.location.pathname === "/start-a-petition/intro" &&
    window.location.search === ""
  ) {
    window.history.replaceState(
      { startedFlow: true },
      "",
      "/start-a-petition/intro?started_flow=true"
    );
  }

  document.querySelectorAll("[data-start-route]").forEach(function (button) {
    button.addEventListener("click", function () {
      var target = new URL(button.getAttribute("data-start-route"), window.location.origin);
      target.search = window.location.search;
      window.location.assign(target.pathname + target.search);
    });
  });

  document.querySelectorAll("[data-auth-boundary]").forEach(function (button) {
    button.addEventListener("click", function () {
      window.location.assign(button.getAttribute("data-auth-boundary"));
    });
  });

  var startFlowPage = document.querySelector("[data-start-flow-step]");
  if (startFlowPage) {
    var flowLoader = startFlowPage.querySelector("[data-flow-loader]");
    var flowContent = startFlowPage.querySelector("[data-flow-content]");
    var flowForm = startFlowPage.querySelector("[data-flow-form]");
    var flowAnswer = startFlowPage.querySelector("#start-flow-answer");
    var flowError = startFlowPage.querySelector(".start-flow-error");
    var flowBack = startFlowPage.querySelector("[data-flow-back-button]");
    var flowGenerating = startFlowPage.querySelector("[data-flow-generating]");
    var flowStep = startFlowPage.getAttribute("data-start-flow-step");
    var flowOptional = startFlowPage.getAttribute("data-flow-optional") === "true";
    var preserveFlowQuery = function (path) {
      var target = new URL(path, window.location.origin);
      target.search = window.location.search;
      return target.pathname + target.search;
    };
    var revealFlowContent = function () {
      if (flowLoader) flowLoader.hidden = true;
      if (flowContent) flowContent.hidden = false;
      if (flowAnswer) {
        flowAnswer.value = window.sessionStorage.getItem(
          "change:start-flow:" + flowStep
        ) || "";
      }
    };
    revealFlowContent();

    if (flowBack) {
      flowBack.addEventListener("click", function () {
        window.location.assign(
          preserveFlowQuery(startFlowPage.getAttribute("data-flow-back"))
        );
      });
    }
    if (flowAnswer) {
      flowAnswer.addEventListener("input", function () {
        if (flowError) flowError.hidden = true;
        flowAnswer.removeAttribute("aria-invalid");
      });
    }
    if (flowForm) {
      flowForm.addEventListener("submit", function (event) {
        event.preventDefault();
        var value = flowAnswer ? flowAnswer.value.trim() : "";
        if (!flowOptional && !value) {
          if (flowError) flowError.hidden = false;
          if (flowAnswer) {
            flowAnswer.setAttribute("aria-invalid", "true");
            flowAnswer.focus();
          }
          return;
        }
        window.sessionStorage.setItem("change:start-flow:" + flowStep, value);
        if (flowGenerating) {
          if (flowContent) flowContent.hidden = true;
          flowGenerating.hidden = false;
          window.setTimeout(function () {
            window.location.assign(
              preserveFlowQuery(startFlowPage.getAttribute("data-flow-next"))
            );
          }, 2400);
          return;
        }
        window.location.assign(
          preserveFlowQuery(startFlowPage.getAttribute("data-flow-next"))
        );
      });
    }
  }

  function pathWithCurrentQuery(path) {
    var target = new URL(path, window.location.origin);
    target.search = window.location.search;
    return target.pathname + target.search;
  }

  function draftIssue() {
    var queryIssue = new URLSearchParams(window.location.search).get("issue");
    if (queryIssue && queryIssue.trim()) {
      window.sessionStorage.setItem("change:start-flow:issue", queryIssue.trim());
    }
    return (
      (queryIssue && queryIssue.trim()) ||
      window.sessionStorage.getItem("change:start-flow:issue") ||
      "EA1 DFS controlled test petition"
    ).trim();
  }

  function draftTitleFromIssue(issue) {
    var title = issue.trim().replace(/[.!?]+$/, "");
    if (/^protect\b/i.test(title)) {
      title = title.replace(/^protect\b/i, "Preserve");
    } else if (/^require\b/i.test(title)) {
      title = title.replace(/^require\b/i, "Require");
    }
    return title.charAt(0).toUpperCase() + title.slice(1);
  }

  function draftSubject(issue) {
    return issue
      .replace(/^(protect|preserve|save|support|require)\s+/i, "")
      .replace(/[.!?]+$/, "")
      .trim() || "this important community place";
  }

  function deterministicDraftBody(issue) {
    if (issue.trim().toLowerCase() === "ea1 dfs controlled test petition") {
      return "This is controlled test content for observing the petition creation workflow. It does not contact or name any unrelated person or organisation.";
    }
    var subject = draftSubject(issue);
    if (subject.toLowerCase() === "the offline clone test park") {
      return [
        "Growing up in [City/Town/Area Name], the offline clone test park was a place where adventure and imagination felt limitless. In a fast-urbanizing world, this space has been my refuge, a sanctuary for both locals and visitors alike. The sounds of laughter, the sight of open skies, and the feel of the breeze through the trees are irreplaceable memories that have been a part of many residents' lives.",
        "However, this beloved park is now under threat of being destroyed to make way for a new commercial complex. This decision has been made without adequate community consultation, and without considering the environmental and social impact on our community. We cannot allow our cherished green spaces to be sacrificed for short-term gains.",
        "The offline clone test park has not only been a place of respite but also an ecological haven. It is home to several plant and animal species and represents an important ecological buffer that supports the local climate. Destroying it would mean losing much of our biodiversity and contributing to an increase in urban heat.",
        "Furthermore, studies show that access to green spaces significantly improves mental health and community well-being. According to a study from the University of Exeter Medical School, people living in greener urban areas report less mental distress and higher life satisfaction.",
        "We urge the city council and local authorities to reconsider this decision. Instead of a commercial complex, we propose revitalizing the park and enhancing its facilities to better serve the community. By doing so, we can make it an even greater asset without losing its essential character and purpose.",
        "Please help protect the offline clone test park for future generations by signing this petition. Let's show our officials that this community space is invaluable and worth preserving. Together, we can make a difference and stand up for the green spaces that enhance our quality of life."
      ].join("\n\n");
    }
    return [
      "Growing up in [City/Town/Area Name], " + subject +
        " was a place where adventure and imagination felt limitless. " +
        "It has been a refuge and a gathering place for local people and visitors alike.",
      "Today, " + subject +
        " needs our help. Decisions that affect our community should be made transparently, " +
        "with meaningful consultation and careful attention to their social and environmental impact.",
      "We urge the relevant decision makers to protect " + subject +
        " and work with the community on a lasting solution. Please support this petition " +
        "so we can preserve what matters for current and future generations."
    ].join("\n\n");
  }

  var draftEditor = document.querySelector("[data-draft-editor]");
  if (draftEditor) {
    var draftTitle = draftEditor.querySelector("[data-draft-title]");
    var draftBody = draftEditor.querySelector("[data-draft-body]");
    var storedIssue = draftIssue();
    var storedTitle = window.sessionStorage.getItem("change:start-flow:title");
    var storedBody = window.sessionStorage.getItem("change:start-flow:body");
    if (
      document.body.classList.contains("page-start-petition-create")
      && window.matchMedia("(min-width: 761px)").matches
    ) {
      [200, 350, 600].forEach(function (delay) {
        window.setTimeout(function () {
          if (window.scrollY >= 260 && window.scrollY < 273) {
            window.scrollTo(0, 273);
          }
        }, delay);
      });
    }
    if (draftTitle) {
      draftTitle.value = storedTitle || draftTitleFromIssue(storedIssue);
      draftTitle.addEventListener("input", function () {
        window.sessionStorage.setItem("change:start-flow:title", draftTitle.value);
      });
    }
    if (draftBody) {
      draftBody.value = storedBody || deterministicDraftBody(storedIssue);
      draftBody.addEventListener("input", function () {
        window.sessionStorage.setItem("change:start-flow:body", draftBody.value);
      });
    }
    draftEditor.querySelectorAll("[data-start-scratch]").forEach(function (button) {
      button.addEventListener("click", function () {
        if (draftTitle) draftTitle.value = "";
        if (draftBody) draftBody.value = "";
        window.sessionStorage.setItem("change:start-flow:title", "");
        window.sessionStorage.setItem("change:start-flow:body", "");
        if (draftTitle) draftTitle.focus();
      });
    });
    draftEditor.querySelectorAll("[data-editor-command]").forEach(function (button) {
      button.addEventListener("click", function () {
        if (draftBody) draftBody.focus();
        var command = button.getAttribute("data-editor-command");
        var value = command === "createLink" ? "/start-a-petition/preview" : null;
        if (draftBody && draftBody.isContentEditable) {
          document.execCommand(command, false, value);
        }
      });
    });
    var editorMore = draftEditor.querySelector("[data-editor-more]");
    if (editorMore) {
      editorMore.addEventListener("click", function () {
        var expanded = editorMore.getAttribute("aria-expanded") === "true";
        editorMore.setAttribute("aria-expanded", expanded ? "false" : "true");
        editorMore.textContent = expanded ? "•••" : "•••";
      });
    }
    var generatedImageButton = draftEditor.querySelector("[data-generate-image]");
    if (generatedImageButton) {
      generatedImageButton.addEventListener("click", function () {
        generatedImageButton.textContent = "Image ready";
      });
    }
    var draftBack = draftEditor.querySelector("[data-draft-back]");
    if (draftBack) {
      draftBack.addEventListener("click", function () {
        var path = draftEditor.getAttribute("data-recommended") === "true"
          ? "/start-a-petition/personal-story"
          : "/start-a-petition/intro";
        window.location.assign(pathWithCurrentQuery(path));
      });
    }
    var draftContinue = draftEditor.querySelector("[data-draft-continue]");
    function saveAndPreview() {
        var title = draftTitle ? draftTitle.value.trim() : "";
        var body = draftBody ? draftBody.value.trim() : "";
        if (!title) {
          draftTitle.setAttribute("aria-invalid", "true");
          draftTitle.focus();
          return;
        }
        if (!body) {
          draftBody.setAttribute("aria-invalid", "true");
          draftBody.focus();
          return;
        }
        window.sessionStorage.setItem("change:start-flow:title", title);
        window.sessionStorage.setItem("change:start-flow:body", body);
        window.location.assign(pathWithCurrentQuery("/start-a-petition/optional-preview"));
    }
    if (draftContinue) {
      draftContinue.addEventListener("click", function () {
        saveAndPreview();
      });
    }
    var previewDraft = draftEditor.querySelector("[data-preview-draft]");
    if (previewDraft) {
      previewDraft.addEventListener("click", saveAndPreview);
    }
  }

  var draftPreview = document.querySelector("[data-draft-preview]");
  if (draftPreview) {
    var previewTitle = draftPreview.querySelector("[data-preview-title]");
    var previewBody = draftPreview.querySelector("[data-preview-body]");
    if (previewTitle) {
      previewTitle.textContent = window.sessionStorage.getItem("change:start-flow:title")
        || draftTitleFromIssue(draftIssue());
    }
    if (previewBody) {
      var paragraphs = (
        window.sessionStorage.getItem("change:start-flow:body")
        || deterministicDraftBody(draftIssue())
      ).split(/\n{2,}/);
      paragraphs.forEach(function (paragraph) {
        var element = document.createElement("p");
        element.textContent = paragraph;
        previewBody.appendChild(element);
      });
    }
    draftPreview.querySelector("[data-preview-back]").addEventListener("click", function () {
      window.location.assign(pathWithCurrentQuery("/start-a-petition/edit"));
    });
    draftPreview.querySelector("[data-preview-continue]").addEventListener("click", function () {
      window.location.assign(pathWithCurrentQuery("/start-a-petition/location"));
    });
  }

  var petitionScope = document.querySelector("[data-petition-scope]");
  if (petitionScope) {
    var selectedScope = window.sessionStorage.getItem("change:start-flow:scope") || "";
    var localField = petitionScope.querySelector("[data-local-field]");
    var locationInput = petitionScope.querySelector("#petition-location");
    var scopeTip = petitionScope.querySelector("[data-scope-tip]");
    function syncScope() {
      petitionScope.querySelectorAll("[data-scope]").forEach(function (button) {
        var selected = button.getAttribute("data-scope") === selectedScope;
        button.classList.toggle("selected", selected);
        button.setAttribute("aria-pressed", selected ? "true" : "false");
      });
      if (localField) localField.hidden = selectedScope !== "local";
      if (scopeTip) scopeTip.hidden = selectedScope !== "local";
    }
    petitionScope.querySelectorAll("[data-scope]").forEach(function (button) {
      button.addEventListener("click", function () {
        selectedScope = button.getAttribute("data-scope");
        window.sessionStorage.setItem("change:start-flow:scope", selectedScope);
        syncScope();
      });
    });
    petitionScope.querySelector("[data-scope-back]").addEventListener("click", function () {
      window.location.assign(pathWithCurrentQuery("/start-a-petition/create"));
    });
    petitionScope.querySelector("form").addEventListener("submit", function (event) {
      event.preventDefault();
      if (!selectedScope) return;
      if (selectedScope === "local" && !locationInput.value.trim()) {
        var error = petitionScope.querySelector(".scope-error");
        error.hidden = false;
        locationInput.setAttribute("aria-invalid", "true");
        var scopeMain = document.querySelector("main");
        if (scopeMain) {
          scopeMain.setAttribute("tabindex", "-1");
          scopeMain.focus({ preventScroll: true });
        }
        return;
      }
      window.sessionStorage.setItem(
        "change:start-flow:location",
        selectedScope === "local" ? locationInput.value.trim() : ""
      );
      window.location.assign(pathWithCurrentQuery("/start-a-petition/prepublish"));
    });
    syncScope();
  }

  var prepublish = document.querySelector("[data-prepublish]");
  if (prepublish) {
    var prepublishForm = prepublish.querySelector("[data-prepublish-form]");
    prepublish.querySelector("[data-prepublish-back]").addEventListener("click", function () {
      window.location.assign(pathWithCurrentQuery("/start-a-petition/location"));
    });
    prepublishForm.addEventListener("submit", function () {
      var scope = window.sessionStorage.getItem("change:start-flow:scope") || "national";
      var location = window.sessionStorage.getItem("change:start-flow:location") || "";
      prepublishForm.querySelector("[data-publish-topic]").value = draftIssue();
      prepublishForm.querySelector("[data-publish-title]").value =
        window.sessionStorage.getItem("change:start-flow:title")
        || draftTitleFromIssue(draftIssue());
      prepublishForm.querySelector("[data-publish-target]").value =
        scope === "global" ? "Global community leaders"
          : scope === "local" ? "Local community leaders"
            : "National community leaders";
      prepublishForm.querySelector("[data-publish-location]").value = location;
      prepublishForm.querySelector("[data-publish-body]").value =
        window.sessionStorage.getItem("change:start-flow:body")
        || deterministicDraftBody(draftIssue());
    });
  }

  var overlay = document.getElementById("fixture-overlay");
  var trigger = document.querySelector(".overlay-trigger");
  var closeButton = overlay ? overlay.querySelector(".overlay-close") : null;

  function openOverlay() {
    if (!overlay) return;
    overlay.hidden = false;
    if (closeButton) closeButton.focus();
  }

  function closeOverlay() {
    if (!overlay) return;
    overlay.hidden = true;
    if (trigger) trigger.focus();
  }

  if (trigger) trigger.addEventListener("click", openOverlay);
  if (closeButton) closeButton.addEventListener("click", closeOverlay);
  if (overlay) {
    overlay.addEventListener("click", function (event) {
      if (event.target === overlay) closeOverlay();
    });
  }

  var progressiveLogin = document.querySelector("[data-progressive-login]");
  if (progressiveLogin) {
    var passwordStage = progressiveLogin.querySelector("[data-password-stage]");
    var loginContinue = document.querySelector("[data-login-continue]");
    progressiveLogin.addEventListener("submit", function (event) {
      if (passwordStage && passwordStage.hidden) {
        event.preventDefault();
        passwordStage.hidden = false;
        if (loginContinue) {
          var loginContinueLabel = loginContinue.querySelector("span");
          if (loginContinueLabel) {
            loginContinueLabel.textContent = "Log in";
          } else {
            loginContinue.textContent = "Log in";
          }
        }
        var password = passwordStage.querySelector("input");
        if (password) {
          password.disabled = false;
          password.focus();
        }
      }
    });
  }
  document.addEventListener("keydown", function (event) {
    if (event.key === "Escape" && overlay && !overlay.hidden) {
      closeOverlay();
    }
  });

  function requestJson(path, options) {
    return fetch(path, options || {}).then(function (response) {
      return response.json().then(function (payload) {
        if (!response.ok || !payload.ok) {
          throw new Error(payload.message || "Request failed");
        }
        return payload;
      });
    });
  }

  var notificationCount = document.querySelector("[data-notification-count]");
  function refreshNotificationCount() {
    if (!notificationCount) return;
    requestJson("/api/notifications/unread-count").then(function (payload) {
      notificationCount.textContent = String(payload.unread_count);
      notificationCount.hidden = payload.unread_count === 0;
    }).catch(function () {
      // The visible notification page remains the fallback.
    });
  }
  if (notificationCount) {
    refreshNotificationCount();
    window.setInterval(refreshNotificationCount, 15000);
  }

  var engagement = document.querySelector(".petition-engagement");
  if (engagement) {
    var slug = engagement.getAttribute("data-petition");
    var csrf = engagement.getAttribute("data-csrf");
    var followButton = engagement.querySelector(".follow-toggle");
    var shareButton = engagement.querySelector(".share-trigger");
    var shareResult = engagement.querySelector(".share-result");
    var following = false;
    requestJson("/api/follows?object_type=petition&limit=100").then(function (payload) {
      following = payload.items.some(function (item) { return item.object_id === slug; });
      followButton.setAttribute("aria-pressed", following ? "true" : "false");
      followButton.textContent = following ? "Following" : "Follow petition";
    }).catch(function () {});
    followButton.addEventListener("click", function () {
      var options = {
        method: following ? "DELETE" : "POST",
        headers: { "Content-Type": "application/json", "X-CSRF-Token": csrf }
      };
      if (!following) {
        options.body = JSON.stringify({
          type: "petition", id: slug, idempotency_key: "follow:" + slug
        });
      }
      requestJson(
        following ? "/api/follows/petition/" + encodeURIComponent(slug) : "/api/follows",
        options
      ).then(function () {
        following = !following;
        followButton.setAttribute("aria-pressed", following ? "true" : "false");
        followButton.textContent = following ? "Following" : "Follow petition";
      }).catch(function (error) {
        followButton.textContent = error.message;
      });
    });
    var shareDialog = document.querySelector("[data-share-dialog]");
    var shareDialogClose = shareDialog ? shareDialog.querySelector(".share-dialog-close") : null;
    var shareDialogStatus = shareDialog ? shareDialog.querySelector("[data-share-dialog-status]") : null;
    var qrPanel = shareDialog ? shareDialog.querySelector("[data-qr-panel]") : null;

    shareButton.addEventListener("click", function () {
      if (shareDialog && typeof shareDialog.showModal === "function") {
        shareDialog.showModal();
        if (shareDialogClose) shareDialogClose.focus();
      }
    });
    if (shareDialogClose) {
      shareDialogClose.addEventListener("click", function () {
        shareDialog.close();
        shareButton.focus();
      });
    }
    if (shareDialog) {
      shareDialog.addEventListener("click", function (event) {
        if (event.target === shareDialog) shareDialog.close();
        var option = event.target.closest("[data-share-channel]");
        if (!option) return;
        var channel = option.getAttribute("data-share-channel");
        if (channel === "qr") {
          if (qrPanel) qrPanel.hidden = !qrPanel.hidden;
          if (shareDialogStatus) shareDialogStatus.textContent = "";
          return;
        }
        requestJson("/api/petitions/" + encodeURIComponent(slug) + "/shares", {
          method: "POST",
          headers: { "Content-Type": "application/json", "X-CSRF-Token": csrf },
          body: JSON.stringify({
            channel: channel,
            idempotency_key: "share:" + slug + ":" + channel
          })
        }).then(function (payload) {
          shareResult.hidden = false;
          shareResult.textContent = "Share link ready.";
          if (channel === "copy" && navigator.clipboard) {
            return navigator.clipboard.writeText(payload.share_url).then(function () {
              if (shareDialogStatus) shareDialogStatus.textContent = "Link copied.";
            });
          }
          if (shareDialogStatus) {
            shareDialogStatus.textContent =
              channel.charAt(0).toUpperCase() + channel.slice(1) + " share link created.";
          }
        }).catch(function (error) {
          if (shareDialogStatus) shareDialogStatus.textContent = error.message;
        });
      });
    }
    document.querySelectorAll("[data-share-open]").forEach(function (option) {
      option.addEventListener("click", function () {
        if (!shareDialog || typeof shareDialog.showModal !== "function") return;
        var wanted = option.getAttribute("data-share-open");
        var target = shareDialog.querySelector(
          '[data-share-channel="' + wanted + '"]'
        );
        shareDialog.showModal();
        if (target) target.click();
        if (target) target.focus();
        else if (shareDialogClose) shareDialogClose.focus();
      });
    });
  }

  var notificationCenter = document.querySelector("[data-notification-center]");
  if (notificationCenter) {
    var notificationCsrf = notificationCenter.getAttribute("data-csrf");
    function postRead(path) {
      return requestJson(path, {
        method: "POST", headers: { "X-CSRF-Token": notificationCsrf }
      });
    }
    notificationCenter.addEventListener("click", function (event) {
      var readButton = event.target.closest(".mark-read");
      var readAll = event.target.closest(".read-all");
      if (readButton) {
        var card = readButton.closest("[data-notification-id]");
        postRead("/api/notifications/" + encodeURIComponent(card.dataset.notificationId) + "/read")
          .then(function () {
            card.classList.remove("unread");
            readButton.remove();
            refreshNotificationCount();
          });
      } else if (readAll) {
        postRead("/api/notifications/read-all").then(function () {
          notificationCenter.querySelectorAll(".notification-card.unread").forEach(function (card) {
            card.classList.remove("unread");
            var button = card.querySelector(".mark-read");
            if (button) button.remove();
          });
          readAll.disabled = true;
          refreshNotificationCount();
        });
      }
    });
    if (window.EventSource) {
      var stream = new EventSource("/api/notifications/stream");
      stream.addEventListener("notification", refreshNotificationCount);
    }
  }

  var settings = document.querySelector(".notification-settings");
  if (settings) {
    settings.addEventListener("submit", function (event) {
      event.preventDefault();
      var status = settings.querySelector(".settings-status");
      var payload = {
        csrf: settings.dataset.csrf,
        row_version: Number(settings.dataset.version),
        email_mode: settings.elements.email_mode.value
      };
      ["in_app_enabled", "double_opt_in", "petition_updates", "organization_updates",
       "topic_recommendations", "growth_tips"].forEach(function (name) {
        payload[name] = settings.elements[name].checked;
      });
      requestJson("/api/notification-preferences", {
        method: "PUT",
        headers: { "Content-Type": "application/json", "X-CSRF-Token": settings.dataset.csrf },
        body: JSON.stringify(payload)
      }).then(function (result) {
        settings.dataset.version = String(result.row_version);
        status.textContent = "Settings saved.";
      }).catch(function (error) {
        status.textContent = error.message;
      });
    });
  }

  var mobileMenuButton = document.querySelector("[data-mobile-menu-toggle]");
  var mobileMenu = document.querySelector("[data-mobile-menu]");
  function closeMobileMenu() {
    if (!mobileMenuButton || !mobileMenu) return;
    mobileMenu.hidden = true;
    mobileMenuButton.setAttribute("aria-expanded", "false");
    document.body.removeAttribute("data-menu-open");
  }
  if (mobileMenuButton && mobileMenu) {
    mobileMenuButton.addEventListener("click", function () {
      var opening = mobileMenu.hidden;
      mobileMenu.hidden = !opening;
      mobileMenuButton.setAttribute("aria-expanded", opening ? "true" : "false");
      if (opening) {
        document.body.setAttribute("data-menu-open", "true");
      } else {
        document.body.removeAttribute("data-menu-open");
      }
      if (opening) {
        var first = mobileMenu.querySelector("a,button");
        if (first) first.focus();
      }
    });
    document.addEventListener("click", function (event) {
      if (
        !mobileMenu.hidden
        && !mobileMenu.contains(event.target)
        && !mobileMenuButton.contains(event.target)
      ) {
        closeMobileMenu();
        mobileMenuButton.focus();
      }
    });
  }

  var accountMenu = document.querySelector("[data-account-menu]");
  var accountMenuToggle = document.querySelector("[data-account-menu-toggle]");
  function closeAccountMenu(restoreFocus) {
    if (!accountMenu || !accountMenuToggle) return;
    accountMenu.open = false;
    accountMenuToggle.setAttribute("aria-expanded", "false");
    if (restoreFocus) accountMenuToggle.focus();
  }
  if (accountMenu && accountMenuToggle) {
    accountMenu.addEventListener("toggle", function () {
      accountMenuToggle.setAttribute(
        "aria-expanded",
        accountMenu.open ? "true" : "false"
      );
      if (accountMenu.open) {
        var firstAccountAction = accountMenu.querySelector(
          "nav a, nav button, nav input, nav select"
        );
        if (firstAccountAction) firstAccountAction.focus();
      }
    });
    document.addEventListener("click", function (event) {
      if (accountMenu.open && !accountMenu.contains(event.target)) {
        closeAccountMenu(true);
      }
    });
  }

  var languageOpen = document.querySelector("[data-language-open]");
  var languageDialog = document.querySelector("[data-language-dialog]");
  if (languageOpen && languageDialog) {
    languageOpen.addEventListener("click", function () {
      if (typeof languageDialog.showModal === "function") languageDialog.showModal();
    });
    languageDialog.addEventListener("close", function () {
      languageOpen.focus();
    });
  }

  var storyDots = document.querySelectorAll("[data-story-dot]");
  var homeStories = document.querySelectorAll(".home-story");
  storyDots.forEach(function (dot) {
    dot.addEventListener("click", function () {
      var index = Number(dot.getAttribute("data-story-dot"));
      storyDots.forEach(function (candidate) { candidate.classList.remove("active"); });
      dot.classList.add("active");
      homeStories.forEach(function (story, storyIndex) {
        story.classList.toggle("is-hidden", storyIndex !== index);
      });
    });
  });
  window.addEventListener("resize", function () {
    if (window.innerWidth > 760 && homeStories.length) {
      homeStories.forEach(function (story) { story.classList.remove("is-hidden"); });
    }
  });

  var impactStoryControls = document.querySelector("[data-home-story-controls]");
  var impactStoryScroller = document.querySelector("[data-home-story-scroller]");
  if (
    impactStoryControls
    && impactStoryScroller
    && window.innerWidth <= 760
  ) {
    var impactStories = Array.from(
      impactStoryScroller.querySelectorAll("[data-home-story]")
    );
    var impactStoryTitle = impactStoryControls.querySelector(
      "[data-home-story-title]"
    );
    var impactStoryPrevious = impactStoryControls.querySelector(
      "[data-home-story-previous]"
    );
    var impactStoryNext = impactStoryControls.querySelector(
      "[data-home-story-next]"
    );
    var selectedImpactStory = Number(
      impactStoryScroller.getAttribute("data-home-story-initial") || "0"
    );
    var impactScrollTimer = 0;

    function renderImpactStory(index, behavior) {
      if (!impactStories.length) return;
      selectedImpactStory = (
        (index % impactStories.length) + impactStories.length
      ) % impactStories.length;
      impactStories.forEach(function (story, storyIndex) {
        var selected = storyIndex === selectedImpactStory;
        story.classList.toggle("is-selected", selected);
        if (selected) {
          story.setAttribute("aria-current", "true");
        } else {
          story.removeAttribute("aria-current");
        }
      });
      var story = impactStories[selectedImpactStory];
      impactStoryTitle.textContent = story.getAttribute("data-story-title") || "";
      if (window.innerWidth < 768) {
        var left = story.offsetLeft -
          ((impactStoryScroller.clientWidth - story.offsetWidth) / 2);
        impactStoryScroller.scrollTo({
          left: Math.max(0, left),
          behavior: behavior || "auto"
        });
      }
    }

    impactStoryPrevious.addEventListener("click", function () {
      renderImpactStory(selectedImpactStory - 1, "smooth");
    });
    impactStoryNext.addEventListener("click", function () {
      renderImpactStory(selectedImpactStory + 1, "smooth");
    });
    impactStoryScroller.addEventListener("scroll", function () {
      window.clearTimeout(impactScrollTimer);
      impactScrollTimer = window.setTimeout(function () {
        if (window.innerWidth >= 768) return;
        var centre = impactStoryScroller.scrollLeft +
          (impactStoryScroller.clientWidth / 2);
        var nearestIndex = 0;
        var nearestDistance = Infinity;
        impactStories.forEach(function (story, storyIndex) {
          var storyCentre = story.offsetLeft + (story.offsetWidth / 2);
          var distance = Math.abs(storyCentre - centre);
          if (distance < nearestDistance) {
            nearestDistance = distance;
            nearestIndex = storyIndex;
          }
        });
        if (nearestIndex !== selectedImpactStory) {
          renderImpactStory(nearestIndex, "auto");
        }
      }, 90);
    }, { passive: true });
    window.addEventListener("resize", function () {
      renderImpactStory(selectedImpactStory, "auto");
    });
    renderImpactStory(selectedImpactStory, "auto");
  }

  var verifiedSignatures = document.querySelector(".verified-signatures");
  if (verifiedSignatures) {
    var verifiedCopy = document.querySelector(".verified-copy");
    verifiedSignatures.addEventListener("click", function () {
      var expanded = verifiedSignatures.getAttribute("aria-expanded") === "true";
      verifiedSignatures.setAttribute("aria-expanded", expanded ? "false" : "true");
      if (verifiedCopy) {
        verifiedCopy.textContent = expanded
          ? "Change.org helps verify signatures are from real people."
          : "Signatures are checked for duplicate and suspicious activity.";
      }
    });
  }

  var filterDetails = document.querySelector(".search-filter-panel");
  if (filterDetails) {
    var lastFilterTrigger = null;
    var filterSummary = filterDetails.querySelector("summary");
    if (filterSummary) {
      filterSummary.addEventListener("click", function () {
        lastFilterTrigger = filterSummary;
      });
    }
    filterDetails.addEventListener("toggle", function () {
      document.documentElement.classList.toggle("filter-drawer-open", filterDetails.open);
    });

    document.querySelectorAll("[data-open-filters]").forEach(function (trigger) {
      trigger.addEventListener("click", function () {
        lastFilterTrigger = trigger;
        filterDetails.open = true;
        var focusTarget = trigger.getAttribute("data-filter-focus");
        if (focusTarget) {
          window.setTimeout(function () {
            var control = filterDetails.querySelector(focusTarget);
            if (control) control.focus();
          }, 0);
        }
      });
    });

    document.addEventListener("keydown", function (event) {
      if (event.key === "Escape" && filterDetails.open) {
        filterDetails.open = false;
        if (lastFilterTrigger) lastFilterTrigger.focus();
      }
    });
  }

  var clearSearch = document.querySelector("[data-clear-search]");
  if (clearSearch) {
    clearSearch.addEventListener("click", function () {
      window.location.assign("/search");
    });
  }

  document.querySelectorAll("[data-filter-auto-submit]").forEach(function (control) {
    control.addEventListener("change", function () {
      if (control.form) control.form.submit();
    });
  });

  var paymentForm = document.querySelector("[data-payment-form]");
  if (paymentForm) {
    var customAmount = paymentForm.elements.custom_amount;
    var amountRadios = paymentForm.querySelectorAll('input[name="amount"]');
    if (customAmount) {
      customAmount.addEventListener("input", function () {
        if (customAmount.value.trim()) {
          amountRadios.forEach(function (radio) { radio.checked = false; });
        }
      });
    }
    amountRadios.forEach(function (radio) {
      radio.addEventListener("change", function () {
        if (customAmount) customAmount.value = "";
      });
    });
  }

  var sortSelect = document.querySelector("[data-sort-select]");
  if (sortSelect) {
    sortSelect.addEventListener("change", function () {
      sortSelect.form.submit();
    });
  }

  var searchLanding = document.querySelector("[data-search-landing]");
  if (searchLanding) {
    var landingInput = searchLanding.querySelector("[data-search-landing-input]");
    var landingSubmit = searchLanding.querySelector("[data-search-landing-submit]");
    var syncLandingSubmit = function () {
      if (landingInput && landingSubmit) {
        landingSubmit.disabled = !landingInput.value.trim();
      }
    };
    if (landingInput) {
      landingInput.addEventListener("input", syncLandingSubmit);
      syncLandingSubmit();
    }
    searchLanding.querySelectorAll("[data-search-explore]").forEach(function (button) {
      button.addEventListener("click", function () {
        window.location.assign(button.getAttribute("data-search-explore"));
      });
    });
    window.setTimeout(function () {
      searchLanding.classList.add("topics-loaded");
    }, 2500);
  }

  var updateBody = document.querySelector("[data-update-body]");
  var updateSubmit = document.querySelector("[data-update-submit]");
  var updatePreview = document.querySelector("[data-update-preview]");
  if (updateBody && updateSubmit) {
    // Server-rendered enabled so the form still posts without scripting;
    // with scripting the empty editor matches the source's disabled state.
    var syncUpdateSubmit = function () {
      var empty = !updateBody.value.trim();
      updateSubmit.disabled = empty;
      if (updatePreview) updatePreview.disabled = empty;
    };
    updateBody.addEventListener("input", syncUpdateSubmit);
    syncUpdateSubmit();
  }

  var videoPlaceholder = document.querySelector("[data-video-placeholder]");
  if (videoPlaceholder) {
    videoPlaceholder.addEventListener("click", function () {
      videoPlaceholder.textContent = "Video unavailable offline";
      videoPlaceholder.classList.add("video-unavailable");
    });
  }

  if (progressiveLogin && loginContinue) {
    var loginEmail = progressiveLogin.querySelector("#login-email");
    if (loginEmail) {
      var syncLoginContinue = function () {
        var value = loginEmail.value.trim();
        loginContinue.disabled = !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
      };
      loginEmail.addEventListener("input", function () {
        syncLoginContinue();
      });
      loginEmail.addEventListener("keydown", function (event) {
        if (
          event.key === "Enter" &&
          passwordStage &&
          passwordStage.hidden &&
          !loginContinue.disabled
        ) {
          event.preventDefault();
          progressiveLogin.requestSubmit(loginContinue);
        }
      });
      syncLoginContinue();
    }
  }

  document.addEventListener("keydown", function (event) {
    if (event.key !== "Escape") return;
    if (mobileMenu && !mobileMenu.hidden) {
      closeMobileMenu();
      mobileMenuButton.focus();
    }
    if (accountMenu && accountMenu.open) closeAccountMenu(true);
    if (languageDialog && languageDialog.open) languageDialog.close();
    if (filterDetails && filterDetails.open) {
      filterDetails.open = false;
      if (lastFilterTrigger) lastFilterTrigger.focus();
    }
  });
})();