{% extends "base.j2" -%}

{% block content -%}

<section class="one-column">
  <section class="shop-settings well">

    <h3>Shop Settings</h3>

    <form method="post" action="/s/{{ request.shop.id }}/settings" onsubmit="submit.disabled = true; return true;">
      <input type="hidden" name="form_section" value="shop-settings" />
  
      <label for="name_input">Shop Name</label>
      <input
          name        = "name"
          type        = "text"
          id          = "name_input"
          class       = "mps-shop-name"
          value       = "{{ name }}"
          placeholder = "Shop Name"
          required />
  
      <br />
      <br />
  
  
      <label for="phone_number_input">Phone Number</label>
      <input
          name        = "phone_number"
          type        = "tel"
          id          = "phone_number_input"
          class       = "mps-phone-number"
          value       = "{{ phone_number }}"
          placeholder = "Phone Number"
          required />
  
  
      <br />
      <br />
  
      <label for="billing_address_input">Billing Address</label>
      <textarea
          name        = "billing_address"
          id          = "billing_address_input"
          class       = "mps-billing-address"
          placeholder = "Billing Address"
          required />{{ billing_address }}</textarea>
  
      <br />
      <br />
  
      <label for="description_input">Shop Description</label>
      <textarea
          name        = "description"
          id          = "description_input"
          class       = "mps-shop-description"
          placeholder = "Shop Description"
          required />{{ description }}</textarea>
  
      <br />
      <br />

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

    </section>
</section>

<br />
<br />

<section class="one-column">
  <section class="shop-settings well">

    <h3>Integration Settings</h3>

    <form method="post" action="/s/{{ request.shop.id }}/settings" onsubmit="submit.disabled = true; return true;">
      <input type="hidden" name="form_section" value="integration-settings" />

      <label for="domain_name_input">Custom Shop Domain Name</label>
      <input
          name        = "domain_name"
          type        = "text"
          id          = "domain_name_input"
          class       = "mps-shop-name"
          value       = "{% if domain_name %}{{ domain_name }}{% endif %}"
          placeholder = "Domain Name"
          />

      <br />
      <br />

      <label for="plausible_domain_name_input">Plausible Analytics Domain Name (optional)</label>
      <input
          name        = "plausible_domain_name"
          type        = "text"
          id          = "plausible_domain_name"
          class       = "mps-shop-name"
          value       = "{% if plausible_domain_name %}{{ plausible_domain_name }}{% endif %}"
          placeholder = "ex: plausible.io"
          />

      <br />
      <br />

      <label for="google_site_verification_input">Google Site Verification Code (optional)</label>
      <input
          name        = "google_site_verification"
          type        = "text"
          id          = "google_site_verification_input"
          class       = "full-width-input"
          value       = "{% if google_site_verification %}{{ google_site_verification }}{% endif %}"
          placeholder = "ex: abc123xyz..."
          />
      <br />
      <small>Paste the verification code from Google Search Console (just the code, not the full meta tag)</small>

      <br />
      <br />

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

      <br />
      <br />

    </form>
     
  </section>
</section>

<br />
<br />

{% if request.stripe_globally_enabled %}
<section class="one-column">
  <section class="shop-settings well">

    <h3>Stripe Settings 💳</h3>

    <form method="post" action="/s/{{ request.shop.id }}/settings" onsubmit="submit.disabled = true; return true;">
      <input type="hidden" name="form_section" value="stripe-settings" />

      <details class="api-key-details">
      <summary class="toggle-summary">Show Public & Secret Stripe API Keys</summary>

      <div class="api-key-fields">

      <br />

      <label for="stripe_public_api_key_input">Stripe Public API Key</label>
      <input
          name        = "stripe_public_api_key"
          type        = "text"
          id          = "stripe_public_api_key"
          class       = "full-width-input{% if not request.shop.stripe_enabled %} disabled-input{% endif %}"
          value       = "{% if stripe_public_api_key %}{{ stripe_public_api_key }}{% endif %}"
          placeholder = "Stripe Public API Key (pk)"
          {% if not request.shop.stripe_enabled %}readonly{% endif %}
          />

      <br />
      <br />

      <label for="stripe_secret_api_key_input">Stripe Secret API Key</label>
      <input
          name        = "stripe_secret_api_key"
          type        = "text"
          id          = "stripe_secret_api_key"
          class       = "full-width-input{% if not request.shop.stripe_enabled %} disabled-input{% endif %}"
          value       = "{% if stripe_secret_api_key %}{{ stripe_secret_api_key }}{% endif %}"
          placeholder = "Stripe Secret API Key (sk)"
          {% if not request.shop.stripe_enabled %}readonly{% endif %}
          />

      <br />
      <br />

      {% if request.shop.stripe_enabled %}
        <small class="success-indicator">✓ Stripe configured and ready to accept credit card payments</small>
        <br />
        <br />
        <input type="submit" name="submit" class="mps-submit" value="Save Stripe Settings" />
        <input type="submit" name="disable_stripe" class="payment-toggle-button disable" value="Disable Stripe" />
      {% else %}
        <small class="error-indicator">✗ Stripe payments are currently disabled</small>
        <br />
        <br />
        <small class="status-message">Your API keys are preserved but customers cannot select credit card as a payment method.</small>
        <br />
        <br />
        <input type="submit" name="submit" class="payment-toggle-button enable" value="Re-enable Stripe" />
        <small class="status-message">Re-enable Stripe payments to update your API keys</small>
      {% endif %}

      </div>
      </details>

      <br />
      <br />

    </form>

  </section>
</section>

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

{% if request.paypal_globally_enabled %}
<section class="one-column">
  <section class="shop-settings well">

    <h3>PayPal Settings 💰</h3>

    <form method="post" action="/s/{{ request.shop.id }}/settings" onsubmit="submit.disabled = true; return true;">
      <input type="hidden" name="form_section" value="paypal-settings" />

      <details class="api-key-details">
      <summary class="toggle-summary">Show PayPal Client ID & Secret API Keys</summary>

      <div class="api-key-fields">

      <br />

      <label for="paypal_client_id_input">PayPal Client ID</label>
      <input
          name        = "paypal_client_id"
          type        = "text"
          id          = "paypal_client_id"
          class       = "full-width-input{% if not request.shop.paypal_enabled %} disabled-input{% endif %}"
          value       = "{% if paypal_client_id %}{{ paypal_client_id }}{% endif %}"
          placeholder = "PayPal Client ID (from developer.paypal.com)"
          {% if not request.shop.paypal_enabled %}readonly{% endif %}
          />

      <br />
      <br />

      <label for="paypal_secret_input">PayPal Secret Key</label>
      <input
          name        = "paypal_secret"
          type        = "text"
          id          = "paypal_secret"
          class       = "full-width-input{% if not request.shop.paypal_enabled %} disabled-input{% endif %}"
          value       = "{% if paypal_secret %}{{ paypal_secret }}{% endif %}"
          placeholder = "PayPal Secret Key (from developer.paypal.com)"
          {% if not request.shop.paypal_enabled %}readonly{% endif %}
          />

      <br />
      <br />

      {% if request.shop.paypal_enabled %}
        <small class="success-indicator">✓ PayPal configured and ready to accept PayPal payments</small>
        <br />
        <br />
        <input type="submit" name="submit" class="mps-submit" value="Save PayPal Settings" />
        <input type="submit" name="disable_paypal" class="payment-toggle-button disable" value="Disable PayPal" />
      {% else %}
        <small class="error-indicator">✗ PayPal payments are currently disabled</small>
        <br />
        <br />
        <small class="status-message">Your API keys are preserved but customers cannot select PayPal as a payment method.</small>
        <br />
        <br />
        <input type="submit" name="submit" class="payment-toggle-button enable" value="Re-enable PayPal" />
        <small class="status-message">Re-enable PayPal payments to update your API keys</small>
      {% endif %}

      </div>
      </details>

      <br />
      <br />

    </form>

  </section>
