{% extends "modern/base.html" %}

{% block title %}{{ obj.euid }} - BLOOM LIMS{% endblock %}

{% block content %}
<div class="page-header">
  <div>
    <nav class="breadcrumb">
      <a href="/">Dashboard</a>
      <span class="separator">/</span>
      <span>{{ obj.type | capitalize }}</span>
      <span class="separator">/</span>
      <span class="current">{{ obj.euid }}</span>
    </nav>
    <h1>
      <span class="badge badge-euid" style="font-size: 1.25rem;">{{ obj.euid }}</span>
      {{ obj.name | default(obj.subtype) }}
    </h1>
  </div>
  <div class="page-actions">
    {% if obj.category.endswith('_template') %}
    <a href="/create_object?template_euid={{ obj.euid }}" class="btn btn-success btn-sm" title="Create an instance from this template">
      <i class="fas fa-plus-circle"></i> Create Instance
    </a>
    {% endif %}
    <a href="/dindex2?start_euid={{ obj.euid }}" class="btn btn-primary btn-sm" title="View in DAG Explorer">
      <i class="fas fa-project-diagram"></i> Graph
    </a>
    <button class="btn btn-outline btn-sm" onclick="copyToClipboard('{{ obj.euid }}')" title="Copy EUID">
      <i class="fas fa-copy"></i>
    </button>
  </div>
</div>

<div class="grid grid-3">
  <!-- Main Info -->
  <div class="card" style="grid-column: span 2;">
    <div class="card-header">
      <h3 class="card-title"><i class="fas fa-info-circle"></i> Object Details</h3>
      {% if is_admin %}
      <button class="btn btn-outline btn-sm" id="edit-mode-toggle" onclick="toggleEditMode()">
        <i class="fas fa-edit"></i> <span id="edit-mode-text">Edit</span>
      </button>
      {% endif %}
    </div>
    <div class="card-body">
      <div class="detail-grid">
        <div class="detail-item">
          <div class="detail-label">EUID</div>
          <div class="detail-value font-mono">{{ obj.euid }}</div>
        </div>
        <div class="detail-item">
          <div class="detail-label">Category</div>
          <div class="detail-value">{{ obj.category }}</div>
        </div>
        <div class="detail-item">
          <div class="detail-label">Type</div>
          <div class="detail-value">{{ obj.type }}</div>
        </div>
        <div class="detail-item">
          <div class="detail-label">Subtype</div>
          <div class="detail-value">{{ obj.subtype }}</div>
        </div>
        <div class="detail-item">
          <div class="detail-label">Version</div>
          <div class="detail-value">{{ obj.version }}</div>
        </div>
        <div class="detail-item editable-field" data-field="status">
          <div class="detail-label">Status {% if is_admin %}<i class="fas fa-pencil-alt edit-icon" style="display:none;"></i>{% endif %}</div>
          <div class="detail-value">
            <span class="display-value">{{ obj.bstatus }}</span>
            {% if is_admin %}
            <input type="text" class="edit-input" value="{{ obj.bstatus }}" style="display:none;">
            {% endif %}
          </div>
        </div>
        <div class="detail-item editable-field" data-field="name">
          <div class="detail-label">Name {% if is_admin %}<i class="fas fa-pencil-alt edit-icon" style="display:none;"></i>{% endif %}</div>
          <div class="detail-value">
            <span class="display-value">{{ obj.json_addl.get('properties', {}).get('name') | default(obj.name) | default('-') }}</span>
            {% if is_admin %}
            <input type="text" class="edit-input" value="{{ obj.json_addl.get('properties', {}).get('name') | default(obj.name) | default('') }}" style="display:none;">
            {% endif %}
          </div>
        </div>
        <div class="detail-item editable-field" data-field="created_dt">
          <div class="detail-label">Created {% if is_admin %}<i class="fas fa-pencil-alt edit-icon" style="display:none;"></i>{% endif %}</div>
          <div class="detail-value">
            <span class="display-value">{{ obj.created_dt | format_dt('standard') if obj.created_dt else '-' }}</span>
            {% if is_admin %}
            <input type="datetime-local" class="edit-input" value="{{ obj.created_dt | dt_local_input if obj.created_dt else '' }}" style="display:none;">
            {% endif %}
          </div>
        </div>
        <div class="detail-item">
          <div class="detail-label">Is Deleted?</div>
          <div class="detail-value">
            {% if obj.is_deleted %}
            <span class="badge badge-error">Yes</span>
            {% if is_admin %}
            <button class="btn btn-sm btn-outline" onclick="undeleteObject('{{ obj.euid }}')" style="margin-left: var(--spacing-xs);">
              <i class="fas fa-undo"></i> Restore
            </button>
            {% endif %}
            {% else %}
            <span class="badge badge-success">No</span>
            {% if is_admin %}
            <button class="btn btn-sm btn-outline" onclick="softDeleteObject('{{ obj.euid }}')" style="margin-left: var(--spacing-xs);">
              <i class="fas fa-trash"></i> Delete
            </button>
            {% endif %}
            {% endif %}
          </div>
        </div>
        <div class="detail-item">
          <div class="detail-label">Template EUID</div>
          <div class="detail-value">
            {% if obj.template %}
            <a href="/euid_details?euid={{ obj.template.euid }}" class="link-euid">{{ obj.template.euid }}</a>
            {% elif obj_dict.parent_template_euid %}
            <a href="/euid_details?euid={{ obj_dict.parent_template_euid }}" class="link-euid">{{ obj_dict.parent_template_euid }}</a>
            {% else %}
            <span class="badge badge-info">TEMPLATE</span>
            {% endif %}
          </div>
        </div>
        {% if obj.category == 'file' and obj.json_addl and obj.json_addl.get('properties', {}).get('current_s3_uri') %}
        <div class="detail-item" style="grid-column: span 2;">
          <div class="detail-label">S3 URI</div>
          <div class="detail-value" style="display: flex; align-items: center; gap: var(--spacing-sm); flex-wrap: wrap;">
            <a href="{{ obj.json_addl.get('properties', {}).get('current_s3_uri') }}" target="_blank" class="link-uri font-mono" style="word-break: break-all;">
              {{ obj.json_addl.get('properties', {}).get('current_s3_uri') }}
            </a>
            {% if obj.json_addl.get('properties', {}).get('current_s3_bucket_name') and obj.json_addl.get('properties', {}).get('current_s3_key') %}
            <a href="https://us-east-1.console.aws.amazon.com/s3/object/{{ obj.json_addl.get('properties', {}).get('current_s3_bucket_name') }}?region=us-east-1&prefix={{ obj.json_addl.get('properties', {}).get('current_s3_key') }}"
               target="_blank" class="btn btn-outline btn-sm" title="Open in AWS S3 Console">
              <i class="fab fa-aws"></i> AWS Console
            </a>
            {% endif %}
            <button class="btn btn-outline btn-sm" onclick="copyToClipboard('{{ obj.json_addl.get('properties', {}).get('current_s3_uri') }}')" title="Copy S3 URI">
              <i class="fas fa-copy"></i>
            </button>
          </div>
        </div>
        {% endif %}
      </div>
    </div>
  </div>

  <!-- Quick Actions -->
  <div class="card">
    <div class="card-header">
      <h3 class="card-title"><i class="fas fa-bolt"></i> Actions</h3>
    </div>
    <div class="card-body">
      <div class="action-list">
        <a href="/dindex2?start_euid={{ obj.euid }}" class="btn btn-primary btn-block">
          <i class="fas fa-project-diagram"></i> View Graph
        </a>
        <a href="/search?q={{ obj.euid }}" class="btn btn-outline btn-block">
          <i class="fas fa-search"></i> Related Objects
        </a>
        <button class="btn btn-outline btn-block" onclick="printLabel('{{ obj.euid }}')">
          <i class="fas fa-print"></i> Print Label
        </button>
      </div>
    </div>
  </div>
