<!DOCTYPE html>
<html lang="{{HTML_LANG}}">
<head>
<meta charset="UTF-8">
<title>{{MENU_COMPONENT_STATS}}</title>
<style>
  * { box-sizing: border-box; }
  body { margin: 0; font-family: "Segoe UI", Arial, sans-serif; font-size: 13px; color: #222; }
  .app { display: flex; height: 100vh; }
  .side { width: 160px; flex: 0 0 160px; border-right: 1px solid #ddd; padding: 12px 10px; display: flex; flex-direction: column; gap: 8px; }
  .tab { padding: 10px; text-align: center; border: 1px solid #ddd; border-radius: 4px; cursor: pointer; background: #fff; }
  .tab.active { background: #eef1f6; font-weight: 600; }
  .btn { padding: 10px; text-align: center; border: 1px solid #1e8e5a; color: #1e8e5a; border-radius: 4px; cursor: pointer; background: #fff; font-weight: 600; }
  .btn.dark { border-color: #37474f; color: #37474f; }
  .btn:active { transform: translateY(1px); }
  .main { flex: 1; overflow: auto; }
  table { border-collapse: collapse; width: 100%; }
  th, td { border: 1px solid #e3e6ea; padding: 6px 8px; white-space: nowrap; }
  th { background: #37474f; color: #fff; text-align: left; position: sticky; top: 0; }
  td.num, th.num { text-align: right; }
  tr.group td { background: #c9ccd1; font-weight: 700; }
  tr.grand td { background: #1e8e5a; color: #fff; font-weight: 700; }
  tr:nth-child(even):not(.group):not(.grand) td { background: #fafbfc; }
  tr.group td, tr.grand td { background-clip: padding-box; }
  /* Editable cells read as plain text; the input box only appears on click (focus). */
  input.cell { width: 90px; border: 1px solid transparent; border-radius: 3px; padding: 3px 5px; text-align: right; font: inherit; background: transparent; }
  input.cell:hover { border-color: #e3e6ea; }
  input.cell:focus { border-color: #1e8e5a; background: #fff; outline: none; }
  input.cell[type=number]::-webkit-inner-spin-button, input.cell[type=number]::-webkit-outer-spin-button { -webkit-appearance: none; margin: 0; }
  input.txt { width: 160px; text-align: left; }
  input.cell.unit { width: 45px; text-align: left; }
  input.cell.coef { width: 45px; }
  input.cell.qty { width: 63px; }
  .ico { width: 16px; height: 16px; vertical-align: middle; }
  .rm { cursor: pointer; }
  td.sttcell { white-space: nowrap; }
  td.sttcell .rm { margin-right: 6px; }
  td.sttcell span { color: #555; }
  .add { color: #1e8e5a; cursor: pointer; font-weight: 700; padding: 4px 8px; display: inline-block; }
  .add .ico { margin-right: 2px; }
  .hide { display: none; }
  .iconbtn { width: 44px; height: 44px; border: 1px solid #ddd; border-radius: 6px; cursor: pointer; background: #fff; align-self: center; display: flex; align-items: center; justify-content: center; }
  .iconbtn img { width: 26px; height: 26px; }
  .iconbtn:active { transform: translateY(1px); }
  .iconrow { display: flex; gap: 8px; justify-content: center; }
  .iconbtn.locked { background: #ffebee; border-color: #e57373; }
  .disabled { opacity: .45; pointer-events: none; }
  .lockbadge { text-align: center; color: #c62828; font-weight: 700; font-size: 12px; }
  .overlay { position: fixed; inset: 0; background: rgba(0,0,0,.35); display: none; align-items: center; justify-content: center; z-index: 50; }
  .overlay.show { display: flex; }
  .modal { background: #fff; border-radius: 8px; padding: 18px 20px; width: 340px; box-shadow: 0 10px 34px rgba(0,0,0,.3); display: flex; flex-direction: column; gap: 10px; }
  .modal h3 { margin: 0 0 4px; font-size: 15px; color: #37474f; }
  .modal label { font-size: 12px; color: #666; display: block; margin-bottom: 3px; }
  .modal input, .modal select { width: 100%; padding: 7px 8px; border: 1px solid #cfd4da; border-radius: 4px; font: inherit; }
  .modal .row { display: flex; gap: 8px; justify-content: flex-end; margin-top: 6px; }
  .modal .row .btn { padding: 8px 18px; }
  .modal .grid3 { display: flex; gap: 8px; }
  .modal .grid3 > div { flex: 1; }
</style>
</head>
<body>
<div class="app">
  <div class="side">
    <div class="tab active" id="tabPK" onclick="showTab('PK')">{{COMPONENT_STATS_TAB_ACCESSORIES}}</div>
    <div class="tab" id="tabCK" onclick="showTab('CK')">{{COMPONENT_STATS_TAB_PARTS}}</div>
    <div style="flex:1"></div>
    <div id="lockBadge" class="lockbadge hide">{{COMPONENT_STATS_LOCKED_BADGE}}</div>
    <div class="iconrow">
      <div class="iconbtn" id="btnRefresh" title="{{COMPONENT_STATS_REFRESH_TITLE}}" onclick="doRefresh()"><img src="{{ICON_BASE_URL}}WAREHOUSE_REFRESH.svg"></div>
      <div class="iconbtn" id="btnLock" title="{{COMPONENT_STATS_LOCK_TITLE}}" onclick="onLockClick()"><img src="{{ICON_BASE_URL}}CAM_LOCK.svg"></div>
      <div class="iconbtn" title="{{COMPONENT_STATS_CREATE_STAT}}" onclick="openStatModal()"><img src="{{ICON_BASE_URL}}CS_STAT_ADD.svg"></div>
    </div>
    <div class="btn dark" id="btnSave" onclick="doSave()">{{COMPONENT_STATS_SAVE_MODEL}}</div>
    <div class="btn" onclick="doExport()">{{COMPONENT_STATS_EXPORT_BTN}}</div>
  </div>
  <div class="main">
    <div id="viewPK"></div>
    <div id="viewCK" class="hide"></div>
  </div>
</div>

<div class="overlay" id="statModal">
  <div class="modal">
    <h3>{{COMPONENT_STATS_CREATE_STAT}}</h3>
    <div>
      <label for="statName">{{COMPONENT_STATS_STAT_NAME_LABEL}}</label>
      <input id="statName" type="text" placeholder="{{COMPONENT_STATS_STAT_NAME_PLACEHOLDER}}">
    </div>
    <div>
      <label for="statMode">{{COMPONENT_STATS_STAT_MODE_LABEL}}</label>
      <select id="statMode" onchange="onStatModeChange()">
        <option value="count">{{COMPONENT_STATS_MODE_COUNT}}</option>
        <option value="length">{{COMPONENT_STATS_MODE_LENGTH}}</option>
      </select>
    </div>
    <div class="grid3">
      <div><label for="statUnit">{{COMPONENT_STATS_STAT_UNIT_LABEL}}</label><input id="statUnit" type="text" placeholder="{{COMPONENT_STATS_UNIT_PLACEHOLDER}}"></div>
      <div><label for="statPrice">{{COMPONENT_STATS_STAT_PRICE_LABEL}}</label><input id="statPrice" type="text" value="0"></div>
      <div><label for="statCoef">{{COMPONENT_STATS_STAT_COEF_LABEL}}</label><input id="statCoef" type="number" step="0.01" value="1"></div>
    </div>
    <div class="row">
      <div class="btn dark" onclick="closeStatModal()">{{GCM_COMMON_CANCEL}}</div>
      <div class="btn" onclick="okStatModal()">OK</div>
    </div>
  </div>
</div>

<div class="overlay" id="unlockModal">
  <div class="modal">
    <h3>{{COMPONENT_STATS_UNLOCK_TITLE}}</h3>
    <div>
      <label for="unlockPw">{{COMPONENT_STATS_UNLOCK_PROMPT}}</label>
      <input id="unlockPw" type="password" autocomplete="current-password" onkeydown="if(event.key==='Enter')submitUnlock()">
      <div id="unlockErr" style="color:#c62828;font-size:12px;margin-top:6px;"></div>
    </div>
    <div class="row">
      <div class="btn dark" onclick="closeUnlock()">{{GCM_COMMON_CANCEL}}</div>
      <div class="btn" onclick="submitUnlock()">OK</div>
    </div>
  </div>
</div>

<script>
  var ICON = '{{ICON_BASE_URL}}';
  var COL_HEADERS = {{COMPONENT_STATS_COL_HEADERS_JSON}};
  var L = {
    grandTotal: '{{COMPONENT_STATS_GRAND_TOTAL}}',
    removeRow: '{{COMPONENT_STATS_REMOVE_ROW}}',
    addRow: '{{COMPONENT_STATS_ADD_ROW}}',
    unitCount: '{{COMPONENT_STATS_UNIT_PIECE}}',
    unitLength: '{{COMPONENT_STATS_UNIT_METER}}'
  };
  // The create-stat unit follows the mode: count → "cái", length → "m".
  function defaultUnit(mode) { return mode === 'length' ? L.unitLength : L.unitCount; }
  var DATA = { summary: { groups: [], total: 0 }, parts: [], prices: {}, manual: {}, meta: {} };
  var AUTO_GROUPS = { phu_kien_lien_ket: 1, doi_tuong_thong_ke: 1, chi_dan_canh: 1, tam: 1 };

  function num(v) { return (Number(v) || 0); }
  function money(v) { return Math.round(num(v)).toLocaleString('en-US', { maximumFractionDigits: 0 }); }
  function qtyfmt(v) { return num(v).toLocaleString('en-US', { maximumFractionDigits: 4 }); }

  function showTab(t) {
    document.getElementById('tabPK').classList.toggle('active', t === 'PK');
    document.getElementById('tabCK').classList.toggle('active', t === 'CK');
    document.getElementById('viewPK').classList.toggle('hide', t !== 'PK');
    document.getElementById('viewCK').classList.toggle('hide', t !== 'CK');
  }

  function recompute() {
    var grand = 0;
    DATA.summary.groups.forEach(function (g) {
      var gt = 0;
      g.rows.forEach(function (r) { r.amount = num(r.qty) * num(r.price) * (r.coef == null ? 1 : num(r.coef)); gt += r.amount; });
      g.total = gt; grand += gt;
    });
    DATA.summary.total = grand;
  }

  function onPrice(gi, ri, field, value) {
    var r = DATA.summary.groups[gi].rows[ri];
    if (field === 'unit') { r.unit = value; }
    else { r[field] = value === '' ? (field === 'coef' ? 1 : 0) : num(value); }
    var g = DATA.summary.groups[gi];
    if (AUTO_GROUPS[g.key] && r.key) { DATA.prices[r.key] = { price: num(r.price), coef: num(r.coef), unit: r.unit }; }
    else { syncManual(); }
    recompute(); renderTotals(); pushState();
  }

  function syncManual() {
    DATA.summary.groups.forEach(function (g) {
      if (AUTO_GROUPS[g.key]) return;
      DATA.manual[g.key] = g.rows.map(function (r) {
        return { loai: r.loai, mota: r.mota, qty: num(r.qty), unit: r.unit, price: num(r.price), coef: num(r.coef) };
      });
    });
  }

  function onManual(gi, ri, field, value) {
    var r = DATA.summary.groups[gi].rows[ri];
    r[field] = (field === 'qty' || field === 'price' || field === 'coef') ? num(value) : value;
    syncManual(); recompute(); renderTotals(); pushState();
  }

  function addManual(gi) {
    DATA.summary.groups[gi].rows.push({ stt: DATA.summary.groups[gi].rows.length + 1, loai: '', mota: '', qty: 1, unit: '', price: 0, coef: 1, amount: 0 });
    syncManual(); recompute(); renderPK(); pushState();
  }
  function rmManual(gi, ri) {
    DATA.summary.groups[gi].rows.splice(ri, 1);
    DATA.summary.groups[gi].rows.forEach(function (r, i) { r.stt = i + 1; });
    syncManual(); recompute(); renderPK(); pushState();
  }

  function renderTotals() {
    DATA.summary.groups.forEach(function (g, gi) {
      var gt = document.getElementById('gt' + gi); if (gt) gt.textContent = money(g.total);
      g.rows.forEach(function (r, ri) { var a = document.getElementById('amt' + gi + '_' + ri); if (a) a.textContent = money(r.amount); });
    });
    var grand = document.getElementById('grand'); if (grand) grand.textContent = money(DATA.summary.total);
  }

  function renderPK() {
    var html = '<table><thead><tr>' +
      COL_HEADERS.map(function (h, i) { return '<th' + (i >= 3 ? ' class="num"' : '') + '>' + h + '</th>'; }).join('') +
      '</tr></thead><tbody>';
    DATA.summary.groups.forEach(function (g, gi) {
      html += '<tr class="group"><td></td><td colspan="7">' + esc(g.title) + '</td><td class="num" id="gt' + gi + '">' + money(g.total) + '</td></tr>';
      var manual = !AUTO_GROUPS[g.key];
      g.rows.forEach(function (r, ri) {
        if (manual) {
          html += '<tr><td class="sttcell"><img class="ico rm" src="' + ICON + 'CS_REMOVE.svg" title="' + esc(L.removeRow) + '" onclick="rmManual(' + gi + ',' + ri + ')"><span>' + r.stt + '</span></td>' +
            tdInput('text', 'loai', gi, ri, r.loai, 'txt') +
            tdInput('text', 'mota', gi, ri, r.mota, 'txt') +
            tdInput('number', 'qty', gi, ri, r.qty, 'qty') +
            tdInput('text', 'unit', gi, ri, r.unit, 'unit') +
            moneyCell('onManual', gi, ri, 'price', r.price) +
            tdInput('number', 'coef', gi, ri, r.coef, 'coef') +
            '<td class="num" id="amt' + gi + '_' + ri + '">' + money(r.amount) + '</td>' +
            '<td></td></tr>';
        } else {
          html += '<tr><td class="num">' + r.stt + '</td><td>' + esc(r.loai) + '</td><td>' + esc(r.mota) + '</td>' +
            '<td class="num">' + qtyfmt(r.qty) + '</td>' + unitCell('onPrice', gi, ri, r.unit) +
            moneyCell('onPrice', gi, ri, 'price', r.price) + coefCell('onPrice', gi, ri, r.coef) +
            '<td class="num" id="amt' + gi + '_' + ri + '">' + money(r.amount) + '</td><td></td></tr>';
        }
      });
      if (manual) html += '<tr><td></td><td colspan="8"><span class="add" onclick="addManual(' + gi + ')"><img class="ico" src="' + ICON + 'CS_ADD.svg"> ' + esc(L.addRow) + '</span></td></tr>';
    });
    html += '<tr class="grand"><td></td><td colspan="7">' + esc(L.grandTotal) + '</td><td class="num" id="grand">' + money(DATA.summary.total) + '</td></tr>';
    html += '</tbody></table>';
    document.getElementById('viewPK').innerHTML = html;
  }

  function tdInput(type, field, gi, ri, val, cls) {
    return '<td><input class="cell ' + (cls || '') + '" type="' + type + '" value="' + esc(val) + '" ' +
      'oninput="onManual(' + gi + ',' + ri + ',\'' + field + '\',this.value)"></td>';
  }
  function parseMoney(s) { return Number(String(s).replace(/[^0-9.\-]/g, '')) || 0; }
  function moneyCell(handler, gi, ri, field, val) {
    return '<td class="num"><input class="cell" type="text" value="' + money(val) + '" ' +
      'oninput="' + handler + '(' + gi + ',' + ri + ',\'' + field + '\',parseMoney(this.value))" ' +
      'onblur="this.value=money(parseMoney(this.value))"></td>';
  }
  function coefCell(handler, gi, ri, val) {
    return '<td class="num"><input class="cell coef" type="number" step="0.01" value="' + num(val) + '" ' +
      'oninput="' + handler + '(' + gi + ',' + ri + ',\'coef\',this.value)"></td>';
  }
  function unitCell(handler, gi, ri, val) {
    return '<td><input class="cell unit" type="text" value="' + esc(val) + '" ' +
      'oninput="' + handler + '(' + gi + ',' + ri + ',\'unit\',this.value)"></td>';
  }

  function renderCK() {
    var d = DATA.detail || { columns: [], rows: [] };
    var html = '<table><thead><tr>' +
      d.columns.map(function (c) { return '<th>' + esc(c) + '</th>'; }).join('') +
      '</tr></thead><tbody>';
    d.rows.forEach(function (row) {
      html += '<tr>' + row.map(function (v) {
        var n = (typeof v === 'number');
        return '<td' + (n ? ' class="num"' : '') + '>' + esc(n ? qtyfmt(v) : v) + '</td>';
      }).join('') + '</tr>';
    });
    html += '</tbody></table>';
    document.getElementById('viewCK').innerHTML = html;
  }

  function esc(v) { return (v == null ? '' : String(v)).replace(/[&<>"]/g, function (c) { return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]; }); }

  function renderAll(payload) {
    DATA = payload || DATA;
    DATA.prices = DATA.prices || {}; DATA.manual = DATA.manual || {}; DATA.meta = DATA.meta || {};
    recompute(); renderPK(); renderCK();
  }

  function statePayload() { syncManual(); return JSON.stringify({ prices: DATA.prices, manual: DATA.manual, meta: DATA.meta }); }
  function fullPayload() { syncManual(); return JSON.stringify(DATA); }
  function pushState() { if (window.sketchup && sketchup.sync) sketchup.sync(fullPayload()); }
  function doSave() { if (DATA.locked) return; if (window.sketchup && sketchup.save) sketchup.save(fullPayload()); }
  function doExport() { if (window.sketchup && sketchup.export) sketchup.export(statePayload()); }

  // ── lock (driven by Ruby via setLock) ──────────────────────────────────────
  function applyLock() {
    var on = !!DATA.locked;
    var badge = document.getElementById('lockBadge'); if (badge) badge.classList.toggle('hide', !on);
    ['btnSave', 'btnRefresh'].forEach(function (id) {
      var e = document.getElementById(id); if (e) e.classList.toggle('disabled', on);
    });
    var lk = document.getElementById('btnLock'); if (lk) lk.classList.toggle('locked', on);
  }
  function setLock(locked) { DATA.locked = !!locked; if (!DATA.locked) closeUnlock(); applyLock(); }
  function doRefresh() { if (DATA.locked) return; if (window.sketchup && sketchup.refresh) sketchup.refresh(''); }
  function onLockClick() {
    if (DATA.locked) { openUnlock(); }
    else if (window.sketchup && sketchup.lock) { sketchup.lock(''); }
  }
  function openUnlock() {
    setVal('unlockPw', ''); var e = document.getElementById('unlockErr'); if (e) e.textContent = '';
    document.getElementById('unlockModal').classList.add('show');
    var p = document.getElementById('unlockPw'); if (p) p.focus();
  }
  function closeUnlock() { var m = document.getElementById('unlockModal'); if (m) m.classList.remove('show'); }
  function submitUnlock() { if (window.sketchup && sketchup.unlock) sketchup.unlock(val('unlockPw')); }
  function unlockFailed(msg) { var e = document.getElementById('unlockErr'); if (e) e.textContent = msg || ''; }

  function val(id) { var e = document.getElementById(id); return e ? e.value : ''; }
  function setVal(id, v) { var e = document.getElementById(id); if (e) e.value = v; }
  function openStatModal() {
    setVal('statName', ''); setVal('statPrice', '0'); setVal('statCoef', '1');
    setVal('statUnit', defaultUnit(val('statMode') || 'count'));
    document.getElementById('statModal').classList.add('show');
    var n = document.getElementById('statName'); if (n) n.focus();
  }
  // Keep the unit in sync with the mode; the user can still Tab in and override it.
  function onStatModeChange() { setVal('statUnit', defaultUnit(val('statMode'))); }
  function closeStatModal() { document.getElementById('statModal').classList.remove('show'); }
  function okStatModal() {
    var data = {
      name: val('statName'), mode: val('statMode') || 'count',
      unit: val('statUnit'), price: parseMoney(val('statPrice')), coef: num(val('statCoef')) || 1
    };
    if (window.sketchup && sketchup.create_stat) sketchup.create_stat(JSON.stringify(data));
    closeStatModal();
  }

  window.addEventListener('load', function () { if (window.sketchup && sketchup.ready) sketchup.ready(); });
</script>
</body>
</html>