</section>

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

{% if request.adyen_globally_enabled %}
<section class="one-column">
  <section class="shop-settings well">

    <h3>Adyen Settings 💳</h3>

    <form method="post" action="/s/{{ request.shop.id }}/settings" onsubmit="submit.disabled = true; return true;">
      <input type="hidden" name="form_section" value="adyen-settings" />

      <details class="api-key-details">
      <summary class="toggle-summary">Show Adyen API Keys</summary>

      <div class="api-key-fields">

      <br />

      <label for="adyen_api_key_input">Adyen API Key</label>
      <input
          name        = "adyen_api_key"
          type        = "text"
          id          = "adyen_api_key"
          class       = "mps-adyen-api-key{% if not adyen_enabled %} disabled-input{% endif %}"
          value       = "{% if adyen_api_key %}{{ adyen_api_key }}{% endif %}"
          placeholder = "Adyen API Key (from Adyen dashboard)"
          {% if not adyen_enabled %}readonly{% endif %}
          />

      <br />
      <br />

      <label for="adyen_merchant_account_input">Adyen Merchant Account</label>
      <input
          name        = "adyen_merchant_account"
          type        = "text"
          id          = "adyen_merchant_account"
          class       = "mps-adyen-merchant-account{% if not adyen_enabled %} disabled-input{% endif %}"
          value       = "{% if adyen_merchant_account %}{{ adyen_merchant_account }}{% endif %}"
          placeholder = "Adyen Merchant Account"
          {% if not adyen_enabled %}readonly{% endif %}
          />

      <br />
      <br />

      <label for="adyen_client_key_input">Adyen Client Key</label>
      <input
          name        = "adyen_client_key"
          type        = "text"
          id          = "adyen_client_key"
          class       = "mps-adyen-client-key{% if not adyen_enabled %} disabled-input{% endif %}"
          value       = "{% if adyen_client_key %}{{ adyen_client_key }}{% endif %}"
          placeholder = "Adyen Client Key (for Drop-in/Components)"
          {% if not adyen_enabled %}readonly{% endif %}
          />

      <br />
      <br />

      <label for="adyen_hmac_key_input">Adyen HMAC Key (for webhooks)</label>
      <input
          name        = "adyen_hmac_key"
          type        = "text"
          id          = "adyen_hmac_key"
          class       = "mps-adyen-hmac-key{% if not adyen_enabled %} disabled-input{% endif %}"
          value       = "{% if adyen_hmac_key %}{{ adyen_hmac_key }}{% endif %}"
          placeholder = "Adyen HMAC Key (for webhook verification)"
          {% if not adyen_enabled %}readonly{% endif %}
          />

      <br />
      <br />

      {% if adyen_enabled %}
        <small class="success-indicator">✓ Adyen configured and ready to accept payments</small>
        <br />
        <br />
        <input type="submit" name="submit" class="mps-submit" value="Save Adyen Settings" />
        <input type="submit" name="disable_adyen" class="payment-toggle-button disable" value="Disable Adyen" />
      {% else %}
        <small class="error-indicator">✗ Adyen payments are currently disabled</small>
        <br />
        <br />
        <small class="status-message">Your API keys are preserved but customers cannot select Adyen as a payment method.</small>
        <br />
        <br />
        <input type="submit" name="submit" class="payment-toggle-button enable" value="Re-enable Adyen" />
        <small class="status-message">Re-enable Adyen payments to update your API keys</small>
      {% endif %}

      </div>
      </details>

      <br />
      <br />

    </form>

  </section>
</section>

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

{% if request.karaoke_enabled %}
<section class="one-column">
  <section class="shop-settings well">

    <h3>Unsandbox Settings 🎤</h3>
    <p>API keys for vocal isolation (karaoke mode). Media is processed in zerotrust containers — no network, destroyed after use.</p>

    <form method="post" action="/s/{{ request.shop.id }}/settings" onsubmit="submit.disabled = true; return true;">
      <input type="hidden" name="form_section" value="unsandbox-settings" />

      <details class="api-key-details">
      <summary class="toggle-summary">Show Unsandbox API Keys</summary>

      <div class="api-key-fields">

      <br />

      <label for="unsandbox_public_key_input">Public Key</label>
      <input
          name        = "unsandbox_public_key"
          type        = "text"
          id          = "unsandbox_public_key_input"
          class       = "full-width-input"
          value       = "{% if unsandbox_public_key %}{{ unsandbox_public_key }}{% endif %}"
          placeholder = "unsb-pk-xxxx-xxxx-xxxx-xxxx"
          />

      <br />
      <br />

      <label for="unsandbox_secret_key_input">Secret Key</label>
      <input
          name        = "unsandbox_secret_key"
          type        = "text"
          id          = "unsandbox_secret_key_input"
          class       = "full-width-input"
          value       = "{% if unsandbox_secret_key %}{{ unsandbox_secret_key }}{% endif %}"
          placeholder = "unsb-sk-xxxxx-xxxxx-xxxxx-xxxxx"
          />

      <br />
      <br />

      {% if request.shop.unsandbox_public_key and request.shop.unsandbox_secret_key %}
        <small class="success-indicator">✓ Unsandbox configured — karaoke mode active on new uploads</small>
      {% else %}
        <small class="status-message">Add your unsandbox.com API keys to enable vocal isolation on audio/video products.</small>
      {% endif %}

      <br />
      <br />

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

      <br />
      <br />
      <small><a href="https://unsandbox.com/keys" target="_blank">Get or extend API keys at unsandbox.com</a></small>

      </div>
      </details>

      <br />
      <br />

    </form>

    {% if request.shop.unsandbox_public_key and request.shop.unsandbox_secret_key %}
    <form method="post" action="/s/{{ request.shop.id }}/settings" onsubmit="this.querySelector('[type=submit]').disabled = true; return true;">
      <input type="hidden" name="form_section" value="backfill-karaoke" />
      <input type="submit" class="mps-submit" value="Backfill Vocal Isolation" />
      <br />
      <small>Process all existing audio/video products for vocal isolation. Runs in background.</small>
    </form>
    {% endif %}

  </section>
