{%- comment -%}
  Gift Box — free-gift showcase with an optional scratch-to-reveal overlay.
  Each gift is a block. The scratch layer is a canvas the shopper wipes with
  pointer/touch; once enough is cleared it fades out. Purely decorative —
  the gift itself is whatever promotion you run, this does not grant it.
{%- endcomment -%}

{%- liquid
  assign s = section.settings
  assign uid = section.id
-%}

{% style %}
  .gb-{{ uid }} { padding-top: {{ s.padding_top }}px; padding-bottom: {{ s.padding_bottom }}px; }
  .gb-{{ uid }}__head { text-align: center; margin-bottom: 22px; }
  .gb-{{ uid }}__title { margin: 0 0 6px; font-size: {{ s.title_size }}px; color: {{ s.title_color }}; }
  .gb-{{ uid }}__grid {
    display: grid; gap: {{ s.gap }}px;
    grid-template-columns: repeat({{ s.columns }}, minmax(0, 1fr));
    max-width: {{ s.max_width }}px; margin: 0 auto;
  }
  .gb-{{ uid }}__card {
    position: relative; overflow: hidden; text-align: center;
    padding: {{ s.card_padding }}px;
    border-radius: {{ s.card_radius }}px;
    border: {{ s.border_width }}px {{ s.border_style }} {{ s.border_color }};
    background: {{ s.card_bg }};
  }
  .gb-{{ uid }}__badge {
    position: absolute; top: 10px; right: 10px; z-index: 2;
    font-size: 11px; font-weight: 700; letter-spacing: .04em; text-transform: uppercase;
    padding: 4px 9px; border-radius: 999px;
    background: {{ s.badge_bg }}; color: {{ s.badge_text }};
  }
  .gb-{{ uid }}__img { width: {{ s.image_size }}px; height: {{ s.image_size }}px; object-fit: contain; margin: 0 auto 10px; display: block; }
  .gb-{{ uid }}__label { margin: 0; font-size: 15px; font-weight: 600; color: {{ s.label_color }}; }
  .gb-{{ uid }}__was { margin: 4px 0 0; font-size: 13px; opacity: .7; text-decoration: line-through; }
  .gb-{{ uid }}__free { margin: 2px 0 0; font-size: 13px; font-weight: 700; color: {{ s.free_color }}; }
  .gb-{{ uid }}__scratch {
    position: absolute; inset: 0; z-index: 3; cursor: grab;
    transition: opacity .45s ease;
  }
  .gb-{{ uid }}__scratch.is-done { opacity: 0; pointer-events: none; }
  .gb-{{ uid }}__scratch canvas { width: 100%; height: 100%; display: block; touch-action: none; }
  @media screen and (max-width: 749px) {
    .gb-{{ uid }}__grid { grid-template-columns: repeat({{ s.columns_mobile }}, minmax(0,1fr)); }
  }
{% endstyle %}

<div class="gb-{{ uid }} color-{{ s.color_scheme }} gradient">
  <div class="page-width">
    {%- if s.title != blank or s.subtitle != blank -%}
      <div class="gb-{{ uid }}__head">
        {%- if s.title != blank -%}<h2 class="gb-{{ uid }}__title">{{ s.title | escape }}</h2>{%- endif -%}
        {%- if s.subtitle != blank -%}<div>{{ s.subtitle }}</div>{%- endif -%}
      </div>
    {%- endif -%}

    <div class="gb-{{ uid }}__grid">
      {%- for block in section.blocks -%}
        {%- assign scratch = false -%}
        {%- if s.enable_scratch and block.settings.scratch -%}{%- assign scratch = true -%}{%- endif -%}
        <div class="gb-{{ uid }}__card" {{ block.shopify_attributes }}>
          {%- if block.settings.badge != blank -%}
            <span class="gb-{{ uid }}__badge">{{ block.settings.badge | escape }}</span>
          {%- endif -%}

          {%- if block.settings.image != blank -%}
            {%- capture gift_class -%}gb-{{ uid }}__img{%- endcapture -%}
            {{ block.settings.image | image_url: width: 400 | image_tag:
                 class: gift_class, loading: "lazy", alt: block.settings.label | default: "" }}
          {%- else -%}
            <div class="gb-{{ uid }}__img">{{ 'product-1' | placeholder_svg_tag }}</div>
          {%- endif -%}

          <p class="gb-{{ uid }}__label">{{ block.settings.label | escape }}</p>
          {%- if block.settings.original_price != blank -%}
            <p class="gb-{{ uid }}__was">{{ block.settings.original_price | escape }}</p>
          {%- endif -%}
          {%- if s.free_text != blank -%}
            <p class="gb-{{ uid }}__free">{{ s.free_text | escape }}</p>
          {%- endif -%}

          {%- if scratch -%}
            <div class="gb-{{ uid }}__scratch" data-scratch
                 data-color="{{ s.scratch_color }}"
                 data-text="{{ s.scratch_text | escape }}"
                 data-text-color="{{ s.scratch_text_color }}"
                 data-text-size="{{ s.scratch_text_size }}">
              <canvas></canvas>
            </div>
          {%- endif -%}
        </div>
      {%- endfor -%}
    </div>
  </div>