</div>

{% if external_refs %}
<div class="card" style="margin-top: var(--spacing-lg);">
  <div class="card-header">
    <h3 class="card-title"><i class="fas fa-up-right-from-square"></i> External References</h3>
  </div>
  <div class="card-body">
    <div style="display: grid; gap: var(--spacing-sm);">
      {% for ref in external_refs %}
      <div style="border: 1px solid var(--color-border); border-radius: 8px; padding: var(--spacing-sm);">
        <div style="display: flex; justify-content: space-between; gap: var(--spacing-sm); flex-wrap: wrap; align-items: flex-start;">
          <div>
            <div style="font-weight: 600;">{{ ref.label }}</div>
            <div style="color: var(--color-gray-400); font-size: 0.875rem; margin-top: 0.25rem;">
              {{ ref.system }} :: {{ ref.root_euid }}{% if ref.tenant_id %} :: {{ ref.tenant_id }}{% endif %}
            </div>
            {% if not ref.graph_expandable and ref.reason %}
            <div style="color: var(--color-gray-400); font-size: 0.8rem; margin-top: 0.35rem;">{{ ref.reason }}</div>
            {% endif %}
          </div>
          <div style="display: flex; gap: var(--spacing-xs); flex-wrap: wrap;">
            {% if ref.href %}
            <a href="{{ ref.href }}" target="_blank" rel="noreferrer" class="btn btn-outline btn-sm">
              <i class="fas fa-up-right-from-square"></i> Open Remote
            </a>
            {% endif %}
            {% if ref.graph_expandable %}
            <a href="/dindex2?start_euid={{ obj.euid }}&depth=4&merge_ref={{ ref.ref_index }}" class="btn btn-primary btn-sm">
              <i class="fas fa-project-diagram"></i> Open In Graph
            </a>
            {% else %}
            <button type="button" class="btn btn-primary btn-sm" disabled>
              <i class="fas fa-project-diagram"></i> Open In Graph
            </button>
            {% endif %}
          </div>
        </div>
      </div>
      {% endfor %}
    </div>
  </div>
</div>
{% endif %}

<!-- Object Actions -->
{% if action_groups %}
<div class="card" style="margin-top: var(--spacing-lg);">
  <div class="card-header">
    <h3 class="card-title"><i class="fas fa-bolt"></i> Object Actions</h3>
  </div>
  <div class="card-body">
    {% for group_key, group_value in action_groups.items() %}
    <div class="action-group-section" style="margin-bottom: var(--spacing-md);">
      <h4 style="font-size: 0.875rem; color: var(--color-gray-400); margin-bottom: var(--spacing-sm); text-transform: uppercase;">
        {{ group_value.group_name }}
      </h4>
      <div style="display: flex; gap: var(--spacing-sm); flex-wrap: wrap;">
        {% for action_key, action_value in group_value.actions.items() %}
        <button class="btn btn-outline btn-sm action-button"
          data-action-json="{{ action_value | tojson | e }}"
          data-euid="{{ obj.euid }}"
          data-action-name="{{ action_key }}"
          data-action-group="{{ group_key }}"
          onclick="showCapturedDataFormFromDataAttributes(this)"
          {% if action_value.action_enabled == "0" %}disabled style="opacity: 0.5;"{% endif %}>
          <i class="fas fa-play"></i> {{ action_value.action_name }}
        </button>
        {% endfor %}
      </div>
    </div>
    {% endfor %}
  </div>
