{% extends "base.html" %}
{% block content %}

<script src="https://cdn.plot.ly/plotly-3.0.1.min.js" charset="utf-8"></script>
<script src="https://unpkg.com/@panzoom/panzoom@4.6.0/dist/panzoom.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/alpinejs@3.13.5/dist/cdn.min.js" defer></script>

<script>
  function alignTable(rows) {
    const colWidths = [];

    // Calculate max width for each column
    rows.forEach(row => {
      row.forEach((cell, i) => {
        colWidths[i] = Math.max(colWidths[i] || 0, cell.length);
      });
    });

    // Pad each cell and join with space
    return rows.map(row =>
      row.map((cell, i) => cell.padEnd(colWidths[i], ' ')).join('  ')
    ).join('\n');
  }
</script>

<style>
  [x-cloak] {
    display: none !important;
  }

  .calibration-layout {
    display: grid;
    gap: 1rem;
    align-items: start;
    grid-template-columns: minmax(0, 1fr);
    grid-template-areas:
      "session"
      "heading"
      "plot";
  }

  .calibration-session {
    grid-area: session;
  }

  .calibration-heading {
    grid-area: heading;
  }

  .calibration-plot {
    grid-area: plot;
  }

  .detail-card {
    --detail-card-surface: rgb(255 255 255 / 0.7);
    border: 1px solid rgb(229 231 235);
    border-radius: 0.75rem;
    background: var(--detail-card-surface);
    padding: 1rem;
    box-shadow: 0 1px 2px rgb(15 23 42 / 0.08);
  }

  .dark .detail-card {
    --detail-card-surface: rgb(31 41 55 / 0.8);
    border-color: rgb(55 65 81);
    background: var(--detail-card-surface);
  }

  .detail-card-title {
    margin-bottom: 1rem;
    font-size: 0.875rem;
    font-weight: 600;
    letter-spacing: 0.18em;
    text-transform: uppercase;
    color: rgb(75 85 99);
  }

  .dark .detail-card-title {
    color: rgb(209 213 219);
  }

  .detail-table {
    width: 100%;
    border-collapse: collapse;
    text-align: left;
  }

  .detail-table tr {
    border-bottom: 1px solid rgb(229 231 235);
  }

  .detail-table tr:last-child {
    border-bottom: none;
  }

  .dark .detail-table tr {
    border-color: rgb(55 65 81);
  }

  .detail-table th,
  .detail-table td {
    padding: 0.75rem 1rem 0.75rem 0;
    vertical-align: top;
  }

  .detail-table th:last-child,
  .detail-table td:last-child {
    padding-right: 0;
  }

  .detail-table th {
    font-weight: 600;
    color: rgb(55 65 81);
  }

  .dark .detail-table th {
    color: rgb(229 231 235);
  }

  .detail-table td {
    color: rgb(37 99 235);
  }

  .dark .detail-table td {
    color: rgb(96 165 250);
  }

  .detail-table a {
    color: inherit;
  }

  .detail-table a:hover {
    text-decoration: underline;
  }

  .detail-sticky-col {
    position: sticky;
    left: 0;
    z-index: 10;
    box-shadow: none;
  }

  .detail-card-scroll {
    height: 18rem;
    overflow: hidden;
  }

  .detail-card-scroll-inner {
    height: 100%;
    overflow: auto;
    padding-right: 0.25rem;
  }

  .detail-card-scroll .detail-table thead {
    position: sticky;
    top: 0;
    z-index: 5;
  }

  .details-two-up,
  .details-three-up {
    display: flex;
    flex-direction: column;
    gap: 1rem;
    align-items: stretch;
  }

  @media (min-width: 1280px) {
    .details-two-up,
    .details-three-up {
      flex-direction: row;
    }

    .details-two-up > *,
    .details-three-up > * {
      flex: 1 1 0;
      min-width: 0;
    }
  }

  .phd2-plot-shell {
    min-height: 34rem;
  }

  .phd2-plot-shell [data-role="plot"] {
    min-height: 440px;
  }

  @media (min-width: 1024px) {
    .calibration-layout {
      grid-template-columns: minmax(260px, 320px) minmax(0, 1fr);
      grid-template-areas:
        "session plot"
        "heading plot";
    }

    .calibration-heading {
      max-height: 28rem;
    }
  }
</style>

