{% comment %}
  Framesmith Designer — "See it framed" for Shopify product pages.

  Install (Online Store 2.0 themes — Dawn etc.):
    1. Online Store → Themes → ⋯ → Edit code.
    2. Sections → Add a new section → name it "framesmith-designer" →
       replace its contents with this file → Save.
    3. Online Store → Customize → open a Product template → Add section →
       Apps & custom → Framesmith Designer.
    4. In the section settings, paste your studio URL (pre-filled if you
       copied this file from your admin panel) and Save.

  The button opens the framing designer in an overlay with the product photo,
  title, and the selected variant's print size piped in. The designer adopts
  the store's light/dark automatically (or force it in the settings below).
  Vintage (non-2.0) themes: use the script-tag install from the embed guide.
{% endcomment %}

{%- if product -%}
<div class="framesmith-designer-block" data-fs-app="{{ section.settings.studio_url | escape }}">
  <button type="button" class="framesmith-designer-btn" id="framesmith-open-{{ section.id }}">
    {{ section.settings.button_label | escape }}
  </button>
</div>

<style>
  .framesmith-designer-btn {
    display: inline-block; width: 100%; padding: 12px 18px; margin-top: 8px;
    font: inherit; font-size: 15px; cursor: pointer;
    background: {{ section.settings.button_bg }}; color: {{ section.settings.button_fg }};
    border: 1px solid {{ section.settings.button_bg }}; border-radius: 6px;
  }
  .framesmith-overlay {
    position: fixed; inset: 0; z-index: 99999; background: rgba(0,0,0,0.55);
    display: flex; align-items: center; justify-content: center; padding: 3vh 3vw;
  }
  .framesmith-overlay iframe {
    width: min(1200px, 100%); height: 100%; border: 0; border-radius: 10px; background: #fff;
  }
  .framesmith-overlay-close {
    position: absolute; top: 10px; right: 14px; font-size: 26px; line-height: 1;
    background: none; border: none; color: #fff; cursor: pointer; padding: 8px;
  }
</style>

<script>
(function () {
  var btn = document.getElementById('framesmith-open-{{ section.id }}');
  if (!btn) return;
  var app = {{ section.settings.studio_url | json }};
  if (!app) return;
  if (app.slice(-1) !== '/') app += '/';
  var art = {{ product.featured_image | image_url: width: 2500 | prepend: 'https:' | json }};
  var title = {{ product.title | json }};
  var variants = {{ product.variants | json }};
  var themeSetting = {{ section.settings.designer_theme | json }};
  var showPricing = {{ section.settings.show_pricing | json }};

  // Variant title → print mm. Recognises A-series names, "420 x 594 mm",
  // "42 x 59.4 cm", and 16" x 20" style titles (same rules as the embed guide).
  var A = { A5:[148,210], A4:[210,297], A3:[297,420], A2:[420,594], A1:[594,841], A0:[841,1189] };
  function parseMm(t) {
    if (!t) return null;
    var a = t.toUpperCase().match(/\bA[0-5]\b/);
    if (a && A[a[0]]) return A[a[0]];
    var m = t.match(/(\d+(?:\.\d+)?)\s*[x×]\s*(\d+(?:\.\d+)?)\s*(mm|cm|in|inch|")?/i);
    if (!m) return null;
    var w = parseFloat(m[1]), h = parseFloat(m[2]), u = (m[3] || 'mm').toLowerCase();
    if (u === 'cm') { w *= 10; h *= 10; }
    else if (u !== 'mm') { w *= 25.4; h *= 25.4; }
    return [Math.round(w), Math.round(h)];
  }
  function currentVariant() {
    var form = document.querySelector('form[action*="/cart/add"]');
    var idInput = form && form.querySelector('[name="id"]');
    if (!idInput) return null;
    for (var i = 0; i < variants.length; i++) {
      if (String(variants[i].id) === String(idInput.value)) return variants[i];
    }
    return null;
  }
  function hostTheme() {
    if (themeSetting === 'light' || themeSetting === 'dark') return themeSetting;
    try {
      var bg = getComputedStyle(document.body).backgroundColor;
      var m = bg.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
      if (m) return (0.2126 * m[1] + 0.7152 * m[2] + 0.0722 * m[3]) < 96 ? 'dark' : 'light';
    } catch (e) {}
    return 'light';
  }

  btn.addEventListener('click', function () {
    var v = currentVariant();
    var mm = parseMm(v && v.title) || parseMm(title);
    var url = app + '?embed=1&theme=' + hostTheme() + '&art=' + encodeURIComponent(art) +
              '&title=' + encodeURIComponent(title);
    if (mm) url += '&w=' + mm[0] + '&h=' + mm[1];
    if (v && v.price != null && showPricing) url += '&printPrice=' + (v.price / 100);
    var overlay = document.createElement('div');
    overlay.className = 'framesmith-overlay';
    overlay.innerHTML = '<button type="button" class="framesmith-overlay-close" aria-label="Close">×</button>' +
      '<iframe src="' + url.replace(/"/g, '&quot;') + '" allow="clipboard-write"></iframe>';
    overlay.addEventListener('click', function (e) {
      if (e.target === overlay || e.target.classList.contains('framesmith-overlay-close')) overlay.remove();
    });
    document.body.appendChild(overlay);
  });
})();
</script>
{%- endif -%}

{% schema %}
{
  "name": "Framesmith Designer",
  "tag": "section",
  "settings": [
    { "type": "url", "id": "studio_url", "label": "Your studio URL",
      "info": "e.g. https://yourstudio.framesmith.com.au/" },
    { "type": "text", "id": "button_label", "label": "Button label", "default": "See it framed" },
    { "type": "select", "id": "designer_theme", "label": "Designer theme",
      "options": [
        { "value": "auto", "label": "Match my store" },
        { "value": "light", "label": "Light" },
        { "value": "dark", "label": "Dark" }
      ], "default": "auto" },
    { "type": "checkbox", "id": "show_pricing", "label": "Pipe the product price into the quote", "default": true },
    { "type": "color", "id": "button_bg", "label": "Button colour", "default": "#4A3728" },
    { "type": "color", "id": "button_fg", "label": "Button text colour", "default": "#F5E6C8" }
  ],
  "presets": [{ "name": "Framesmith Designer" }]
}
{% endschema %}
