{{ define "repo/pulls/fragments/pullStepReview" }}
    {{ $root   := . }}
    {{ $params := .StepReviewParams }}
    <section class="flex flex-col gap-3">
        {{ if not $params }}
            <div class="p-4 border border-gray-200 dark:border-gray-700 rounded bg-gray-50 dark:bg-gray-800/30 text-sm text-gray-600 dark:text-gray-400">
                {{ if eq $root.Source "patch" }}
                    Paste a patch above to see a comparison.
                {{ else }}
                    Pick a source and target above to see a comparison.
                {{ end }}
            </div>
        {{ else if eq .Source "patch" }}
            <!-- TODO: implement patch based PR -->
        {{ else }}
            {{ if $params.Commits }}
                {{ $commits := $params.Commits }}
                <div class="flex flex-col gap-2">
                    <div class="flex items-center justify-between gap-3 min-w-0 text-sm text-gray-500 dark:text-gray-400">
                        <span class="flex-shrink-0">{{ len $commits }} commit{{ if ne (len $commits) 1 }}s{{ end }}</span>
                        {{ if and $root.SourceBranch $root.TargetBranch }}
                            <span class="inline-flex items-center gap-2 font-mono text-gray-600 dark:text-gray-300 truncate">
                                <span>{{ $root.TargetBranch }}</span>
                                {{ i "arrow-left-right" "w-4 h-4 flex-shrink-0" }}
                                <span>{{ $root.SourceBranch }}</span>
                            </span>
                        {{ end }}
                    </div>
                    {{ template "pullReviewCommits" (list $root.SourceRepo $params.Commits) }}
                </div>

                <!-- query diff on load -->
                <div class="w-full relative min-w-0">
                    <div
                        id="diff-area"
                        hx-get="/{{ $root.SourceRepo }}/pulls/_/composediff?baseRepo={{ $root.RepoInfo.RepoDid }}&base={{ $root.TargetBranch }}&headRepo={{ $root.SourceRepo }}&head={{ $root.SourceBranch }}&view=unified"
                        hx-target="this"
                        hx-swap="outerHTML"
                        hx-trigger="load"
                    >
                        Loading...
                    </div>
                </div>
            {{ else }}
                <div class="p-4 border border-gray-200 dark:border-gray-700 rounded bg-gray-50 dark:bg-gray-800/30 text-sm text-gray-600 dark:text-gray-400">
                    {{ if and .SourceBranch .TargetBranch (eq .SourceBranch .TargetBranch) }}
                        Source and target are the same branch, nothing to merge.
                    {{ else }}
                        No commits between target and source. Make sure your source branch has commits not on the target.
                    {{ end }}
                </div>
            {{ end }}
        {{ end }}
    </section>
{{ end }}

{{ define "pullReviewCommits" }}
    {{ $sourceRepo := index . 0 }}
    {{ $commits    := index . 1 }}
    <ul class="flex flex-col gap-2">
        {{ range $commits }}
            {{- $messageParts := splitN .Message "\n\n" 2 -}}
            {{- $title := index $messageParts 0 -}}
            <li class="border border-gray-200 dark:border-gray-700 rounded bg-white dark:bg-gray-800 px-3 py-2 flex items-center gap-3">
                <span class="text-gray-700 dark:text-gray-300 flex-shrink-0">
                    {{ i "git-commit-vertical" "size-4" }}
                </span>
                <span class="flex-1 min-w-0 truncate text-sm dark:text-gray-200">{{ $title }}</span>
                <span class="flex items-center gap-2 text-xs text-gray-500 dark:text-gray-400 flex-shrink-0">
                    {{ if not .Author.When.IsZero }}
                        {{ template "repo/fragments/shortTimeAgo" .Author.When }}
                    {{ end }}
                    <span class="font-mono bg-gray-100 dark:bg-gray-900 text-gray-700 dark:text-gray-300 px-2 py-0.5 rounded">{{ slice .Hash.String 0 8 }}</span>
                </span>
                <span class="-my-2 self-stretch w-px bg-gray-200 dark:bg-gray-700"></span>
                <span class="flex items-center gap-1 text-gray-700 dark:text-gray-300 flex-shrink-0">
                    <button type="button"
                        class="p-1 hover:bg-gray-100 dark:hover:bg-gray-700 rounded text-gray-700 dark:text-gray-300"
                        title="Copy SHA"
                        onclick='event.preventDefault(); event.stopPropagation(); navigator.clipboard.writeText(`{{ .Hash.String }}`); this.innerHTML=`{{ i "copy-check" "size-4" }}`; setTimeout(() => this.innerHTML=`{{ i "copy" "size-4" }}`, 1500)'>
                        {{ i "copy" "size-4" }}
                    </button>
                    <a href="/{{ $sourceRepo }}/tree/{{ .Hash.String }}"
                       onclick="event.stopPropagation()"
                       class="p-1 hover:bg-gray-100 dark:hover:bg-gray-700 rounded text-gray-700 dark:text-gray-300"
                       title="Browse repository at this commit">
                        {{ i "folder-code" "size-4" }}
                    </a>
                </span>
            </li>
        {{ end }}
    </ul>
{{ end }}

