<!DOCTYPE html>
<html lang="{{HTML_LANG}}">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  {{BOOTSTRAP_CSS}}
  <style>{{DIALOG_CSS}}</style>
</head>
<body class="p-3">
  <div class="container-fluid">
    <div class="mb-2">
      <h2 class="h6 mb-0">{{SETTINGS_TITLE}}</h2>
      <p class="text-muted small mb-0">{{SETTINGS_SUBTITLE}}</p>
    </div>

    <ul class="nav nav-tabs mb-2" id="gg-settings-main-tabs" role="tablist">
      <li class="nav-item" role="presentation">
        <button class="nav-link active" id="gg-main-tab-user-btn" data-bs-toggle="tab" data-bs-target="#gg-main-tab-user" type="button" role="tab">{{SETTINGS_TAB_USER_INFO}}</button>
      </li>
      <li class="nav-item" role="presentation">
        <button class="nav-link" id="gg-main-tab-nesting-btn" data-bs-toggle="tab" data-bs-target="#gg-main-tab-nesting" type="button" role="tab">{{SETTINGS_TAB_NESTING}}</button>
      </li>
      <li class="nav-item" role="presentation">
        <button class="nav-link" id="gg-main-tab-toolbar-btn" data-bs-toggle="tab" data-bs-target="#gg-main-tab-toolbar" type="button" role="tab">{{SETTINGS_TAB_TOOLBAR}}</button>
      </li>
    </ul>

    <div class="tab-content">

      <div class="tab-pane fade show active" id="gg-main-tab-user" role="tabpanel">
        <div class="d-flex align-items-center gap-2 flex-wrap justify-content-end mb-2">
          <button type="button" class="btn btn-sm btn-warning text-nowrap flex-shrink-0" onclick="sketchup.on_upgrade_to_pro()">{{SETTINGS_GO_PRO}}</button>
          <div class="btn-group btn-group-sm flex-shrink-0" role="group" aria-label="Language">
            <button type="button" class="btn {{LANG_EN_CLASS}}" onclick="sketchup.on_set_locale('en')">EN</button>
            <button type="button" class="btn {{LANG_VI_CLASS}}" onclick="sketchup.on_set_locale('vi')">VI</button>
          </div>
          <button type="button" class="btn btn-outline-danger btn-sm" onclick="sketchup.on_sign_out()">{{SETTINGS_SIGN_OUT}}</button>
        </div>

        <div class="d-flex flex-wrap align-items-center gap-2 mb-2 p-2 bg-white rounded border">
          <span class="fw-medium">{{USER_EMAIL}}</span>
          <span class="badge bg-primary">{{PLAN_DISPLAY}}</span>
          {{PRO_DAYS_LEFT}}
          {{UPGRADE_BTN}}
          <span class="text-muted">&#183;</span>
          <span class="text-muted small">{{SETTINGS_CURRENT_VERSION}}</span>
          <span class="fw-bold text-primary" id="cur-ver">{{CUR_VER}}</span>
        </div>

        <div class="card border mb-2">
          <div class="card-body py-2 px-3">
            <div class="d-flex gap-2 align-items-center">
              <input id="promo-code-input" type="text" class="form-control form-control-sm" placeholder="{{SETTINGS_PROMO_PLACEHOLDER}}" style="max-width:160px;text-transform:uppercase;" oninput="this.value=this.value.toUpperCase()">
              <button type="button" class="btn btn-sm btn-success" onclick="settingsUi.redeemPromo()">{{SETTINGS_PROMO_REDEEM}}</button>
              <span id="promo-status" class="small"></span>
            </div>
          </div>
        </div>
      </div>

      <div class="tab-pane fade" id="gg-main-tab-nesting" role="tabpanel">
        <div class="mb-2">
          <h3 class="h6 mb-0">{{NESTING_SETTINGS_TITLE}}</h3>
          <p class="text-muted small mb-0">{{NESTING_SETTINGS_SUBTITLE}}</p>
        </div>
        <div class="card border">
          <div class="card-body py-2 px-3">
            <div class="mb-2">
              <label class="form-label small mb-1" for="nesting-parts-margin">{{NESTING_PARTS_MARGIN_LABEL}}</label>
              <input id="nesting-parts-margin" type="text" inputmode="decimal" class="form-control form-control-sm" value="{{NESTING_PARTS_MARGIN_VAL}}">
              <div class="form-text small">{{NESTING_PARTS_MARGIN_HINT}}</div>
            </div>
            <div class="mb-2">
              <label class="form-label small mb-1" for="nesting-sheet-border-margin">{{NESTING_SHEET_BORDER_MARGIN_LABEL}}</label>
              <input id="nesting-sheet-border-margin" type="text" inputmode="decimal" class="form-control form-control-sm" value="{{NESTING_SHEET_BORDER_MARGIN_VAL}}">
              <div class="form-text small">{{NESTING_SHEET_BORDER_MARGIN_HINT}}</div>
            </div>
            <div class="mb-2">
              <label class="form-label small mb-1" for="nesting-refine-step">{{NESTING_REFINE_STEP_LABEL}}</label>
              <input id="nesting-refine-step" type="text" inputmode="decimal" class="form-control form-control-sm" value="{{NESTING_REFINE_STEP_VAL}}">
              <div class="form-text small">{{NESTING_REFINE_STEP_HINT}}</div>
            </div>
            <div class="mb-2">
              <label class="form-label small mb-1">{{NESTING_SHEET_SIZE_LABEL}}</label>
              <div class="d-flex gap-2 align-items-center">
                <input id="nesting-sheet-w" type="text" inputmode="decimal" class="form-control form-control-sm" value="{{NESTING_SHEET_W_VAL}}" aria-label="{{NESTING_SHEET_W_LABEL}}">
                <span class="small">×</span>
                <input id="nesting-sheet-h" type="text" inputmode="decimal" class="form-control form-control-sm" value="{{NESTING_SHEET_H_VAL}}" aria-label="{{NESTING_SHEET_H_LABEL}}">
              </div>
              <div class="form-text small">{{NESTING_SHEET_SIZE_HINT}}</div>
            </div>
            <div class="mb-2 form-check">
              <input class="form-check-input" type="checkbox" id="nesting-in-holes" {{NESTING_IN_HOLES_CHECKED}}>
              <label class="form-check-label small" for="nesting-in-holes">{{NESTING_IN_HOLES_LABEL}}</label>
              <div class="form-text small">{{NESTING_IN_HOLES_HINT}}</div>
            </div>
            <div class="mb-2 form-check">
              <input class="form-check-input" type="checkbox" id="nesting-allow-rotate" {{NESTING_ALLOW_ROTATE_CHECKED}}>
              <label class="form-check-label small" for="nesting-allow-rotate">{{NESTING_ALLOW_ROTATE_LABEL}}</label>
              <div class="form-text small">{{NESTING_ALLOW_ROTATE_HINT}}</div>
            </div>
            <div class="mb-2">
              <div class="small mb-1">{{NESTING_ORIGIN_LABEL}}</div>
              <div class="d-flex gap-3 align-items-center">
                <label class="d-flex align-items-center gap-1" style="cursor:pointer" for="nesting-origin-min">
                  <input class="form-check-input" type="radio" name="nesting-origin" id="nesting-origin-min" value="min" {{NESTING_ORIGIN_MIN_CHECKED}}>
                  <!-- origin x0,y0: fill goes UP the column, columns advance RIGHT -->
                  <svg width="30" height="46" viewBox="0 0 30 46" aria-hidden="true">
                    <rect x="4" y="3" width="22" height="40" fill="#f4f4f4" stroke="#999"/>
                    <line x1="15" y1="38" x2="15" y2="22" stroke="#c00" stroke-width="1.6"/>
                    <polygon points="15,19 12,24 18,24" fill="#c00"/>
                    <line x1="8" y1="39" x2="18" y2="39" stroke="#c00" stroke-width="1.6"/>
                    <polygon points="21,39 16,36 16,42" fill="#c00"/>
                  </svg>
                </label>
                <label class="d-flex align-items-center gap-1" style="cursor:pointer" for="nesting-origin-max">
                  <input class="form-check-input" type="radio" name="nesting-origin" id="nesting-origin-max" value="max" {{NESTING_ORIGIN_MAX_CHECKED}}>
                  <!-- origin xmax,ymax: fill goes DOWN the column, columns advance LEFT -->
                  <svg width="30" height="46" viewBox="0 0 30 46" aria-hidden="true">
                    <rect x="4" y="3" width="22" height="40" fill="#f4f4f4" stroke="#999"/>
                    <line x1="15" y1="8" x2="15" y2="24" stroke="#c00" stroke-width="1.6"/>
                    <polygon points="15,27 12,22 18,22" fill="#c00"/>
                    <line x1="22" y1="7" x2="12" y2="7" stroke="#c00" stroke-width="1.6"/>
                    <polygon points="9,7 14,4 14,10" fill="#c00"/>
                  </svg>
                </label>
              </div>
              <div class="form-text small">{{NESTING_ORIGIN_HINT}}</div>
            </div>
            <div class="mb-2 form-check">
              <input class="form-check-input" type="checkbox" id="nesting-auto-cut" {{NESTING_AUTO_CUT_CHECKED}}>
              <label class="form-check-label small" for="nesting-auto-cut">{{NESTING_AUTO_CUT_LABEL}}</label>
              <div class="form-text small">{{NESTING_AUTO_CUT_HINT}}</div>
            </div>
            <div class="d-flex gap-2 align-items-center">
              <button type="button" class="btn btn-sm btn-primary" onclick="settingsUi.saveNesting()">{{NESTING_SAVE_BTN}}</button>
              <span id="nesting-status" class="small"></span>
            </div>
          </div>
        </div>
      </div>

      <div class="tab-pane fade" id="gg-main-tab-toolbar" role="tabpanel">
        <div class="mb-2">
          <h3 class="h6 mb-0">{{TOOLBAR_SETTINGS_TITLE}}</h3>
          <p class="text-muted small mb-0">{{TOOLBAR_SETTINGS_SUBTITLE}}</p>
        </div>
        <div class="card border">
          <div class="card-body py-2 px-3">
            <ul id="gg-toolbar-list" class="list-group list-group-flush mb-2"></ul>
            <div class="d-flex gap-2 align-items-center">
              <button type="button" class="btn btn-sm btn-primary" onclick="settingsUi.saveToolbar()">{{TOOLBAR_SAVE_BTN}}</button>
              <button type="button" class="btn btn-sm btn-outline-secondary" onclick="settingsUi.resetToolbar()">{{TOOLBAR_RESET_BTN}}</button>
              <span id="toolbar-status" class="small"></span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  {{BOOTSTRAP_JS}}
  <script>
  var GG_SETTINGS_STRINGS = {
    promo_enter_code: {{SETTINGS_PROMO_ENTER_CODE_JSON}},
    promo_applying: {{SETTINGS_PROMO_APPLYING_JSON}},
    nesting_saved: {{NESTING_SAVED_JSON}},
    toolbar_saved: {{TOOLBAR_SAVED_JSON}},
    toolbar_reset_done: {{TOOLBAR_RESET_DONE_JSON}},
    toolbar_copy_name: {{TOOLBAR_COPY_NAME_JSON}}
  };
  var GG_TOOLBAR_ITEMS = {{TOOLBAR_ITEMS_JSON}};
  window.settingsUi = {
    redeemPromo: function() {
      var inp = document.getElementById('promo-code-input');
      var st  = document.getElementById('promo-status');
      if (!inp) return;
      var code = inp.value.trim();
      if (!code) { if (st) { st.className = 'small text-danger'; st.textContent = GG_SETTINGS_STRINGS.promo_enter_code; } return; }
      if (st) { st.className = 'small text-muted'; st.textContent = GG_SETTINGS_STRINGS.promo_applying; }
      sketchup.on_redeem_promo(code);
    },
    showPromoResult: function(ok, msg) {
      var st = document.getElementById('promo-status');
      if (!st) return;
      st.className = 'small ' + (ok ? 'text-success' : 'text-danger');
      st.textContent = msg;
    },
    saveNesting: function() {
      var p = document.getElementById('nesting-parts-margin');
      var b = document.getElementById('nesting-sheet-border-margin');
      var r = document.getElementById('nesting-refine-step');
      var h = document.getElementById('nesting-in-holes');
      var sw = document.getElementById('nesting-sheet-w');
      var sh = document.getElementById('nesting-sheet-h');
      var ac = document.getElementById('nesting-auto-cut');
      var ar = document.getElementById('nesting-allow-rotate');
      var og = document.querySelector('input[name="nesting-origin"]:checked');
      if (!p || !b) return;
      sketchup.on_nesting_save(p.value, b.value, r ? r.value : '', h && h.checked ? '1' : '0',
                               sw ? sw.value : '', sh ? sh.value : '', ac && ac.checked ? '1' : '0',
                               ar && ar.checked ? '1' : '0', og ? og.value : 'min');
    },
    showNestingResult: function(ok, msg) {
      var st = document.getElementById('nesting-status');
      if (!st) return;
      st.className = 'small ' + (ok ? 'text-success' : 'text-danger');
      st.textContent = msg;
    },
    // ── Toolbar tab: drag to reorder, toggle to hide ──────────────────────────
    renderToolbar: function() {
      var list = document.getElementById('gg-toolbar-list');
      if (!list || !Array.isArray(GG_TOOLBAR_ITEMS)) return;
      list.innerHTML = '';
      GG_TOOLBAR_ITEMS.forEach(function(it) {
        var li = document.createElement('li');
        li.className = 'list-group-item d-flex align-items-center gap-2 py-1 px-2';
        li.setAttribute('draggable', 'true');
        li.setAttribute('data-id', it.id);
        var handle = document.createElement('span');
        handle.className = 'text-muted';
        handle.style.cursor = 'grab';
        handle.textContent = '⋮⋮';
        var label = document.createElement('span');
        label.className = 'flex-grow-1 small';
        label.textContent = it.name || it.id; // textContent => no HTML injection
        var wrap = document.createElement('div');
        wrap.className = 'form-check form-switch m-0';
        var cb = document.createElement('input');
        cb.className = 'form-check-input gg-tb-show';
        cb.type = 'checkbox';
        cb.checked = !it.hidden;
        wrap.appendChild(cb);
        li.appendChild(handle);
        if (it.icon) {
          var img = document.createElement('img');
          img.src = it.icon;
          img.width = 22;
          img.height = 22;
          img.className = 'border rounded bg-light';
          img.style.flexShrink = '0';
          li.appendChild(img);
        }
        // Real shortcut the user assigned in SketchUp's Preferences (read-only).
        var sc = document.createElement('span');
        sc.className = 'badge ' + (it.shortcut ? 'text-bg-secondary' : 'text-bg-light text-muted');
        sc.style.flexShrink = '0';
        sc.textContent = it.shortcut ? it.shortcut : '—';
        // Copy the tool name to paste into Preferences > Shortcuts > Filter.
        var copy = document.createElement('button');
        copy.type = 'button';
        copy.className = 'btn btn-sm btn-outline-secondary py-0 px-1';
        copy.style.flexShrink = '0';
        copy.title = GG_SETTINGS_STRINGS.toolbar_copy_name;
        copy.innerHTML = '<svg width="13" height="13" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="5.5" y="5.5" width="8" height="8" rx="1.5"/><path d="M3.5 10.5h-1a1 1 0 0 1-1-1v-7a1 1 0 0 1 1-1h7a1 1 0 0 1 1 1v1"/></svg>';
        copy.addEventListener('click', function() { settingsUi.copyName(it.name, copy); });
        li.appendChild(label);
        li.appendChild(sc);
        li.appendChild(copy);
        li.appendChild(wrap);
        settingsUi._wireDrag(li);
        list.appendChild(li);
      });
    },
    _wireDrag: function(li) {
      li.addEventListener('dragstart', function(e) {
        settingsUi._dragEl = li;
        li.classList.add('opacity-50');
        if (e.dataTransfer) e.dataTransfer.effectAllowed = 'move';
      });
      li.addEventListener('dragend', function() {
        li.classList.remove('opacity-50');
        settingsUi._dragEl = null;
      });
      li.addEventListener('dragover', function(e) {
        e.preventDefault();
        var d = settingsUi._dragEl;
        if (!d || d === li) return;
        var r = li.getBoundingClientRect();
        var after = (e.clientY - r.top) > r.height / 2;
        li.parentNode.insertBefore(d, after ? li.nextSibling : li);
      });
    },
    saveToolbar: function() {
      var list = document.getElementById('gg-toolbar-list');
      if (!list) return;
      var order = [], hidden = [];
      var lis = list.querySelectorAll('li');
      for (var i = 0; i < lis.length; i++) {
        var id = lis[i].getAttribute('data-id');
        order.push(id);
        var cb = lis[i].querySelector('.gg-tb-show');
        if (cb && !cb.checked) hidden.push(id);
      }
      sketchup.on_toolbar_layout_save(order.join(','), hidden.join(','));
    },
    resetToolbar: function() {
      sketchup.on_toolbar_layout_reset();
    },
    applyToolbarItems: function(json) {
      try { GG_TOOLBAR_ITEMS = (typeof json === 'string') ? JSON.parse(json) : json; }
      catch (e) { return; }
      settingsUi.renderToolbar();
    },
    showToolbarResult: function(ok, msg) {
      var st = document.getElementById('toolbar-status');
      if (!st) return;
      st.className = 'small ' + (ok ? 'text-success' : 'text-danger');
      st.textContent = msg;
    },
    // ── Copy a tool's name to paste into SketchUp's Shortcuts filter ──────────
    copyName: function(name, btn) {
      try {
        var ta = document.createElement('textarea');
        ta.value = name;
        ta.style.position = 'fixed';
        ta.style.opacity = '0';
        document.body.appendChild(ta);
        ta.select();
        document.execCommand('copy');
        document.body.removeChild(ta);
      } catch (e) { /* clipboard not available */ }
      if (btn) {
        var old = btn.innerHTML;
        btn.classList.add('btn-success');
        btn.classList.remove('btn-outline-secondary');
        btn.textContent = '✓';
        setTimeout(function() {
          btn.innerHTML = old;
          btn.classList.remove('btn-success');
          btn.classList.add('btn-outline-secondary');
        }, 900);
      }
      // Guide the user where to paste it and assign the hotkey.
      sketchup.on_copy_help(name);
    }
  };
  settingsUi.renderToolbar();
  </script>
</body>
</html>