</section>

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

<section class="one-column">
  <section class="shop-settings well">

    <h3>S3 Mirror Bucket</h3>
    <p>Connect an S3-compatible bucket to automatically mirror all uploaded files. Works with DigitalOcean Spaces, AWS S3, MinIO, Backblaze B2, and any S3-compatible service. Your MPS bucket remains the origin — this is a backup/mirror.</p>

    <form method="post" action="/s/{{ request.shop.id }}/settings" onsubmit="submit.disabled = true; return true;">
      <input type="hidden" name="form_section" value="mirror-settings" />

      <details class="api-key-details">
      <summary class="toggle-summary">Show Mirror Bucket Settings</summary>

      <div class="api-key-fields">

      <br />

      <label for="mirror_s3_enabled_checkbox">
        <input type="checkbox" name="mirror_s3_enabled_checkbox" id="mirror_s3_enabled_checkbox"
               {% if mirror_s3_enabled %}checked{% endif %} />
        Enable mirror sync
      </label>

      <br />
      <br />

      <label for="mirror_s3_endpoint_input">S3 Endpoint URL</label>
      <input
          name        = "mirror_s3_endpoint"
          type        = "url"
          id          = "mirror_s3_endpoint_input"
          class       = "full-width-input"
          value       = "{{ mirror_s3_endpoint }}"
          placeholder = "https://nyc3.digitaloceanspaces.com" />

      <br />
      <br />

      <label for="mirror_s3_region_input">Region (optional)</label>
      <input
          name        = "mirror_s3_region"
          type        = "text"
          id          = "mirror_s3_region_input"
          class       = "full-width-input"
          value       = "{{ mirror_s3_region }}"
          placeholder = "nyc3" />

      <br />
      <br />

      <label for="mirror_s3_bucket_input">Bucket Name</label>
      <input
          name        = "mirror_s3_bucket"
          type        = "text"
          id          = "mirror_s3_bucket_input"
          class       = "full-width-input"
          value       = "{{ mirror_s3_bucket }}"
          placeholder = "my-shop-backup" />

      <br />
      <br />

      <label for="mirror_s3_access_key_input">Access Key</label>
      <input
          name        = "mirror_s3_access_key"
          type        = "text"
          id          = "mirror_s3_access_key_input"
          class       = "full-width-input"
          value       = "{{ mirror_s3_access_key }}"
          placeholder = "Access Key ID" />

      <br />
      <br />

      <label for="mirror_s3_secret_key_input">Secret Key</label>
      <input
          name        = "mirror_s3_secret_key"
          type        = "password"
          id          = "mirror_s3_secret_key_input"
          class       = "full-width-input"
          value       = "{{ mirror_s3_secret_key }}"
          placeholder = "Secret Access Key" />

      <br />
      <br />

      {% if request.shop.has_s3_mirror %}
        <small class="success-indicator">Mirror configured and enabled</small>
      {% elif request.shop.mirror_s3_bucket %}
        <small class="status-message">Mirror credentials saved but not enabled. Check the box above to activate.</small>
      {% else %}
        <small class="status-message">Add S3-compatible bucket credentials to enable file mirroring.</small>
      {% endif %}

      <br />
      <br />

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

      </div>
      </details>
    </form>

    {% if request.shop.has_s3_mirror %}
    <form method="post" action="/s/{{ request.shop.id }}/settings" onsubmit="this.querySelector('[type=submit]').disabled = true; return true;">
      <input type="hidden" name="form_section" value="backfill-s3-mirror" />
      <input type="submit" class="mps-submit" value="Backfill Mirror Bucket" />
      <br />
      <small>Copy all existing files to your mirror bucket. Runs in background.</small>
    </form>
    {% endif %}

  </section>
</section>

<br />
<br />