</div>
{% endif %}

<!-- Collapsible Sections -->
<div class="collapsible-nav" style="margin-top: var(--spacing-lg);">
  <button class="collapsible-btn" data-target="relationshipsSection">
    <i class="fas fa-link"></i> Relationships
  </button>
  {% if subjects_for_object %}
  <button class="collapsible-btn" data-target="subjectsSection">
    <i class="fas fa-users"></i> Subjects ({{ subjects_for_object|length }})
  </button>
  {% endif %}
  <button class="collapsible-btn" data-target="auditLogSection">
    <i class="fas fa-history"></i> Audit Log
  </button>
  <button class="collapsible-btn" data-target="editPropertiesSection">
    <i class="fas fa-edit"></i> Edit Properties
  </button>
  {% if not obj.template %}
  <button class="collapsible-btn" data-target="editTemplateSection">
    <i class="fas fa-cogs"></i> Edit Template Form
  </button>
  {% endif %}
</div>

<!-- Relationships Section -->
<div id="relationshipsSection" class="collapsible-content" style="display: none;">
  <div class="card">
    <div class="card-header">
      <h3 class="card-title"><i class="fas fa-link"></i> Relationships</h3>
    </div>
    <div class="card-body">
      <!-- Child Of Lineages (Parents) -->
      <h4 class="section-subtitle"><i class="fas fa-arrow-up"></i> Parent Relationships (Child Of)</h4>
      {% if obj.child_of_lineages %}
      <div class="table-container">
        <table class="table">
          <thead>
            <tr>
              <th>Status</th>
              <th>Parent EUID</th>
              <th>Type</th>
              <th>Sub Type</th>
              <th>Version</th>
              <th>Relationship</th>
              <th>Lineage EUID</th>
            </tr>
          </thead>
          <tbody>
            {% for lineage in obj.child_of_lineages %}
            <tr class="{% if lineage.is_deleted %}row-deleted{% endif %}">
              <td>
                {% if lineage.is_deleted %}
                <span class="badge badge-error"><i class="fas fa-trash"></i> Deleted</span>
                {% else %}
                <span class="badge badge-success"><i class="fas fa-check"></i> Active</span>
                {% endif %}
              </td>
              <td><a href="/euid_details?euid={{ lineage.parent_instance.euid }}" class="link-euid">{{ lineage.parent_instance.euid }}</a></td>
              <td>{{ lineage.parent_instance.type }}</td>
              <td>{{ lineage.parent_instance.subtype }}</td>
              <td>{{ lineage.parent_instance.version }}</td>
              <td>{{ lineage.relationship_type | default(lineage.type) }}</td>
              <td><a href="/euid_details?euid={{ lineage.euid }}" class="link-euid-secondary">{{ lineage.euid }}</a></td>
            </tr>
            {% endfor %}
          </tbody>
        </table>
      </div>
      {% else %}
      <p class="text-muted">No parent relationships found.</p>
      {% endif %}

      <!-- Parent Of Lineages (Children) -->
      <h4 class="section-subtitle" style="margin-top: var(--spacing-lg);"><i class="fas fa-arrow-down"></i> Child Relationships (Parent Of)</h4>
      {% if obj.parent_of_lineages %}
      <div class="table-container">
        <table class="table">
          <thead>
            <tr>
              <th>Status</th>
              <th>Child EUID</th>
              <th>Type</th>
              <th>Sub Type</th>
              <th>Version</th>
              <th>Relationship</th>
              <th>Lineage EUID</th>
            </tr>
          </thead>
          <tbody>
            {% for lineage in obj.parent_of_lineages %}
            <tr class="{% if lineage.is_deleted %}row-deleted{% endif %}">
              <td>
                {% if lineage.is_deleted %}
                <span class="badge badge-error"><i class="fas fa-trash"></i> Deleted</span>
                {% else %}
                <span class="badge badge-success"><i class="fas fa-check"></i> Active</span>
                {% endif %}
              </td>
              <td><a href="/euid_details?euid={{ lineage.child_instance.euid }}" class="link-euid">{{ lineage.child_instance.euid }}</a></td>
              <td>{{ lineage.child_instance.type }}</td>
              <td>{{ lineage.child_instance.subtype }}</td>
              <td>{{ lineage.child_instance.version }}</td>
              <td>{{ lineage.relationship_type | default(lineage.type) }}</td>
              <td><a href="/euid_details?euid={{ lineage.euid }}" class="link-euid-secondary">{{ lineage.euid }}</a></td>
            </tr>
            {% endfor %}
          </tbody>
        </table>
      </div>
      {% else %}
      <p class="text-muted">No child relationships found.</p>
      {% endif %}
    </div>
  </div>
</div>