</div>

{%- if s.enable_scratch -%}
<script>
  (() => {
    const root = document.querySelector('.gb-{{ uid }}');
    if (!root) return;
    const setup = (host) => {
      const cv = host.querySelector('canvas');
      const ctx = cv.getContext('2d');
      let drawing = false, cleared = false;
      const paint = () => {
        const r = host.getBoundingClientRect();
        const dpr = window.devicePixelRatio || 1;
        cv.width = Math.max(1, r.width * dpr); cv.height = Math.max(1, r.height * dpr);
        ctx.scale(dpr, dpr);
        ctx.fillStyle = host.dataset.color; ctx.fillRect(0, 0, r.width, r.height);
        if (host.dataset.text) {
          ctx.fillStyle = host.dataset.textColor;
          ctx.font = `600 ${host.dataset.textSize}px system-ui, sans-serif`;
          ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
          ctx.fillText(host.dataset.text, r.width / 2, r.height / 2);
        }
        ctx.globalCompositeOperation = 'destination-out';
      };
      const pct = () => {
        try {
          const d = ctx.getImageData(0, 0, cv.width, cv.height).data;
          let clear = 0;
          for (let i = 3; i < d.length; i += 4 * 40) { if (d[i] === 0) clear++; }
          return clear / (d.length / (4 * 40));
        } catch { return 0; }
      };
      const scratch = (e) => {
        if (!drawing) return;
        const r = cv.getBoundingClientRect();
        const x = (e.clientX ?? e.touches?.[0]?.clientX) - r.left;
        const y = (e.clientY ?? e.touches?.[0]?.clientY) - r.top;
        ctx.beginPath(); ctx.arc(x, y, {{ s.scratch_radius }}, 0, Math.PI * 2); ctx.fill();
        if (!cleared && pct() > 0.5) { cleared = true; host.classList.add('is-done'); }
      };
      paint();
      addEventListener('resize', paint);
      host.addEventListener('pointerdown', e => { drawing = true; scratch(e); });
      addEventListener('pointerup', () => drawing = false);
      host.addEventListener('pointermove', scratch);
    };
    root.querySelectorAll('[data-scratch]').forEach(setup);
  })();
</script>
{%- endif -%}