{% if request.monero_enabled %}
<section class="one-column">
  <section class="shop-settings well">

    <h3>Crypto Settings 🪙</h3>
    
    <h4>Payment Risk Thresholds</h4>
    
    <form method="post" action="/s/{{ request.shop.id }}/settings" onsubmit="submit.disabled = true; return true;">
      <input type="hidden" name="form_section" value="crypto-settings" />
    
      <label for="payment_risk_threshold_mid_dollars_input">Medium Risk Threshold ($)</label>
      <input
          name        = "payment_risk_threshold_mid_dollars"
          type        = "number"
          id          = "payment_risk_threshold_mid_dollars_input"
          class       = "mps-threshold"
          value       = "{{ payment_risk_threshold_mid_dollars }}"
          placeholder = "10.00"
          min         = "1"
          max         = "1000"
          step        = "0.01"
          />
      <br />
      <small>Orders below this amount require minimal confirmations. Default: $10.00</small>

      <br />
      <br />
      
      <label for="payment_risk_threshold_high_dollars_input">High Risk Threshold ($)</label>
      <input
          name        = "payment_risk_threshold_high_dollars"
          type        = "number"
          id          = "payment_risk_threshold_high_dollars_input"
          class       = "mps-threshold"
          value       = "{{ payment_risk_threshold_high_dollars }}"
          placeholder = "100.00"
          min         = "10"
          max         = "10000"
          step        = "0.01"
          />
      <br />
      <small>Orders above this amount require maximum confirmations. Default: $100.00</small>

      <br />
      <br />
      
      <label for="crypto_quote_expiry_seconds_input">Cryptocurrency Quote Expiry Time (seconds)</label>
      <input
          name        = "crypto_quote_expiry_seconds"
          type        = "number"
          id          = "crypto_quote_expiry_seconds_input"
          class       = "mps-crypto-quote-expiry"
          value       = "{{ crypto_quote_expiry_seconds }}"
          placeholder = "3600"
          min         = "300"
          max         = "7200"
          step        = "60"
          />
      <br />
      <small>How long cryptocurrency payment quotes are valid (300-7200 seconds, default 3600 = 60 minutes)</small>

      <br />
      <br />

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

      <br />
      <br />

    </form>
    
    <br />
    
    <input type="checkbox" id="show-crypto-wallets" onchange="toggleCryptoWallets()">
    <label for="show-crypto-wallets" class="inline-label">Show wallet configuration forms</label>
    
    <br />
    <br />
    
    <small class="note-text">
      Note: We cannot verify you control these addresses. Please double-check they're correct!
      Consider sending a small test amount from another wallet to verify.
      <br />
      <strong>Once set, cold wallet addresses cannot be removed, only replaced with new addresses.</strong>
    </small>
    
    <br />
    <br />

    <div id="crypto-wallets">
    
    <h4>Monero (XMR) Configuration</h4>
    
    <form method="post" action="/s/{{ request.shop.id }}/crypto-processor/XMR" onsubmit="submit.disabled = true; return true;">

      <label for="xmr_sweep_to_address_input">Cold Wallet Address (Required to accept Monero)</label>
      <input
          name        = "sweep_to_address"
          type        = "text"
          id          = "xmr_sweep_to_address_input"
          class       = "mps-sweep-address full-width-input{% if xmr_processor and not xmr_processor.enabled %} disabled-input{% endif %}"
          value       = "{% if xmr_processor %}{{ xmr_processor.sweep_to_address }}{% endif %}"
          placeholder = "Monero address to sweep funds to"
          {% if xmr_processor and not xmr_processor.enabled %}readonly{% endif %}
          {% if xmr_processor and xmr_processor.sweep_to_address %}required{% endif %}
          />
      <br />
      <small>
        Configure your cold wallet address where this shop's Monero funds will be swept. This is required to accept Monero payments.
      </small>
      
      {% if xmr_processor %}
        {% if xmr_processor.enabled %}
          <br />
          <br />
          <small class="success-indicator">✓ Monero wallet configured and ready to accept payments</small>
        {% else %}
          <br />
          <br />
          <small class="error-indicator">✗ Monero payments are currently disabled</small>
          <br />
          <small class="status-message">
            Your cold wallet address is preserved but customers cannot select Monero as a payment method.
          </small>
        {% endif %}
      {% endif %}

      <br />
      <br />

      {% if xmr_processor %}
        {% if xmr_processor.enabled %}
          <input type="submit" name="submit" class="mps-submit" value="Save Monero Settings" />
          <input type="submit" name="disable" class="payment-toggle-button disable" value="Disable Monero" />
        {% else %}
          <input type="submit" name="submit" class="payment-toggle-button enable" value="Re-enable Monero" />
          <small class="status-message">Re-enable Monero payments to update your cold wallet address</small>
        {% endif %}
      {% else %}
      <input type="submit" name="submit" class="mps-submit" value="Enable Monero Payments" />
      {% endif %}

      <br />
      <br />

    </form>

    <h4>Dogecoin (DOGE) Configuration 🐕</h4>

    <form method="post" action="/s/{{ request.shop.id }}/crypto-processor/DOGE" onsubmit="submit.disabled = true; return true;">
      {% include "snippets/csrf.j2" %}
      <label for="doge_sweep_to_address_input">Cold Wallet Address (Required to accept Dogecoin)</label>
      <input
          type        = "text"
          name        = "sweep_to_address"
          id          = "doge_sweep_to_address_input"
          {% if doge_processor and doge_processor.sweep_to_address %}required{% endif %}
          value       = "{% if doge_processor %}{{ doge_processor.sweep_to_address }}{% endif %}"
          placeholder = "Dogecoin address to sweep funds to (e.g. DQA4...)"
          class       = "full-width-input{% if doge_processor and not doge_processor.enabled %} disabled-input{% endif %}"
          {% if doge_processor and not doge_processor.enabled %}readonly{% endif %}
      />
      <br/>
      <small>
        Configure your cold wallet address where this shop's Dogecoin funds will be swept. This is required to accept Dogecoin payments.
      </small>

      {% if doge_processor %}
        {% if doge_processor.enabled %}
        <br />
        <br />
        <small class="success-indicator">✓ Dogecoin wallet configured and ready to accept payments</small>
        {% else %}
        <br />
        <br />
        <small class="error-indicator">✗ Dogecoin payments are currently disabled</small>
        <br />
        <br />
        <small>
          Your cold wallet address is preserved but customers cannot select Dogecoin as a payment method.
        </small>
        {% endif %}
      {% else %}
      <br />
      <br />
      <small>Enter your Dogecoin address to start accepting DOGE payments. Such wow! Much payments!</small>
      {% endif %}

      <br />
      <br />

      {% if doge_processor %}
        {% if doge_processor.enabled %}
          <input type="submit" name="submit" class="mps-submit" value="Save Dogecoin Settings" />
          <input type="submit" name="disable" class="payment-toggle-button disable" value="Disable Dogecoin" />
        {% else %}
          <input type="submit" name="submit" class="payment-toggle-button enable" value="Re-enable Dogecoin" />
          <small class="status-message">Re-enable Dogecoin payments to update your cold wallet address</small>
        {% endif %}
      {% else %}
      <input type="submit" name="submit" class="mps-submit" value="Enable Dogecoin Payments" />
      {% endif %}

      <br />
      <br />

    </form>
    
    </div>

  </section>
</section>

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

<section class="one-column">
  <section class="shop-settings well">

    <h3>Branding Settings</h3>

    <label for="logo-banner">Banner Logo</label>
    <a href="{{ get_endpoints["shop-logo-banner"] }}?ts={{ request.shop.updated_timestamp }}"><img src="{{ get_endpoints["shop-logo-banner"] }}?ts={{ request.shop.updated_timestamp }}" width="420px" /></a>
    {% set signed_post = signed_posts["shop-logo-banner"] %}
    <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 Shop Banner" />
    </form>

    <hr />

    <br />

    <label for="logo-banner">favicon.ico</label>
    <a href="{{ get_endpoints["shop-favicon"] }}?ts={{ request.shop.updated_timestamp }}"><img src="{{ get_endpoints["shop-favicon"] }}?ts={{ request.shop.updated_timestamp }}" class="favicon-preview" /></a>
    {% set signed_post = signed_posts["shop-favicon"] %}
    <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 favicon.ico" />
    </form>

  </section>
</section>

<br />
<br />