<!-- Subjects Section -->
{% if subjects_for_object %}
<div id="subjectsSection" class="collapsible-content" style="display: none;">
  <div class="card">
    <div class="card-header">
      <h3 class="card-title"><i class="fas fa-users"></i> Subjects (Decision Scopes)</h3>
    </div>
    <div class="card-body">
      <p class="text-muted" style="margin-bottom: var(--spacing-md);"><em>This object is part of the following subjects:</em></p>
      <div class="table-container">
        <table class="table">
          <thead>
            <tr>
              <th>Subject EUID</th>
              <th>Kind</th>
              <th>Role</th>
              <th>Status</th>
              <th>Subject Key</th>
              <th>Name</th>
            </tr>
          </thead>
          <tbody>
            {% for subject in subjects_for_object %}
            <tr>
              <td><a href="/euid_details?euid={{ subject.euid }}" class="link-euid">{{ subject.euid }}</a></td>
              <td>{{ subject.kind }}</td>
              <td>
                {% if subject.role == 'anchor' %}
                <span class="badge badge-info"><i class="fas fa-anchor"></i> Anchor</span>
                {% elif subject.role == 'member' %}
                <span class="badge badge-success"><i class="fas fa-paperclip"></i> Member</span>
                {% else %}
                {{ subject.role }}
                {% endif %}
              </td>
              <td>{{ subject.status }}</td>
              <td><code class="code-inline">{{ subject.subject_key }}</code></td>
              <td>{{ subject.name }}</td>
            </tr>
            {% endfor %}
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>
{% endif %}

<!-- Audit Log Section -->
<div id="auditLogSection" class="collapsible-content" style="display: none;">
  <div class="card">
    <div class="card-header">
      <h3 class="card-title"><i class="fas fa-history"></i> Audit Log</h3>
    </div>
    <div class="card-body">
      {% if audit_logs %}
      <div class="table-container">
        <table class="table" id="auditLogTable">
          <thead>
            <tr>
              <th onclick="sortAuditTable(0)" style="cursor: pointer;">Column Name <i class="fas fa-sort"></i></th>
              <th onclick="sortAuditTable(1)" style="cursor: pointer;">Old Value <i class="fas fa-sort"></i></th>
              <th onclick="sortAuditTable(2)" style="cursor: pointer;">New Value <i class="fas fa-sort"></i></th>
              <th onclick="sortAuditTable(3)" style="cursor: pointer;">Changed By <i class="fas fa-sort"></i></th>
              <th onclick="sortAuditTable(4)" style="cursor: pointer;">Changed At <i class="fas fa-sort"></i></th>
              <th onclick="sortAuditTable(5)" style="cursor: pointer;">Operation <i class="fas fa-sort"></i></th>
            </tr>
          </thead>
          <tbody>
            {% for log in audit_logs %}
            <tr>
              <td>{{ log.column_name }}</td>
              {% if log.column_name == 'json_addl' %}
              <td>
                <button class="btn btn-outline btn-sm" onclick="toggleJsonDiff({{ loop.index }})">
                  <i class="fas fa-code"></i> Show JSON
                </button>
                <div id="jsonOld-{{ loop.index }}" class="json-diff-content" style="display: none;">
                  <pre class="json-display-sm">{{ log.old_value }}</pre>
                </div>
              </td>
              <td>
                <div id="jsonNew-{{ loop.index }}" class="json-diff-content" style="display: none;">
                  <pre class="json-display-sm">{{ log.new_value }}</pre>
                </div>
              </td>
              {% else %}
              <td class="text-truncate" title="{{ log.old_value }}">{{ log.old_value | truncate(50) if log.old_value else '-' }}</td>
              <td class="text-truncate" title="{{ log.new_value }}">{{ log.new_value | truncate(50) if log.new_value else '-' }}</td>
              {% endif %}
              <td>{{ log.changed_by }}</td>
              <td>{{ log.changed_at }}</td>
              <td>
                {% if log.operation_type == 'UPDATE' %}
                <span class="badge badge-warning">{{ log.operation_type }}</span>
                {% elif log.operation_type == 'INSERT' %}
                <span class="badge badge-success">{{ log.operation_type }}</span>
                {% elif log.operation_type == 'DELETE' %}
                <span class="badge badge-error">{{ log.operation_type }}</span>
                {% else %}
                <span class="badge badge-info">{{ log.operation_type }}</span>
                {% endif %}
              </td>
            </tr>
            {% endfor %}
          </tbody>
        </table>
      </div>
      {% else %}
      <p class="text-muted">No audit log entries found.</p>
      {% endif %}
    </div>
  </div>
</div>

<!-- Edit Object Properties Section -->
<div id="editPropertiesSection" class="collapsible-content" style="display: none;">
  <div class="card">
    <div class="card-header">
      <h3 class="card-title"><i class="fas fa-edit"></i> Edit Object Properties</h3>
    </div>
    <div class="card-body">
      <p class="text-muted" style="margin-bottom: var(--spacing-md);">Edit the <code>json_addl['properties']</code> for this object.</p>
      <div id="json-editor-properties" class="json-editor-container"></div>
      <div style="margin-top: var(--spacing-md);">
        <button class="btn btn-primary" onclick="saveProperties()">
          <i class="fas fa-save"></i> Save Properties
        </button>
      </div>
    </div>
  </div>
</div>