{% schema %}
{
  "name": "Gift Box",
  "tag": "section",
  "class": "section",
  "disabled_on": { "groups": ["header", "footer"] },
  "settings": [
    { "type": "text", "id": "title", "label": "Title", "default": "Your free gifts" },
    { "type": "richtext", "id": "subtitle", "label": "Subtitle" },
    { "type": "text", "id": "free_text", "label": "Free label", "default": "FREE" },
    { "type": "header", "content": "Layout" },
    { "type": "range", "id": "columns", "min": 1, "max": 5, "step": 1, "label": "Columns", "default": 3 },
    { "type": "range", "id": "columns_mobile", "min": 1, "max": 3, "step": 1, "label": "Columns on mobile", "default": 1 },
    { "type": "range", "id": "gap", "min": 8, "max": 48, "step": 2, "unit": "px", "label": "Gap", "default": 18 },
    { "type": "range", "id": "max_width", "min": 400, "max": 1400, "step": 50, "unit": "px", "label": "Max width", "default": 1000 },
    { "type": "range", "id": "image_size", "min": 40, "max": 220, "step": 5, "unit": "px", "label": "Image size", "default": 110 },
    { "type": "header", "content": "Scratch to reveal" },
    { "type": "checkbox", "id": "enable_scratch", "label": "Enable scratch effect", "default": false },
    { "type": "text", "id": "scratch_text", "label": "Scratch text", "default": "Scratch here" },
    { "type": "color", "id": "scratch_color", "label": "Overlay colour", "default": "#c9c2b6" },
    { "type": "color", "id": "scratch_text_color", "label": "Scratch text colour", "default": "#ffffff" },
    { "type": "range", "id": "scratch_text_size", "min": 10, "max": 28, "step": 1, "unit": "px", "label": "Scratch text size", "default": 15 },
    { "type": "range", "id": "scratch_radius", "min": 8, "max": 50, "step": 2, "unit": "px", "label": "Brush size", "default": 22 },
    { "type": "header", "content": "Card style" },
    { "type": "range", "id": "card_padding", "min": 8, "max": 40, "step": 2, "unit": "px", "label": "Card padding", "default": 18 },
    { "type": "range", "id": "card_radius", "min": 0, "max": 32, "step": 2, "unit": "px", "label": "Card radius", "default": 12 },
    { "type": "color", "id": "card_bg", "label": "Card background", "default": "#ffffff" },
    { "type": "range", "id": "border_width", "min": 0, "max": 6, "step": 1, "unit": "px", "label": "Border width", "default": 1 },
    { "type": "select", "id": "border_style", "label": "Border style", "default": "dashed",
      "options": [ {"value":"solid","label":"Solid"}, {"value":"dashed","label":"Dashed"}, {"value":"dotted","label":"Dotted"}, {"value":"none","label":"None"} ] },
    { "type": "color", "id": "border_color", "label": "Border colour", "default": "#d9d2c6" },
    { "type": "color", "id": "badge_bg", "label": "Badge background", "default": "#111111" },
    { "type": "color", "id": "badge_text", "label": "Badge text", "default": "#ffffff" },
    { "type": "color", "id": "title_color", "label": "Title colour", "default": "#111111" },
    { "type": "color", "id": "label_color", "label": "Label colour", "default": "#111111" },
    { "type": "color", "id": "free_color", "label": "Free label colour", "default": "#1e8f4e" },
    { "type": "range", "id": "title_size", "min": 16, "max": 48, "step": 1, "unit": "px", "label": "Title size", "default": 26 },
    { "type": "header", "content": "Section" },
    { "type": "color_scheme", "id": "color_scheme", "label": "Colour scheme", "default": "scheme-1" },
    { "type": "range", "id": "padding_top", "min": 0, "max": 100, "step": 4, "unit": "px", "label": "Top padding", "default": 40 },
    { "type": "range", "id": "padding_bottom", "min": 0, "max": 100, "step": 4, "unit": "px", "label": "Bottom padding", "default": 40 }
  ],
  "blocks": [
    {
      "type": "gift",
      "name": "Gift",
      "settings": [
        { "type": "image_picker", "id": "image", "label": "Image" },
        { "type": "text", "id": "label", "label": "Label", "default": "Free gift" },
        { "type": "text", "id": "badge", "label": "Badge text" },
        { "type": "text", "id": "original_price", "label": "Original price", "info": "Shown struck through." },
        { "type": "checkbox", "id": "scratch", "label": "Scratch this one", "default": true }
      ]
    }
  ],
  "presets": [
    {
      "name": "Gift Box",
      "blocks": [
        { "type": "gift", "settings": { "label": "Mini plush keyring", "badge": "Gift 1", "original_price": "৳490" } },
        { "type": "gift", "settings": { "label": "Gift wrapping", "badge": "Gift 2", "original_price": "৳250" } },
        { "type": "gift", "settings": { "label": "Handwritten note", "badge": "Gift 3", "original_price": "৳150" } }
      ]
    }
  ]
}
{% endschema %}
