{% extends "base.j2" -%}

{%- block append_to_head_tag_section %}
  <link rel="canonical" href="{{ product.absolute_url(request) }}" />
  <title>{{ product.title }}</title>
  <meta property="og:title" content="{{ product.title }}" />
  <meta name="description" content="{{ product.description|truncate(500) }}">
  <meta property="og:description" content="{{ product.description|truncate(500) }}" />
  <meta property="og:type" content="article" />
  <meta property="og:url" content="{{ product.absolute_url(request) }}" />
  <meta property="og:site_name" content="{{ request.shop.name }}" />
  {%- if "thumbnail1" in product.extensions %}
  <meta property="og:image" content="{{ request.shop_cdn_endpoint }}/{{ product.s3_path }}/thumbnail1?ts={{ product.updated_timestamp }}" />
  <meta name="twitter:card" content="summary_large_image" />
  <meta name="twitter:title" content="{{ product.title }}" />
  <meta name="twitter:description" content="{{ product.description|truncate(500) }}" />
  <meta name="twitter:image" content="{{ request.shop_cdn_endpoint }}/{{ product.s3_path }}/thumbnail1?ts={{ product.updated_timestamp }}" />
  {%- endif %}

  {# Removed auto-refresh timer - better UX to let download links expire than interrupt reading #}
{%- endblock append_to_head_tag_section -%}

{%- block call_to_action -%}
{% if request.user and request.user.can_edit_shop(request.shop) %}
<a href="/p/{{ product.id }}/edit" class="product-edit-button mps-button mps-button-small">&#9998; Edit</a>
{% endif %}
{%- endblock call_to_action -%}

{% block content -%}

<section class="two-column{% if request.shop.watch_mode_enabled %} watch-mode{% endif %}" data-signal-product-id="{{ product.id }}" data-signal-shop-id="{{ product.shop_id }}"{% if request.user and request.user.can_edit_shop(request.shop) %} data-signal-is-owner="1"{% endif %}>

{% if request.shop.watch_mode_enabled %}<div class="watch-left" data-watch-product-id="{{ product.id }}"{% if request.user and request.user.can_edit_shop(request.shop) %} data-watch-is-mod="1"{% endif %}>{% endif %}

  <div class="product-images">
    <h1>{{ product.title }}<br/><span class="subtitle-text">sold by <a href="{{ product.shop.absolute_about_url(request) }}" rel="nofollow" class="shop-theme-link-color">{{ product.shop.name }}</a></span></h1>

    {% set video_extensions = ["mp4", "avi", "mov", "wmv", "flv", "mkv", "webm", "m4v"] %}
    {% set audio_extensions = ["mp3", "wav", "ogg", "m4a", "flac", "aac", "opus"] %}
    {% if request.shop.watch_mode_enabled and signed_get_object_url and product.extensions.get("product") in video_extensions %}
      {# Watch mode: direct video render with autoplay #}
      {% if request.popout_player_enabled and product.visibility == 1 and "preview" in product.extensions %}
      {% set watch_video_url = request.shop_cdn_endpoint ~ "/" ~ product.s3_path ~ "/preview" %}
      {% else %}
      {% set watch_video_url = signed_get_object_url %}
      {% endif %}
      <div id="watch-media-container">
        <div class="watch-video-container">
          <video id="watch-video" src="{{ watch_video_url }}" autoplay controls playsinline class="product-main"></video>
          <button class="unmute-overlay">Tap to unmute</button>
        </div>
      </div>
      <div id="watch-countdown" class="watch-countdown js-only" style="display:none">
        <img id="countdown-thumb" class="countdown-thumb" />
        <div class="countdown-text">
          <span id="countdown-title">Up next: ...</span>
          <span id="countdown-number">7</span>
        </div>
        <button id="countdown-play-now" class="mps-button mps-button-blue">Play Now</button>
        <button id="countdown-cancel" class="mps-button">Cancel</button>
      </div>
      <noscript>
        <a href="{{ watch_video_url }}" target="_blank">Open video</a>
      </noscript>
    {% elif request.shop.watch_mode_enabled and signed_get_object_url and product.extensions.get("product") in audio_extensions %}
      {# Watch mode: audio with album art #}
      {% if request.popout_player_enabled and product.visibility == 1 and "preview" in product.extensions %}
      {% set watch_audio_url = request.shop_cdn_endpoint ~ "/" ~ product.s3_path ~ "/preview" %}
      {% else %}
      {% set watch_audio_url = signed_get_object_url %}
      {% endif %}
      <div id="watch-media-container">
        <div class="watch-audio-container">
          {% if "thumbnail1" in product.extensions %}
          <img src="{{ request.shop_cdn_endpoint }}/{{ product.s3_path }}/thumbnail1?ts={{ product.updated_timestamp }}" class="product-main audio-cover" />
          {% endif %}
          <audio id="watch-audio" src="{{ watch_audio_url }}" autoplay controls></audio>
        </div>
      </div>
      <div id="watch-countdown" class="watch-countdown js-only" style="display:none">
        <img id="countdown-thumb" class="countdown-thumb" />
        <div class="countdown-text">
          <span id="countdown-title">Up next: ...</span>
          <span id="countdown-number">7</span>
        </div>
        <button id="countdown-play-now" class="mps-button mps-button-blue">Play Now</button>
        <button id="countdown-cancel" class="mps-button">Cancel</button>
      </div>
      <noscript>
        <a href="{{ watch_audio_url }}" target="_blank">Listen</a>
      </noscript>
    {% elif "thumbnail1" in product.extensions %}
      {% if signed_get_object_url and product.extensions.get("product") in video_extensions %}
      {% if request.popout_player_enabled and product.visibility == 1 and "preview" in product.extensions %}
      {% set preview_url = request.shop_cdn_endpoint ~ "/" ~ product.s3_path ~ "/preview" %}
      <div id="video-container-{{ product.id }}" class="video-thumbnail-container" onclick="playInline(this, '{{ preview_url }}')">
        <img src="{{ request.shop_cdn_endpoint }}/{{ product.s3_path }}/thumbnail1?ts={{ product.updated_timestamp }}" class="product-main" />
        <div class="video-play-overlay"></div>
      </div>
      <noscript>
        <a href="{{ preview_url }}" target="_blank">Open video</a>
      </noscript>
      <div class="video-click-to-play">click ▶ to play</div>
      {% else %}
      <a href="{{ signed_get_object_url }}" target="_blank" class="video-thumbnail-container">
        <img src="{{ request.shop_cdn_endpoint }}/{{ product.s3_path }}/thumbnail1?ts={{ product.updated_timestamp }}" class="product-main" />
        <div class="video-play-overlay"></div>
      </a>
      <div class="video-click-to-play">click &#9654; to play</div>
      {% endif %}
      {% else %}
    <img src="{{ request.shop_cdn_endpoint }}/{{ product.s3_path }}/thumbnail1?ts={{ product.updated_timestamp }}" class="product-main" />
      {% endif %}
    {% endif %}
    {% if request.shop.watch_mode_enabled and product.extensions.get("product") not in video_extensions and product.extensions.get("product") not in audio_extensions %}
    {# Countdown overlay for static content (PDFs, images) #}
    <div id="watch-countdown" class="watch-countdown js-only" style="display:none">
      <img id="countdown-thumb" class="countdown-thumb" />
      <div class="countdown-text">
        <span id="countdown-title">Up next: ...</span>
        <span id="countdown-number">7</span>
      </div>
      <button id="countdown-play-now" class="mps-button mps-button-blue">Play Now</button>
      <button id="countdown-cancel" class="mps-button">Cancel</button>
    </div>
    {% endif %}
    <br/>

    {% for file_key in product.file_thumbnail_keys %}
    {% if file_key in product.s3_key_thumbnails %}
    {% set get_endpoint = request.shop_cdn_endpoint + "/" + product.s3_key_thumbnails[file_key] %}
    <a href="{{ get_endpoint }}" target="_blank"><img src="{{ get_endpoint }}?ts={{ product.updated_timestamp }}" class="product-thumbnail" /></a>
    {% endif %}
    {% endfor %}
  </div>

  <div class="cinema-content-stack">
  <div class="product-description">
    <br/>
    <br/>

    <b>Description</b>
    <section>{{ product.description_html | safe }}</section>

    <br/>
    <br/>

    {% if product.is_bundle %}
      {% if product.products_in_this_bundle %}
      <b>Bundle Contents</b>
      <ul>
      {% for p in product.products_in_this_bundle %}
      <li>
        {{p.title}}
      </li>
      {% endfor %}
      </ul>
      {% endif %}
    {% elif product.has_product_file %}
      <b>File Type</b>
      <br/>
      {{ product.get_content_type("product") }} {{ product_size }}
      <br/>
      Please make sure you have an application to open this file type.
    {% endif %}

    {% if request.shop.show_dates %}
    <div class="product-meta-dates">
      Created {{ product.human_created_timestamp }}{% if product.human_created_timestamp != product.human_updated_timestamp %} · Updated {{ product.human_updated_timestamp }}{% endif %}{% if product.human_view_count %} · <span class="product-view-count">{{ product.human_view_count }}</span>{% endif %}
    </div>
    {% endif %}
  </div>

  <div class="product-comments">
    <br/>
    <br/>

    <!-- Comments Section -->
    {% include 'snippets/comments.j2' %}

    <br/>
    <a href="/" class="product-edit-button mps-button">Back to shop</a>
  </div>
  </div>

{% if request.shop.watch_mode_enabled %}</div>{% endif %}

  <section class="product-right">
  <br/>
  <div class="well">
  <h1>${{ '{:,.2f}'.format(product.price) }}</h1>

  {% if product.is_ready %}

    {% if not product.is_physical %}

      {% if signed_get_object_url is not none %}
        <a href="{{ signed_get_object_url }}" class="product-download-button mps-button" download>&#11123 Download</a>
        <br/>
        <br/>
      {% endif %}
    {% endif %}

    {% if product.is_physical %}
      {# MPS-20 + MPS-21: physical Add To Cart only renders when
         pricing_mode permits direct purchase (modes 0, 2, 4).
         Auction-only (1) and offer-only (3) modes hide it so buyers
         use the bidding or offer flow instead. #}
      {% if product.is_buy_now_allowed %}
        {% set inventory = product.inventories | selectattr('shop_location_id', 'equalto', request.shop_location.id) | first %}
        {% if inventory and inventory.quantity > 0 %}
<form method="POST" action="{{ request.route_url('cart_add_product') }}">
  {% include "snippets/csrf.j2" %}
  <input type="hidden" name="product_id" value="{{ product.id }}">
  <button type="submit" class="product-download-button mps-button">Add To Cart</button>
</form>
        {% else %}
          <button class="product-download-button mps-button sold-out-button" disabled>Sold Out</button>
          {% if request.shop.shop_locations.all()|length > 1 %}
            <p>This item is sold out at this location.
            <br> You can <a href="{{ request.route_url('shop_locations', shop_id=request.shop.id, _query={'next': request.url}) }}">switch shop locations</a> to check availability.</p>
          {% endif %}
        {% endif %}
      {% endif %}
    {% else %}
{% if product.is_buy_now_allowed %}
<form method="POST" action="{{ request.route_url('cart_add_product') }}">
  {% include "snippets/csrf.j2" %}
  <input type="hidden" name="product_id" value="{{ product.id }}">
  <button type="submit" class="product-download-button mps-button">Add To Cart</button>
</form>
{% endif %}
    {% endif %}

    {# MPS-20: View Auction link when product is in auction mode. #}
    {% if product.is_auction and product.auction %}
    <p style="margin-top: var(--space-3)">
      <a href="/a/{{ product.auction.uuid_str }}" class="mps-button mps-button-blue">
        View live auction &rarr;
      </a>
    </p>
    {% endif %}

    {# MPS-21: Make Offer button when offers are allowed for this product. #}
    {% if product.offers_allowed and request.user and request.user.authenticated and request.user not in product.shop.owners %}
    <details style="margin-top: var(--space-3)">
      <summary class="mps-button">Make an offer</summary>
      <form method="POST" action="/p/{{ product.id }}/offer" class="product-offer-form">
        {% include "snippets/csrf.j2" %}
        <label for="offer_amount">Your offer (USD)</label>
        <input type="number" step="0.01" min="0.01" name="amount" id="offer_amount" required />
        <input type="text" name="message" placeholder="Optional message" />
        <input type="submit" class="mps-submit" value="Submit Offer" />
      </form>
    </details>
    {% elif product.offers_allowed and (not request.user or not request.user.authenticated) %}
    <p style="margin-top: var(--space-3)">
      <a href="/join-or-log-in?next={{ request.path | urlencode }}" class="mps-button">
        Log in to make an offer
      </a>
    </p>
    {% elif product.offers_allowed and request.user and request.user in product.shop.owners %}
    <p style="margin-top: var(--space-3); color: var(--color-text-muted, #888); font-size: 0.9em;">
      &#10003; Offers enabled &mdash; buyers see a "Make an offer" button here.
      You can't offer on your own product.
    </p>
    {% endif %}
    {% if product.offers_allowed %}
    <script src="/static/js/offer.js?v={{ request.git_hash }}"></script>
    {% endif %}

    <br/>
    {% if (not request.user or not request.user.authenticated) and signed_get_object_url is none %}
    <br/>
    Already purchased? <a href="/join-or-log-in">log in</a>
    <br/>
    <br/>
    <br/>
    {% endif %}

    {% if "preview" in product.extensions %}
      <a href="{{ request.shop_cdn_endpoint }}/{{ product.s3_path }}/preview" target="_blank" class="product-preview-button mps-button">▶ Play Preview</a>
      <br/>
    {% endif %}

  {% else %}

  <br>
  This product is not ready for sale yet.

  {% endif %}
  </div>

  {% if shop.comments_enabled %}
  <a href="#comments" class="product-comments-link">Comments ({{ product.public_comment_count }})</a>
  {% endif %}

  {% if price_history | length > 1 %}
  <details class="price-history-details">
    <summary>Price History ({{ price_history | length }})</summary>
    <div class="analytics-table-wrap">
      <table class="analytics-table">
        <thead>
          <tr>
            <th>Price</th>
            <th>When</th>
          </tr>
        </thead>
        <tbody>
          {% for ph in price_history %}
          <tr{% if ph.is_current %} class="price-history-current"{% endif %}>
            <td>{{ ph.price_formatted }}</td>
            <td title="{{ ph.datetime }}">{{ ph.ago }}</td>
          </tr>
          {% endfor %}
        </tbody>
      </table>
    </div>
  </details>
  {% endif %}

  <div id="watch-queue" class="js-only" style="display:none">
    <h4>Queue</h4>
    <div id="queue-items"></div>
  </div>
  {% include 'snippets/related_content.j2' %}

  </section>

</section>

<script>
// Replace thumbnail with inline video player
function playInline(container, videoUrl) {
  // Create video element
  const video = document.createElement('video');
  video.src = videoUrl;
  video.controls = true;
  video.autoplay = true;
  video.className = 'product-main';
  video.style.maxWidth = '100%';

  // Replace container content with video
  container.innerHTML = '';
  container.onclick = null;
  container.appendChild(video);
}
</script>
{% if request.shop.watch_mode_enabled %}
<script src="/static/js/watch.js"></script>
{% endif %}
<script src="/static/js/signals.js"></script>

{%- endblock -%}