<!-- Edit Template Form Properties Section (only for templates) -->
{% if not obj.template %}
<div id="editTemplateSection" class="collapsible-content" style="display: none;">
  <div class="card">
    <div class="card-header">
      <h3 class="card-title"><i class="fas fa-cogs"></i> Edit Template Form Properties</h3>
    </div>
    <div class="card-body">
      <p class="text-muted" style="margin-bottom: var(--spacing-md);">Edit the <code>json_addl['controlled_properties']</code> for this template.</p>
      <div id="json-editor-template" class="json-editor-container"></div>
      <div style="margin-top: var(--spacing-md);">
        <button class="btn btn-primary" onclick="saveTemplateProperties()">
          <i class="fas fa-save"></i> Save Template Properties
        </button>
      </div>
    </div>
  </div>
</div>
{% endif %}

<!-- JSON Properties Display -->
{% if obj.json_addl %}
<div class="card" style="margin-top: var(--spacing-lg);">
  <div class="card-header">
    <h3 class="card-title"><i class="fas fa-code"></i> Full JSON (json_addl)</h3>
    <div>
      <button class="btn btn-outline btn-sm" onclick="toggleFullJsonView()">
        <i class="fas fa-expand" id="json-toggle-icon"></i> <span id="json-toggle-text">Expand</span>
      </button>
      {% if is_admin %}
      <button class="btn btn-outline btn-sm" id="json-edit-toggle" onclick="toggleJsonEditMode()">
        <i class="fas fa-edit"></i> <span id="json-edit-text">Edit</span>
      </button>
      {% endif %}
    </div>
  </div>
  <div class="card-body">
    <pre class="json-display" id="json-display">{{ obj.json_addl | tojson }}</pre>
    {% if is_admin %}
    <div id="json-editor-full" class="json-editor-container" style="display: none; min-height: 400px;"></div>
    <div id="json-save-buttons" style="display: none; margin-top: var(--spacing-md);">
      <button class="btn btn-primary" onclick="saveFullJson()">
        <i class="fas fa-save"></i> Save JSON
      </button>
      <button class="btn btn-outline" onclick="cancelJsonEdit()">
        <i class="fas fa-times"></i> Cancel
      </button>
    </div>
    {% endif %}
  </div>
</div>
{% endif %}
{% endblock %}

{% block extra_css %}
<!-- JSONEditor CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jsoneditor/9.5.6/jsoneditor.min.css">
<style>
.breadcrumb {
  font-size: 0.875rem;
  color: var(--color-gray-400);
  margin-bottom: var(--spacing-sm);
}
.breadcrumb a { color: var(--color-highlight); text-decoration: none; }
.breadcrumb a:hover { text-decoration: underline; }
.breadcrumb .separator { margin: 0 var(--spacing-xs); }
.breadcrumb .current { color: var(--color-gray-300); }

.detail-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: var(--spacing-md);
}
.detail-item { padding: var(--spacing-sm); background: var(--color-gray-700); border-radius: var(--radius-sm); }
.detail-label { font-size: 0.75rem; color: var(--color-gray-400); text-transform: uppercase; margin-bottom: var(--spacing-xs); }
.detail-value { font-weight: 500; }
.font-mono { font-family: var(--font-mono); }

/* Editable field styles */
.editable-field .edit-icon { font-size: 0.65rem; margin-left: var(--spacing-xs); color: var(--color-highlight); }
.editable-field .edit-input {
  width: 100%;
  padding: var(--spacing-xs) var(--spacing-sm);
  background: var(--color-gray-800);
  border: 1px solid var(--color-highlight);
  border-radius: var(--radius-sm);
  color: var(--color-white);
  font-size: inherit;
  font-weight: 500;
}
.editable-field.editing { background: var(--color-gray-600); }
.edit-mode-active .editable-field { cursor: pointer; }
.edit-mode-active .editable-field:hover { background: var(--color-gray-600); }

/* Edit mode buttons */
#edit-mode-toggle.active { background: var(--color-highlight); color: white; }
.edit-actions { margin-top: var(--spacing-md); display: flex; gap: var(--spacing-sm); }
.edit-actions.hidden { display: none; }

.action-list { display: flex; flex-direction: column; gap: var(--spacing-sm); }
.btn-block { width: 100%; justify-content: flex-start; }

.link-euid {
  color: var(--color-euid);
  text-decoration: none;
  font-family: var(--font-mono);
  font-weight: 500;
}
.link-euid:hover { text-decoration: underline; }
.link-euid-secondary {
  color: var(--color-gray-400);
  text-decoration: none;
  font-family: var(--font-mono);
  font-size: 0.875rem;
}
.link-euid-secondary:hover { color: var(--color-highlight); text-decoration: underline; }
.link-uri { color: var(--color-gray-400); text-decoration: none; }
.link-uri:hover { color: var(--color-highlight); text-decoration: underline; }

.collapsible-nav {
  display: flex;
  flex-wrap: wrap;
  gap: var(--spacing-sm);
  padding: var(--spacing-md);
  background: var(--color-gray-800);
  border-radius: var(--radius-md);
}
.collapsible-btn {
  background: var(--color-gray-700);
  color: var(--color-gray-200);
  border: 1px solid var(--color-gray-600);
  padding: var(--spacing-sm) var(--spacing-md);
  border-radius: var(--radius-sm);
  cursor: pointer;
  font-size: 0.875rem;
  font-weight: 500;
  transition: all var(--transition-normal);
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
}
.collapsible-btn:hover {
  background: var(--color-secondary);
  border-color: var(--color-highlight);
}
.collapsible-btn.active {
  background: var(--color-highlight);
  color: var(--color-white);
  border-color: var(--color-highlight);
}

