{% extends "base.j2" -%}

{%- block call_to_action -%}
<section class="edit-status-bar">
  {% if product.visibility == 1 %}
    <span class="edit-status-pill edit-status-pill-public">Public</span>
  {% elif product.visibility == 2 %}
    <span class="edit-status-pill edit-status-pill-unlisted">Unlisted</span>
  {% else %}
    <span class="edit-status-pill edit-status-pill-private">Private</span>
  {% endif %}

  {% if product.is_ready %}
    <span class="edit-status-pill edit-status-pill-ready">&#10003; Ready to sell</span>
  {% else %}
    <span class="edit-status-pill edit-status-pill-incomplete">&#9888; Missing required files</span>
  {% endif %}

  {% if product.is_sellable %}
    <span class="edit-status-pill" style="background: var(--color-text-muted, #888);">${{ '{:.2f}'.format(price) }}</span>
  {% endif %}
</section>
<p class="edit-permanent-link">permanent link: <a href="{{ product.absolute_url(request) }}">{{ product.absolute_url(request) }}</a></p>
{%- endblock call_to_action -%}

{% block content -%}

{% set video_extensions = ["mp4", "avi", "mov", "wmv", "flv", "mkv", "webm", "m4v"] %}
{% set audio_extensions = ["mp3", "wav", "ogg", "m4a", "flac", "aac", "opus"] %}
{% set image_extensions = ["jpg", "jpeg", "png", "gif", "webp", "svg", "bmp", "ico"] %}

<div class="edit-page">

<section class="upload-product-and-preview well2">

  {% if product.is_bundle %}

  <h3>
    <span class="edit-card-icon">&#128230;</span>
    Product IDs or URLs to include in this bundle
  </h3>

  <form method="post" action="/p/{{ product.id }}/bundle/edit" onsubmit="submit.disabled = true; return true;">
    <textarea
        name        = "bundle-data"
        class       = "mps-bundle-data"
        placeholder = "Product IDs or URLs to include in this bundle."
        required /></textarea>
    <input type="submit" name="submit" class="mps-submit" value="Add to bundle" />
  </form>

  <br>

    {% if product.products_in_this_bundle %}
    <ul>
    {% for p in product.products_in_this_bundle %}
    <li>
      <form method="post" action="/p/{{ product.id }}/bundle/remove/{{ p.id }}" onsubmit="submit.disabled = true; return true;">
      {{p.title}}
      <input type="submit" name="submit" class="mps-submit remove-button-small" value="remove"/>
      </form>
    </li>
    <br>
    {% endfor %}
    </ul>
    {% endif %}

  {% elif product.is_physical %}

  <h3>
    <span class="edit-card-icon">&#128230;</span>
    Inventory Management
  </h3>

  <form method="post" action="/p/{{ product.id }}/inventory/edit" onsubmit="submit.disabled = true; return true;">
    <table>
      <thead>
        <tr>
          <th>Location</th>
          <th>Quantity</th>
        </tr>
      </thead>
      <tbody>
        {% for location in locations %}
        <tr>
          <td>{{ location.name }}</td>
          <td>
            <input
              type="number"
              name="inventory_{{ location.id }}"
              value="{{ inventories[location.id] if location.id in inventories else 0 }}"
              min="0"
              required
            />
          </td>
        </tr>
        {% endfor %}
      </tbody>
    </table>
    <input type="submit" name="submit" class="mps-submit" value="Update Inventory" />
  </form>

  {% else %}

  <h3>
    <span class="edit-card-icon">&#128193;</span>
    Upload or Replace {% if product.is_sellable %}Product{% else %}Content{% endif %} File
  </h3>

  People may download this file{% if product.is_sellable %} after making a purchase{% endif %}.

  <p class="file-meta total-capacity">
    <span class="file-meta-item">Total capacity: {{ product.human_total_file_bytes }}</span>
  </p>

  <br>

  {% if "product" in product.originals %}
  <p class="bold-text">Current File: {{ product.originals["product"] }}</p>
  <p class="file-meta">
    <span class="file-meta-item">File Type: {{ product.extensions.get("product", "unknown") }}</span>
    <span class="file-meta-item">File Size: {{ product.human_file_bytes("product") }}</span>
  </p>

  {% set ext = product.extensions.get("product", "") %}
  {% if signed_product_url %}
    {% if ext in video_extensions %}
    <video src="{{ signed_product_url }}" controls playsinline class="edit-media-preview"></video>
    {% elif ext in audio_extensions %}
    <audio src="{{ signed_product_url }}" controls></audio>
    {% elif ext == "pdf" %}
    <iframe src="{{ signed_product_url }}" class="edit-pdf-preview"></iframe>
    {% elif ext in image_extensions %}
    <img src="{{ signed_product_url }}" class="edit-media-preview" />
    {% endif %}
  {% endif %}

  {% endif %}

  {% set signed_post = signed_posts["product"] %}
  <form method="post" action="{{ signed_post["url"] }}" enctype="multipart/form-data" onsubmit="submit.disabled = true; return true;">
      {% for field_name, field_value in signed_post["fields"].items() %}
      <input type="hidden" name="{{ field_name }}" value="{{ field_value }}" />
      {% endfor %}
      <input type="file" name="file" class="file-input" /> <br />
      <input type="submit" name="submit" class="mps-upload" value="Upload Product" />
  </form>


  {% endif %}