<div class="relative flex flex-col items-center justify-center bg-repeat md:bg-cover dark:text-white"
  style="background-image: url('{{ url_for('blog.upload', filename=background_image) }}');">

  <div class="absolute w-full h-full backdrop-blur-md"></div>

  <div class="relative w-0 top-0 h-4 border-1 border-gray-200 dark:border-gray-400">
  </div>

  {% for il in images %}
  <div id="uid-{{il.image.id}}" class="relative flex flex-col items-center justify-center w-full space-y-0 p-2">
    <!-- Title under the date -->
    <h2 class="text-xl text-white text-center">
      {{ il.image.title }}
      {% if il.image.short_description %} - {{ il.image.short_description }}{% endif %}
    </h2>

    <!-- Date -->
    <span class="text-gray-200 font-light text-md">
      {{ il.image.created_at.strftime('%b %Y')|default('No date available') }}
    </span>
  </div>

  <div class="relative w-full md:max-w-4/5 lg:max-w-7/12 px-1 mx-auto">
    <!-- Main Card Container -->
    <div x-data="{ mainTab: 'image', explorePane: 'hr', showObjects: false }"
      x-init="
        const storageKey = `image-tabs:${window.location.pathname}:{{ il.image.id }}`;
        const validMainTabs = ['image', 'details', 'explore'];
        const validExplorePanes = ['hr'{% if il.meta_json and 'variable' in il.meta_json %}, 'analyse'{% endif %}{% if il.guiding_plot %}, 'guiding'{% endif %}{% if il.calibration_plot %}, 'calibration'{% endif %}];
        const resizeExplorePane = value => {
          requestAnimationFrame(() => {
            requestAnimationFrame(() => {
              let plot = null;
              if (value === 'hr') {
                plot = document.getElementById('dist-scatter');
              } else if (value === 'analyse') {
                plot = document.getElementById('framesPlot');
              } else {
                const root = document.getElementById(`${value}-root-{{ il.image.id }}`);
                plot = root ? root.querySelector(`[data-role='plot']`) : null;
              }

              if (plot && window.Plotly) {
                Plotly.Plots.resize(plot);
              }
            });
          });
        };

        try {
          const savedTabs = JSON.parse(localStorage.getItem(storageKey) || '{}');

          if (validMainTabs.includes(savedTabs.mainTab)) {
            mainTab = savedTabs.mainTab;
          }

          if (validExplorePanes.includes(savedTabs.explorePane)) {
            explorePane = savedTabs.explorePane;
          }
        } catch (error) {
          console.warn('Failed to restore image tab state', error);
        }

        if (mainTab === 'explore') {
          resizeExplorePane(explorePane);
        }

        $watch('mainTab', value => {
          if (!validMainTabs.includes(value)) {
            return;
          }

          if (value === 'explore') {
            resizeExplorePane(explorePane);
          }

          localStorage.setItem(storageKey, JSON.stringify({ mainTab: value, explorePane }));
        });

        $watch('explorePane', value => {
          if (!validExplorePanes.includes(value)) {
            return;
          }

          resizeExplorePane(value);
          localStorage.setItem(storageKey, JSON.stringify({ mainTab, explorePane: value }));
        });
      "
      class="rounded-xl md:rounded-2xl shadow-xl bg-white/80 dark:bg-gray-800/80">

      <!-- Main Tabs -->
      <div x-cloak
        class="flex overflow-x-auto border-b border-gray-200 dark:border-gray-700 justify-center items-center whitespace-nowrap">
        {% set main_tabs = [
        ('image', 'Image'),
        ('details', 'Details'),
        ('explore', 'Explore')
        ] %}

        {% for tab_id, tab_label in main_tabs %}
        <button @click="mainTab = '{{ tab_id }}'"
          :class="mainTab === '{{ tab_id }}' ? 'border-b-2 border-blue-600 text-blue-600 dark:text-blue-400' : 'text-gray-600 dark:text-gray-300'"
          class="px-4 py-2 text-sm font-medium">
          {{ tab_label }}
        </button>
        {% endfor %}
      </div>

      <!-- Image Tab -->
      <div x-show="mainTab === 'image'" class="space-y-2 md:p-4">
        <div id="zoom-container-{{il.image.id}}"
          class="relative w-full max-w-full overflow-x-auto overflow-y-hidden md:rounded-[10px]  px-1 flex items-center justify-center group touch-none">

          <div class="relative transition-transform duration-100 ease-in-out origin-center w-full h-full"
            id="zoom-wrapper-{{il.image.id}}">
            <img
              class="object-contain block w-full h-auto origin-center transition-transform duration-100 ease-in-out cursor-grab select-none"
              id="zoomable-image-{{il.image.id}}"
              src="{{ url_for('blog.upload', filename=il.image.image_path|replace('\\', '/')) }}"
              alt="{{ il.image.title }}">
            <div id="svg-overlay-{{il.image.id}}"
              class="absolute top-0 left-0 w-full h-full pointer-events-none z-10  duration-300">
            </div>
            <div id="compare-{{il.image.id}}" class="absolute top-0 left-0 pointer-events-none z-20 w-full h-full">
              {% set moon_width = (1800 / il.image.pixel_scale) | int %}

              <svg id="comp-wrapper-{{ il.image.id }}"
                class="absolute top-0 left-0 hidden pointer-events-auto w-full h-full z-5000"
                viewBox="0 0 {{ moon_width }} {{ moon_width }}">
                <image href="{{ url_for('static', filename='assets/images/moon.png') }}"
                  class="w-[{{ moon_width }}px] h-[{{ moon_width }}px]" id="comp-img-{{ il.image.id }}"
                  alt="Moon overlay" />
              </svg>
            </div>
            <div id="graticule-{{il.image.id}}" class="absolute top-0 left-0 w-full h-full pointer-events-none z-3000 ">
            </div>
          </div>

          <div class="pointer-events-none absolute inset-x-0 bottom-0 z-20 flex items-end justify-between p-1">
            <a href="{{ url_for('profile.public', username=il.image.author) }}"
              class="pointer-events-auto flex max-w-[70%] items-center gap-3 rounded-full bg-black/20 px-3 py-1 text-white shadow-lg backdrop-blur-sm transition hover:bg-gray-600/60">
              {% if il.image.user_image %}
              <img
                src="{{ url_for('blog.upload', filename=il.image.user_image) }}"
                class="h-8 w-8 rounded-full object-cover border border-white/40"
                alt="author image">
              {% else %}
              <img
                src="{{ url_for('static', filename='default_profile.png') }}"
                class="h-8 w-8 rounded-full object-cover border border-white/40"
                alt="default profile">
              {% endif %}
              <span class="flex min-w-0 flex-col leading-tight">
                <span class="truncate font-medium text-white">@{{ il.image.author }}</span>
                <span class="truncate text-xs text-gray-200">{{ il.image.location }}</span>
              </span>
            </a>

            <div class="pointer-events-auto flex items-center gap-2">
              <button id="reset-btn-{{il.image.id}}" title="Resize"
                class="p-1 border-2 opacity-15 border-gray-600 dark:border-white rounded-md bg-gray-200/15 hover:opacity-100 transition"
                aria-label="Resize image" type="button">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="14" height="14" fill="none" stroke="grey"
                  stroke-width="6">
                  <line x1="36" y1="28" x2="60" y2="4" />
                  <polyline points="38 4 60 4 60 26" />

                  <line x1="28" y1="36" x2="4" y2="60" />
                  <polyline points="4 38 4 60 26 60 " />
                </svg>
              </button>

              <button id="fullscreen-btn-{{il.image.id}}" title="Full Screen"
                class="p-1 border-2 opacity-15 border-gray-600 dark:border-white rounded-md bg-gray-200/15 hover:opacity-100 transition"
                aria-label="Full Screen" type="button">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="14" height="14" fill="none" stroke="grey"
                  stroke-width="6" stroke-linecap="round" stroke-linejoin="round">
                  <polyline points="24 4 4 4 4 24" />
                  <line x1="4" y1="4" x2="22" y2="22" />

                  <polyline points="40 4 60 4 60 24" />
                  <line x1="60" y1="4" x2="42" y2="22" />

                  <polyline points="4 40 4 60 24 60" />
                  <line x1="4" y1="60" x2="22" y2="42" />

                  <polyline points="40 60 60 60 60 40" />
                  <line x1="60" y1="60" x2="42" y2="42" />
                </svg>
              </button>
            </div>
          </div>
        </div>

        <div id="fullscreen-modal-{{il.image.id}}"
          class="fixed inset-0 hidden items-center justify-center bg-black/85 p-3 md:p-6"
          style="z-index: 90;">
          <div id="fullscreen-backdrop-{{il.image.id}}" class="absolute inset-0"></div>

          <div class="relative flex h-full w-full items-center justify-center">
            <div id="fullscreen-zoom-container-{{il.image.id}}"
              class="relative flex h-full w-full items-center justify-center overflow-hidden rounded-xl bg-black/40 touch-none">

              <div class="relative inline-block shrink-0 transition-transform duration-100 ease-in-out origin-center"
                id="fullscreen-zoom-wrapper-{{il.image.id}}">
                <img
                  class="object-contain block w-auto h-auto origin-center transition-transform duration-100 ease-in-out cursor-grab select-none"
                  style="max-width: 100%; max-height: calc(100vh - 10rem);"
                  id="fullscreen-zoomable-image-{{il.image.id}}"
                  src="{{ url_for('blog.upload', filename=il.image.image_path|replace('\\', '/')) }}"
                  alt="{{ il.image.title }} fullscreen">
                <div id="fullscreen-svg-overlay-{{il.image.id}}"
                  class="absolute top-0 left-0 w-full h-full pointer-events-none z-10 duration-300">
                </div>
                <div id="fullscreen-compare-{{il.image.id}}" class="absolute top-0 left-0 pointer-events-none z-20 w-full h-full">
                  <svg id="fullscreen-comp-wrapper-{{ il.image.id }}"
                    class="absolute top-0 left-0 hidden pointer-events-auto w-full h-full"
                    viewBox="0 0 {{ moon_width }} {{ moon_width }}">
                    <image href="{{ url_for('static', filename='assets/images/moon.png') }}"
                      class="w-[{{ moon_width }}px] h-[{{ moon_width }}px]" id="fullscreen-comp-img-{{ il.image.id }}"
                      alt="Moon overlay fullscreen" />
                  </svg>
                </div>
                <div id="fullscreen-graticule-{{il.image.id}}"
                  class="absolute top-0 left-0 w-full h-full pointer-events-none">
                </div>
              </div>

              <button id="fullscreen-close-btn-{{il.image.id}}" title="Close fullscreen viewer"
                class="absolute top-3 right-3 p-2 border-2 border-gray-600 dark:border-white rounded-md z-20 bg-gray-200/20 text-white hover:bg-gray-200/35 transition"
                aria-label="Close fullscreen viewer" type="button">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16" height="16" fill="none"
                  stroke="currentColor" stroke-width="2.5" stroke-linecap="round">
                  <line x1="5" y1="5" x2="19" y2="19" />
                  <line x1="19" y1="5" x2="5" y2="19" />
                </svg>
              </button>

              <button id="fullscreen-reset-btn-{{il.image.id}}" title="Resize"
                class="absolute bottom-4 right-4 p-2 border-2 opacity-15 border-gray-600 dark:border-white rounded-md z-20 bg-gray-200/20 hover:bg-gray-200/35 hover:opacity-100 transition"
                aria-label="Resize image" type="button">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="16" height="16" fill="none" stroke="grey"
                  stroke-width="6">
                  <line x1="36" y1="28" x2="60" y2="4" />
                  <polyline points="38 4 60 4 60 26" />

                  <line x1="28" y1="36" x2="4" y2="60" />
                  <polyline points="4 38 4 60 26 60 " />
                </svg>
              </button>

              <div class="pointer-events-none absolute inset-x-0 bottom-4 z-20 flex justify-center px-4">
                <div class="pointer-events-auto flex items-center space-x-2 rounded-full bg-black/55 px-3 py-2 backdrop-blur-sm">
                  <div>
                    <input id="fullscreen-graticule-toggle-{{il.image.id}}" type="checkbox" class="peer hidden" />
                    <label for="fullscreen-graticule-toggle-{{il.image.id}}" title="Overlay Coordinate Grid" class="inline-block px-3 py-1.5 rounded-full cursor-pointer shadow-sm text-sm font-medium
                      bg-gray-300 text-gray-900 border-slate-300 
                      hover:bg-gray-400 hover:border-slate-500 
                      hover:dark:bg-slate-600 hover:dark:border-slate-400
                      peer-checked:bg-green-800 peer-checked:text-white
                      peer-checked:hover:bg-green-700
                      dark:bg-slate-800 dark:text-gray-100 dark:border-slate-600 
                      dark:peer-checked:bg-green-500 dark:peer-checked:text-black">
                      <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 fill-current" viewBox="0 0 100 100"
                        preserveAspectRatio="xMidYMid meet">
                        <g fill="none" stroke="currentColor" stroke-width="4">
                          <circle cx="50" cy="50" r="45" />
                          <ellipse cx="50" cy="50" rx="45" ry="15" />
                          <ellipse cx="50" cy="50" rx="45" ry="30" />
                          <path d="M5,50 a45,45 0 0,1 90,0" />
                          <path d="M95,50 a45,45 0 0,1 -90,0" />
                          <line x1="50" y1="5" x2="50" y2="95" />
                          <path d="M35,5 A50,100 0 0,0 35,95" />
                          <path d="M65,5 A50,100 0 0,1 65,95" />
                        </g>
                      </svg>
                    </label>
                  </div>

                  <div>
                    <input id="fullscreen-compare-toggle-{{il.image.id}}" type="checkbox" class="peer hidden" />
                    <label for="fullscreen-compare-toggle-{{il.image.id}}" title="Compare with apparent size of solar objects" class="inline-block px-3 py-1.5 rounded-full cursor-pointer text-sm font-medium
                      bg-gray-300 text-gray-900 border-slate-300
                      hover:bg-gray-400 hover:border-slate-500
                      hover:dark:bg-slate-600 hover:dark:border-slate-400
                      peer-checked:hover:bg-green-700 
                      peer-checked:bg-green-800 peer-checked:text-white
                      dark:bg-slate-800 dark:text-gray-100 dark:border-slate-600
                      dark:peer-checked:bg-green-500 dark:peer-checked:text-black
                      shadow">
                      <svg class="w-5 h-5 fill-current" viewBox="0 0 128 128" xmlns="http://www.w3.org/2000/svg"
                        aria-hidden="true" role="img">
                        <image href="{{ url_for('static', filename='assets/images/moon.png') }}" width="128" height="128"
                          class="object-contain" alt="Moon overlay fullscreen" />
                      </svg>
                    </label>
                  </div>

                  <div>
                    <input id="fullscreen-overlay-toggle-{{il.image.id}}" type="checkbox" class="peer hidden" />
                    <label for="fullscreen-overlay-toggle-{{il.image.id}}" title="Label celestial objects in the image" class="inline-block px-3 p-1.5 rounded-full cursor-pointer shadow-sm text-sm font-medium
                      bg-gray-300 text-gray-900 border-slate-300 
                      hover:bg-gray-400 hover:border-slate-500 hover:dark:bg-slate-600 hover:dark:border-slate-400
                      peer-checked:hover:bg-green-700 
                      peer-checked:bg-green-800 peer-checked:text-white
                      dark:bg-slate-800 dark:text-gray-100 dark:border-slate-600 
                      dark:peer-checked:bg-green-500 dark:peer-checked:text-black">
                      <svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" id="_x32_" class="w-5 h-5 fill-current"
                        version="1.1" viewBox="0 0 512 512">
                        <path
                          d="M480.931 191.431c-1.37-3.032-3.171-5.863-5.495-8.326a24.85 24.85 0 0 0-7.877-5.643L115.761 2.619l-.258-.101C111.459.781 107.158 0 102.903 0 96.322.01 89.87 1.838 83.74 4.881c-9.199 4.595-17.839 11.928-25.651 21.248-7.83 9.338-14.796 20.724-20.256 33.638-7.132 16.846-10.67 33.711-10.68 48.784.01 10.349 1.655 19.926 5.359 28.114 1.866 4.108 4.255 7.867 7.298 11.093 3.014 3.217 6.69 5.864 10.863 7.629l.266.11 201.799 71.539v57.846L130.3 470.789c-2.821 4.283-1.627 10.055 2.656 12.876 4.283 2.831 10.055 1.626 12.876-2.647l106.906-162.324V502.69a9.302 9.302 0 0 0 9.309 9.31c5.128 0 9.292-4.162 9.292-9.31V317.564l107.65 163.455c2.84 4.274 8.594 5.478 12.894 2.647 4.292-2.821 5.469-8.593 2.638-12.876L271.339 283.761v-50.126l149.881 53.14v-.019a25.038 25.038 0 0 0 9.191 1.756c5.045-.028 9.852-1.425 14.346-3.631 6.736-3.373 12.867-8.621 18.39-15.21 5.505-6.59 10.376-14.567 14.218-23.582 4.981-11.792 7.472-23.611 7.482-34.31-.01-7.361-1.168-14.254-3.916-20.348zM65.295 139.706c-1.875 0-3.658-.238-5.367-.753l-2.106-.736c-1.654-.735-3.097-1.746-4.484-3.217-2.123-2.242-4.072-5.643-5.441-10.146-1.351-4.503-2.151-10.054-2.151-16.304 0-12.132 2.96-26.8 9.218-41.532 6.36-15.045 15.073-27.581 24.006-36.036 4.43-4.218 8.915-7.408 13.05-9.448 4.136-2.058 7.858-2.95 10.882-2.95 1.939.01 3.612.359 5.22 1.002l2.049 1.029a19.243 19.243 0 0 1 4.283 3.364c2.758 2.876 5.037 6.866 6.599 11.855 1.572 4.964 2.408 10.864 2.399 17.389.008 11.791-2.748 25.495-8.566 39.189-6.139 14.484-14.641 26.524-23.638 34.768-4.485 4.127-9.089 7.288-13.519 9.402-4.429 2.104-8.638 3.124-12.434 3.124zm92.862 34.071-76.76-27.214c.285-.129.598-.258.9-.387 8.336-3.979 16.378-10.495 23.63-18.95 7.279-8.437 13.722-18.841 18.73-30.642 6.332-14.944 9.42-29.962 9.42-43.361 0-8.208-1.168-15.827-3.575-22.498l72.918 36.229c.653 1.433 1.268 2.922 1.793 4.55 1.58 4.953 2.407 10.89 2.407 17.397.01 11.783-2.748 25.495-8.565 39.207-6.14 14.466-14.65 26.506-23.639 34.75-4.484 4.127-9.089 7.288-13.519 9.402a37.1 37.1 0 0 1-3.74 1.517zm238.082 84.406L172.108 178.73c6.323-3.952 12.398-9.301 17.986-15.816 7.28-8.447 13.722-18.851 18.73-30.661 6.323-14.953 9.42-29.933 9.42-43.352 0-5.404-.515-10.541-1.535-15.348l212.892 105.812c1.369 1.738 2.518 3.944 3.373 6.682 1.066 3.382 1.654 7.454 1.654 11.975.019 8.189-1.911 17.784-5.992 27.406-4.301 10.156-10.284 18.584-16.506 24.309-3.124 2.868-6.296 5.037-9.292 6.452-2.352 1.121-4.576 1.755-6.599 1.994zm63.995-19.347c-4.164 9.862-9.898 18.078-15.624 23.446-2.84 2.72-5.652 4.696-8.134 5.946-2.5 1.232-4.567 1.672-6.066 1.672-.984 0-1.737-.166-2.454-.469l-.257-.119-16.25-5.753c4.724-2.922 9.209-6.884 13.345-11.672 5.284-6.158 9.98-13.721 13.611-22.306 4.596-10.854 6.856-21.744 6.856-31.56 0-4.052-.432-7.876-1.213-11.488l15.486 7.692.257.12c.744.303 1.398.763 2.123 1.535 1.057 1.084 2.17 2.968 2.997 5.68.845 2.721 1.342 6.213 1.342 10.22.001 7.775-1.911 17.369-6.019 27.056z"
                          class="st0" />
                        <path
                          d="M97.811 48.26c1.727-.909 3.225-1.286 4.494-1.286.459 0 .91.046 1.342.148a5.32 5.32 0 0 0 6.359-3.989 5.317 5.317 0 0 0-4.016-6.36 15.962 15.962 0 0 0-3.685-.413c-3.336 0-6.553.947-9.485 2.509-4.402 2.372-8.327 6.048-11.902 10.68-3.538 4.594-6.7 10.183-9.346 16.506-1.14 2.702.137 5.799 2.849 6.956a5.298 5.298 0 0 0 6.939-2.858c3.134-7.454 7.022-13.529 10.9-17.517 1.911-2.005 3.832-3.466 5.551-4.376z"
                          class="st0" />
                      </svg>
                    </label>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="flex px-1 justify-between items-center text-sm md:text-gp-1.5 text-gray-600 dark:text-gray-300">

          <div class="flex items-start space-x-2">
            <div>
              <input id="graticule-toggle-{{il.image.id}}" type="checkbox" class="peer hidden" />

              <label for="graticule-toggle-{{il.image.id}}" title="Overlay Coordinate Grid" class="inline-block px-3 py-1.5 rounded-full cursor-pointer shadow-sm text-sm font-medium
         bg-gray-300 text-gray-900 border-slate-300 
         hover:bg-gray-400 hover:border-slate-500 
         hover:dark:bg-slate-600 hover:dark:border-slate-400
         peer-checked:bg-green-800 peer-checked:text-white
         peer-checked:hover:bg-green-700
         dark:bg-slate-800 dark:text-gray-100 dark:border-slate-600 
         dark:peer-checked:bg-green-500 dark:peer-checked:text-black">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 fill-current" viewBox="0 0 100 100"
                  preserveAspectRatio="xMidYMid meet">
                  <g fill="none" stroke="currentColor" stroke-width="4">
                    <!-- Outer circle -->
                    <circle cx="50" cy="50" r="45" />

                    <!-- Latitude lines (declination) -->
                    <ellipse cx="50" cy="50" rx="45" ry="15" />
                    <ellipse cx="50" cy="50" rx="45" ry="30" />

                    <!-- Longitude lines (RA) -->
                    <path d="M5,50 a45,45 0 0,1 90,0" />
                    <path d="M95,50 a45,45 0 0,1 -90,0" />

                    <!-- Meridians -->
                    <line x1="50" y1="5" x2="50" y2="95" />
                    <path d="M35,5 A50,100 0 0,0 35,95" />
                    <path d="M65,5 A50,100 0 0,1 65,95" /> <!-- Flipped this one -->
                  </g>
                </svg>

              </label>
            </div>

            <div>
              <input id="compare-toggle-{{il.image.id}}" type="checkbox" class="peer hidden" />

              <label for="compare-toggle-{{il.image.id}}" title="compare with apparent size of solar objects" class="inline-block px-3 py-1.5 rounded-full cursor-pointer text-sm font-medium
           bg-gray-300 text-gray-900 border-slate-300
           hover:bg-gray-400 hover:border-slate-500
           hover:dark:bg-slate-600 hover:dark:border-slate-400
            peer-checked:hover:bg-green-700 
           peer-checked:bg-green-800 peer-checked:text-white
           dark:bg-slate-800 dark:text-gray-100 dark:border-slate-600
           dark:peer-checked:bg-green-500 dark:peer-checked:text-black
           shadow">

                <svg class="w-5 h-5 fill-current" viewBox="0 0 128 128" xmlns="http://www.w3.org/2000/svg"
                  aria-hidden="true" role="img">
                  <image href="{{ url_for('static', filename='assets/images/moon.png') }}" width="128" height="128"
                    class="object-contain" alt="Moon overlay" />
                </svg>
              </label>
            </div>

            <div>
              <input id="overlay-toggle-{{il.image.id}}" type="checkbox" class="peer hidden" />

              <label for="overlay-toggle-{{il.image.id}}" title="Label celestial objects in the image" class="inline-block px-3 p-1.5 rounded-full cursor-pointer  shadow-sm text-sm font-medium
         bg-gray-300 text-gray-900 border-slate-300 
         hover:bg-gray-400 hover:border-slate-500 hover:dark:bg-slate-600 hover:dark:border-slate-400
         peer-checked:hover:bg-green-700 
         peer-checked:bg-green-800 peer-checked:text-white
         dark:bg-slate-800 dark:text-gray-100 dark:border-slate-600 
         dark:peer-checked:bg-green-500 dark:peer-checked:text-black">
                <svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" id="_x32_" class="w-5 h-5 fill-current"
                  version="1.1" viewBox="0 0 512 512">
                  <path
                    d="M480.931 191.431c-1.37-3.032-3.171-5.863-5.495-8.326a24.85 24.85 0 0 0-7.877-5.643L115.761 2.619l-.258-.101C111.459.781 107.158 0 102.903 0 96.322.01 89.87 1.838 83.74 4.881c-9.199 4.595-17.839 11.928-25.651 21.248-7.83 9.338-14.796 20.724-20.256 33.638-7.132 16.846-10.67 33.711-10.68 48.784.01 10.349 1.655 19.926 5.359 28.114 1.866 4.108 4.255 7.867 7.298 11.093 3.014 3.217 6.69 5.864 10.863 7.629l.266.11 201.799 71.539v57.846L130.3 470.789c-2.821 4.283-1.627 10.055 2.656 12.876 4.283 2.831 10.055 1.626 12.876-2.647l106.906-162.324V502.69a9.302 9.302 0 0 0 9.309 9.31c5.128 0 9.292-4.162 9.292-9.31V317.564l107.65 163.455c2.84 4.274 8.594 5.478 12.894 2.647 4.292-2.821 5.469-8.593 2.638-12.876L271.339 283.761v-50.126l149.881 53.14v-.019a25.038 25.038 0 0 0 9.191 1.756c5.045-.028 9.852-1.425 14.346-3.631 6.736-3.373 12.867-8.621 18.39-15.21 5.505-6.59 10.376-14.567 14.218-23.582 4.981-11.792 7.472-23.611 7.482-34.31-.01-7.361-1.168-14.254-3.916-20.348zM65.295 139.706c-1.875 0-3.658-.238-5.367-.753l-2.106-.736c-1.654-.735-3.097-1.746-4.484-3.217-2.123-2.242-4.072-5.643-5.441-10.146-1.351-4.503-2.151-10.054-2.151-16.304 0-12.132 2.96-26.8 9.218-41.532 6.36-15.045 15.073-27.581 24.006-36.036 4.43-4.218 8.915-7.408 13.05-9.448 4.136-2.058 7.858-2.95 10.882-2.95 1.939.01 3.612.359 5.22 1.002l2.049 1.029a19.243 19.243 0 0 1 4.283 3.364c2.758 2.876 5.037 6.866 6.599 11.855 1.572 4.964 2.408 10.864 2.399 17.389.008 11.791-2.748 25.495-8.566 39.189-6.139 14.484-14.641 26.524-23.638 34.768-4.485 4.127-9.089 7.288-13.519 9.402-4.429 2.104-8.638 3.124-12.434 3.124zm92.862 34.071-76.76-27.214c.285-.129.598-.258.9-.387 8.336-3.979 16.378-10.495 23.63-18.95 7.279-8.437 13.722-18.841 18.73-30.642 6.332-14.944 9.42-29.962 9.42-43.361 0-8.208-1.168-15.827-3.575-22.498l72.918 36.229c.653 1.433 1.268 2.922 1.793 4.55 1.58 4.953 2.407 10.89 2.407 17.397.01 11.783-2.748 25.495-8.565 39.207-6.14 14.466-14.65 26.506-23.639 34.75-4.484 4.127-9.089 7.288-13.519 9.402a37.1 37.1 0 0 1-3.74 1.517zm238.082 84.406L172.108 178.73c6.323-3.952 12.398-9.301 17.986-15.816 7.28-8.447 13.722-18.851 18.73-30.661 6.323-14.953 9.42-29.933 9.42-43.352 0-5.404-.515-10.541-1.535-15.348l212.892 105.812c1.369 1.738 2.518 3.944 3.373 6.682 1.066 3.382 1.654 7.454 1.654 11.975.019 8.189-1.911 17.784-5.992 27.406-4.301 10.156-10.284 18.584-16.506 24.309-3.124 2.868-6.296 5.037-9.292 6.452-2.352 1.121-4.576 1.755-6.599 1.994zm63.995-19.347c-4.164 9.862-9.898 18.078-15.624 23.446-2.84 2.72-5.652 4.696-8.134 5.946-2.5 1.232-4.567 1.672-6.066 1.672-.984 0-1.737-.166-2.454-.469l-.257-.119-16.25-5.753c4.724-2.922 9.209-6.884 13.345-11.672 5.284-6.158 9.98-13.721 13.611-22.306 4.596-10.854 6.856-21.744 6.856-31.56 0-4.052-.432-7.876-1.213-11.488l15.486 7.692.257.12c.744.303 1.398.763 2.123 1.535 1.057 1.084 2.17 2.968 2.997 5.68.845 2.721 1.342 6.213 1.342 10.22.001 7.775-1.911 17.369-6.019 27.056z"
                    class="st0" />
                  <path
                    d="M97.811 48.26c1.727-.909 3.225-1.286 4.494-1.286.459 0 .91.046 1.342.148a5.32 5.32 0 0 0 6.359-3.989 5.317 5.317 0 0 0-4.016-6.36 15.962 15.962 0 0 0-3.685-.413c-3.336 0-6.553.947-9.485 2.509-4.402 2.372-8.327 6.048-11.902 10.68-3.538 4.594-6.7 10.183-9.346 16.506-1.14 2.702.137 5.799 2.849 6.956a5.298 5.298 0 0 0 6.939-2.858c3.134-7.454 7.022-13.529 10.9-17.517 1.911-2.005 3.832-3.466 5.551-4.376z"
                    class="st0" />
                </svg>
              </label>
            </div>

          </div>

            <div x-data="{ open: false }" class="relative inline-block">
              <button @click="open = !open" title="Share this image" class="flex items-center p-1 rounded-full bg-gray-300 text-gray-900   shadow
           hover:bg-gray-400
           hover:dark:bg-slate-600
           dark:bg-slate-800 dark:text-gray-100 overflow-hidden">

                <!-- Left: Share Icon -->
                <div class="flex items-center justify-center w-10 h-full px-2">
                  <svg xmlns="http://www.w3.org/2000/svg" class="w-5 h-5 fill-current" viewBox="0 0 22 22">
                    <path
                      d="M12.5 6.25a.75.75 0 0 0 0-1.5v1.5Zm7.75 6.25a.75.75 0 0 0-1.5 0h1.5Zm-.75-6.25a.75.75 0 0 0 0-1.5v1.5Zm-4.088-1.5a.75.75 0 0 0 0 1.5v-1.5Zm4.838.75a.75.75 0 0 0-1.5 0h1.5Zm-1.5 4.141a.75.75 0 0 0 1.5 0h-1.5Zm1.28-3.61a.75.75 0 0 0-1.06-1.061l1.06 1.06Zm-8.06 5.939a.75.75 0 1 0 1.06 1.06l-1.06-1.06Zm.53-7.22h-3v1.5h3v-1.5Zm-3 0A4.75 4.75 0 0 0 4.75 9.5h1.5A3.25 3.25 0 0 1 9.5 6.25v-1.5ZM4.75 9.5v6h1.5v-6h-1.5Zm0 6a4.75 4.75 0 0 0 4.75 4.75v-1.5a3.25 3.25 0 0 1-3.25-3.25h-1.5Zm4.75 4.75h6v-1.5h-6v1.5Zm6 0a4.75 4.75 0 0 0 4.75-4.75h-1.5a3.25 3.25 0 0 1-3.25 3.25v1.5Zm4.75-4.75v-3h-1.5v3h1.5ZM19.5 4.75h-4.088v1.5H19.5v-1.5Zm-.75.75v4.141h1.5V5.5h-1.5Zm.22-.53-7 7 1.06 1.06 7-7-1.06-1.06Z" />
                  </svg>
                </div>

                <!-- Divider -->
                <div class="h-6 w-px bg-gray-400 dark:bg-gray-500"></div>

                <!-- Right: Dropdown arrow -->
                <div class="flex items-center justify-center w-8 h-full">
                  <svg xmlns="http://www.w3.org/2000/svg" class="w-5 h-5 fill-current" viewBox="0 0 20 20">
                    <path d="M5.5 7l4.5 5 4.5-5h-9z" />
                  </svg>
                </div>
              </button>

              <!-- Dropdown menu -->
              <div x-show="open" @click.outside="open = false"
                class="absolute right-0 z-300 mt-2 w-48 rounded-md shadow-lg bg-white ring-1 ring-black ring-opacity-5 dark:bg-gray-800 overflow-visible"
                style="display: none;">
                <div class="py-1 text-sm text-gray-700 dark:text-gray-100 overflow-visible">
                  <button id="copy-link-{{il.image.id}}"
                    class="w-full px-4 py-2 text-left hover:bg-gray-100 dark:hover:bg-gray-700 ">Share
                    link</button>
                  <button id="copy-link-details-{{il.image.id}}"
                    class="w-full px-4 py-2 text-left hover:bg-gray-100 dark:hover:bg-gray-700">Share link with
                    details </button>
                </div>
              </div>
            </div>
        </div>

        <div class=" p-2 text-gray-700 dark:text-gray-200">

          <p>{{ il.image.description | safe }}</p>
        </div>
      </div>

      <div x-show="mainTab === 'details'" x-cloak class="p-6 dark:text-white">
        {% set rows = {
          'Lights': 'light_count',
          'Single Exposure': 'exposure_time',
          'Total Exposure': 'total_time',
          'Gain': 'gain',
          'Offset': 'offset_cam',
          'Temp (°C)': 'temperature'
        } %}
        {% set weighted_source = il.lights[0] if il.lights else {} %}
        {% set has_weighted_exposure = il.lights and (
          'effective_total' in weighted_source or
          'effective_red' in weighted_source or
          'effective_green' in weighted_source or
          'effective_blue' in weighted_source
        ) %}
        {% set weighted_rows = [
          ('Red Channel', weighted_source.get('effective_red')),
          ('Green Channel', weighted_source.get('effective_green')),
          ('Blue Channel', weighted_source.get('effective_blue')),
          ('Total', weighted_source.get('effective_total'))
        ] %}

        {% set acquisition_software = il.software_list | selectattr('type', 'equalto', 'acquisition') | list %}
        {% set processing_software = il.software_list | selectattr('type', 'equalto', 'processing') | list %}

        <div class="space-y-4">
          <div class="details-two-up">
            <section class="detail-card">
              <h3 class="detail-card-title">Lights</h3>
              <div class="overflow-x-auto">
                <table html-id="light-{{il.image.id}}" class="detail-table min-w-max">
                  <tbody>
                    <tr>
                      <th class="detail-sticky-col min-w-[11rem]">Filter</th>
                      {% for light in il.lights %}
                      <td class="min-w-[9rem]">
                        <a href="{{ light.filter_link }}" target="_blank">
                          {{ light.cam_filter|replace("Filter", "") }}
                        </a>
                      </td>
                      {% endfor %}
                    </tr>

                    {% for label, field in rows.items() if field in il.lights[0] %}
                    <tr>
                      <th class="detail-sticky-col min-w-[11rem]">{{ label }}</th>
                      {% for light in il.lights %}
                      <td class="min-w-[9rem]">{{ light[field] }}</td>
                      {% endfor %}
                    </tr>
                    {% endfor %}
                  </tbody>
                </table>
              </div>
            </section>

            <section class="detail-card">
              <h3 class="detail-card-title">Equipment</h3>
              <table html-id="equipment-{{il.image.id}}" class="detail-table">
                <tbody>
                  {% for equipment in il.equipment_list %}
                  <tr>
                    <th>{{ equipment.table|replace('_', ' ')|title }}</th>
                    <td>
                      <a href="{{ equipment.link }}" target="_blank">
                        {{ equipment.brand | default('') + " " + equipment.name|replace(equipment.brand | default(''), '') }}
                      </a>
                    </td>
                  </tr>
                  {% else %}
                  <tr>
                    <td colspan="2" class="text-gray-500 dark:text-gray-400">No equipment recorded.</td>
                  </tr>
                  {% endfor %}
                </tbody>
              </table>
            </section>
          </div>

          <div class="details-three-up">
            {% if has_weighted_exposure %}
            <section class="detail-card detail-card-scroll">
              <h3 class="detail-card-title">Weighted Exposure</h3>
              <div class="detail-card-scroll-inner">
                <table html-id="weighted-{{il.image.id}}" class="detail-table">
                  <tbody>
                    {% for label, value in weighted_rows %}
                    <tr>
                      <th>{{ label }}</th>
                      <td>{{ value or 'N/A' }}</td>
                    </tr>
                    {% endfor %}
                  </tbody>
                </table>
              </div>
            </section>
            {% endif %}

            {% if il.dates %}
            <section class="detail-card detail-card-scroll">
              <h3 class="detail-card-title">Nights</h3>
              <div class="detail-card-scroll-inner">
                <table html-id="night-summary-{{il.image.id}}" class="detail-table">
                  <thead>
                    <tr>
                      <th>Capture Dates</th>
                      <th>Moon Illumination</th>
                    </tr>
                  </thead>
                  <tbody>
                    {% for date in il.dates %}
                    <tr>
                      <th>{{ date.capture_date }}</th>
                      <td>{{ date.moon_phase }} ({{ date.moon_illumination }}%)</td>
                    </tr>
                    {% endfor %}
                  </tbody>
                </table>
              </div>
            </section>
            {% endif %}

            <section class="detail-card detail-card-scroll">
              <h3 class="detail-card-title">Software</h3>
              <div class="detail-card-scroll-inner">
                <table html-id="software-{{il.image.id}}" class="detail-table">
                  <tbody>
                    <tr>
                      <th>Acquisition</th>
                      <td>
                        {% if acquisition_software %}
                        <div class="space-y-2">
                          {% for software in acquisition_software %}
                          <p><a href="{{ software.link }}" target="_blank">{{ software.name }}</a></p>
                          {% endfor %}
                        </div>
                        {% else %}
                        <span class="text-gray-500 dark:text-gray-400">No acquisition software recorded.</span>
                        {% endif %}
                      </td>
                    </tr>
                    <tr>
                      <th>Processing</th>
                      <td>
                        {% if processing_software %}
                        <div class="space-y-2">
                          {% for software in processing_software %}
                          {% if software.metadata %}
                          <p>{{ software.metadata | safe }}</p>
                          {% else %}
                          <p><a href="{{ software.link }}" target="_blank">{{ software.name }}</a></p>
                          {% endif %}
                          {% endfor %}
                        </div>
                        {% else %}
                        <span class="text-gray-500 dark:text-gray-400">No processing software recorded.</span>
                        {% endif %}
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </section>
          </div>
        </div>
      </div>

      <div x-show="mainTab === 'explore'" x-cloak class="space-y-4 md:p-4 dark:text-white">
        {% set explore_tabs = [('hr', 'Hertzsprung Russel Diagram')] %}
        {% if il.meta_json and 'variable' in il.meta_json %}
        {% set explore_tabs = explore_tabs + [('analyse', 'Analyse')] %}
        {% endif %}
        {% if il.guiding_plot %}
        {% set explore_tabs = explore_tabs + [('guiding', 'Guiding')] %}
        {% endif %}
        {% if il.calibration_plot %}
        {% set explore_tabs = explore_tabs + [('calibration', 'Calibration')] %}
        {% endif %}

        {% if explore_tabs|length > 1 %}
        <div class="flex justify-center">
          <fieldset class="inline-flex flex-wrap justify-center rounded-full bg-gray-100 p-1 shadow-sm dark:bg-gray-900/70" aria-label="Explore view mode">
            {% for pane_id, pane_label in explore_tabs %}
            <label class="cursor-pointer">
              <input type="radio" class="sr-only peer" name="explore-pane-{{il.image.id}}" value="{{ pane_id }}" x-model="explorePane">
              <span class="inline-flex items-center rounded-full border border-transparent px-4 py-2 text-sm font-semibold text-gray-500 transition peer-checked:border-blue-200 peer-checked:bg-blue-600 peer-checked:text-white peer-checked:shadow-sm dark:text-gray-300 dark:peer-checked:border-blue-400/50 dark:peer-checked:bg-blue-500 dark:peer-checked:text-gray-950">{{ pane_label }}</span>
            </label>
            {% endfor %}
          </fieldset>
        </div>
        {% endif %}

        <div x-show="explorePane === 'hr'" class="space-y-2 items-center justify-center dark:text-white display-inline">
          <div id="dist-scatter"
            class="w-full rounded-xl bg-white/70 dark:bg-white/70 mx-auto aspect-[3/4] sm:aspect-[4/5] md:aspect-[5/4] lg:aspect-[4/3] max-w-[95vw] sm:max-w-[600px] md:max-w-[800px] lg:max-w-[1000px]">
          </div>
        </div>

        {% if il.meta_json and 'variable' in il.meta_json %}
        <div x-show="explorePane === 'analyse'" class="detail-card space-y-4">
          <div class="flex flex-wrap gap-4 items-center text-black dark:text-white">
            <label for="xAxisSelect">X axis:</label>
            <select id="xAxisSelect"
                    class="input_container bg-white dark:bg-gray-700 text-black dark:text-white"></select>

            <div class="flex flex-col gap-1">
              <label>Y axis 1:</label>
              <select id="yAxisType1"
                      class="input_container bg-white dark:bg-gray-700 text-black dark:text-white" value="line">
                <option value="line" selected>Line</option>
                <option value="scatter">Scatter</option>
                <option value="bar">Bar</option>
              </select>
            </div>
            <select id="yAxisSelect1" class="input_container bg-white dark:bg-gray-700 text-black dark:text-white" multiple size="4"></select>

            <div class="flex flex-col gap-1">
              <label>Y axis 2:</label>
              <select id="yAxisType2"
                      class="input_container bg-white dark:bg-gray-700 text-black dark:text-white">
                <option value="scatter">Scatter</option>
                <option value="line">Line</option>
                <option value="bar">Bar</option>
              </select>
            </div>
            <select id="yAxisSelect2"
                    class="input_container bg-white dark:bg-gray-700 text-black dark:text-white" multiple size="4"></select>

            <div class="flex flex-col gap-1">
              <label>Y axis 3:</label>
              <select id="yAxisType3"
                      class="input_container bg-white dark:bg-gray-700 text-black dark:text-white">
                <option value="scatter">Scatter</option>
                <option value="line">Line</option>
                <option value="bar">Bar</option>
              </select>
            </div>
            <select id="yAxisSelect3"
                    class="input_container bg-white dark:bg-gray-700 text-black dark:text-white" multiple size="4"></select>

            <button id="updatePlotBtn"
                    class="px-4 py-2 bg-blue-500 text-white rounded">
              Update Plot
            </button>
          </div>

          <div id="framesPlot" class="w-full min-h-[500px]"></div>
        </div>
        {% endif %}

        {% if il.guiding_plot %}
        <div id="guiding-root-{{il.image.id}}" x-show="explorePane === 'guiding'" class="phd2-plot-shell detail-card">
          <div class="flex flex-col xl:flex-row gap-4">
            <div class="xl:w-80 space-y-3">
              <select data-role="session" aria-label="Guiding session" class="input_container bg-white dark:bg-gray-700 text-black dark:text-white w-full"></select>
              <div data-role="stats" class="rounded-lg border border-gray-200 dark:border-gray-700 p-3"></div>
              <div data-role="heading" class="rounded-lg border border-gray-200 dark:border-gray-700 p-3 max-h-64 overflow-auto"></div>
            </div>
            <div data-role="plot" class="flex-1"></div>
          </div>
        </div>
        {% endif %}

        {% if il.calibration_plot %}
        <div id="calibration-root-{{il.image.id}}" x-show="explorePane === 'calibration'" class="phd2-plot-shell detail-card">
          <div class="calibration-layout">
            <select data-role="session" aria-label="Calibration session" class="input_container bg-white dark:bg-gray-700 text-black dark:text-white w-full calibration-session"></select>
            <div data-role="heading" class="rounded-lg border border-gray-200 dark:border-gray-700 p-3 overflow-auto w-full calibration-heading"></div>
            <div data-role="plot" class="w-full calibration-plot"></div>
          </div>
        </div>
        {% endif %}
      </div>

    </div>

      <div class="relative flex flex-col items-center justify-center">
        <div class="relative w-0 top-0 h-6 border-1 mt-2 border-gray-200 dark:border-gray-400">
        </div>
      </div>


      <script type="module">
      import { drawHRDiagram } from "{{ url_for('static', filename='js/plotHR.js') }}";
      import { renderGuidingPlot, renderCalibrationPlot } from "{{ url_for('static', filename='js/phd2Plotly.js') }}";
      import { populateAxisSelects, drawVariablePlot } from "{{ url_for('static', filename='js/subFramePlot.js') }}";
        (function () {
          const imageId = "{{ il.image.id }}";

          function copyCurrentURL() {
            const link = `${window.location.origin}${window.location.pathname}#uid-${imageId}`;
            navigator.clipboard.writeText(link)
              .then(() => {
                alert("Link copied to clipboard!");
              })
              .catch(err => {
                alert("Failed to copy: " + err);
              });
          }

          document.getElementById("copy-link-{{il.image.id}}").addEventListener("click", copyCurrentURL);

          function copyCurrentURLwithDetails() {
            const id = "{{il.image.id}}";  // use your actual id injection method here
            const link = `${window.location.origin}${window.location.pathname}#uid-${id}`;

            // Define tables and their section titles in the order you want
            const tablesInfo = [
              { selector: `table[html-id="light-${id}"]`, title: "Lights:\n-------" },
              { selector: `table[html-id="weighted-${id}"]`, title: "Weighted Exposure:\n------------------" },
              { selector: `table[html-id="night-summary-${id}"]`, title: "Nights:\n-------" },
              { selector: `table[html-id="equipment-${id}"]`, title: "Equipment:\n-----------" },
              { selector: `table[html-id="software-${id}"]`, title: "Software:\n----------" }
            ];

            let fullText = {{ (
                il.image.title ~ " - " ~ il.image.short_description ~ "\n\n" ~
                il.image.description ~ "\n\nImage By: " ~ il.image.author ~ "\n\n"
            ) | tojson }};

        tablesInfo.forEach(({ selector, title }) => {
          const table = document.querySelector(selector);
          if (!table) return;  // skip if table not found

          const rows = table.querySelectorAll("tr");
          const tableData = [];

          rows.forEach(row => {
            const cells = Array.from(row.querySelectorAll("th, td"));
            const rowText = cells.map(cell => {
              const pElements = cell.querySelectorAll("p");
              if (pElements.length > 0) {
                return Array.from(pElements).map(p => p.innerText.trim()).join(", ");
              } else {
                return cell.innerText.trim();
              }
            });
            tableData.push(rowText);
          });

          const formattedTable = alignTable(tableData);

          fullText += `${title}\n${formattedTable}\n\n`;
        });

        fullText += link;
        console.log(fullText);
        navigator.clipboard.writeText(fullText)
          .then(() => {
            alert("Link copied to clipboard!");
          })
          .catch(err => {
            alert("Failed to copy: " + err);
          });
          }

        document.getElementById("copy-link-details-{{il.image.id}}").addEventListener("click", copyCurrentURLwithDetails);


        function copyCurrentURLwithDetailsHTML() {
          const link = `${window.location.origin}${window.location.pathname}#uid-{{il.image.id}}`;
          const lightTable = document.querySelector(`table[light-id="light-{{il.image.id}}"]`);

          //console.log(link);
          // Clone the table to avoid modifying the DOM
          const tableClone = lightTable.cloneNode(true);

          // Optionally remove classes or inline styles
          tableClone.removeAttribute("class");

          // Create a full HTML snippet
          const htmlContent = `<p>Link: <a href="${link}">${link}</a></p>${tableClone.outerHTML}`;
          //console.log(htmlContent);
          // Copy as HTML
          const blobt = new Blob([htmlContent], { type: "text/plain" });
          const blob = new Blob([htmlContent], { type: "text/html" });
          const clipboardItem = new ClipboardItem({ "text/plain": blobt }, { "text/html": blob });

          navigator.clipboard.write([clipboardItem])
            .then(() => {
              alert("HTML table and link copied to clipboard!");
            })
            .catch(err => {
              alert("Failed to copy HTML: " + err);
            });
        }

        // document.getElementById("copy-html-details-{{il.image.id}}").addEventListener("click", copyCurrentURLwithDetailsHTML); 

        const overlayData = {{ il.svg_image | tojson | safe  }};

        function renderObjectOverlay(target, enabled) {
          if (!enabled) {
            target.innerHTML = "";
            return;
          }

          let svg = `<svg viewBox="0 0 ${overlayData.width} ${overlayData.height}" preserveAspectRatio="xMidYMid meet" style="position: absolute; top: 0; left: 0; pointer-events: auto;" xmlns="http://www.w3.org/2000/svg">

          <style>
            .astro-group {
              opacity: 0.2;
              transition: opacity 0.2s ease;
              cursor: pointer;
              pointer-events: all;
            }
            .astro-group:hover {
              opacity: 0.9;
            }
          </style>
        `;

          const overlays = overlayData.overlays.name.map((_, i) => ({
            id: overlayData.overlays.name[i],
            x: overlayData.overlays.x[i],
            y: overlayData.overlays.y[i],
            rx: overlayData.overlays.rx[i],
            ry: overlayData.overlays.ry[i],
            angle: overlayData.overlays.angle[i],
            otype: overlayData.overlays.otype[i],
          }));

          for (const item of overlays) {
            if (item.rx < 25 || item.ry < 25) {
              continue;
            }

            const rawId = item.id ?? "";
            const id = String(rawId).trim();
            const rawOtype = item.otype === "Unknown" || !item.otype ? "" : item.otype;
            const otype = String(rawOtype).trim();

            let query = (otype ? `${otype} ${id}` : id).trim();
            if (!query || typeof query !== "string") {
              query = id || "";
            }
            query = query.replace(/\s+/g, " ").trim();

            const searchURL = `https://www.google.com/search?q=${encodeURIComponent(query)}`;
            const transform = item.angle
              ? ` transform="rotate(${item.angle}, ${item.x.toFixed(2)}, ${item.y.toFixed(2)}) "`
              : "";

            svg += `
              <g class="astro-group" data-search="${searchURL}" data-query="${query}">
                <ellipse cx="${item.x.toFixed(2)}" cy="${item.y.toFixed(2)}"
                  rx="${item.rx.toFixed(2)}" ry="${item.ry.toFixed(2)}"${transform}
                  fill="none" stroke="white" stroke-width="10"></ellipse>

                <text x="${(item.x + 60).toFixed(2)}" y="${(item.y - item.ry - 60).toFixed(2)}"
                  font-size="72" fill="white" stroke="black" stroke-width="2"
                  text-anchor="middle" alignment-baseline="middle">
                  ${item.id}
                </text>
              </g>
            `;
          }

          svg += "</svg>";
          target.innerHTML = svg;

          target.querySelectorAll(".astro-group").forEach(group => {
            group.addEventListener("dblclick", (evt) => {
              const query = group.dataset.query;
              const url = group.dataset.search;

              const confirmSearch = confirm(
                `Search for:\n\n${query}\n\nProceed using your default search engine?`
              );

              if (confirmSearch) {
                window.open(url, "_blank");
              }

              evt.stopPropagation();
            });
          });
        }

        function renderGraticuleOverlay(target, enabled) {
          if (!enabled) {
            target.innerHTML = "";
            return;
          }

          let svg = `<svg viewBox="0 0 ${overlayData.width} ${overlayData.height}" preserveAspectRatio="xMidYMid meet" style="position: absolute; top: 0; left: 0; pointer-events: auto;">`;

          overlayData.grid_lines.ra_lines.forEach(line => {
            const points = line.map(pt => `${pt[0]},${pt[1]}`).join(" ");
            svg += `<polyline class="ra-line" stroke="white" stroke-width="8" fill="none" opacity="0.7" points="${points}" />`;
          });

          overlayData.grid_lines.dec_lines.forEach(line => {
            const points = line.map(pt => `${pt[0]},${pt[1]}`).join(" ");
            svg += `<polyline class="dec-line" stroke="white" stroke-width="8" fill="none" opacity="0.7" points="${points}" />`;
          });

          overlayData.grid_lines.labels.forEach(label => {
            svg += `<text x="${label.x}" y="${label.y}"font-family="Arial" font-weight="bold" font-size="60" fill="white" stroke="black" stroke-width="1" paint-order="stroke fill" opacity="0.7" transform="rotate(${label.rotation}, ${label.x}, ${label.y})">${label.text}</text>`;
          });

          svg += "</svg>";
          target.innerHTML = svg;
        }

        function syncCompareOverlay(compareWrapper, enabled) {
          if (!enabled) {
            compareWrapper.classList.add("hidden");
            return;
          }

          compareWrapper.classList.remove("hidden");

          if (!compareWrapper._panzoomInstance) {
            compareWrapper.setAttribute("viewBox", `0 0 ${overlayData.width} ${overlayData.height}`);
            compareWrapper._panzoomInstance = Panzoom(compareWrapper, {
              cursor: "grab",
              disableZoom: true
            });
          }
        }

        function createViewer(prefix) {
          const elements = {
            container: document.getElementById(`${prefix}zoom-container-${imageId}`),
            wrapper: document.getElementById(`${prefix}zoom-wrapper-${imageId}`),
            overlay: document.getElementById(`${prefix}svg-overlay-${imageId}`),
            graticule: document.getElementById(`${prefix}graticule-${imageId}`),
            compareWrapper: document.getElementById(`${prefix}comp-wrapper-${imageId}`),
            overlayToggle: document.getElementById(`${prefix}overlay-toggle-${imageId}`),
            graticuleToggle: document.getElementById(`${prefix}graticule-toggle-${imageId}`),
            compareToggle: document.getElementById(`${prefix}compare-toggle-${imageId}`),
            resetButton: document.getElementById(`${prefix}reset-btn-${imageId}`),
          };

          const panzoom = Panzoom(elements.wrapper, {
            maxScale: 50
          });

          elements.container.addEventListener("wheel", panzoom.zoomWithWheel, { passive: false });

          const renderAll = () => {
            renderObjectOverlay(elements.overlay, elements.overlayToggle.checked);
            renderGraticuleOverlay(elements.graticule, elements.graticuleToggle.checked);
            syncCompareOverlay(elements.compareWrapper, elements.compareToggle.checked);
          };

          elements.resetButton.addEventListener("click", () => {
            panzoom.reset();
            elements.compareWrapper._panzoomInstance?.reset?.();
          });

          elements.overlayToggle.addEventListener("change", renderAll);
          elements.graticuleToggle.addEventListener("change", renderAll);
          elements.compareToggle.addEventListener("change", renderAll);

          renderAll();

          return {
            elements,
            reset() {
              panzoom.reset();
              elements.compareWrapper._panzoomInstance?.reset?.();
            },
            setToolState(state) {
              elements.overlayToggle.checked = !!state.overlay;
              elements.graticuleToggle.checked = !!state.graticule;
              elements.compareToggle.checked = !!state.compare;
              renderAll();
            }
          };
        }

        const inlineViewer = createViewer("");
        let fullscreenViewer = null;

        const fullscreenModal = document.getElementById(`fullscreen-modal-${imageId}`);
        const fullscreenOpenButton = document.getElementById(`fullscreen-btn-${imageId}`);
        const fullscreenCloseButton = document.getElementById(`fullscreen-close-btn-${imageId}`);
        const fullscreenBackdrop = document.getElementById(`fullscreen-backdrop-${imageId}`);

        function ensureFullscreenViewer() {
          if (!fullscreenViewer) {
            // Initialize the fullscreen panzoom after the modal is visible so reset uses the rendered size.
            fullscreenViewer = createViewer("fullscreen-");
          }

          return fullscreenViewer;
        }

        function openFullscreenViewer() {
          fullscreenModal.classList.remove("hidden");
          fullscreenModal.classList.add("flex");
          document.body.style.overflow = "hidden";

          requestAnimationFrame(() => {
            requestAnimationFrame(() => {
              const viewer = ensureFullscreenViewer();
              viewer.setToolState({
                overlay: inlineViewer.elements.overlayToggle.checked,
                graticule: inlineViewer.elements.graticuleToggle.checked,
                compare: inlineViewer.elements.compareToggle.checked,
              });
              viewer.reset();
            });
          });
        }

        function closeFullscreenViewer() {
          fullscreenModal.classList.add("hidden");
          fullscreenModal.classList.remove("flex");
          document.body.style.overflow = "";
        }

        fullscreenOpenButton.addEventListener("click", openFullscreenViewer);
        fullscreenCloseButton.addEventListener("click", closeFullscreenViewer);
        fullscreenBackdrop.addEventListener("click", closeFullscreenViewer);

        document.addEventListener("keydown", (event) => {
          if (event.key === "Escape" && !fullscreenModal.classList.contains("hidden")) {
            closeFullscreenViewer();
          }
        });

        document.addEventListener("DOMContentLoaded", () => {
            drawHRDiagram(overlayData);
            renderGuidingPlot("guiding-root-{{il.image.id}}", {{ il.guiding_plot | tojson | safe }});
            renderCalibrationPlot("calibration-root-{{il.image.id}}", {{ il.calibration_plot | tojson | safe }});

            {% if il.meta_json %}
            const metaVariable = {{ il.meta_json.variable | tojson | safe }};
            const metaComments = {{ il.meta_json.comments | tojson | safe }};

            populateAxisSelects(metaVariable);

            const update = () => {
                const xKey = document.getElementById("xAxisSelect").value;

                const getSelectedValues = (id) =>
                    Array.from(document.getElementById(id).selectedOptions)
                        .map(o => o.value);

                const yKeys = [
                    getSelectedValues("yAxisSelect1"),
                    getSelectedValues("yAxisSelect2"),
                    getSelectedValues("yAxisSelect3"),
                ]

                const chartTypes = [
                    document.getElementById("yAxisType1").value,
                    document.getElementById("yAxisType2").value,
                    document.getElementById("yAxisType3").value,
                ];

                drawVariablePlot(
                    metaVariable,
                    metaComments,
                    xKey,
                    yKeys,
                    chartTypes
                );
            };

            document
                .getElementById("updatePlotBtn")
                .addEventListener("click", update);

            update(); // initial plot 
            {% endif %}
        });
      })();
      </script>


    </div>
    {% endfor %}
    <div class="relative min-h-[35vh] flex flex-col items-center justify-center shadow-5xl">
      <div
        class="flex-grow flex items-center justify-center border-1 border-gray-200 dark:border-gray-400   shadow-5xl">
        <div class="w-0 top-0 h-full shadow-2xl">
        </div>
      </div>
    </div>
  </div>
  {% endblock %}