.collapsible-content {
  margin-top: var(--spacing-md);
  animation: fadeIn 0.3s ease-out;
}
@keyframes fadeIn {
  from { opacity: 0; transform: translateY(-10px); }
  to { opacity: 1; transform: translateY(0); }
}

.section-subtitle {
  font-size: 1rem;
  font-weight: 600;
  color: var(--color-gray-200);
  margin-bottom: var(--spacing-md);
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
}
.section-subtitle i { color: var(--color-gray-400); }

.row-deleted {
  background: rgba(239, 68, 68, 0.1) !important;
  text-decoration: line-through;
  opacity: 0.7;
}

.code-inline {
  font-family: var(--font-mono);
  background: var(--color-gray-700);
  padding: 2px 6px;
  border-radius: var(--radius-sm);
  font-size: 0.8rem;
}

.json-display {
  background: var(--color-gray-900);
  padding: var(--spacing-md);
  border-radius: var(--radius-sm);
  overflow-x: auto;
  font-family: var(--font-mono);
  font-size: 0.875rem;
  color: var(--color-gray-300);
  max-height: 300px;
  margin: 0;
  white-space: pre-wrap;
  word-break: break-word;
}
.json-display-sm {
  background: var(--color-gray-900);
  padding: var(--spacing-sm);
  border-radius: var(--radius-sm);
  font-family: var(--font-mono);
  font-size: 0.75rem;
  color: var(--color-gray-300);
  max-height: 200px;
  overflow: auto;
  margin-top: var(--spacing-sm);
  white-space: pre-wrap;
  word-break: break-word;
}

.json-editor-container {
  min-height: 400px;
  border-radius: var(--radius-sm);
  overflow: hidden;
}
.jsoneditor {
  border: 1px solid var(--color-gray-600) !important;
}
.jsoneditor-menu {
  background-color: var(--color-gray-700) !important;
  border-bottom: 1px solid var(--color-gray-600) !important;
}
.jsoneditor-navigation-bar {
  background-color: var(--color-gray-700) !important;
  border-bottom: 1px solid var(--color-gray-600) !important;
}

.text-muted { color: var(--color-gray-400); }
.text-truncate {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
{% endblock %}


{% block extra_js %}
<!-- Action Buttons -->
<script src="/static/modern/js/action_buttons.js"></script>
<!-- JSONEditor JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jsoneditor/9.5.6/jsoneditor.min.js"></script>
<script>
// Fallback action handler in case cached legacy JS lacks the newer helper.
if (typeof window.showCapturedDataFormFromDataAttributes !== 'function') {
  window.showCapturedDataFormFromDataAttributes = function(button) {
    try {
      var rawActionData = button.getAttribute('data-action-json');
      if (!rawActionData) {
        throw new Error('Missing data-action-json');
      }

      var actionData;
      try {
        actionData = JSON.parse(rawActionData);
      } catch (parseError) {
        var decoder = document.createElement('textarea');
        decoder.innerHTML = rawActionData;
        actionData = JSON.parse(decoder.value);
      }

      if (typeof window.showCapturedDataForm !== 'function') {
        throw new Error('showCapturedDataForm is unavailable');
      }

      window.showCapturedDataForm(
        button,
        actionData,
        button.getAttribute('data-euid') || '',
        button.getAttribute('data-action-name') || '',
        button.getAttribute('data-action-group') || ''
      );
    } catch (error) {
      console.error('Error opening action form:', error);
      if (typeof window.BloomToast !== 'undefined' && typeof window.BloomToast.error === 'function') {
        window.BloomToast.error('Action Error', error.message || 'Unable to open action form');
      }
    }
  };
}

// JSONEditor instances
var editorProperties = null;
var editorTemplate = null;

// Collapsible section toggle
document.querySelectorAll('.collapsible-btn').forEach(function(btn) {
  btn.addEventListener('click', function() {
    var targetId = this.getAttribute('data-target');
    var targetEl = document.getElementById(targetId);

    // Toggle active class on button
    this.classList.toggle('active');

    // Toggle visibility of content
    if (targetEl.style.display === 'none') {
      targetEl.style.display = 'block';
    } else {
      targetEl.style.display = 'none';
    }
  });
});

// Format JSON on page load
document.addEventListener('DOMContentLoaded', function() {
  var jsonEl = document.getElementById('json-display');
  if (jsonEl) {
    try {
      var jsonData = JSON.parse(jsonEl.textContent);
      jsonEl.textContent = JSON.stringify(jsonData, null, 2);
    } catch (e) {
      // JSON is already formatted or invalid, leave as-is
    }
  }
});

// Toggle full JSON view
function toggleFullJsonView() {
  var el = document.getElementById('json-display');
  var icon = document.getElementById('json-toggle-icon');
  var text = document.getElementById('json-toggle-text');

  if (el.style.maxHeight === 'none') {
    el.style.maxHeight = '300px';
    icon.className = 'fas fa-expand';
    text.textContent = 'Expand';
  } else {
    el.style.maxHeight = 'none';
    icon.className = 'fas fa-compress';
    text.textContent = 'Collapse';
  }
}

// Toggle JSON diff display in audit log
function toggleJsonDiff(index) {
  var oldEl = document.getElementById('jsonOld-' + index);
  var newEl = document.getElementById('jsonNew-' + index);

  if (oldEl.style.display === 'none') {
    oldEl.style.display = 'block';
    newEl.style.display = 'block';
  } else {
    oldEl.style.display = 'none';
    newEl.style.display = 'none';
  }
}

// Sort audit log table
var auditSortColumn = -1;
var auditSortAsc = true;

function sortAuditTable(columnIndex) {
  var table = document.getElementById('auditLogTable');
  if (!table) return;

  if (columnIndex === auditSortColumn) {
    auditSortAsc = !auditSortAsc;
  } else {
    auditSortColumn = columnIndex;
    auditSortAsc = true;
  }

  var tbody = table.querySelector('tbody');
  var rows = Array.from(tbody.querySelectorAll('tr'));

  rows.sort(function(a, b) {
    var aVal = a.cells[columnIndex].textContent.trim().toLowerCase();
    var bVal = b.cells[columnIndex].textContent.trim().toLowerCase();

    if (auditSortAsc) {
      return aVal.localeCompare(bVal);
    } else {
      return bVal.localeCompare(aVal);
    }
  });

  rows.forEach(function(row) {
    tbody.appendChild(row);
  });
}

// Save object properties
function saveProperties() {
  if (!editorProperties) {
    BloomToast.error('Error', 'Editor not initialized');
    return;
  }

  try {
    var jsonData = editorProperties.get();

    fetch('/save_json_addl_key', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        euid: '{{ obj.euid }}',
        json_data: jsonData,
        json_addl_key: 'properties'
      })
    })
    .then(function(response) {
      if (response.ok || response.status === 303) {
        BloomToast.success('Saved', 'Properties saved successfully');
        setTimeout(function() {
          window.location.href = '/euid_details?euid={{ obj.euid }}';
        }, 1000);
      } else {
        return response.text().then(function(text) {
          throw new Error(text);
        });
      }
    })
    .catch(function(error) {
      BloomToast.error('Error', 'Failed to save properties: ' + error.message);
    });
  } catch (e) {
    BloomToast.error('Invalid JSON', e.message);
  }
}