<section class="one-column">
  <section class="shop-settings well">

    <form method="post" action="/s/{{ request.shop.id }}/settings" onsubmit="submit.disabled = true; return true;">
      <input type="hidden" name="form_section" value="ribbon-settings" />
 
      <h3>Announcement Ribbon Settings 🎀</h3>

      <label for="ribbon_text_input">Ribbon Text</label>
      <textarea
          name        = "ribbon_text"
          id          = "ribbon_text_input"
          class       = "mps-shop-ribbon-text"
          placeholder = "The announcement ribbon is displayed on the top of all shop pages."
          />{{ ribbon_text }}</textarea>

      <br />
      <br />

      <label for="ribbon_text_color_input">Ribbon Text Color</label>
      <input
          name        = "ribbon_text_color"
          type        = "text"
          id          = "ribbon_text_color_input"
          class       = "mps-shop-ribbon-text-color"
          value       = "{{ ribbon_text_color }}"
          placeholder = "#FFFFFF"
          />

      <br />
      <br />

      <label for="ribbon_color_1_input">Ribbon Background Color 1</label>
      <input
          name        = "ribbon_color_1"
          type        = "text"
          id          = "ribbon_color_1_input"
          class       = "mps-shop-ribbon-color"
          value       = "{{ ribbon_color_1 }}"
          placeholder = "#5871AD"
          />

      <br />
      <br />

      <label for="ribbon_color_2_input">Ribbon Background Color 2</label>
      <input
          name        = "ribbon_color_2"
          type        = "text"
          id          = "ribbon_color_2_input"
          class       = "mps-shop-ribbon-color"
          value       = "{{ ribbon_color_2 }}"
          placeholder = "#82A8FF"
          />

      <br />
      <br />

      <label>Default Theme for Visitors</label>
      <br />
      <input type="radio" name="default_theme" id="shop_light_mode" value="1" {% if default_theme == 1 %}checked{% endif %} />
      <label for="shop_light_mode" class="inline-label">Light Mode</label>
      <br />
      <input type="radio" name="default_theme" id="shop_dark_mode" value="0" {% if default_theme == 0 %}checked{% endif %} />
      <label for="shop_dark_mode" class="inline-label">Dark Mode</label>
      <br />
      <small class="note-text">Choose the default theme that new visitors see. Users can override this in their profile settings.</small>

      <br />
      <br />

      <label>Product Layout</label>
      <br />
      <input type="checkbox" name="grid-lanes-checkbox" id="grid-lanes-checkbox" {% if request.shop.grid_lanes_enabled %}checked{% endif %} />
      <label for="grid-lanes-checkbox" class="inline-label"><b>Enable Masonry Layout (Grid Lanes)</b></label>
      <br />
      <small class="note-text">When enabled, products flow into a waterfall/masonry layout where items fill the shortest column first. This creates a Pinterest-style layout that better handles varying product image heights. Requires browser support for CSS Grid Lanes.</small>

      <br />
      <br />

      <label>Product & Content Dates</label>
      <br />
      <input type="radio" name="show_dates" id="show_dates_on" value="1" {% if request.shop.show_dates %}checked{% endif %} />
      <label for="show_dates_on" class="inline-label">Show created and updated dates</label>
      <br />
      <input type="radio" name="show_dates" id="show_dates_off" value="0" {% if not request.shop.show_dates %}checked{% endif %} />
      <label for="show_dates_off" class="inline-label">Hide dates</label>
      <br />
      <small class="note-text">Show or hide the created and last updated dates on product and content pages.</small>

      <br />
      <br />

      <label>Watch Mode</label>
      <br />
      <input type="radio" name="watch_mode" id="watch_mode_on" value="1"
             {% if request.shop.watch_mode_enabled %}checked{% endif %} />
      <label for="watch_mode_on" class="inline-label">Enable watch mode (sticky video, autoplay, related content sidebar)</label>
      <br />
      <input type="radio" name="watch_mode" id="watch_mode_off" value="0"
             {% if not request.shop.watch_mode_enabled %}checked{% endif %} />
      <label for="watch_mode_off" class="inline-label">Disable watch mode</label>
      <br />
      <small class="note-text">When enabled, video content pages autoplay, the video stays visible while scrolling, and a related content sidebar appears.</small>

      <br />
      <br />

      <label>Color Filter</label>
      <br />
      <input type="radio" name="color_filter" id="color_filter_off" value="0"
             {% if not request.shop.color_filter %}checked{% endif %} />
      <label for="color_filter_off" class="inline-label">Off (full color)</label>
      <br />
      <input type="radio" name="color_filter" id="color_filter_grayscale" value="1"
             {% if request.shop.color_filter == 1 %}checked{% endif %} />
      <label for="color_filter_grayscale" class="inline-label">Grayscale (black and white)</label>
      <br />
      <input type="radio" name="color_filter" id="color_filter_red" value="2"
             {% if request.shop.color_filter == 2 %}checked{% endif %} />
      <label for="color_filter_red" class="inline-label">Red only</label>
      <br />
      <input type="radio" name="color_filter" id="color_filter_green" value="3"
             {% if request.shop.color_filter == 3 %}checked{% endif %} />
      <label for="color_filter_green" class="inline-label">Green only</label>
      <br />
      <input type="radio" name="color_filter" id="color_filter_blue" value="4"
             {% if request.shop.color_filter == 4 %}checked{% endif %} />
      <label for="color_filter_blue" class="inline-label">Blue only</label>
      <br />
      <input type="radio" name="color_filter" id="color_filter_red_green" value="5"
             {% if request.shop.color_filter == 5 %}checked{% endif %} />
      <label for="color_filter_red_green" class="inline-label">Red + Green</label>
      <br />
      <input type="radio" name="color_filter" id="color_filter_red_blue" value="6"
             {% if request.shop.color_filter == 6 %}checked{% endif %} />
      <label for="color_filter_red_blue" class="inline-label">Red + Blue</label>
      <br />
      <input type="radio" name="color_filter" id="color_filter_green_blue" value="7"
             {% if request.shop.color_filter == 7 %}checked{% endif %} />
      <label for="color_filter_green_blue" class="inline-label">Green + Blue</label>
      <br />
      <small class="note-text">Applies a color filter to the entire site — images, video, text, and UI. Original files are not modified.</small>

      <br />
      <br />

      <label>Sandbox Mode</label>
      <br />
      <input type="radio" name="sandbox_mode" id="sandbox_mode_on" value="1"
             {% if request.shop.sandbox_mode %}checked{% endif %} />
      <label for="sandbox_mode_on" class="inline-label">Enable sandbox mode (floating creative filter toolbar for visitors)</label>
      <br />
      <input type="radio" name="sandbox_mode" id="sandbox_mode_off" value="0"
             {% if not request.shop.sandbox_mode %}checked{% endif %} />
      <label for="sandbox_mode_off" class="inline-label">Disable sandbox mode</label>
      <br />
      <small class="note-text">When enabled, visitors see a floating toolbar to apply real-time filters to images and video. Includes 30+ presets, adjustment sliders, and image/video export. All processing is client-side — original files are never modified.</small>

      <br />
      <br />

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

      <br />
      <br />

    </form>

  </section>
</section>

<br />
<br />



<section class="one-column">
  <section class="shop-settings well">

    <form method="post" action="/s/{{ request.shop.id }}/settings">
      <input type="hidden" name="form_section" value="maintenance-settings" />

    <h3>Maintenance Mode 🏗️</h3>

    <input type="checkbox" name="maint-mode-checkbox" id="maint-mode-checkbox" {% if request.shop.maint_mode %}checked{% endif %}></input>
<b>If checked, enabled maintenance mode.</b>

<br />
<br />

Temporarily prevent new searches or sales on this shop.
Existing sales honored for download buy purchasers.


    <br />
    <br />

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

    <br />
    <br />

    </form>

  </section>

</section>

<br />
<br />