</section>

{# Preview file: its own card, sits in the right column of the edit grid. #}
{% if not product.is_bundle and not product.is_physical and product.is_sellable %}
<section class="upload-preview well2">
  <h3>
    <span class="edit-card-icon">&#128250;</span>
    Upload or Replace Preview File
  </h3>

  <p>People may download this file before making a purchase.</p>

  {% if "preview" in product.originals %}
  <p class="bold-text">Current File: {{ product.originals["preview"] }}</p>
  <p class="file-meta">
    <span class="file-meta-item">File Type: {{ product.extensions.get("preview", "unknown") }}</span>
    <span class="file-meta-item">File Size: {{ product.human_file_bytes("preview") }}</span>
  </p>

  {% set preview_ext = product.extensions.get("preview", "") %}
  {% set preview_url = request.shop_cdn_endpoint ~ "/" ~ product.s3_path ~ "/preview?ts=" ~ product.updated_timestamp %}
  {% if preview_ext in video_extensions %}
    <video src="{{ preview_url }}" controls playsinline class="edit-media-preview"></video>
  {% elif preview_ext in audio_extensions %}
    <audio src="{{ preview_url }}" controls></audio>
  {% elif preview_ext == "pdf" %}
    <iframe src="{{ preview_url }}" class="edit-pdf-preview"></iframe>
  {% elif preview_ext in image_extensions %}
    <img src="{{ preview_url }}" class="edit-media-preview" />
  {% endif %}

  {% endif %}

  {% set signed_post = signed_posts["preview"] %}
  <form method="post" action="{{ signed_post["url"] }}" enctype="multipart/form-data" onsubmit="submit.disabled = true; return true;">
      {% for field_name, field_value in signed_post["fields"].items() %}
      <input type="hidden" name="{{ field_name }}" value="{{ field_value }}" />
      {% endfor %}
      <br/>
      <input type="file" name="file" class="file-input" /> <br />
      <input type="submit" name="submit" class="mps-upload" value="Upload Preview" />
  </form>
</section>
{% endif %}

<section class="upload-thumbnails well2 edit-card-full">

<div class="upload-thumbnails-header">
  <h3>
    <span class="edit-card-icon">&#127912;</span>
    Upload or Replace Thumbnail Files
  </h3>
  <p class="upload-thumbnails-hint">
    Your cover (<code>thumbnail1</code>) will show up on search pages.
  </p>
</div>

{% set s3_key_thumbnails = product.s3_key_thumbnails %}

<div class="upload-thumbnails-grid">

{% for thumbnail_key in product.file_thumbnail_keys %}

  <div class="upload-thumbnail-item">

  {% if thumbnail_key in s3_key_thumbnails %}
  {% set get_endpoint = request.shop_cdn_endpoint ~ "/" ~ s3_key_thumbnails[thumbnail_key] %}
  {% set thumb_ext = product.extensions.get(thumbnail_key, "") %}
  {% if thumb_ext in video_extensions %}
    <video src="{{ get_endpoint }}?ts={{ product.updated_timestamp }}" controls playsinline class="edit-media-preview"></video>
  {% elif thumb_ext in audio_extensions %}
    <audio src="{{ get_endpoint }}?ts={{ product.updated_timestamp }}" controls></audio>
  {% elif thumb_ext == "pdf" %}
    <iframe src="{{ get_endpoint }}?ts={{ product.updated_timestamp }}" class="edit-pdf-preview"></iframe>
  {% else %}
    <a href="{{ get_endpoint }}?ts={{ product.updated_timestamp }}">
      <img src="{{ get_endpoint }}?ts={{ product.updated_timestamp }}" class="edit-media-preview" />
    </a>
  {% endif %}
  {% endif %}

  <h4 class="thumbnail-label">{{ thumbnail_key }}</h4>

  {% if thumbnail_key in product.originals %}
  <p class="bold-text">Current File: {{ product.originals[thumbnail_key] }}</p>
  <p class="file-meta">
    <span class="file-meta-item">File Type: {{ product.extensions.get(thumbnail_key, "unknown") }}</span>
    <span class="file-meta-item">File Size: {{ product.human_file_bytes(thumbnail_key) }}</span>
  </p>
  {% endif %}

  {% set signed_post = signed_posts[thumbnail_key] %}
  <form method="post" action="{{ signed_post["url"] }}" enctype="multipart/form-data" onsubmit="submit.disabled = true; return true;">
      {% for field_name, field_value in signed_post["fields"].items() %}
      <input type="hidden" name="{{ field_name }}" value="{{ field_value }}" />
      {% endfor %}
      <input type="file" name="file" class="file-input" /> <br />
      <input type="submit" name="submit" class="mps-upload" value="Upload {{ thumbnail_key }}" />
  </form>

  <hr/>

  <br />

  </div>

{% endfor %}

</div>
</section>

<section class="product-title-and-description well2 edit-card-full">
  <form method="post" action="{{ product.absolute_edit_url(request) }}" onsubmit="submit.disabled = true; return true;">
  <h3>
    <span class="edit-card-icon">&#9998;</span>
    Edit Title, Description, or Visibility
  </h3>

    <label for="title_input">Title</label>
    <input
        name        = "title"
        type        = "text"
        id          = "title_input"
        class       = "mps-product-title"
        value       = "{{ title }}"
        placeholder = "Product Title"
        required />

    <br />
    <br />

    <label for="description_input">
      Description
      <a href="{{ product.absolute_edit_url(request, subject='description') }}">(advanced editor)</a>
    </label>
    <small class="form-help">Supports Markdown and some HTML.</small>
    <textarea
        name        = "description"
        id          = "description_input"
        class       = "mps-product-description"
        placeholder = "Product Description"
        required />{{ description }}</textarea>

    <br />
    <br />

  {% if product.is_sellable %}
    <label for="price_input">Price</label>
    <input
        name        = "price"
        type        = "text"
        id          = "price_input"
        class       = "mps-product-price"
        value       = "{{ '%0.2f' % price }}"
        placeholder = "Product Price"
        required />

    <br />
    <br />

    {# MPS-20 + MPS-21: pricing mode #}
    <fieldset>
      <legend>Pricing mode</legend>
      <label style="display:block">
        <input type="radio" name="pricing_mode" value="0"
               {% if product.pricing_mode == 0 %}checked{% endif %} />
        Fixed price (today's behavior)
      </label>
      <label style="display:block">
        <input type="radio" name="pricing_mode" value="1"
               {% if product.pricing_mode == 1 %}checked{% endif %} />
        Auction
      </label>
      <label style="display:block">
        <input type="radio" name="pricing_mode" value="2"
               {% if product.pricing_mode == 2 %}checked{% endif %} />
        Auction with buy-now
      </label>
      <label style="display:block">
        <input type="radio" name="pricing_mode" value="3"
               {% if product.pricing_mode == 3 %}checked{% endif %} />
        Make an offer (negotiation)
      </label>
      <label style="display:block">
        <input type="radio" name="pricing_mode" value="4"
               {% if product.pricing_mode == 4 %}checked{% endif %} />
        Make an offer with buy-now
      </label>
    </fieldset>

    <br />

    {# MPS-21: per-product offer override #}
    {% if product.is_offer_mode %}
    <fieldset>
      <legend>Allow offers (override shop default)</legend>
      <label style="display:block">
        <input type="radio" name="allow_offers" value="inherit"
               {% if product.allow_offers is none %}checked{% endif %} />
        Use shop default
        ({% if request.shop.offer_enabled %}enabled{% else %}disabled{% endif %})
      </label>
      <label style="display:block">
        <input type="radio" name="allow_offers" value="yes"
               {% if product.allow_offers == True %}checked{% endif %} />
        Yes — accept offers on this product
      </label>
      <label style="display:block">
        <input type="radio" name="allow_offers" value="no"
               {% if product.allow_offers == False %}checked{% endif %} />
        No — block offers on this product
      </label>
    </fieldset>

    <br />
    {% endif %}

    {% if product.auction %}
    <fieldset>
      <legend>Auction settings</legend>

      <p>
        <a href="/a/{{ product.auction.uuid_str }}" class="mps-button">View live auction page</a>
        <small>(state: {{ product.auction.state_human }})</small>
      </p>

      {# Owner controls — only editable while auction is in DRAFT state.
         Once SCHEDULED or ACTIVE, fields lock to prevent rules-changes
         mid-flight (preserves bidder trust). #}
      {% set locked = product.auction.state > 0 %}

      <label for="auction_quantity">Quantity (units in this auction)</label>
      <input type="number" name="auction_quantity" id="auction_quantity"
             min="1" step="1" required
             value="{{ product.auction.quantity }}"
             {% if locked or not product.is_physical %}disabled{% endif %} />
      <small>
        {% if not product.is_physical -%}
          Digital products always sell 1 unit per auction.
        {%- elif locked -%}
          Locked once auction is scheduled.
        {%- else -%}
          How many units of inventory to lot in this auction. Other units stay at list price (mode 2).
        {%- endif %}
      </small>

      <br /><br />

      <label for="auction_start">Start time</label>
      <input type="datetime-local" name="auction_start" id="auction_start"
             value="{{ auction_start_iso }}"
             {% if locked %}disabled{% endif %} />

      <br /><br />

      <label for="auction_end">End time</label>
      <input type="datetime-local" name="auction_end" id="auction_end"
             value="{{ auction_end_iso }}"
             {% if locked %}disabled{% endif %} />

      <br /><br />

      <label for="auction_start_price">Start price ($)</label>
      <input type="number" name="auction_start_price" id="auction_start_price"
             min="0" step="0.01"
             value="{{ '%.2f'|format(product.auction.start_price) }}"
             {% if locked %}disabled{% endif %} />

      <br /><br />

      <label for="auction_reserve_price">Reserve price ($, optional)</label>
      <input type="number" name="auction_reserve_price" id="auction_reserve_price"
             min="0" step="0.01"
             value="{% if product.auction.reserve_price_in_cents %}{{ '%.2f'|format(product.auction.reserve_price) }}{% endif %}"
             placeholder="No reserve"
             {% if locked %}disabled{% endif %} />
      <small>Hidden from bidders. Auction with no high bid above reserve = no winner.</small>

      <br /><br />

      {% if product.pricing_mode == 2 or product.pricing_mode == 4 %}
      <label for="auction_buy_now_price">Buy-now price ($, optional)</label>
      <input type="number" name="auction_buy_now_price" id="auction_buy_now_price"
             min="0" step="0.01"
             value="{% if product.auction.buy_now_price_in_cents %}{{ '%.2f'|format(product.auction.buy_now_price) }}{% endif %}"
             placeholder="No buy-now"
             {% if locked %}disabled{% endif %} />
      <small>Lets a buyer end the auction immediately at this price.</small>

      <br /><br />
      {% endif %}

      <label for="auction_increment">Bid increment ($)</label>
      <input type="number" name="auction_increment" id="auction_increment"
             min="0.01" step="0.01"
             value="{{ '%.2f'|format(product.auction.bid_increment) }}"
             {% if locked %}disabled{% endif %} />

      <br /><br />

      <label for="auction_soft_close">Soft-close window (seconds)</label>
      <input type="number" name="auction_soft_close" id="auction_soft_close"
             min="0" step="1"
             value="{{ product.auction.soft_close_seconds }}"
             {% if locked %}disabled{% endif %} />
      <small>A bid placed within this window of the end time extends the end by the same window.</small>

      <br /><br />

      {% if not locked %}
      <label>
        <input type="checkbox" name="auction_schedule" value="on" />
        Schedule this auction (lock fields and move to SCHEDULED state)
      </label>
      <br /><br />
      {% endif %}
    </fieldset>

    <br />
    {% endif %}
  {% endif %}

    <style>
      label.visibility_radio {
        display: inline;
      }
    </style>

    <fieldset>

    <legend>Visibility</legend>

    <input type="radio" name="visibility" id="visibility_public" value="1" {% if visibility == 1 %}checked{% endif %} />
    <label class="visibility_radio" for="visibility_public">Public</label>

    <input type="radio" name="visibility" id="visibility_unlisted" value="2" {% if visibility == 2 %}checked{% endif %} />
    <label class="visibility_radio" for="visibility_unlisted">Unlisted</label>

    <input type="radio" name="visibility" id="visibility_private" value="0" {% if visibility == 0 %}checked{% endif %} />
    <label class="visibility_radio" for="visibility_private">Private</label>

    </fieldset>

    <br />
    <br />

    {% if request.torrent_enabled and torrent_enabled %}
    <label>Torrent Distribution</label>

    {% if torrent_seeded_but_private %}
    <p style="color:var(--color-warning,#b45309);background:var(--color-warning-subtle,#fffbeb);border:1px solid currentColor;border-radius:var(--radius-md);padding:var(--space-3);margin:.5rem 0">
      <strong>Active torrent — file cannot be recalled.</strong>
      This product is no longer public, so the magnet link is hidden from visitors.
      However, the file is already seeded in the BitTorrent network and will remain
      available to anyone who already has the magnet link.
    </p>
    {% endif %}

    <label style="font-weight:normal;display:grid;grid-template-columns:auto 1fr;align-items:center;gap:.5rem;margin:.25rem 0">
      <input type="checkbox" name="torrent_opt_in"
             {% if torrent_opt_in %}checked{% endif %} />
      Seed this product via BitTorrent
    </label>
    <p style="color:var(--color-text-muted,#888);font-size:.85em;margin:.25rem 0 .75rem">
      Once seeded, the file persists in the BitTorrent network permanently —
      it cannot be recalled even if you disable this or make the product private.
      Only enable for files you intend to distribute publicly forever.
    </p>

    {% if torrent_magnet_link %}
      <div style="display:grid;grid-template-columns:1fr auto auto auto;gap:.5rem;align-items:center">
        <input type="text" id="torrent_magnet_link_display"
               value="{{ torrent_magnet_link }}" readonly
               class="mps-text-input" style="min-width:0;color:#888" />
        <button type="button"
                onclick="navigator.clipboard.writeText(document.getElementById('torrent_magnet_link_display').value)"
                class="mps-button" style="white-space:nowrap">Copy Magnet</button>
        <a href="{{ torrent_magnet_link }}" class="mps-button" style="white-space:nowrap">&#9697; Open</a>
        {% if torrent_file_url %}
        <a href="{{ torrent_file_url }}" class="mps-button" style="white-space:nowrap" download>&#8615; .torrent</a>
        {% else %}
        <span></span>
        {% endif %}
      </div>
    {% elif torrent_opt_in %}
      <p style="color:#888;margin:.25rem 0">
        Seeding enabled — magnet link will be generated when you upload the product file.
      </p>
    {% else %}
      <p style="color:#888;margin:.25rem 0">
        Enable seeding above, then upload the product file to generate a magnet link.
      </p>
    {% endif %}

    <br />
    {% endif %}

    <input type="submit" name="submit" class="mps-submit" value="Save Settings" />
  </form>
</section>

{% if price_history | length > 1 %}
<section class="price-history well2">
  <h3>Price History</h3>
  <div class="analytics-table-wrap">
    <table class="analytics-table">
      <thead>
        <tr>
          <th>Price</th>
          <th>When</th>
          <th>Date</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>{{ ph.ago }}</td>
          <td>{{ ph.datetime }}</td>
        </tr>
        {% endfor %}
      </tbody>
    </table>
  </div>
</section>
{% endif %}

</div>

{%- endblock -%}