// Save template properties
function saveTemplateProperties() {
  if (!editorTemplate) {
    BloomToast.error('Error', 'Template editor not initialized');
    return;
  }

  try {
    var jsonData = editorTemplate.get();

    fetch('/save_json_addl_key', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        euid: '{{ obj.euid }}',
        json_data: jsonData,
        json_addl_key: 'controlled_properties'
      })
    })
    .then(function(response) {
      if (response.ok || response.status === 303) {
        BloomToast.success('Saved', 'Template properties saved successfully');
        setTimeout(function() {
          window.location.href = '/euid_details?euid={{ obj.euid }}';
        }, 1000);
      } else {
        return response.text().then(function(text) {
          throw new Error(text);
        });
      }
    })
    .catch(function(error) {
      BloomToast.error('Error', 'Failed to save template properties: ' + error.message);
    });
  } catch (e) {
    BloomToast.error('Invalid JSON', e.message);
  }
}

// Print label
function printLabel(euid) {
  BloomToast.info('Print Label', 'Printing label for ' + euid);
}

// Edit mode state
var isEditMode = false;
var editorFull = null;
var isJsonEditMode = false;

// Toggle edit mode for inline fields
function toggleEditMode() {
  isEditMode = !isEditMode;
  var btn = document.getElementById('edit-mode-toggle');
  var text = document.getElementById('edit-mode-text');
  var detailGrid = document.querySelector('.detail-grid');

  if (isEditMode) {
    btn.classList.add('active');
    text.textContent = 'Save';
    detailGrid.classList.add('edit-mode-active');

    // Show edit inputs and icons
    document.querySelectorAll('.editable-field .edit-icon').forEach(function(icon) {
      icon.style.display = 'inline';
    });
    document.querySelectorAll('.editable-field .edit-input').forEach(function(input) {
      input.style.display = 'block';
    });
    document.querySelectorAll('.editable-field .display-value').forEach(function(val) {
      val.style.display = 'none';
    });
  } else {
    // Save changes
    saveFieldChanges();
  }
}

// Save inline field changes
function saveFieldChanges() {
  var updates = {};

  document.querySelectorAll('.editable-field').forEach(function(field) {
    var fieldName = field.dataset.field;
    var input = field.querySelector('.edit-input');
    if (input) {
      var value = input.value;
      if (fieldName === 'created_dt' && value) {
        // Convert to ISO format
        updates[fieldName] = new Date(value).toISOString();
      } else if (fieldName === 'status') {
        updates[fieldName] = value;
      } else if (fieldName === 'name') {
        updates[fieldName] = value;
      }
    }
  });

  if (Object.keys(updates).length === 0) {
    exitEditMode();
    return;
  }

  fetch('/api/v1/objects/{{ obj.euid }}', {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(updates)
  })
  .then(function(response) {
    if (response.ok) {
      BloomToast.success('Saved', 'Changes saved successfully');
      setTimeout(function() {
        window.location.reload();
      }, 1000);
    } else {
      return response.json().then(function(data) {
        throw new Error(data.detail || 'Failed to save');
      });
    }
  })
  .catch(function(error) {
    BloomToast.error('Error', error.message);
    exitEditMode();
  });
}