<section class="one-column">
  <section class="shop-settings well">

    <form method="post" action="/s/{{ request.shop.id }}/settings">
      <input type="hidden" name="form_section" value="subscription-settings" />

    <h3>Subscription Settings</h3>

    <input type="checkbox" name="subscriptions-enabled-checkbox" id="subscriptions-enabled-checkbox" {% if request.shop.subscriptions_enabled %}checked{% endif %}></input>
    <b>Enable "Stay in the Loop" email digest subscriptions</b>

    <br />
    <br />

    Allow visitors to subscribe to email digests of new products and content.
    Subscribers can choose daily or weekly frequency. Emails are only sent when
    new items are published.

    <br />
    <br />

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

    <br />
    <br />

    </form>

    <form method="post" action="/s/{{ request.shop.id }}/settings">
      <input type="hidden" name="form_section" value="comment-settings" />

    <h3>Comment System Settings 💬</h3>

    <input type="checkbox" name="comments-enabled-checkbox" id="comments-enabled-checkbox" {% if request.shop.comments_enabled %}checked{% endif %}></input>
    <b>Enable comments and reviews on product pages</b>

    <br />
    <br />

    <input type="checkbox" name="comments-require-purchase-checkbox" id="comments-require-purchase-checkbox" {% if request.shop.comments_require_purchase %}checked{% endif %}></input>
    <b>Only allow customers who purchased the product to leave comments</b>

    <br />
    <br />

    <input type="checkbox" name="comments-require-approval-checkbox" id="comments-require-approval-checkbox" {% if request.shop.comments_require_approval %}checked{% endif %}></input>
    <b>Hide comments until approved by shop owner/editor</b>

    <br />
    <br />

    Allow customers to leave comments and reviews on your product pages.
    Comments appear on both product detail pages and content pages.

    <br />
    <br />

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

    <br />
    <br />

    </form>

  </section>

  <section class="well">
    <h3>Gift Cards</h3>

    <form action="/s/{{ request.shop.uuid_str }}/settings" method="POST">
      {% include "snippets/csrf.j2" %}
      <input type="hidden" name="form_section" value="gift-card-settings" />

      <label>
        <input type="checkbox" name="gift-card-enabled-checkbox"
               {% if gift_card_enabled %}checked{% endif %} />
        Enable Gift Cards
      </label>

      <br /><br />

      <label for="gift_card_min">Minimum Amount ($)</label>
      <input type="number" name="gift_card_min" id="gift_card_min"
             value="{{ '{:.2f}'.format(gift_card_min_dollars) }}"
             min="1.00" step="0.01" class="mps-text-input" />

      <br /><br />

      <label for="gift_card_max">Maximum Amount ($)</label>
      <input type="number" name="gift_card_max" id="gift_card_max"
             value="{{ '{:.2f}'.format(gift_card_max_dollars) }}"
             min="1.00" max="10000.00" step="0.01" class="mps-text-input" />

      <br /><br />

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

      <br /><br />

      {% if gift_card_enabled %}
      <a href="/s/{{ request.shop.uuid_str }}/gift-cards/manage" class="mps-button mps-button-small">Manage Gift Cards</a>
      {% endif %}

    </form>

  </section>

</section>

<br />
<br />

