<div class="container-fluid" id="container-wrapper">
    <div class="d-sm-flex align-items-center justify-content-between mb-4">
        <h1 class="h3 mb-0 text-gray-800">Patch aplikasi</h1>
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="./">Home</a></li>
            <li class="breadcrumb-item active" aria-current="page">Patch aplikasi</li>
        </ol>
    </div>
    <div class="row">
        <div class="col-md-12">

            <!-- Quick actions -->
            <div class="mb-3 d-flex flex-wrap" style="gap:.5rem">
                <button type="button" class="btn btn-sm btn-outline-primary" data-cmd="versions">Cek Versi</button>
                <button type="button" class="btn btn-sm btn-primary" data-cmd="update">Update App</button>
                <button type="button" class="btn btn-sm btn-outline-warning" data-cmd="patch">Cek Patch</button>
                <button type="button" class="btn btn-sm btn-warning" data-cmd="installpatch">Install Patch</button>
                <button type="button" class="btn btn-sm btn-outline-info" data-cmd="log">Lihat Log</button>
                <button type="button" class="btn btn-sm btn-outline-secondary" data-cmd="clearlog">Bersihkan Log</button>
                <button type="button" class="btn btn-sm btn-outline-secondary" data-cmd="cleartmp">Bersihkan Temp</button>
                <button type="button" class="btn btn-sm btn-outline-dark" data-cmd="ping">Cek Koneksi</button>
            </div>

            <div class="card">
                <div class="card-body">
                    <div class="card-block">
                        <div class="code-window mt-2">
                            <div class="dots">
                                <div class="red"></div>
                                <div class="orange"></div>
                                <div class="green"></div>
                                <!--code>command : help/? |  patch | readme | clear | wa</code-->
                            </div>
                            <div id="update-terminal" class="terminal" tabindex="0" style="height:500px;max-height:600px; cursor:text;"></div>
                        </div>
                    </div><!-- /.card -->
                </div><!-- /.card -->
            </div><!-- /.card -->

        </div>
    </div>
</div>

<style>
.code-window {
  border-radius: .45rem;
  background-color: #000;
  padding: 1.52rem;
  box-shadow: 0 8px 24px 0 rgba(0, 0, 0, 0.1);
}

pre[class*="language-"].line-numbers {
  position: relative;
  padding: 0;
  counter-reset: linenumber;
}

pre[class*="language-"] {
  background: #000;
}

#update-terminal{pointer-events:auto;}
#update-terminal .cmd, #update-terminal .cmd *{user-select:text;}
#update-terminal .cursor{opacity:1 !important;}

#update-terminal:focus { outline: none; }
#update-terminal .terminal-input { caret-color: #fff; }

/* FORCE warna teks terminal supaya tidak hitam di atas hitam */
#update-terminal,
#update-terminal .terminal-output,
#update-terminal .terminal-output * ,
#update-terminal .terminal-prompt,
#update-terminal .terminal-input {
  color: #7dd3fc !important;
}

#update-terminal .terminal-cursor {
  background: #7dd3fc !important;
}
</style>

<script src="<?= base_url('assets/'); ?>js/prism.min.js"></script>
<script src="<?= base_url('assets/'); ?>js/prism-line-numbers.min.js"></script>

<!-- IMPORTANT: cukup 1x include jquery.terminal -->
<script src="<?= base_url('assets/'); ?>js/jquery.terminal.min.js"></script>
<script src="//unpkg.com/jquery.terminal/js/xml_formatting.js"></script>

<script>
$(function() {
  window.base_url = window.base_url || "<?= base_url(); ?>";
  var nama = '<?= isset($nama)?$nama:''; ?>';

  function toText(v){
    if (v === null || v === undefined) return '';
    if (typeof v === 'string') return v;
    if (typeof v === 'number') return String(v);
    try { return JSON.stringify(v); } catch(e){ return String(v); }
  }

  function arrayToMultiline(arr){
    if (!Array.isArray(arr)) return toText(arr);
    return arr.map(toText).join("\n");
  }

  function safeEcho(term, text){
    // agar string seperti [22:04:31] tidak dianggap formatting terminal
    text = $.terminal.escape_brackets(String(text || ''));
    term.echo(text);
  }

  // ===== LOADING ANIMASI: titik berjalan =====
  function startLoader(term) {
    var dots = 0;
    var maxDots = 10;
    var alive = true;

    // buat 1 baris loader
    safeEcho(term, ""); 
    var lineId = term.last_index();

    function render() {
      if (!alive) return;
      dots = (dots + 1) % (maxDots + 1);

      // contoh animasi: "." bertambah lalu reset
      var txt = '.'.repeat(dots) + ' '.repeat(maxDots - dots);

      // update baris loader (bukan echo baru)
      term.update(lineId, txt);
    }

    render();
    var timer = setInterval(render, 120);

    return {
      stop: function(replaceWith) {
        alive = false;
        clearInterval(timer);
        // kosongkan baris loader (atau bisa isi teks lain)
        term.update(lineId, replaceWith || "");
      }
    };
  }

  var term = $('#update-terminal').terminal(function(command, term) {
    command = $.trim(command || '');
    if (!command) return;

    // mulai loader animasi
    var loader = startLoader(term);

    $.ajax({
      url: window.base_url + 'updateversi/update_app',
      method: 'POST',
      data: { command: command },
      dataType: 'json',
      timeout: 180000
    })
    .done(function(response) {
      // hentikan loader & hapus barisnya
      loader.stop("");

      if (Array.isArray(response)) {
        safeEcho(term, arrayToMultiline(response));
      } else if (response && typeof response === 'object' && response.status === 'log') {
        safeEcho(term, toText(response.data));
      } else {
        safeEcho(term, toText(response));
      }

      term.scroll_to_bottom();
      term.focus(true);
    })
    .fail(function(xhr) {
      // hentikan loader & hapus barisnya
      loader.stop("");

      var msg = 'Request gagal (HTTP ' + (xhr.status || '-') + ')';
      try {
        var parsed = JSON.parse(xhr.responseText);
        if (parsed && parsed.msg) msg = parsed.msg;
      } catch(e) {}
      safeEcho(term, msg);
      term.scroll_to_bottom();
      term.focus(true);
    });

  }, {
    greetings: null,
    height: 500,
    prompt: '> ',
    onInit: function(t) {
      safeEcho(t, "Selamat datang " + (nama || "Admin App"));
      safeEcho(t, "");
      t.focus(true);
    }
  });

  // tombol quick action
  $(document).on('click', 'button[data-cmd]', function(){
    var cmd = $(this).data('cmd');
    if (!cmd) return;
    term.exec(String(cmd));
    term.focus(true);
  });

  // klik area terminal untuk fokus
  $(document).on('click', '#update-terminal', function(){
    term.focus(true);
  });
});
</script>