// Exit edit mode without saving
function exitEditMode() {
  isEditMode = false;
  var btn = document.getElementById('edit-mode-toggle');
  var text = document.getElementById('edit-mode-text');
  var detailGrid = document.querySelector('.detail-grid');

  btn.classList.remove('active');
  text.textContent = 'Edit';
  detailGrid.classList.remove('edit-mode-active');

  document.querySelectorAll('.editable-field .edit-icon').forEach(function(icon) {
    icon.style.display = 'none';
  });
  document.querySelectorAll('.editable-field .edit-input').forEach(function(input) {
    input.style.display = 'none';
  });
  document.querySelectorAll('.editable-field .display-value').forEach(function(val) {
    val.style.display = 'inline';
  });
}

// Soft delete object
function softDeleteObject(euid) {
  if (!confirm('Are you sure you want to delete this object? This is a soft delete and can be undone.')) {
    return;
  }

  fetch('/api/v1/objects/' + euid, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ is_deleted: true })
  })
  .then(function(response) {
    if (response.ok) {
      BloomToast.success('Deleted', 'Object soft deleted');
      setTimeout(function() {
        window.location.href = '/euid_details?euid=' + euid + '&is_deleted=true';
      }, 1000);
    } else {
      return response.json().then(function(data) {
        throw new Error(data.detail || 'Failed to delete');
      });
    }
  })
  .catch(function(error) {
    BloomToast.error('Error', error.message);
  });
}

// Undelete (restore) object
function undeleteObject(euid) {
  fetch('/api/v1/objects/' + euid, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ is_deleted: false })
  })
  .then(function(response) {
    if (response.ok) {
      BloomToast.success('Restored', 'Object restored');
      setTimeout(function() {
        window.location.href = '/euid_details?euid=' + euid;
      }, 1000);
    } else {
      return response.json().then(function(data) {
        throw new Error(data.detail || 'Failed to restore');
      });
    }
  })
  .catch(function(error) {
    BloomToast.error('Error', error.message);
  });
}

// Toggle JSON edit mode
function toggleJsonEditMode() {
  isJsonEditMode = !isJsonEditMode;
  var jsonDisplay = document.getElementById('json-display');
  var jsonEditor = document.getElementById('json-editor-full');
  var saveButtons = document.getElementById('json-save-buttons');
  var editText = document.getElementById('json-edit-text');
  var editToggle = document.getElementById('json-edit-toggle');

  if (isJsonEditMode) {
    jsonDisplay.style.display = 'none';
    jsonEditor.style.display = 'block';
    saveButtons.style.display = 'block';
    editText.textContent = 'Cancel';
    editToggle.classList.add('active');

    // Initialize editor if not done
    if (!editorFull) {
      editorFull = new JSONEditor(jsonEditor, {
        mode: 'tree',
        modes: ['tree', 'code', 'view'],
        search: true
      });
      editorFull.set({{ obj.json_addl | tojson }});
    }
  } else {
    cancelJsonEdit();
  }
}

// Save full JSON
function saveFullJson() {
  if (!editorFull) return;

  try {
    var jsonData = editorFull.get();

    fetch('/api/v1/objects/{{ obj.euid }}', {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ json_addl: jsonData })
    })
    .then(function(response) {
      if (response.ok) {
        BloomToast.success('Saved', 'JSON saved successfully');
        setTimeout(function() {
          window.location.reload();
        }, 1000);
      } else {
        return response.json().then(function(data) {
          throw new Error(data.detail || 'Failed to save');
        });
      }
    })
    .catch(function(error) {
      BloomToast.error('Error', error.message);
    });
  } catch (e) {
    BloomToast.error('Invalid JSON', e.message);
  }
}

// Cancel JSON edit
function cancelJsonEdit() {
  isJsonEditMode = false;
  var jsonDisplay = document.getElementById('json-display');
  var jsonEditor = document.getElementById('json-editor-full');
  var saveButtons = document.getElementById('json-save-buttons');
  var editText = document.getElementById('json-edit-text');
  var editToggle = document.getElementById('json-edit-toggle');

  jsonDisplay.style.display = 'block';
  jsonEditor.style.display = 'none';
  saveButtons.style.display = 'none';
  editText.textContent = 'Edit';
  editToggle.classList.remove('active');
}

// Initialize JSONEditors on DOMContentLoaded
document.addEventListener('DOMContentLoaded', function() {
  // Properties editor
  var propsContainer = document.getElementById('json-editor-properties');
  if (propsContainer) {
    editorProperties = new JSONEditor(propsContainer, {
      mode: 'tree',
      modes: ['tree', 'code', 'view'],
      search: true
    });
    editorProperties.set({{ jaddl_prop | tojson }});
  }

  // Template properties editor
  var templateContainer = document.getElementById('json-editor-template');
  if (templateContainer) {
    editorTemplate = new JSONEditor(templateContainer, {
      mode: 'tree',
      modes: ['tree', 'code', 'view'],
      search: true
    });
    editorTemplate.set({{ jaddl_controlled_prop | tojson }});
  }
});

// Copy to clipboard utility
function copyToClipboard(text) {
  navigator.clipboard.writeText(text).then(function() {
    BloomToast.success('Copied', 'EUID copied to clipboard');
  }).catch(function() {
    BloomToast.error('Error', 'Failed to copy to clipboard');
  });
}
</script>
{% endblock %}