{# MPS-21: Make-an-Offer settings #}
<section class="one-column">
  <section class="shop-settings well">
    <h3>Make an Offer</h3>
    <p>Allow buyers to negotiate a price for products in offer mode.
       An offer at or above the <strong>auto-accept threshold</strong> is
       accepted instantly. An offer below the <strong>auto-decline
       threshold</strong> is declined automatically &mdash; the buyer is
       told their offer was too low, but you are not notified (no lowball
       pings). Offers in between queue for your review.</p>

    <form method="post" action="/s/{{ request.shop.uuid_str }}/settings" class="settings-form" onsubmit="submit.disabled = true; return true;">
      {% include "snippets/csrf.j2" %}
      <input type="hidden" name="form_section" value="offer-settings" />

      <label class="settings-field settings-field--inline settings-field--full">
        <input type="checkbox" name="offer_enabled_checkbox"
               {% if request.shop.offer_enabled %}checked{% endif %} />
        <span>Enable make-an-offer (shop-wide default)</span>
      </label>

      <div class="settings-form-grid">
        <div class="settings-field">
          <label for="offer_auto_accept">Auto-accept threshold (% of list price)</label>
          <input type="number" name="offer_auto_accept_threshold_pct" id="offer_auto_accept"
                 value="{{ request.shop.offer_auto_accept_threshold_pct }}"
                 min="0" max="100" step="1" />
        </div>

        <div class="settings-field">
          <label for="offer_auto_decline">Auto-decline threshold (% of list price)</label>
          <input type="number" name="offer_auto_decline_threshold_pct" id="offer_auto_decline"
                 value="{{ request.shop.offer_auto_decline_threshold_pct }}"
                 min="0" max="100" step="1" />
          <small class="settings-field-hint">Must be strictly below auto-accept; otherwise auto-clamped.</small>
        </div>

        <div class="settings-field">
          <label for="offer_min">Minimum offer amount ($)</label>
          <input type="number" name="offer_min" id="offer_min"
                 value="{% if request.shop.offer_min_in_cents %}{{ '%.2f'|format(request.shop.offer_min_in_cents / 100.0) }}{% endif %}"
                 min="0" step="0.01" placeholder="No floor" />
          <small class="settings-field-hint">A hard dollar floor, independent of the % thresholds. Leave blank for no floor.</small>
        </div>

        <div class="settings-field">
          <label for="offer_expiration">Offer expiration (hours)</label>
          <input type="number" name="offer_expiration_hours" id="offer_expiration"
                 value="{{ request.shop.offer_expiration_hours }}"
                 min="1" max="8760" step="1" />
          <small class="settings-field-hint">How long a queued offer waits before it auto-expires.</small>
        </div>

        <div class="settings-field">
          <label for="offer_acceptance_payment_hours">Payment window after acceptance (hours)</label>
          <input type="number" name="offer_acceptance_payment_hours" id="offer_acceptance_payment_hours"
                 value="{{ request.shop.offer_acceptance_payment_hours }}"
                 min="1" max="720" step="1" />
          <small class="settings-field-hint">After you accept an offer, the buyer has this many hours to pay before the offer auto-expires. The buyer can also cancel during this window.</small>
        </div>

        <div class="settings-field">
          <label for="offer_max_rounds">Max counter rounds</label>
          <input type="number" name="offer_max_rounds" id="offer_max_rounds"
                 value="{{ request.shop.offer_max_rounds }}"
                 min="1" max="100" step="1" />
          <small class="settings-field-hint">How many back-and-forth counters are allowed before the offer is forced to a yes/no.</small>
        </div>

        <div class="settings-field">
          <label for="offer_min_age">Minimum buyer account age (hours)</label>
          <input type="number" name="offer_min_buyer_account_age_hours" id="offer_min_age"
                 value="{{ request.shop.offer_min_buyer_account_age_hours }}"
                 min="0" max="8760" step="1" placeholder="0 = open" />
          <small class="settings-field-hint">Block brand-new accounts from making offers. 0 = anyone may offer.</small>
        </div>
      </div>

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

<br />
<br />

<section class="one-column">
  <section class="shop-settings well">

    <h3>Environment Settings</h3>

    <p>Non-production shops are hidden from search, feeds, and discovery. Use them to stage or test before going live.</p>

    <form method="post" action="/s/{{ request.shop.id }}/settings" onsubmit="submit.disabled = true; return true;">
      <input type="hidden" name="form_section" value="environment-settings" />

      <fieldset>
        <legend>Environment</legend>

        <input type="radio" name="environment" id="env_production" value="0" {% if environment == 0 %}checked{% endif %} />
        <label for="env_production" class="inline-label">Production</label>

        <input type="radio" name="environment" id="env_staging" value="1" {% if environment == 1 %}checked{% endif %} />
        <label for="env_staging" class="inline-label">Staging</label>

        <input type="radio" name="environment" id="env_development" value="2" {% if environment == 2 %}checked{% endif %} />
        <label for="env_development" class="inline-label">Development</label>
      </fieldset>

      <br />
      <br />

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

    </form>

  </section>

</section>

<br />
<br />

<section class="one-column">
  <section class="shop-settings well">

    <h3>Storage Bucket (BYOB)</h3>

    <p>Configure your own S3-compatible storage bucket. When enabled, all media uploads and CDN URLs will use your bucket instead of the default MPS storage.</p>

    {% if request.shop.is_trial_active %}
    <p><strong>Trial tip:</strong> Setting up your own storage bucket during your trial ensures your media is always under your control. Any S3-compatible provider works (DigitalOcean Spaces, AWS S3, Backblaze B2, etc.).</p>
    {% endif %}

    <form method="post" action="/s/{{ request.shop.id }}/settings" onsubmit="submit.disabled = true; return true;">
      <input type="hidden" name="form_section" value="bucket-settings" />

      <label>
        <input type="checkbox" name="primary_s3_enabled_checkbox"
               {% if primary_s3_enabled %}checked{% endif %} />
        Enable Custom Bucket
      </label>

      <br /><br />

      <label for="primary_s3_endpoint">S3 Endpoint URL</label>
      <input type="url" name="primary_s3_endpoint" id="primary_s3_endpoint"
             value="{{ primary_s3_endpoint or '' }}"
             placeholder="https://nyc3.digitaloceanspaces.com"
             class="mps-text-input" />

      <br /><br />

      <label for="primary_s3_region">Region</label>
      <input type="text" name="primary_s3_region" id="primary_s3_region"
             value="{{ primary_s3_region or '' }}"
             placeholder="nyc3"
             class="mps-text-input" />

      <br /><br />

      <label for="primary_s3_bucket">Bucket Name</label>
      <input type="text" name="primary_s3_bucket" id="primary_s3_bucket"
             value="{{ primary_s3_bucket or '' }}"
             placeholder="my-shop-media"
             class="mps-text-input" />

      <br /><br />

      <label for="primary_s3_access_key">Access Key</label>
      <input type="text" name="primary_s3_access_key" id="primary_s3_access_key"
             value="{{ primary_s3_access_key or '' }}"
             placeholder="Access Key"
             class="mps-text-input" />

      <br /><br />

      <label for="primary_s3_secret_key">Secret Key</label>
      <input type="password" name="primary_s3_secret_key" id="primary_s3_secret_key"
             value="{{ primary_s3_secret_key or '' }}"
             placeholder="Secret Key"
             class="mps-text-input" />

      <br /><br />

      <label for="primary_s3_cdn_endpoint">CDN Endpoint URL</label>
      <input type="url" name="primary_s3_cdn_endpoint" id="primary_s3_cdn_endpoint"
             value="{{ primary_s3_cdn_endpoint or '' }}"
             placeholder="https://my-shop-media.nyc3.cdn.digitaloceanspaces.com"
             class="mps-text-input" />

      <br /><br />

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

    </form>

  </section>

</section>


<br />
<br />

<section class="one-column">
  {% if request.torrent_enabled %}
  <section class="shop-settings well">

    <h3>Torrent Distribution</h3>

    <p>When enabled, you can add a magnet link to each product. Buyers see a torrent download option alongside the standard download link. Off by default.</p>

    <form method="post" action="/s/{{ request.shop.id }}/settings" onsubmit="submit.disabled = true; return true;">
      <input type="hidden" name="form_section" value="torrent-settings" />

      <label>
        <input type="checkbox" name="torrent_enabled_checkbox"
               {% if torrent_enabled %}checked{% endif %} />
        Enable torrent distribution
      </label>

      <br /><br />

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

    </form>

    {% if torrent_enabled %}
    <div id="torrent-backfill" style="margin-top: var(--space-4);">
      <p style="margin: 0 0 var(--space-2);">Backfill progress</p>
      <div style="background: var(--color-surface-alt); border-radius: var(--radius-md); height: 12px; overflow: hidden;">
        <div id="torrent-bar" style="height: 100%; width: 0%; background: var(--color-primary, #16a34a); transition: width 0.4s ease;"></div>
      </div>
      <p id="torrent-status" style="margin: var(--space-2) 0 0; font-size: 0.85em; color: var(--color-text-muted);">Loading…</p>
    </div>
    {% endif %}

  </section>
  {% endif %}

  <section class="shop-settings-checksum well2" style="margin-top: var(--space-6);">
    <h3>File Checksums</h3>
    <p>MD5 and SHA-256 checksums are computed for every uploaded file and displayed on content pages so visitors can verify integrity.</p>
    <form method="post" action="/s/{{ request.shop.id }}/checksum-backfill" onsubmit="submit.disabled = true; return true;">
      <input type="submit" name="submit" class="mps-submit" value="Backfill Checksums" />
    </form>
    <div id="checksum-backfill" style="margin-top: var(--space-4);">
      <p style="margin: 0 0 var(--space-2);">Backfill progress</p>
      <div style="background: var(--color-surface-alt); border-radius: var(--radius-md); height: 12px; overflow: hidden;">
        <div id="checksum-bar" style="height: 100%; width: 0%; background: var(--color-primary, #16a34a); transition: width 0.4s ease;"></div>
      </div>
      <p id="checksum-status" style="margin: var(--space-2) 0 0; font-size: 0.85em; color: var(--color-text-muted);">Loading…</p>
    </div>
  </section>

</section>


<script>
document.addEventListener('DOMContentLoaded', function() {
    // Crypto wallets toggle (still uses checkbox pattern)
    const cryptoCheckbox = document.getElementById('show-crypto-wallets');
    const cryptoWallets = document.getElementById('crypto-wallets');

    if (cryptoCheckbox && cryptoWallets) {
        const cryptoState = localStorage.getItem('show-crypto-wallets') === 'true';
        cryptoCheckbox.checked = cryptoState;
        cryptoWallets.style.display = cryptoState ? 'block' : 'none';
    }

    // Handle shop theme radio buttons for immediate preview
    const shopThemeRadios = document.querySelectorAll('input[name="default_theme"]');
    shopThemeRadios.forEach(function(radio) {
        radio.addEventListener('change', function() {
            const newTheme = this.value === '0' ? 'dark' : 'light';
            document.documentElement.setAttribute('data-theme', newTheme);
            localStorage.setItem('theme-preference', newTheme);
        });
    });
});

function toggleCryptoWallets() {
    const checkbox = document.getElementById('show-crypto-wallets');
    const wallets = document.getElementById('crypto-wallets');

    localStorage.setItem('show-crypto-wallets', checkbox.checked);
    wallets.style.display = checkbox.checked ? 'block' : 'none';
}

(function() {
    const bar    = document.getElementById('torrent-bar');
    const status = document.getElementById('torrent-status');
    if (!bar || !status) return;

    let timer;

    function poll() {
        fetch('/s/{{ request.shop.id }}/torrent-backfill-status')
            .then(function(r) { return r.json(); })
            .then(function(d) {
                const pct = d.total > 0 ? Math.round(d.done / d.total * 100) : 100;
                bar.style.width = pct + '%';
                if (d.total === 0) {
                    status.textContent = 'No products with files yet.';
                } else if (d.done === d.total) {
                    status.textContent = 'Done — ' + d.done + ' of ' + d.total + ' products have magnet links.';
                    clearInterval(timer);
                } else {
                    status.textContent = d.done + ' / ' + d.total + ' done (' + d.remaining + ' pending)…';
                }
            })
            .catch(function() { status.textContent = 'Could not load status.'; });
    }

    poll();
    timer = setInterval(poll, 4000);
})();

(function() {
    const bar    = document.getElementById('checksum-bar');
    const status = document.getElementById('checksum-status');
    if (!bar || !status) return;

    let timer;

    function poll() {
        fetch('/s/{{ request.shop.id }}/checksum-backfill-status')
            .then(function(r) { return r.json(); })
            .then(function(d) {
                const pct = d.total > 0 ? Math.round(d.done / d.total * 100) : 100;
                bar.style.width = pct + '%';
                if (d.total === 0) {
                    status.textContent = 'No files uploaded yet.';
                } else if (d.done === d.total) {
                    status.textContent = 'Done — ' + d.done + ' of ' + d.total + ' files have checksums.';
                    clearInterval(timer);
                } else {
                    status.textContent = d.done + ' / ' + d.total + ' done (' + d.remaining + ' pending)…';
                }
            })
            .catch(function() { status.textContent = 'Could not load status.'; });
    }

    poll();
    timer = setInterval(poll, 4000);
})();
</script>
<script src="/static/js/shop-settings.js"></script>

{%- endblock -%}

{% block after_content %}
<section class="one-column">
  <section class="shop-settings well">

    <h3>REST API Keys</h3>
    <p>HMAC-signed key pairs for CI/CD pipelines and server-to-server integrations.
       Each request is signed with your secret key — it never travels over the wire.</p>

    {% for flash_msg, flash_level in request.session.pop_flash() if flash_level == 'api-secret' %}
    <div class="well" style="background: var(--color-success-subtle, #f0fdf4); border: 1px solid var(--color-success, #16a34a); padding: var(--space-4);">
      <strong>Copy your secret key now — it will not be shown again.</strong>
      <pre style="word-break: break-all; white-space: pre-wrap; margin-top: var(--space-2);">{{ flash_msg }}</pre>
    </div>
    {% endfor %}

    {% if api_keys %}
    <table style="width: 100%; border-collapse: collapse; margin-bottom: var(--space-4);">
      <thead>
        <tr>
          <th style="text-align: left; padding: var(--space-2);">Label</th>
          <th style="text-align: left; padding: var(--space-2);">Public Key</th>
          <th style="text-align: left; padding: var(--space-2);">Secret</th>
          <th style="text-align: left; padding: var(--space-2);">Last Used</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        {% for key in api_keys %}
        <tr>
          <td style="padding: var(--space-2);">{{ key.label or '—' }}</td>
          <td style="padding: var(--space-2); font-family: monospace; font-size: 0.85em;">{{ key.public_key }}</td>
          <td style="padding: var(--space-2); font-family: monospace; font-size: 0.85em; color: var(--color-text-muted);">{{ key.masked_secret }}</td>
          <td style="padding: var(--space-2); font-size: 0.85em;">
            {% if key.last_used_timestamp %}
              {{ key.last_used_timestamp | ago }}
            {% else %}
              never
            {% endif %}
          </td>
          <td style="padding: var(--space-2);">
            <form method="post" action="/s/{{ request.shop.id }}/api-keys/{{ key.id }}/revoke"
                  onsubmit="return confirm('Revoke this key? Any CI using it will stop working.');">
              <button type="submit" class="mps-btn-danger-sm">Revoke</button>
            </form>
          </td>
        </tr>
        {% endfor %}
      </tbody>
    </table>
    {% else %}
    <p style="color: var(--color-text-muted);">No active API keys. Generate one below.</p>
    {% endif %}

    <form method="post" action="/s/{{ request.shop.id }}/api-keys/generate"
          onsubmit="submit.disabled = true; return true;">
      <label for="api_key_label_input">Label (optional)</label>
      <input
          name        = "label"
          type        = "text"
          id          = "api_key_label_input"
          class       = "full-width-input"
          placeholder = "e.g. permacomputer CI"
          maxlength   = "128" />
      <br /><br />
      <input type="submit" name="submit" class="mps-submit" value="Generate API Key Pair" />
    </form>

    <br />
    <details>
      <summary>How to sign requests</summary>
      <pre style="font-size: 0.8em; white-space: pre-wrap; word-break: break-all; background: var(--color-surface-alt); padding: var(--space-3); border-radius: var(--radius-md);">METHOD=POST
PATH=/api/v1/products
TIMESTAMP=$(date +%s)
BODY='{"title":"My Item","description":"...","price":"9.99"}'
BODY_HASH=$(printf '%s' "$BODY" | sha256sum | awk '{print $1}')
STR="${METHOD}\n${PATH}\n${TIMESTAMP}\n${BODY_HASH}"
SIG=$(printf '%b' "$STR" | openssl dgst -sha256 -hmac "$MPS_SECRET_KEY" | awk '{print $2}')

curl -X POST https://my.makepostsell.com/api/v1/products \
  -H "X-MPS-Key: $MPS_PUBLIC_KEY" \
  -H "X-MPS-Timestamp: $TIMESTAMP" \
  -H "X-MPS-Signature: sha256=$SIG" \
  -H "Content-Type: application/json" \
  -d "$BODY"</pre>
    </details>

  </section>
</section>
{% endblock %}