{{ define "pullComposeFlatDiff" }}
    {{ $diff := index . 0 }}
    {{ $opts := index . 1 }}
    {{ $files := $diff.ChangedFiles }}
    {{ $isSplit := $opts.Split }}
    {{ $count := len $files }}
    {{ $stat := $diff.Stats }}

    <style>
        #composeFilesToggle:checked ~ * label[for="composeFilesToggle"] .show-text { display: none; }
        #composeFilesToggle:checked ~ * label[for="composeFilesToggle"] .hide-text { display: inline; }
        #composeFilesToggle:not(:checked) ~ * label[for="composeFilesToggle"] .hide-text { display: none; }
        #composeFilesToggle:checked ~ * div#composeFiles { width: fit-content; max-width: 15vw; }
        #composeFilesToggle:not(:checked) ~ * div#composeFiles { width: 0; display: none; margin-right: 0; }
    </style>

    <input type="checkbox" id="composeFilesToggle" class="hidden"/>

    <div id="diff-area">
        <div class="bg-slate-100 dark:bg-gray-700/50 flex items-center gap-2 h-12 p-2 rounded-t-md border border-b-0 border-gray-200 dark:border-gray-700">
            <label title="Toggle filetree panel" for="composeFilesToggle" class="hidden md:inline-flex items-center justify-center rounded cursor-pointer text-normal font-normal normal-case">
                <span class="show-text">{{ i "panel-left-open" "size-4" }}</span>
                <span class="hide-text">{{ i "panel-left-close" "size-4" }}</span>
            </label>

            {{ template "repo/fragments/diffStatPill" $stat }}
            <span class="text-xs text-gray-600 dark:text-gray-300 hidden md:inline-flex">{{ $count }} changed file{{ if ne $count 1 }}s{{ end }}</span>

            <div class="flex-grow"></div>

            <label title="Expand/Collapse diffs" for="composeCollapseToggle" class="btn font-normal normal-case">
                <input type="checkbox" id="composeCollapseToggle" class="peer/collapse hidden"/>
                <span class="peer-checked/collapse:hidden inline-flex items-center gap-2">
                    {{ i "unfold-vertical" "w-4 h-4" }}
                    <span class="hidden md:inline">Expand all</span>
                </span>
                <span class="peer-checked/collapse:inline-flex hidden flex items-center gap-2">
                    {{ i "fold-vertical" "w-4 h-4" }}
                    <span class="hidden md:inline">Collapse all</span>
                </span>
            </label>

            {{ template "repo/fragments/diffOpts" $opts }}
        </div>

        <div class="flex border border-gray-200 dark:border-gray-700 rounded-b-md">
            <div id="composeFiles" class="hidden md:block overflow-hidden max-h-[60vh] overflow-y-auto border-r border-gray-200 dark:border-gray-700">
                <section class="overflow-x-auto text-sm px-3 py-2 w-full mx-auto">
                    {{ template "repo/fragments/fileTree" $diff.FileTree }}
                </section>
            </div>

            <div class="flex-1 min-w-0 p-2">
                <div class="flex flex-col gap-2">
                    {{ if eq $count 0 }}
                        <div class="text-center text-gray-500 dark:text-gray-400 py-8">
                            <p>No differences found.</p>
                        </div>
                    {{ else if le $count 5 }}
                        {{ range $idx, $file := $files }}
                            {{ template "diffFile" (list $idx $file $isSplit true) }}
                        {{ end }}
                    {{ else }}
                        {{ range $idx, $file := slice $files 0 5 }}
                            {{ template "diffFile" (list $idx $file $isSplit true) }}
                        {{ end }}
                        {{ $remaining := sub $count 5 }}
                        <details class="group/showmore">
                            <summary class="cursor-pointer text-sm text-gray-700 dark:text-gray-300 py-2 px-1 flex items-center gap-2 select-none hover:text-gray-900 dark:hover:text-gray-100 list-none">
                                <span class="group-open/showmore:hidden inline-flex items-center gap-2">
                                    {{ i "chevron-right" "w-4 h-4" }}
                                    Show {{ $remaining }} more file{{ if ne $remaining 1 }}s{{ end }}
                                </span>
                                <span class="hidden group-open/showmore:inline-flex items-center gap-2">
                                    {{ i "chevron-down" "w-4 h-4" }}
                                    Hide {{ $remaining }} file{{ if ne $remaining 1 }}s{{ end }}
                                </span>
                            </summary>
                            <div class="flex flex-col gap-2 mt-2">
                                {{ range $idx, $file := slice $files 5 }}
                                    {{ template "diffFile" (list (add $idx 5) $file $isSplit true) }}
                                {{ end }}
                            </div>
                        </details>
                    {{ end }}
                </div>
            </div>
        </div>
    </div>

    <script>
        (() => {
            const checkbox = document.getElementById('composeCollapseToggle');
            const diffArea = document.getElementById('diff-area');
            if (!checkbox || !diffArea) return;
            const all = () => diffArea.querySelectorAll('details[id^="file-"]');
            checkbox.addEventListener('change', () => {
                all().forEach(d => { d.open = checkbox.checked; });
            });
            diffArea.addEventListener('toggle', (e) => {
                if (!e.target.matches('details[id^="file-"]')) return;
                const dets = Array.from(all());
                const allOpen = dets.every(d => d.open);
                const allClosed = dets.every(d => !d.open);
                if (allOpen) checkbox.checked = true;
                else if (allClosed) checkbox.checked = false;
            }, true);
        })();
    </script>
{{ end }}
