<?php
/**
 * FMANAGER v1.0 - Single File Manager + Web Terminal
 * Support: Linux / Windows / macOS (PHP 5.6+)
 * Fitur: browse, upload chunk, download, edit, rename, copy, move, delete,
 *        zip/unzip, tar/gz, chmod, touch, search, hash, preview, terminal.
 *
 * Password opsional: isi $FM_CONFIG['password']. Kosong = tanpa login.
 */

@set_time_limit(0);
@ini_set('display_errors', '0');
@ini_set('log_errors', '0');
error_reporting(0);

$FM_CONFIG = array(
    'password'     => '',                 // '' = tanpa login
    'session'      => 'fmgr_sess',
    'home'         => '',                 // '' = folder script ini
    'editor_max'   => 8388608,            // 8 MB batas edit
    'exec_timeout' => 60,                 // detik per command terminal
    'upload_chunk' => 1048576,            // 1 MB per potongan
    'win_cp'       => 'CP850',             // codepage output konsol Windows (mis. CP437/CP936)
);

/* ---------------------------------------------------------------- core */

function fm_is_win() { return DIRECTORY_SEPARATOR === '\\'; }

function fm_cfg($k, $d = null) {
    global $FM_CONFIG;
    return isset($FM_CONFIG[$k]) ? $FM_CONFIG[$k] : $d;
}

function fm_slash($p) { return str_replace('\\', '/', (string)$p); }

function fm_join($dir, $name) {
    $dir = rtrim($dir, '/');
    if ($dir === '') $dir = '/';
    if ($dir === '/') return '/' . ltrim($name, '/');
    return $dir . '/' . $name;
}

function fm_norm($p) {
    $p = fm_slash($p);
    if ($p === '') return '';
    if (substr($p, 0, 1) === '~') $p = fm_home() . substr($p, 1);

    $prefix = '';
    if (preg_match('#^([A-Za-z]):(.*)$#', $p, $m)) {
        $prefix = strtoupper($m[1]) . ':/';
        $p = ltrim($m[2], '/');
    } elseif (substr($p, 0, 1) === '/') {
        $prefix = '/';
        $p = ltrim($p, '/');
    } else {
        $h = fm_home();
        if ($p === '' || $p === '.') return $h;
        return fm_norm($h . '/' . $p);
    }

    $out = array();
    foreach (explode('/', $p) as $seg) {
        if ($seg === '' || $seg === '.') continue;
        if ($seg === '..') { array_pop($out); continue; }
        $out[] = $seg;
    }
    return $prefix . implode('/', $out);
}

function fm_home() {
    $h = (string)fm_cfg('home', '');
    if ($h !== '') return rtrim(fm_slash(fm_norm($h)), '/');
    return rtrim(fm_slash(dirname(__FILE__)), '/');
}

function fm_parent($path) {
    $path = rtrim(fm_norm($path), '/');
    if ($path === '' || $path === '/') return '/';
    if (preg_match('#^[A-Za-z]:$#', $path)) return $path . '/';
    if (preg_match('#^[A-Za-z]:/$#', $path)) return $path;
    $pos = strrpos($path, '/');
    if ($pos === false) return fm_home();
    if ($pos === 0) return '/';
    $parent = substr($path, 0, $pos);
    if (preg_match('#^[A-Za-z]:$#', $parent)) $parent .= '/';
    return $parent;
}

function fm_size($b) {
    $b = (float)$b;
    $u = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
    $i = 0;
    while ($b >= 1024 && $i < 5) { $b /= 1024; $i++; }
    return ($i === 0) ? ((int)$b) . ' B' : round($b, 2) . ' ' . $u[$i];
}

function fm_perm($path) {
    $p = @fileperms($path);
    if (!$p) return '----';
    return substr(sprintf('%o', $p), -4);
}

function fm_user() {
    if (!fm_is_win() && function_exists('posix_geteuid')) {
        $p = @posix_getpwuid(posix_geteuid());
        if ($p && isset($p['name'])) return $p['name'];
    }
    $u = @getenv('USERNAME');
    if (!$u) $u = @getenv('USER');
    if (!$u) $u = @get_current_user();
    return $u ? $u : '?';
}

function fm_owner($path) {
    if (fm_is_win()) return '';
    $uid = @fileowner($path);
    if ($uid === false) return '';
    $u = @posix_getpwuid($uid);
    return $u ? $u['name'] : (string)$uid;
}

function fm_utf8_fix($s) {
    $s = (string)$s;
    if ($s === '' || @preg_match('//u', $s)) return $s;
    if (function_exists('mb_convert_encoding')) {
        $c = @mb_convert_encoding($s, 'UTF-8', 'Windows-1252');
        if (is_string($c) && @preg_match('//u', $c)) return $c;
    }
    if (function_exists('iconv')) {
        $c = @iconv('Windows-1252', 'UTF-8//IGNORE', $s);
        if (is_string($c) && $c !== '' && @preg_match('//u', $c)) return $c;
    }
    return preg_replace('/[^\x09\x0A\x0D\x20-\x7E]/', '?', $s);
}

function fm_json_clean($v) {
    if (is_array($v)) {
        $o = array();
        foreach ($v as $k => $x) {
            $o[is_string($k) ? fm_utf8_fix($k) : $k] = fm_json_clean($x);
        }
        return $o;
    }
    if (is_string($v)) return fm_utf8_fix($v);
    return $v;
}

function fm_json($data) {
    while (ob_get_level() > 0) { @ob_end_clean(); }
    header('Content-Type: application/json; charset=utf-8');
    header('Cache-Control: no-store');
    $flags = JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES;
    $out = @json_encode(fm_json_clean($data), $flags);
    if ($out === false) {
        $out = '{"ok":false,"error":"Respons tidak bisa di-encode ke JSON."}';
    }
    echo $out;
    exit;
}

function fm_ok($d = array()) { fm_json(array_merge(array('ok' => true), $d)); }
function fm_err($m) { fm_json(array('ok' => false, 'error' => $m)); }

function fm_raw($path, $download, $name = null) {
    if (!is_file($path) || !is_readable($path)) {
        header('HTTP/1.1 404 Not Found');
        echo 'File not found';
        exit;
    }
    $size = @filesize($path);
    $mime = 'application/octet-stream';
    if (!$download && function_exists('finfo_open')) {
        $fi = @finfo_open(FILEINFO_MIME_TYPE);
        if ($fi) { $m = @finfo_file($fi, $path); if ($m) $mime = $m; finfo_close($fi); }
    }
    while (ob_get_level() > 0) { @ob_end_clean(); }
    header('Content-Type: ' . $mime);
    header('Content-Length: ' . $size);
    header('Accept-Ranges: none');
    if ($download) {
        if ($name === null) $name = basename($path);
        $name = str_replace(array('"', "\r", "\n"), '', $name);
        header('Content-Disposition: attachment; filename="' . $name . '"; filename*=UTF-8\'\'' . rawurlencode($name));
    } else {
        header('Content-Disposition: inline; filename="' . basename($path) . '"');
    }
    $fp = @fopen($path, 'rb');
    if (!$fp) exit;
    while (!feof($fp)) {
        echo fread($fp, 65536);
        @flush();
    }
    fclose($fp);
    exit;
}

/* --------------------------------------------------------------- auth */

if ((string)fm_cfg('password', '') !== '') {
    @session_name((string)fm_cfg('session'));
    @session_start();
    if (isset($_POST['fm_pass'])) {
        if (hash_equals((string)fm_cfg('password'), (string)$_POST['fm_pass'])) {
            $_SESSION['fmgr_auth'] = true;
        } else {
            $GLOBALS['fm_login_error'] = 'Password salah.';
        }
    }
    if (empty($_SESSION['fmgr_auth'])) {
        header('Content-Type: text/html; charset=utf-8');
        $err = isset($GLOBALS['fm_login_error']) ? $GLOBALS['fm_login_error'] : '';
        echo '<!DOCTYPE html><html><head><meta charset="utf-8"><title>Login</title><meta name="viewport" content="width=device-width,initial-scale=1">';
        echo '<style>body{margin:0;height:100vh;display:flex;align-items:center;justify-content:center;background:#0d1117;font:14px/1.4 system-ui,Segoe UI,sans-serif;color:#e6edf3}form{background:#161b22;border:1px solid #30363d;border-radius:10px;padding:28px;width:300px}h2{margin:0 0 16px;font-size:16px}input{width:100%;box-sizing:border-box;background:#0d1117;border:1px solid #30363d;color:#e6edf3;padding:10px;border-radius:6px;margin-bottom:12px}button{width:100%;padding:10px;border:0;border-radius:6px;background:#238636;color:#fff;cursor:pointer;font-weight:600}.e{color:#f85149;margin-bottom:10px}</style></head><body>';
        echo '<form method="post"><h2>&#128273; File Manager</h2>';
        if ($err) echo '<div class="e">' . htmlspecialchars($err) . '</div>';
        echo '<input type="password" name="fm_pass" placeholder="Password" autofocus><button type="submit">Masuk</button></form></body></html>';
        exit;
    }
}

/* ------------------------------------------------------- file helpers */

function fm_recursive_copy($src, $dst) {
    if (is_link($src)) {
        $t = @readlink($src);
        return $t !== false ? @symlink($t, $dst) : false;
    }
    if (is_dir($src)) {
        if (!is_dir($dst) && !@mkdir($dst, 0755, true)) return false;
        $dh = @opendir($src);
        if (!$dh) return false;
        $ok = true;
        while (($f = readdir($dh)) !== false) {
            if ($f === '.' || $f === '..') continue;
            if (!fm_recursive_copy(fm_join($src, $f), fm_join($dst, $f))) $ok = false;
        }
        closedir($dh);
        return $ok;
    }
    return @copy($src, $dst);
}

function fm_recursive_delete($path) {
    if (is_link($path) || is_file($path)) return @unlink($path);
    if (!is_dir($path)) return false;
    $dh = @opendir($path);
    if (!$dh) return false;
    $ok = true;
    while (($f = readdir($dh)) !== false) {
        if ($f === '.' || $f === '..') continue;
        if (!fm_recursive_delete(fm_join($path, $f))) $ok = false;
    }
    closedir($dh);
    if (!@rmdir($path)) $ok = false;
    return $ok;
}

function fm_recursive_size($path, &$count = 0, $limit = 50000) {
    $total = 0;
    if ($count >= $limit) return 0;
    if (is_file($path)) { $count++; return (float)@filesize($path); }
    if (!is_dir($path) || is_link($path)) return 0;
    $dh = @opendir($path);
    if (!$dh) return 0;
    while (($f = readdir($dh)) !== false) {
        if ($f === '.' || $f === '..') continue;
        $total += fm_recursive_size(fm_join($path, $f), $count, $limit);
        if ($count >= $limit) break;
    }
    closedir($dh);
    return $total;
}

function fm_unique($dir, $name) {
    $target = fm_join($dir, $name);
    if (!file_exists($target)) return $target;
    $info = pathinfo($name);
    $base = isset($info['filename']) ? $info['filename'] : $name;
    $ext = isset($info['extension']) && $info['extension'] !== '' ? '.' . $info['extension'] : '';
    for ($i = 2; $i < 1000; $i++) {
        $t = fm_join($dir, $base . ' (' . $i . ')' . $ext);
        if (!file_exists($t)) return $t;
    }
    return fm_join($dir, $base . '_' . time() . $ext);
}

/* ------------------------------------------------------------- listing */

function fm_list($path) {
    $path = fm_norm($path);
    if (!is_dir($path)) fm_err('Folder tidak ditemukan: ' . $path);
    $names = @scandir($path);
    if ($names === false) fm_err('Tidak bisa membaca folder (permission ditolak).');
    $items = array();
    foreach ($names as $name) {
        if ($name === '.' || $name === '..') continue;
        $full = fm_join($path, $name);
        $isDir = @is_dir($full);
        $st = @stat($full);
        $items[] = array(
            'n' => $name,
            'd' => $isDir,
            's' => $isDir ? 0 : (int)@filesize($full),
            'm' => $st ? (int)$st['mtime'] : 0,
            'p' => fm_perm($full),
            'l' => @is_link($full),
            'r' => @is_readable($full),
            'w' => @is_writable($full),
        );
    }
    usort($items, function ($a, $b) {
        if ($a['d'] !== $b['d']) return $a['d'] ? -1 : 1;
        return strnatcasecmp($a['n'], $b['n']);
    });
    $free = @disk_free_space($path);
    $total = @disk_total_space($path);
    fm_ok(array(
        'path'   => $path,
        'parent' => fm_parent($path),
        'home'   => fm_home(),
        'items'  => $items,
        'free'   => $free === false ? 0 : (float)$free,
        'total'  => $total === false ? 0 : (float)$total,
        'free_h' => $free === false ? '?' : fm_size($free),
        'total_h'=> $total === false ? '?' : fm_size($total),
        'os'     => PHP_OS,
        'php'    => PHP_VERSION,
        'user'   => fm_user(),
        'sapi'   => php_sapi_name(),
        'sep'    => DIRECTORY_SEPARATOR,
    ));
}

function fm_tree($path) {
    $path = fm_norm($path);
    if (!is_dir($path)) fm_err('Bukan folder.');
    $out = array();
    $names = @scandir($path);
    if ($names === false) fm_ok(array('items' => $out));
    foreach ($names as $n) {
        if ($n === '.' || $n === '..') continue;
        $full = fm_join($path, $n);
        if (!@is_dir($full) || @is_link($full)) continue;
        $childCount = 0;
        $dh = @opendir($full);
        if ($dh) {
            while (($c = readdir($dh)) !== false) {
                if ($c === '.' || $c === '..') continue;
                if (@is_dir(fm_join($full, $c))) $childCount++;
            }
            closedir($dh);
        }
        $out[] = array('n' => $n, 'has' => $childCount > 0, 'w' => @is_writable($full));
    }
    usort($out, function ($a, $b) { return strnatcasecmp($a['n'], $b['n']); });
    fm_ok(array('path' => $path, 'items' => $out));
}

/* ---------------------------------------------------------- read/write */

function fm_read($path) {
    $path = fm_norm($path);
    if (!is_file($path)) fm_err('File tidak ditemukan.');
    if (!is_readable($path)) fm_err('File tidak bisa dibaca (permission).');
    $size = (int)@filesize($path);
    if ($size > (int)fm_cfg('editor_max')) fm_err('File terlalu besar untuk editor (' . fm_size($size) . '). Pakai Download.');
    $data = @file_get_contents($path);
    if ($data === false) fm_err('Gagal membaca file.');
    $binary = (strpos($data, "\0") !== false);
    fm_ok(array(
        'path'   => $path,
        'size'   => $size,
        'mtime'  => (int)@filemtime($path),
        'perm'   => fm_perm($path),
        'binary' => $binary,
        'data'   => base64_encode($data),
    ));
}

function fm_save($path, $b64) {
    $path = fm_norm($path);
    $data = base64_decode($b64, true);
    if ($data === false) fm_err('Payload tidak valid.');
    $dir = fm_parent($path);
    if (!is_dir($dir)) fm_err('Folder tujuan tidak ada: ' . $dir);
    if (is_dir($path)) fm_err('Path tersebut sebuah folder.');
    $fp = @fopen($path, 'wb');
    if (!$fp) fm_err('Tidak bisa menulis file (permission / read-only).');
    $n = @fwrite($fp, $data);
    fclose($fp);
    if ($n === false) fm_err('Gagal menulis file.');
    @touch($path);
    fm_ok(array('path' => $path, 'size' => (int)@filesize($path), 'perm' => fm_perm($path)));
}

function fm_mkdir($path) {
    $path = fm_norm($path);
    if (file_exists($path)) fm_err('Sudah ada: ' . $path);
    if (!@mkdir($path, 0755, true)) fm_err('Gagal membuat folder.');
    fm_ok(array('path' => $path));
}

function fm_newfile($path) {
    $path = fm_norm($path);
    if (file_exists($path)) fm_err('Sudah ada: ' . $path);
    $fp = @fopen($path, 'wb');
    if (!$fp) fm_err('Gagal membuat file.');
    fclose($fp);
    fm_ok(array('path' => $path));
}

function fm_rename($from, $to) {
    $from = fm_norm($from);
    $to   = fm_norm($to);
    if (!file_exists($from)) fm_err('Sumber tidak ada.');
    if (file_exists($to) && strtolower($from) !== strtolower($to)) fm_err('Tujuan sudah ada: ' . $to);
    if (!@rename($from, $to)) {
        if (!fm_recursive_copy($from, $to)) fm_err('Rename gagal (permission / beda filesystem).');
        fm_recursive_delete($from);
    }
    fm_ok(array('from' => $from, 'to' => $to));
}

function fm_move($items, $dest) {
    $dest = fm_norm($dest);
    if (!is_dir($dest)) {
        /* satu item + tujuan berupa nama file baru = pindah sekaligus rename */
        if (count($items) === 1 && !file_exists($dest) && is_dir(fm_parent($dest))) {
            $src = fm_norm($items[0]);
            if (!file_exists($src)) fm_err('Sumber tidak ada.');
            if (!@rename($src, $dest)) {
                if (!fm_recursive_copy($src, $dest)) fm_err('Pindah gagal (permission / beda filesystem).');
                fm_recursive_delete($src);
            }
            fm_ok(array('moved' => 1, 'dest' => $dest));
        }
        fm_err('Folder tujuan tidak ada: ' . $dest);
    }
    $moved = 0;
    foreach ($items as $it) {
        $src = fm_norm($it);
        if (!file_exists($src)) continue;
        $target = fm_join($dest, basename($src));
        if (strtolower(rtrim($target, '/')) === strtolower(rtrim($src, '/'))) continue;
        if (file_exists($target)) $target = fm_unique($dest, basename($src));
        if (!@rename($src, $target)) {
            if (!fm_recursive_copy($src, $target)) continue;
            fm_recursive_delete($src);
        }
        $moved++;
    }
    fm_ok(array('moved' => $moved, 'dest' => $dest));
}

function fm_copy_items($items, $dest) {
    $dest = fm_norm($dest);
    if (!is_dir($dest)) fm_err('Folder tujuan tidak ada: ' . $dest);
    $copied = 0;
    foreach ($items as $it) {
        $src = fm_norm($it);
        if (!file_exists($src)) continue;
        $target = fm_unique($dest, basename($src));
        if (fm_recursive_copy($src, $target)) $copied++;
    }
    fm_ok(array('copied' => $copied, 'dest' => $dest));
}

function fm_delete($items) {
    $deleted = array();
    foreach ($items as $it) {
        $p = fm_norm($it);
        if ($p === '/' || $p === '' || preg_match('#^[A-Za-z]:/?$#', $p)) continue;
        if (!file_exists($p) && !is_link($p)) continue;
        if (fm_recursive_delete($p)) $deleted[] = basename($p);
    }
    fm_ok(array('deleted' => $deleted));
}

function fm_chmod($path, $mode) {
    $path = fm_norm($path);
    if (!file_exists($path)) fm_err('Tidak ditemukan: ' . $path);
    if (!preg_match('/^[0-7]{3,4}$/', $mode)) fm_err('Mode harus octal 3-4 digit (mis. 644 / 0755).');
    $oct = octdec($mode);
    if (fm_is_win()) {
        /* Windows: satu-satunya bit POSIX yang bisa dipetakan adalah write -> atribut read-only */
        $writable = (bool)($oct & 0200);
        fm_shell('attrib ' . ($writable ? '-R' : '+R') . ' "' . $path . '" 2>&1');
        clearstatcache(true, $path);
        fm_ok(array('perm' => fm_perm($path), 'mode' => $mode, 'note' => 'Windows: dipetakan ke atribut read-only'));
    }
    if (!@chmod($path, $oct)) fm_err('chmod gagal (permission ditolak).');
    clearstatcache(true, $path);
    fm_ok(array('perm' => fm_perm($path), 'mode' => $mode));
}

function fm_touch($path) {
    $path = fm_norm($path);
    if (is_dir($path)) { @touch($path); fm_ok(array('mtime' => (int)@filemtime($path))); }
    if (!file_exists($path)) {
        $dir = fm_parent($path);
        if (!is_dir($dir)) fm_err('Folder tujuan tidak ada: ' . $dir);
        $fp = @fopen($path, 'wb');
        if (!$fp) fm_err('Tidak bisa membuat file (permission).');
        fclose($fp);
    }
    @touch($path);
    clearstatcache(true, $path);
    fm_ok(array('path' => $path, 'mtime' => (int)@filemtime($path), 'size' => (int)@filesize($path)));
}

/* -------------------------------------------------------------- upload */

function fm_upload_chunk() {
    $path   = fm_norm(isset($_POST['path']) ? $_POST['path'] : '');
    $offset = (int)(isset($_POST['offset']) ? $_POST['offset'] : 0);
    $b64    = isset($_POST['data']) ? $_POST['data'] : '';
    if ($path === '') fm_err('Path kosong.');
    $data = base64_decode($b64, true);
    if ($data === false) fm_err('Chunk tidak valid.');
    $dir = fm_parent($path);
    if (!is_dir($dir) && !@mkdir($dir, 0755, true)) fm_err('Folder tujuan tidak bisa dibuat.');
    if (is_dir($path)) fm_err('Path tersebut folder.');
    $fp = @fopen($path, $offset === 0 ? 'wb' : 'r+b');
    if (!$fp) fm_err('Tidak bisa menulis file (permission).');
    if ($offset > 0) @fseek($fp, $offset);
    $written = @fwrite($fp, $data);
    fclose($fp);
    if ($written === false) fm_err('Gagal menulis chunk.');
    fm_ok(array(
        'path'   => $path,
        'offset' => $offset + strlen($data),
        'size'   => (int)@filesize($path),
        'perm'   => fm_perm($path),
    ));
}

/* --------------------------------------------------------------- arsip */

function fm_zip_add_dir($zip, $dir, $rel) {
    $zip->addEmptyDir($rel);
    $dh = @opendir($dir);
    if (!$dh) return;
    while (($f = readdir($dh)) !== false) {
        if ($f === '.' || $f === '..') continue;
        $full = fm_join($dir, $f);
        $name = $rel . '/' . $f;
        if (is_dir($full)) fm_zip_add_dir($zip, $full, $name);
        else $zip->addFile($full, $name);
    }
    closedir($dh);
}

function fm_shell($cmd) {
    if (function_exists('shell_exec')) return @shell_exec($cmd);
    if (function_exists('exec')) {
        $o = array(); @exec($cmd . ' 2>&1', $o); return implode("\n", $o);
    }
    return '';
}

function fm_zip_supported() {
    return class_exists('ZipArchive') && method_exists('ZipArchive', 'open');
}

function fm_create_zip($items, $dest) {
    $dest = fm_norm($dest);
    if (file_exists($dest)) @unlink($dest);
    if (fm_zip_supported()) {
        $okz = false;
        try {
            $zip = new ZipArchive();
            if (@$zip->open($dest, ZipArchive::CREATE | ZipArchive::OVERWRITE) === true) {
                $added = 0;
                foreach ($items as $it) {
                    $src = fm_norm($it);
                    if (!file_exists($src)) continue;
                    $base = basename($src);
                    if (is_dir($src)) fm_zip_add_dir($zip, $src, $base);
                    else $zip->addFile($src, $base);
                    $added++;
                }
                if ($added > 0) $okz = (bool)$zip->close();
                else @$zip->close();
            }
        } catch (Exception $e) { $okz = false; }
        catch (Throwable $e) { $okz = false; }
        if ($okz && @filesize($dest) > 0) {
            fm_ok(array('path' => $dest, 'size' => (int)@filesize($dest), 'size_h' => fm_size(@filesize($dest))));
        }
        @unlink($dest);
    }
    $list = array();
    $psList = array();
    foreach ($items as $it) {
        $src = fm_norm($it);
        if (!file_exists($src)) continue;
        $list[] = '"' . $src . '"';
        $psList[] = "'" . str_replace("'", "''", $src) . "'";
    }
    if (!$list) fm_err('Tidak ada file yang ditambahkan.');
    if (fm_is_win()) {
        $cmd = 'powershell -NoProfile -Command "Compress-Archive -LiteralPath '
            . implode(',', $psList) . ' -DestinationPath \''
            . str_replace("'", "''", $dest) . '\' -Force" 2>&1';
    } else {
        $cmd = 'zip -r -q -o "' . $dest . '" ' . implode(' ', $list) . ' 2>&1';
    }
    fm_shell($cmd);
    if (!file_exists($dest)) fm_err('Gagal membuat zip (zip binary tidak ada?).');
    fm_ok(array('path' => $dest, 'size' => (int)@filesize($dest), 'size_h' => fm_size(@filesize($dest))));
}

function fm_extract($file, $dest) {
    $file = fm_norm($file);
    $dest = fm_norm($dest);
    if (!is_file($file)) fm_err('Arsip tidak ditemukan: ' . $file);
    if (!is_dir($dest) && !@mkdir($dest, 0755, true)) fm_err('Folder tujuan tidak bisa dibuat.');
    $low  = strtolower($file);
    $base = strtolower(basename($file));
    $ok = false;
    $msg = '';

    if (substr($low, -4) === '.zip') {
        if (fm_zip_supported()) {
            try {
                $zip = new ZipArchive();
                if (@$zip->open($file) === true) {
                    $ok = @$zip->extractTo($dest);
                    $zip->close();
                    if (!$ok) $msg = 'extractTo gagal';
                } else { $msg = 'bukan zip valid'; }
            } catch (Exception $e) { $msg = $e->getMessage(); $ok = false; }
            catch (Throwable $e) { $msg = $e->getMessage(); $ok = false; }
        }
        if (!$ok) {
            $cmd = fm_is_win()
                ? 'powershell -NoProfile -Command "Expand-Archive -LiteralPath \'' . str_replace("'", "''", $file) . '\' -DestinationPath \'' . str_replace("'", "''", $dest) . '\' -Force"'
                : 'unzip -o ' . escapeshellarg($file) . ' -d ' . escapeshellarg($dest) . ' 2>&1';
            $msg = fm_shell($cmd);
            $ok = true;
        }
    } elseif (preg_match('/\.(tar|tar\.gz|tgz|tar\.bz2|tbz2|gz)$/', $base)) {
        if (class_exists('PharData')) {
            try {
                $phar = new PharData($file);
                $ok = $phar->extractTo($dest, null, true);
            } catch (Exception $e) { $msg = $e->getMessage(); $ok = false; }
        }
        if (!$ok) {
            $cmd = fm_is_win()
                ? 'tar -xf "' . $file . '" -C "' . $dest . '" 2>&1'
                : 'tar -xf ' . escapeshellarg($file) . ' -C ' . escapeshellarg($dest) . ' 2>&1';
            $msg = fm_shell($cmd);
            $ok = true;
        }
    } elseif (substr($low, -3) === '.gz') {
        $out = fm_join($dest, preg_replace('/\.gz$/i', '', basename($file)));
        $in = @gzopen($file, 'rb');
        if ($in) {
            $fp = @fopen($out, 'wb');
            while (!gzeof($in)) { @fwrite($fp, gzread($in, 65536)); }
            fclose($fp); gzclose($in); $ok = true;
        } else { $msg = 'gagal membuka gzip'; }
    } else {
        fm_err('Format tidak dikenali. Didukung: .zip .tar .tar.gz .tgz .tar.bz2 .gz');
    }

    if (!$ok) fm_err('Ekstrak gagal. ' . substr((string)$msg, 0, 400));
    fm_ok(array('dest' => $dest, 'msg' => substr((string)$msg, 0, 400)));
}

/* -------------------------------------------------------------- search */

function fm_search($root, $q, $content, $limit) {
    $root = fm_norm($root);
    if (!is_dir($root)) fm_err('Folder tidak ada.');
    $q = (string)$q;
    if ($q === '') fm_err('Kata kunci kosong.');
    $limit = (int)$limit;
    if ($limit < 1 || $limit > 1000) $limit = 300;
    $res = array();
    $stack = array($root);
    $scanned = 0;
    $skip = array('.git', 'node_modules', '.svn', '__pycache__', 'vendor');
    while ($stack && count($res) < $limit) {
        $dir = array_pop($stack);
        $names = @scandir($dir);
        if (!$names) continue;
        foreach ($names as $n) {
            if ($n === '.' || $n === '..') continue;
            $full = fm_join($dir, $n);
            $scanned++;
            $nameHit = (stripos($n, $q) !== false);
            if ($nameHit) {
                $res[] = array('p' => $full, 'n' => $n, 'd' => @is_dir($full),
                    'm' => (int)@filemtime($full), 's' => @is_dir($full) ? 0 : (int)@filesize($full),
                    'hit' => 'nama');
            }
            if (@is_dir($full) && !@is_link($full)) {
                if (!in_array($n, $skip, true)) $stack[] = $full;
            } elseif ($content && !$nameHit && count($res) < $limit) {
                $sz = @filesize($full);
                if ($sz !== false && $sz < 2097152 && @is_readable($full)) {
                    $d = @file_get_contents($full);
                    if ($d !== false) {
                        $pos = stripos($d, $q);
                        if ($pos !== false) {
                            $line = substr_count(substr($d, 0, $pos), "\n") + 1;
                            $res[] = array('p' => $full, 'n' => $n, 'd' => false,
                                'm' => (int)@filemtime($full), 's' => (int)$sz,
                                'hit' => 'isi, baris ' . $line);
                        }
                    }
                }
            }
            if (count($res) >= $limit) break;
        }
    }
    fm_ok(array('items' => $res, 'scanned' => $scanned, 'limit' => $limit));
}

function fm_mime($path) {
    if (!function_exists('finfo_open')) return '';
    $fi = @finfo_open(FILEINFO_MIME_TYPE);
    if (!$fi) return '';
    $m = @finfo_file($fi, $path);
    @finfo_close($fi);
    return $m ? $m : '';
}

/* ---------------------------------------------------------------- info */

function fm_info($path) {
    $path = fm_norm($path);
    if (!file_exists($path) && !is_link($path)) fm_err('Tidak ditemukan: ' . $path);
    $isDir = @is_dir($path);
    $st = @stat($path);
    $count = 0;
    $size = $isDir ? fm_recursive_size($path, $count) : (int)@filesize($path);
    $hashes = array();
    if (!$isDir && is_file($path)) {
        foreach (array('md5', 'sha1', 'sha256') as $algo) {
            $h = @hash_file($algo, $path);
            if ($h !== false) $hashes[$algo] = $h;
        }
    }
    $gid = $st ? $st['gid'] : 0;
    $group = '';
    if (!$isDir || true) {
        if (!$isDir && !fm_is_win() && function_exists('posix_getgrgid')) {
            $g = @posix_getgrgid($gid);
            $group = $g ? $g['name'] : (string)$gid;
        }
    }
    fm_ok(array(
        'path'    => $path,
        'name'    => basename($path),
        'dir'     => $isDir,
        'size'    => $size,
        'size_h'  => fm_size($size),
        'items'   => $count,
        'perm'    => fm_perm($path),
        'owner'   => fm_owner($path),
        'group'   => $group,
        'mtime'   => $st ? date('Y-m-d H:i:s', $st['mtime']) : '-',
        'atime'   => $st ? date('Y-m-d H:i:s', $st['atime']) : '-',
        'ctime'   => $st ? date('Y-m-d H:i:s', $st['ctime']) : '-',
        'inode'   => $st ? $st['ino'] : 0,
        'link'    => @is_link($path) ? @readlink($path) : '',
        'readable'=> @is_readable($path),
        'writable'=> @is_writable($path),
        'executable' => @is_executable($path),
        'hashes'  => $hashes,
        'mime'    => $isDir ? '' : fm_mime($path),
    ));
}

/* -------------------------------------------------------------- drives */

function fm_drives() {
    $out = array();
    if (fm_is_win()) {
        for ($i = 65; $i <= 90; $i++) {
            $l = chr($i) . ':/';
            if (@is_dir($l)) {
                $free = @disk_free_space($l);
                $tot  = @disk_total_space($l);
                $out[] = array('p' => $l, 'n' => strtoupper(substr($l, 0, 2)),
                    'free' => $free === false ? 0 : (float)$free,
                    'total'=> $tot === false ? 0 : (float)$tot);
            }
        }
        if (!$out) $out[] = array('p' => fm_home(), 'n' => 'HOME', 'free' => 0, 'total' => 0);
    } else {
        $mounts = array('/');
        foreach (array('/home', '/root', '/var/www', '/var/www/html', '/opt', '/srv', '/mnt', '/media', '/tmp', '/usr/share/nginx') as $m) {
            if (@is_dir($m)) $mounts[] = $m;
        }
        $hp = @realpath('/proc/mounts');
        if ($hp && @is_readable($hp)) {
            foreach (@file($hp) as $line) {
                $p = explode(' ', $line);
                if (count($p) < 2) continue;
                $mp = $p[1];
                if (preg_match('#^/(proc|sys|dev|run|snap|boot)#', $mp)) continue;
                if (!@is_dir($mp)) continue;
                $mounts[] = $mp;
            }
        }
        $mounts[] = fm_home();
        $mounts = array_values(array_unique($mounts));
        foreach ($mounts as $m) {
            if (count($out) > 40) break;
            $free = @disk_free_space($m);
            $tot  = @disk_total_space($m);
            $out[] = array('p' => $m, 'n' => $m,
                'free' => $free === false ? 0 : (float)$free,
                'total'=> $tot === false ? 0 : (float)$tot);
        }
    }
    fm_ok(array('items' => $out));
}

/* ------------------------------------------------------------ terminal */

function fm_run_process($cmd, $cwd) {
    $timeout = (int)fm_cfg('exec_timeout', 60);
    if ($timeout < 1) $timeout = 60;
    $maxOut = 2097152;

    if (!function_exists('proc_open')) {
        $cmd2 = $cmd . (fm_is_win() ? ' 2>&1' : ' 2>&1');
        $out = fm_shell($cmd2);
        return array('out' => (string)$out, 'code' => 0, 'timed' => false);
    }

    $isWin = fm_is_win();
    $env = null;
    if (!$isWin && function_exists('getenv')) {
        $all = @getenv();
        if (is_array($all)) { $all['TERM'] = 'xterm-256color'; $all['LANG'] = 'C.UTF-8'; $env = $all; }
    }
    $desc = array(0 => array('pipe', 'r'), 1 => array('pipe', 'w'), 2 => array('pipe', 'w'));
    $proc = @proc_open($cmd, $desc, $pipes, $cwd, $env);
    if (!is_resource($proc)) return array('out' => 'proc_open gagal dijalankan.', 'code' => -1, 'timed' => false);

    @fclose($pipes[0]);
    @stream_set_blocking($pipes[1], false);
    @stream_set_blocking($pipes[2], false);

    $out = '';
    $err = '';
    $start = microtime(true);
    $timed = false;
    $code = 0;

    while (true) {
        if (!feof($pipes[1])) $out .= (string)@stream_get_contents($pipes[1]);
        if (!feof($pipes[2])) $err .= (string)@stream_get_contents($pipes[2]);
        if (strlen($out) + strlen($err) > $maxOut) {
            $out = substr($out, 0, $maxOut);
            $err .= "\n[output dipotong]";
            @proc_terminate($proc);
            break;
        }
        $st = @proc_get_status($proc);
        if (!$st || empty($st['running'])) {
            $code = isset($st['exitcode']) ? (int)$st['exitcode'] : 0;
            break;
        }
        if ((microtime(true) - $start) > $timeout) {
            $timed = true;
            @proc_terminate($proc);
            break;
        }
        usleep(15000);
    }

    $out .= (string)@stream_get_contents($pipes[1]);
    $err .= (string)@stream_get_contents($pipes[2]);
    @fclose($pipes[1]);
    @fclose($pipes[2]);
    $closing = @proc_close($proc);
    if (!$code) $code = (int)$closing;

    $text = $out;
    if ($err !== '') $text .= ($text !== '' && substr($text, -1) !== "\n" ? "\n" : '') . $err;
    if ($timed) $text .= "\n[timeout {$timeout}s - proses dihentikan]";
    return array('out' => $text, 'code' => $code, 'timed' => $timed);
}

function fm_terminal($cmd, $cwd) {
    $cwd = fm_norm($cwd);
    if (!is_dir($cwd)) $cwd = fm_home();
    $cmd = (string)$cmd;
    $trim = trim($cmd);
    if ($trim === '') fm_ok(array('out' => '', 'cwd' => $cwd, 'code' => 0));

    $lc = strtolower($trim);
    if ($lc === 'pwd') fm_ok(array('out' => $cwd . "\n", 'cwd' => $cwd, 'code' => 0));
    if ($lc === 'clear' || $lc === 'cls') fm_ok(array('out' => '', 'cwd' => $cwd, 'code' => 0, 'clear' => true));

    if (!preg_match('/[;&|`]/', $trim) && preg_match('/^cd(?:\s+(.*))?$/is', $trim, $m)) {
        $t = isset($m[1]) ? trim($m[1]) : '';
        $t = preg_replace('#^/d\s+#i', '', $t);
        $t = trim($t, " \t\"'");
        if ($t === '' || $t === '~') {
            $new = fm_home();
        } elseif (substr($t, 0, 1) === '/' || preg_match('#^[A-Za-z]:#', $t)) {
            $new = fm_norm($t);
        } else {
            $new = fm_norm($cwd . '/' . $t);
        }
        if (!@is_dir($new)) {
            fm_ok(array('out' => 'cd: direktori tidak ditemukan: ' . $t . "\n", 'cwd' => $cwd, 'code' => 1));
        }
        fm_ok(array('out' => '', 'cwd' => $new, 'code' => 0));
    }

    if (fm_is_win()) {
        // paksa cmd memakai UTF-8 bila memungkinkan
        $cmd = 'chcp 65001>nul & ' . $cmd;
    }
    $r = fm_run_process($cmd, $cwd);
    $out = (string)$r['out'];
    if (fm_is_win() && $out !== '' && !@preg_match('//u', $out)) {
        // sebagian build tetap menulis output dalam codepage OEM
        $cp = (string)fm_cfg('win_cp', 'CP850');
        $conv = false;
        if ($cp !== '' && function_exists('mb_convert_encoding')) {
            $conv = @mb_convert_encoding($out, 'UTF-8', $cp);
        } elseif ($cp !== '' && function_exists('iconv')) {
            $conv = @iconv($cp, 'UTF-8//IGNORE', $out);
        }
        if (is_string($conv) && $conv !== '' && @preg_match('//u', $conv)) $out = $conv;
    }
    fm_ok(array('out' => $out, 'cwd' => $cwd, 'code' => $r['code'], 'timed' => $r['timed']));
}

/* --------------------------------------------------------------- router */

function fm_items() {
    if (isset($_POST['items'])) {
        $d = json_decode((string)$_POST['items'], true);
        if (is_array($d)) return array_values(array_filter($d, 'is_string'));
    }
    if (isset($_POST['path'])) return array((string)$_POST['path']);
    return array();
}

$fm_action = isset($_GET['a']) ? (string)$_GET['a'] : '';

if ($fm_action !== '') {
    if (!empty($_POST)) { $_GET = array_merge($_GET, $_POST); }
    $post = $_POST;

    switch ($fm_action) {
        case 'list':
            $lp = isset($_GET['path']) ? (string)$_GET['path'] : '';
            fm_list($lp !== '' ? $lp : fm_home());
            break;
        case 'tree':     fm_tree(isset($_GET['path']) ? $_GET['path'] : fm_home()); break;
        case 'drives':   fm_drives(); break;
        case 'read':     fm_read(isset($_GET['path']) ? $_GET['path'] : ''); break;
        case 'info':     fm_info(isset($_GET['path']) ? $_GET['path'] : ''); break;
        case 'download':
            $p = isset($_GET['path']) ? $_GET['path'] : '';
            fm_raw(fm_norm($p), true, isset($_GET['name']) ? $_GET['name'] : null);
            break;
        case 'raw':      fm_raw(fm_norm(isset($_GET['path']) ? $_GET['path'] : ''), false); break;
        case 'search':
            fm_search(isset($_GET['path']) ? $_GET['path'] : fm_home(),
                isset($_GET['q']) ? $_GET['q'] : '',
                !empty($_GET['content']), isset($_GET['limit']) ? $_GET['limit'] : 300);
            break;
        case 'save':     fm_save(isset($post['path']) ? $post['path'] : '', isset($post['data']) ? $post['data'] : ''); break;
        case 'mkdir':    fm_mkdir(isset($post['path']) ? $post['path'] : ''); break;
        case 'newfile':  fm_newfile(isset($post['path']) ? $post['path'] : ''); break;
        case 'rename':   fm_rename(isset($post['from']) ? $post['from'] : '', isset($post['to']) ? $post['to'] : ''); break;
        case 'copy':     fm_copy_items(fm_items(), isset($post['dest']) ? $post['dest'] : ''); break;
        case 'move':     fm_move(fm_items(), isset($post['dest']) ? $post['dest'] : ''); break;
        case 'delete':   fm_delete(fm_items()); break;
        case 'chmod':    fm_chmod(isset($post['path']) ? $post['path'] : '', isset($post['mode']) ? $post['mode'] : ''); break;
        case 'touch':    fm_touch(isset($post['path']) ? $post['path'] : ''); break;
        case 'upload':   fm_upload_chunk(); break;
        case 'zip':      fm_create_zip(fm_items(), isset($post['dest']) ? $post['dest'] : ''); break;
        case 'extract':  fm_extract(isset($post['path']) ? $post['path'] : '', isset($post['dest']) ? $post['dest'] : fm_home()); break;
        case 'terminal': fm_terminal(isset($post['cmd']) ? $post['cmd'] : '', isset($post['cwd']) ? $post['cwd'] : fm_home()); break;
        default:         fm_err('Aksi tidak dikenal: ' . $fm_action);
    }
    fm_err('Aksi tidak menghasilkan respons.');
}

?><!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Manager</title>
<style>
:root{
  --bg:#0d1117; --bg2:#161b22; --bg3:#1f2630; --bd:#30363d; --tx:#e6edf3; --mut:#8b949e;
  --acc:#2f81f7; --ok:#3fb950; --warn:#d29922; --err:#f85149; --sel:#1f3a5f;
}
*{box-sizing:border-box}
html,body{margin:0;height:100%;background:var(--bg);color:var(--tx);font:13px/1.45 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Ubuntu,sans-serif}
button,input,select,textarea{font-family:inherit;font-size:13px}
::-webkit-scrollbar{width:10px;height:10px}
::-webkit-scrollbar-thumb{background:#3b434d;border-radius:5px}
::-webkit-scrollbar-track{background:transparent}
#app{display:flex;height:100vh;overflow:hidden}

/* sidebar */
#side{width:240px;flex:0 0 240px;background:var(--bg2);border-right:1px solid var(--bd);display:flex;flex-direction:column;min-height:0}
.brand{display:flex;align-items:center;gap:8px;padding:12px 14px;border-bottom:1px solid var(--bd);font-weight:700;letter-spacing:.3px}
.brand .dot{width:9px;height:9px;border-radius:50%;background:var(--ok);box-shadow:0 0 8px var(--ok)}
.brand small{font-weight:400;color:var(--mut);font-size:10px;margin-left:auto}
.side-sec{padding:8px 10px 4px;font-size:10px;text-transform:uppercase;letter-spacing:.8px;color:var(--mut)}
#drives{padding:0 8px 6px;display:flex;flex-wrap:wrap;gap:4px}
.drive{background:var(--bg3);border:1px solid var(--bd);border-radius:5px;padding:4px 8px;cursor:pointer;font-size:11px;max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.drive:hover{border-color:var(--acc);color:#fff}
#tree{flex:1;overflow:auto;padding:0 6px 10px;min-height:0}
.tnode{user-select:none}
.trow{display:flex;align-items:center;gap:4px;padding:3px 6px;border-radius:5px;cursor:pointer;white-space:nowrap;overflow:hidden}
.trow:hover{background:var(--bg3)}
.trow.cur{background:var(--sel);color:#fff}
.trow .ar{width:12px;text-align:center;color:var(--mut);font-size:9px;flex:0 0 12px}
.trow .nm{overflow:hidden;text-overflow:ellipsis}
.tkids{margin-left:12px;border-left:1px dashed #2b323c;padding-left:2px}
.side-foot{padding:8px 12px;border-top:1px solid var(--bd);font-size:10px;color:var(--mut);line-height:1.5;word-break:break-all}

/* main */
#main{flex:1;display:flex;flex-direction:column;min-width:0;min-height:0}
#top{display:flex;align-items:center;gap:6px;padding:8px 10px;border-bottom:1px solid var(--bd);background:var(--bg2);flex-wrap:wrap}
.crumbs{flex:1;display:flex;align-items:center;gap:2px;overflow:hidden;background:var(--bg);border:1px solid var(--bd);border-radius:6px;padding:4px 8px;min-width:140px;white-space:nowrap}
.crumb{cursor:pointer;color:var(--mut);padding:1px 3px;border-radius:3px;max-width:220px;overflow:hidden;text-overflow:ellipsis}
.crumb:hover{color:#fff;background:var(--bg3)}
.crumb.last{color:var(--tx);font-weight:600}
.crumb .sep{color:#444c56;margin:0 2px}
#search{width:180px;background:var(--bg);border:1px solid var(--bd);color:var(--tx);border-radius:6px;padding:6px 9px;outline:none}
#search:focus{border-color:var(--acc)}
.btn{background:var(--bg3);border:1px solid var(--bd);color:var(--tx);border-radius:6px;padding:6px 10px;cursor:pointer;white-space:nowrap;display:inline-flex;align-items:center;gap:5px}
.btn:hover{border-color:#4b5563;background:#2b333d}
.btn:active{transform:translateY(1px)}
.btn.primary{background:#1f6feb;border-color:#1f6feb;color:#fff}
.btn.primary:hover{background:#2f81f7}
.btn.danger:hover{background:#5d1a1a;border-color:var(--err);color:#ffb3b0}
.btn:disabled{opacity:.4;cursor:not-allowed}
.btn.sm{padding:3px 7px;font-size:11px}
#toolbar{display:flex;align-items:center;gap:6px;padding:6px 10px;border-bottom:1px solid var(--bd);background:#12171e;flex-wrap:wrap;min-height:38px}
#selinfo{color:var(--mut);font-size:11px;margin-right:4px}
#listwrap{flex:1;overflow:auto;min-height:0;position:relative}
table#list{width:100%;border-collapse:collapse;table-layout:fixed}
#list th{position:sticky;top:0;background:#12171e;z-index:2;text-align:left;color:var(--mut);font-weight:600;font-size:11px;text-transform:uppercase;letter-spacing:.5px;padding:7px 10px;border-bottom:1px solid var(--bd);cursor:pointer;user-select:none}
#list th:hover{color:#fff}
#list td{padding:5px 10px;border-bottom:1px solid #1b222b;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
#list tbody tr{cursor:default}
#list tbody tr:hover{background:#161d26}
#list tbody tr.sel{background:var(--sel)}
#list tbody tr.dir .nm{font-weight:600}
#list .ico{display:inline-block;width:18px;text-align:center;margin-right:4px}
#list .nm{overflow:hidden;text-overflow:ellipsis}
#list .sz,#list .dt,#list .pm{color:var(--mut);font-size:11px}
#list .pm{font-family:ui-monospace,Consolas,monospace}
.col-name{width:auto}.col-size{width:90px}.col-date{width:150px}.col-perm{width:70px}
.empty{padding:40px;text-align:center;color:var(--mut)}
#status{display:flex;align-items:center;gap:12px;padding:5px 10px;border-top:1px solid var(--bd);background:var(--bg2);font-size:11px;color:var(--mut);flex-wrap:wrap}
#status .grow{flex:1}
#bar{height:3px;background:#1b222b;position:relative;overflow:hidden;display:none}
#bar.on{display:block}
#bar i{position:absolute;left:0;top:0;bottom:0;width:0;background:var(--acc);transition:width .2s}

/* editor */
#editor{position:fixed;inset:0;background:var(--bg);z-index:60;display:none;flex-direction:column}
#editor.on{display:flex}
.ed-head{display:flex;align-items:center;gap:6px;padding:7px 10px;background:var(--bg2);border-bottom:1px solid var(--bd);flex-wrap:wrap}
.ed-title{flex:1;font-family:ui-monospace,Consolas,monospace;font-size:12px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:#c9d1d9}
.ed-title b{color:var(--acc)}
.ed-body{flex:1;display:flex;min-height:0;background:#0b0f14}
#gutter{padding:10px 8px 40px;text-align:right;color:#484f58;font:12px/1.55 ui-monospace,Consolas,monospace;background:#0b0f14;border-right:1px solid #1b222b;overflow:hidden;user-select:none;min-width:44px}
#edtext{flex:1;background:transparent;color:#c9d1d9;border:0;outline:none;resize:none;padding:10px 12px 40px;font:12px/1.55 ui-monospace,Consolas,monospace;white-space:pre;overflow:auto;tab-size:4}
.ed-foot{padding:5px 10px;background:var(--bg2);border-top:1px solid var(--bd);font-size:11px;color:var(--mut);display:flex;gap:14px}

/* terminal */
#term{position:fixed;left:0;right:0;bottom:0;height:46vh;background:#080b0f;border-top:1px solid var(--bd);z-index:55;display:none;flex-direction:column;box-shadow:0 -8px 24px rgba(0,0,0,.5)}
#term.on{display:flex}
.term-head{display:flex;align-items:center;gap:8px;padding:5px 10px;background:var(--bg2);border-bottom:1px solid var(--bd)}
.term-head b{font-size:12px}
.term-head .grow{flex:1}
.term-out{flex:1;overflow:auto;padding:8px 10px;font:12px/1.5 ui-monospace,Consolas,"Courier New",monospace;white-space:pre-wrap;word-break:break-word;color:#c9d1d9}
.term-out .cmd{color:#7ee787}
.term-out .errc{color:#ff7b72}
.term-out .prompt{color:#58a6ff}
.term-input{display:flex;align-items:center;gap:6px;padding:6px 10px;border-top:1px solid #1b222b;background:#0b0f14}
.term-input span{color:#58a6ff;font:12px ui-monospace,Consolas,monospace;white-space:nowrap;overflow:hidden;max-width:45%;text-overflow:ellipsis}
.term-input input{flex:1;background:transparent;border:0;outline:none;color:#e6edf3;font:12px ui-monospace,Consolas,monospace}

/* modal */
#modal{position:fixed;inset:0;background:rgba(1,4,9,.72);z-index:80;display:none;align-items:center;justify-content:center;padding:16px}
#modal.on{display:flex}
.box{background:var(--bg2);border:1px solid var(--bd);border-radius:10px;width:520px;max-width:100%;max-height:90vh;display:flex;flex-direction:column;box-shadow:0 16px 48px rgba(0,0,0,.6)}
.box.wide{width:760px}
.box-head{padding:12px 16px;border-bottom:1px solid var(--bd);font-weight:700;display:flex;align-items:center;gap:8px}
.box-body{padding:16px;overflow:auto;min-height:40px}
.box-foot{padding:10px 16px;border-top:1px solid var(--bd);display:flex;justify-content:flex-end;gap:8px}
.fld{margin-bottom:12px}
.fld label{display:block;margin-bottom:5px;color:var(--mut);font-size:11px;text-transform:uppercase;letter-spacing:.5px}
.fld input[type=text],.fld input[type=password],.fld select,.fld textarea{width:100%;background:var(--bg);border:1px solid var(--bd);color:var(--tx);border-radius:6px;padding:8px 10px;outline:none}
.fld input:focus,.fld select:focus,.fld textarea:focus{border-color:var(--acc)}
.fld .hint{color:var(--mut);font-size:11px;margin-top:4px}
.kv{width:100%;border-collapse:collapse;font-size:12px}
.kv td{padding:4px 6px;border-bottom:1px solid #1b222b;vertical-align:top}
.kv td:first-child{color:var(--mut);width:110px;white-space:nowrap}
.kv td:last-child{word-break:break-all;font-family:ui-monospace,Consolas,monospace}
.prog{display:flex;align-items:center;gap:8px;margin-bottom:8px;font-size:12px}
.prog .nm{flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.prog .pb{width:130px;height:6px;background:#1b222b;border-radius:3px;overflow:hidden}
.prog .pb i{display:block;height:100%;width:0;background:var(--ok);transition:width .15s}
.prog .pc{width:42px;text-align:right;color:var(--mut);font-size:11px}

/* context menu */
#ctx{position:fixed;z-index:90;background:var(--bg2);border:1px solid var(--bd);border-radius:8px;padding:4px;display:none;min-width:190px;box-shadow:0 10px 30px rgba(0,0,0,.6)}
#ctx.on{display:block}
#ctx div{padding:6px 10px;border-radius:5px;cursor:pointer;display:flex;gap:8px;align-items:center}
#ctx div:hover{background:#1f6feb;color:#fff}
#ctx div.sep{height:1px;padding:0;margin:4px 0;background:var(--bd);cursor:default;pointer-events:none}
#ctx div.sep:hover{background:var(--bd)}

/* misc */
#toast{position:fixed;right:14px;bottom:14px;z-index:100;display:flex;flex-direction:column;gap:8px;align-items:flex-end}
.toast{background:var(--bg3);border:1px solid var(--bd);border-left:3px solid var(--acc);padding:9px 13px;border-radius:6px;max-width:420px;box-shadow:0 8px 24px rgba(0,0,0,.5);animation:tin .18s ease}
.toast.ok{border-left-color:var(--ok)}.toast.err{border-left-color:var(--err)}.toast.warn{border-left-color:var(--warn)}
@keyframes tin{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:none}}
#drop{position:fixed;inset:0;z-index:70;background:rgba(47,129,247,.15);border:3px dashed var(--acc);display:none;align-items:center;justify-content:center;font-size:20px;font-weight:700;color:#fff;pointer-events:none}
#drop.on{display:flex}
#menuBtn{display:none}
@media(max-width:820px){
  #side{position:fixed;left:0;top:0;bottom:0;z-index:58;transform:translateX(-100%);transition:transform .18s}
  #side.open{transform:none;box-shadow:8px 0 30px rgba(0,0,0,.6)}
  #menuBtn{display:inline-flex}
  .col-date{width:0;display:none}
  #search{width:120px}
}
</style>
</head>
<body>

<div id="app">
  <aside id="side">
    <div class="brand"><span class="dot"></span>FILE MANAGER<small id="osTag"></small></div>
    <div class="side-sec">Drive / Mount</div>
    <div id="drives"></div>
    <div class="side-sec">Explorer</div>
    <div id="tree"></div>
    <div class="side-foot" id="sysinfo">memuat...</div>
  </aside>

  <main id="main">
    <div id="top">
      <button class="btn" id="menuBtn" onclick="document.getElementById('side').classList.toggle('open')">&#9776;</button>
      <div class="crumbs" id="crumbs"></div>
      <input id="search" placeholder="Cari file / isi..." autocomplete="off">
      <label class="btn sm" title="Cari juga di dalam isi file" style="cursor:pointer"><input type="checkbox" id="searchContent" style="margin:0 4px 0 0">isi</label>
      <button class="btn" onclick="goUp()" title="Naik satu folder">&#8593;</button>
      <button class="btn" onclick="refresh()" title="Muat ulang">&#8635;</button>
      <button class="btn primary" onclick="openUpload()">&#8681; Upload</button>
      <button class="btn" onclick="actNewFolder()">&#43; Folder</button>
      <button class="btn" onclick="actNewFile()">&#43; File</button>
      <button class="btn" onclick="toggleTerm()">&#8250;_ Terminal</button>
    </div>

    <div id="toolbar">
      <span id="selinfo">0 dipilih</span>
      <button class="btn sm" onclick="selectAll()">Pilih semua</button>
      <button class="btn sm" data-sel="download">&#11015; Download</button>
      <button class="btn sm" data-sel="edit">&#9998; Edit</button>
      <button class="btn sm" data-sel="rename">Rename</button>
      <button class="btn sm" data-sel="copy">Copy</button>
      <button class="btn sm" data-sel="move">Move</button>
      <button class="btn sm" id="btnPaste" style="display:none" onclick="doPaste()">Paste</button>
      <button class="btn sm" data-sel="zip">Zip</button>
      <button class="btn sm" data-sel="extract">Extract</button>
      <button class="btn sm" data-sel="chmod">Chmod</button>
      <button class="btn sm" data-sel="info">Info</button>
      <button class="btn sm danger" data-sel="delete">Hapus</button>
    </div>

    <div id="bar"><i></i></div>

    <div id="listwrap">
      <table id="list">
        <thead>
          <tr>
            <th class="col-name" data-sort="name">Nama</th>
            <th class="col-size" data-sort="size">Ukuran</th>
            <th class="col-date" data-sort="date">Diubah</th>
            <th class="col-perm">Perm</th>
          </tr>
        </thead>
        <tbody id="tbody"></tbody>
      </table>
    </div>

    <div id="status">
      <span id="stPath">/</span>
      <span class="grow"></span>
      <span id="stCount">0 item</span>
      <span id="stDisk"></span>
    </div>
  </main>
</div>

<div id="editor">
  <div class="ed-head">
    <span class="ed-title" id="edPath">-</span>
    <label style="font-size:11px;color:var(--mut)"><input type="checkbox" id="edWrap" onchange="edApplyWrap()"> wrap</label>
    <button class="btn sm" onclick="edSave()">&#128190; Simpan</button>
    <button class="btn sm" onclick="edDownload()">&#11015; Download</button>
    <button class="btn sm" onclick="edClose()">&#10005; Tutup</button>
  </div>
  <div class="ed-body">
    <div id="gutter">1</div>
    <textarea id="edtext" spellcheck="false" wrap="off"></textarea>
  </div>
  <div class="ed-foot">
    <span id="edInfo">-</span>
    <span id="edPos">Ln 1, Col 1</span>
    <span id="edDirty"></span>
    <span style="flex:1"></span>
    <span>Ctrl+S simpan &middot; Tab = 4 spasi</span>
  </div>
</div>

<div id="term">
  <div class="term-head">
    <b>Terminal</b>
    <span id="tShell" style="color:var(--mut);font-size:11px"></span>
    <span class="grow"></span>
    <button class="btn sm" onclick="termClear()">Clear</button>
    <button class="btn sm" onclick="termSize()">&#8597;</button>
    <button class="btn sm" onclick="toggleTerm(false)">&#10005;</button>
  </div>
  <div class="term-out" id="termOut"></div>
  <div class="term-input">
    <span id="termPrompt">$</span>
    <input id="termCmd" spellcheck="false" autocomplete="off" autocapitalize="off">
  </div>
</div>

<div id="modal"><div class="box" id="mbox"></div></div>
<div id="ctx"></div>
<div id="toast"></div>
<div id="drop">Lepaskan file untuk upload</div>
<input type="file" id="filePick" multiple style="display:none">

<script>
'use strict';

var S = {
  path: '',
  items: [],
  sel: {},
  sortK: 'name',
  sortD: 1,
  search: null,
  clip: null,
  os: '',
  ed: { path: null, dirty: false },
  term: { cwd: '', hist: [], hi: 0, busy: false }
};

function $(id) { return document.getElementById(id); }

/* ------------------------------------------------------------ helpers */

function b64d(s) {
  var bin = atob(s || '');
  var bytes = new Uint8Array(bin.length);
  for (var i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
  if (window.TextDecoder) { try { return new TextDecoder('utf-8').decode(bytes); } catch (e) {} }
  try { return decodeURIComponent(escape(bin)); } catch (e) { return bin; }
}

function b64e(str) {
  var bytes;
  if (window.TextEncoder) { bytes = new TextEncoder().encode(str); }
  else {
    var u = unescape(encodeURIComponent(str));
    bytes = new Uint8Array(u.length);
    for (var i = 0; i < u.length; i++) bytes[i] = u.charCodeAt(i);
  }
  var bin = '';
  var step = 0x8000;
  for (var j = 0; j < bytes.length; j += step) {
    bin += String.fromCharCode.apply(null, bytes.subarray(j, j + step));
  }
  return btoa(bin);
}

function fmtSize(n) {
  n = Number(n) || 0;
  var u = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'], i = 0;
  while (n >= 1024 && i < 5) { n /= 1024; i++; }
  return i === 0 ? n + ' B' : n.toFixed(2) + ' ' + u[i];
}

function fmtDate(ts) {
  if (!ts) return '-';
  var d = new Date(ts * 1000);
  function p(x) { return x < 10 ? '0' + x : '' + x; }
  return d.getFullYear() + '-' + p(d.getMonth() + 1) + '-' + p(d.getDate()) + ' ' + p(d.getHours()) + ':' + p(d.getMinutes());
}

function toast(msg, type) {
  var el = document.createElement('div');
  el.className = 'toast ' + (type || '');
  el.textContent = msg;
  $('toast').appendChild(el);
  setTimeout(function () {
    el.style.opacity = '0';
    el.style.transition = 'opacity .25s';
    setTimeout(function () { if (el.parentNode) el.parentNode.removeChild(el); }, 260);
  }, type === 'err' ? 6000 : 3200);
}

function api(action, params) {
  var body = new URLSearchParams();
  Object.keys(params || {}).forEach(function (k) {
    var v = params[k];
    body.append(k, (v !== null && typeof v === 'object') ? JSON.stringify(v) : (v === undefined ? '' : v));
  });
  return fetch('?a=' + encodeURIComponent(action), {
    method: 'POST',
    credentials: 'same-origin',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
    body: body.toString()
  }).then(function (r) {
    return r.text().then(function (t) {
      var j;
      try { j = JSON.parse(t); }
      catch (e) { throw new Error('Respons tidak valid: ' + t.slice(0, 200)); }
      return j;
    });
  });
}

function jpath(p) { return '?a=download&path=' + encodeURIComponent(p) + '&name=' + encodeURIComponent(p.split('/').pop()); }

function joinPath(a, b) {
  a = String(a || '');
  if (a === '/') return '/' + b;
  a = a.replace(/\/+$/, '');
  return a + '/' + b;
}

function itemPath(it) { return S.search ? it.p : joinPath(S.path, it.n); }
function selectedItems() {
  return S.items.filter(function (it) { return S.sel[itemPath(it)]; });
}
function selectedPaths() { return selectedItems().map(itemPath); }

function setLoading(on) {
  $('bar').className = on ? 'on' : '';
  if (!on) $('bar').firstElementChild.style.width = '0';
}

/* ------------------------------------------------------------- render */

function sortItems() {
  var k = S.sortK, d = S.sortD;
  S.items.sort(function (a, b) {
    if (a.d !== b.d) return a.d ? -1 : 1;
    var r = 0;
    if (k === 'size') r = (a.s || 0) - (b.s || 0);
    else if (k === 'date') r = (a.m || 0) - (b.m || 0);
    else r = String(a.n).localeCompare(String(b.n), undefined, { numeric: true, sensitivity: 'base' });
    return r * d;
  });
}

function iconFor(it) {
  if (it.d) return '\uD83D\uDCC1';
  var n = String(it.n).toLowerCase();
  var ext = n.indexOf('.') >= 0 ? n.split('.').pop() : '';
  if (/^(png|jpg|jpeg|gif|webp|bmp|svg|ico|avif)$/.test(ext)) return '\uD83D\uDDBC';
  if (/^(zip|rar|7z|tar|gz|tgz|bz2|xz)$/.test(ext)) return '\uD83D\uDDDC';
  if (/^(php|phtml|js|ts|py|rb|pl|sh|bash|c|cpp|h|java|go|rs|html|htm|css|json|xml|yml|yaml|ini|conf|sql|lua|aspx|jsp)$/.test(ext)) return '\uD83D\uDCBB';
  if (/^(mp4|mkv|avi|mov|webm)$/.test(ext)) return '\uD83C\uDFAC';
  if (/^(mp3|wav|ogg|flac|m4a)$/.test(ext)) return '\uD83C\uDFB5';
  if (/^(txt|md|log|csv|rtf)$/.test(ext)) return '\uD83D\uDCC4';
  return '\uD83D\uDCCE';
}

function render() {
  var tb = $('tbody');
  tb.textContent = '';

  if (!S.items.length) {
    var tr0 = document.createElement('tr');
    var td0 = document.createElement('td');
    td0.colSpan = 3;
    td0.className = 'empty';
    td0.textContent = S.search ? 'Tidak ada hasil.' : 'Folder kosong.';
    tr0.appendChild(td0);
    tb.appendChild(tr0);
  } else {
    S.items.forEach(function (it) {
      var p = itemPath(it);
      var tr = document.createElement('tr');
      if (it.d) tr.className = 'dir';
      if (S.sel[p]) tr.className += ' sel';
      tr.setAttribute('data-p', p);

      var td1 = document.createElement('td');
      var ic = document.createElement('span');
      ic.className = 'ico';
      ic.textContent = iconFor(it);
      var nm = document.createElement('span');
      nm.className = 'nm';
      nm.textContent = S.search ? it.p : it.n;
      nm.title = p;
      td1.appendChild(ic);
      td1.appendChild(nm);
      tr.appendChild(td1);

      var td2 = document.createElement('td');
      td2.className = 'sz';
      td2.textContent = it.d ? '<DIR>' : fmtSize(it.s);
      tr.appendChild(td2);

      var td3 = document.createElement('td');
      td3.className = 'dt';
      td3.textContent = fmtDate(it.m);
      tr.appendChild(td3);

      var td4 = document.createElement('td');
      td4.className = 'pm';
      td4.textContent = it.p || '';
      tr.appendChild(td4);

      tb.appendChild(tr);
    });
  }

  $('selinfo').textContent = Object.keys(S.sel).length + ' dipilih';
  $('stPath').textContent = S.path || '/';
  $('stCount').textContent = S.items.length + ' item';
  renderCrumbs();
  markTree();
  updatePasteBtn();
}

function renderCrumbs() {
  var el = $('crumbs');
  el.textContent = '';
  var p = S.path || '/';
  var segs = [];
  var rest = p;

  if (/^[A-Za-z]:\//.test(p)) {
    segs.push({ n: p.substr(0, 2), p: p.substr(0, 3) });
    rest = p.substr(3);
  } else if (p.charAt(0) === '/') {
    segs.push({ n: '/', p: '/' });
    rest = p.substr(1);
  }

  rest.split('/').forEach(function (s) {
    if (!s) return;
    var last = segs[segs.length - 1];
    segs.push({ n: s, p: joinPath(last.p, s) });
  });

  segs.forEach(function (s, i) {
    if (i > 0) {
      var sp = document.createElement('span');
      sp.className = 'sep';
      sp.textContent = '/';
      el.appendChild(sp);
    }
    var c = document.createElement('span');
    c.className = 'crumb' + (i === segs.length - 1 ? ' last' : '');
    c.textContent = s.n;
    c.title = s.p;
    c.onclick = function () { cd(s.p); };
    el.appendChild(c);
  });
}

/* ----------------------------------------------------------- navigate */

function cd(path, keepSel) {
  var want = path;
  if (S.search) { S.search = null; $('search').value = ''; }
  setLoading(true);
  api('list', { path: want }).then(function (r) {
    setLoading(false);
    if (!r.ok) { toast(r.error || 'Gagal membuka folder', 'err'); return; }
    S.path = r.path;
    S.items = r.items || [];
    S.sel = keepSel ? S.sel : {};
    S.os = (r.os || '') + (r.php ? ' / PHP ' + r.php : '');
    if (!S.home && r.home) { S.home = r.home; treeInit(); }
    S.disk = { free: r.free_h, total: r.total_h };
    sortItems();
    render();
    $('stDisk').textContent = 'Disk: ' + r.free_h + ' bebas / ' + r.total_h;
    $('sysinfo').innerHTML = '';
    $('sysinfo').textContent = (r.os || '') + ' | PHP ' + (r.php || '') + ' | ' + (r.user || '');
    if (window.innerWidth <= 820) $('side').classList.remove('open');
    try { history.replaceState(null, '', '#' + encodeURIComponent(S.path)); } catch (e) {}
  }).catch(function (e) { setLoading(false); toast(e.message || 'Error jaringan', 'err'); });
}

function refresh() {
  if (S.search) { doSearch(); return; }
  cd(S.path, true);
}

function goUp() {
  var p = S.path.replace(/\/+$/, '');
  if (/^[A-Za-z]:$/.test(p)) { cd(p + '/'); return; }
  var i = p.lastIndexOf('/');
  if (i <= 0) { cd('/'); return; }
  var up = p.substr(0, i);
  if (/^[A-Za-z]:$/.test(up)) up += '/';
  cd(up);
}

/* --------------------------------------------------------------- tree */

function markTree() {
  var rows = $('tree').querySelectorAll('.trow');
  for (var i = 0; i < rows.length; i++) {
    var p = rows[i].getAttribute('data-path');
    if (p && p === S.path) rows[i].classList.add('cur');
    else rows[i].classList.remove('cur');
  }
}

function treeRow(path, name, hasKids) {
  var node = document.createElement('div');
  node.className = 'tnode';

  var row = document.createElement('div');
  row.className = 'trow';
  row.setAttribute('data-path', path);
  row.title = path;

  var ar = document.createElement('span');
  ar.className = 'ar';
  ar.textContent = hasKids ? '\u25B8' : '';
  var ic = document.createElement('span');
  ic.textContent = '\uD83D\uDCC1';
  ic.style.fontSize = '11px';
  var nm = document.createElement('span');
  nm.className = 'nm';
  nm.textContent = name;

  row.appendChild(ar);
  row.appendChild(ic);
  row.appendChild(nm);
  node.appendChild(row);

  var kids = document.createElement('div');
  kids.className = 'tkids';
  kids.style.display = 'none';
  node.appendChild(kids);

  row.onclick = function (ev) {
    if (ev.target === ar) { toggleTree(node, path, ar, kids); return; }
    cd(path);
  };
  ar.onclick = function (ev) { ev.stopPropagation(); toggleTree(node, path, ar, kids); };
  return node;
}

function toggleTree(node, path, ar, kids) {
  if (kids.getAttribute('data-loaded') === '1') {
    var open = kids.style.display !== 'none';
    kids.style.display = open ? 'none' : '';
    ar.textContent = open ? '\u25B8' : '\u25BE';
    return;
  }
  ar.textContent = '\u2026';
  api('tree', { path: path }).then(function (r) {
    kids.textContent = '';
    kids.setAttribute('data-loaded', '1');
    if (!r.ok) { ar.textContent = ''; return; }
    (r.items || []).forEach(function (d) {
      kids.appendChild(treeRow(joinPath(r.path, d.n), d.n, d.has));
    });
    ar.textContent = '\u25BE';
    kids.style.display = '';
    markTree();
  }).catch(function () { ar.textContent = '\u25B8'; });
}

function treeInit() {
  var t = $('tree');
  t.textContent = '';
  var root = document.createElement('div');
  root.className = 'tnode';
  var row = document.createElement('div');
  row.className = 'trow';
  row.innerHTML = '<span class="ar"></span><span>\uD83C\uDFE0</span><span class="nm">HOME</span>';
  row.title = 'Folder script';
  row.onclick = function () { cd(S.home || S.path); };
  root.appendChild(row);
  t.appendChild(root);

  api('tree', { path: S.home || '/' }).then(function (r) {
    if (!r.ok) return;
    (r.items || []).forEach(function (d) {
      t.appendChild(treeRow(joinPath(r.path, d.n), d.n, d.has));
    });
    markTree();
  }).catch(function () {});
}

/* ------------------------------------------------------------- drives */

function loadDrives() {
  api('drives', {}).then(function (r) {
    var box = $('drives');
    box.textContent = '';
    (r.items || []).forEach(function (d) {
      var b = document.createElement('div');
      b.className = 'drive';
      b.textContent = d.n;
      b.title = d.p + (d.total ? '  ' + fmtSize(d.free) + ' bebas / ' + fmtSize(d.total) : '');
      b.onclick = function () { cd(d.p); };
      box.appendChild(b);
    });
  }).catch(function () {});
}

/* -------------------------------------------------------------- modal */

function closeModal() {
  $('modal').classList.remove('on');
  $('mbox').textContent = '';
}

function modal(title, bodyEl, buttons, wide) {
  var box = $('mbox');
  box.className = 'box' + (wide ? ' wide' : '');
  box.textContent = '';

  var h = document.createElement('div');
  h.className = 'box-head';
  h.textContent = title;

  var b = document.createElement('div');
  b.className = 'box-body';
  b.appendChild(bodyEl);

  var f = document.createElement('div');
  f.className = 'box-foot';
  (buttons || []).forEach(function (cfg) {
    var btn = document.createElement('button');
    btn.className = 'btn ' + (cfg.cls || '');
    btn.textContent = cfg.t;
    btn.onclick = function () { if (cfg.fn) cfg.fn(); else closeModal(); };
    f.appendChild(btn);
  });

  box.appendChild(h);
  box.appendChild(b);
  box.appendChild(f);
  $('modal').classList.add('on');
  return { body: b, close: closeModal };
}

function field(label, value, placeholder) {
  var wrap = document.createElement('div');
  if (label) {
    var l = document.createElement('label');
    l.textContent = label;
    wrap.appendChild(l);
  }
  var inp = document.createElement('input');
  inp.type = 'text';
  inp.value = value || '';
  inp.placeholder = placeholder || '';
  wrap.appendChild(inp);
  wrap.input = inp;
  return wrap;
}

function askDialog(o) {
  var wrap = document.createElement('div');
  var f = field(o.label || '', o.value || '', o.placeholder || '');
  wrap.appendChild(f);
  if (o.hint) {
    var hint = document.createElement('div');
    hint.className = 'hint';
    hint.textContent = o.hint;
    wrap.appendChild(hint);
  }
  modal(o.title, wrap, [
    { t: 'Batal' },
    {
      t: o.ok || 'Simpan', cls: 'primary', fn: function () {
        var v = f.input.value;
        closeModal();
        if (o.onOk) o.onOk(v);
      }
    }
  ]);
  setTimeout(function () { f.input.focus(); f.input.select(); }, 40);
  f.input.onkeydown = function (e) {
    if (e.key === 'Enter') {
      e.preventDefault();
      var v = f.input.value;
      closeModal();
      if (o.onOk) o.onOk(v);
    }
  };
}

function confirmDialog(title, msg, onYes) {
  var wrap = document.createElement('div');
  wrap.textContent = msg;
  wrap.style.whiteSpace = 'pre-wrap';
  modal(title, wrap, [
    { t: 'Batal' },
    { t: 'Ya, lanjut', cls: 'danger', fn: function () { closeModal(); onYes(); } }
  ]);
}

/* ---------------------------------------------------------- selection */

function clearSel() { S.sel = {}; render(); }

function selectAll() {
  var all = Object.keys(S.sel).length === S.items.length;
  S.sel = {};
  if (!all) S.items.forEach(function (it) { S.sel[itemPath(it)] = 1; });
  render();
}

function updatePasteBtn() {
  var b = $('btnPaste');
  if (!b) return;
  if (S.clip && S.clip.items.length) {
    b.style.display = '';
    b.textContent = 'Paste ' + S.clip.items.length + ' (' + (S.clip.mode === 'copy' ? 'copy' : 'move') + ')';
  } else {
    b.style.display = 'none';
  }
}

/* ---------------------------------------------------------- listeners */

document.addEventListener('DOMContentLoaded', function () {
  $('tbody').addEventListener('click', function (e) {
    var tr = e.target.closest ? e.target.closest('tr') : null;
    if (!tr || !tr.getAttribute('data-p')) return;
    var p = tr.getAttribute('data-p');
    var rows = Array.prototype.slice.call($('tbody').children);
    var idx = rows.indexOf(tr);

    if (e.ctrlKey || e.metaKey) {
      if (S.sel[p]) delete S.sel[p]; else S.sel[p] = 1;
    } else if (e.shiftKey && S.lastIdx != null && rows[S.lastIdx]) {
      var a = Math.min(S.lastIdx, idx), b = Math.max(S.lastIdx, idx);
      for (var i = a; i <= b; i++) {
        var q = rows[i].getAttribute('data-p');
        if (q) S.sel[q] = 1;
      }
    } else {
      S.sel = {};
      S.sel[p] = 1;
    }
    S.lastIdx = idx;
    render();
  });

  $('tbody').addEventListener('dblclick', function (e) {
    var tr = e.target.closest ? e.target.closest('tr') : null;
    if (!tr || !tr.getAttribute('data-p')) return;
    openItem(tr.getAttribute('data-p'));
  });

  $('tbody').addEventListener('contextmenu', function (e) {
    var tr = e.target.closest ? e.target.closest('tr') : null;
    if (!tr || !tr.getAttribute('data-p')) return;
    e.preventDefault();
    var p = tr.getAttribute('data-p');
    if (!S.sel[p]) { S.sel = {}; S.sel[p] = 1; render(); }
    var it = null;
    S.items.forEach(function (x) { if (itemPath(x) === p) it = x; });
    ctxMenu(e.clientX, e.clientY, it);
  });

  $('search').addEventListener('keydown', function (e) {
    if (e.key === 'Enter') { e.preventDefault(); doSearch(); }
    if (e.key === 'Escape') { $('search').value = ''; if (S.search) { S.search = null; cd(S.path); } }
  });

  document.querySelectorAll('#list thead th[data-sort]').forEach(function (th) {
    th.onclick = function () {
      var k = th.getAttribute('data-sort');
      if (S.sortK === k) S.sortD = -S.sortD; else { S.sortK = k; S.sortD = 1; }
      sortItems(); render();
    };
  });

  var map = {
    download: actDownload, edit: actEdit, rename: actRename, copy: actCopy,
    move: actMove, zip: actZip, extract: actExtract, chmod: actChmod,
    info: actInfo, delete: actDelete
  };
  document.querySelectorAll('[data-sel]').forEach(function (b) {
    b.onclick = function () {
      var fn = map[b.getAttribute('data-sel')];
      if (!Object.keys(S.sel).length) { toast('Pilih file dulu.', 'warn'); return; }
      if (fn) fn();
    };
  });

  document.addEventListener('keydown', function (e) {
    if (e.key === 'Escape') {
      $('ctx').classList.remove('on');
      if ($('modal').classList.contains('on')) closeModal();
    }
    if (e.key === 'F5') { e.preventDefault(); refresh(); }
    if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'a' && document.activeElement.tagName !== 'INPUT' && document.activeElement.tagName !== 'TEXTAREA') {
      e.preventDefault(); selectAll();
    }
    if (e.key === 'Delete' && document.activeElement.tagName !== 'INPUT' && document.activeElement.tagName !== 'TEXTAREA' && Object.keys(S.sel).length) {
      actDelete();
    }
    if (e.key === 'F2' && Object.keys(S.sel).length === 1) actRename();
  });

  document.addEventListener('click', function (e) {
    if (!e.target.closest || !e.target.closest('#ctx')) $('ctx').classList.remove('on');
  });
  window.addEventListener('resize', function () {});

  init();
});

/* -------------------------------------------------------- context menu */

function ctxMenu(x, y, it) {
  var c = $('ctx');
  c.textContent = '';
  var p = it ? itemPath(it) : S.path;

  function add(t, fn, cls) {
    var d = document.createElement('div');
    if (cls === 'sep') {
      d.className = 'sep';
    } else {
      d.textContent = t;
      if (fn) d.onclick = function () { c.classList.remove('on'); fn(); };
    }
    c.appendChild(d);
  }

  if (it) {
    add(it.d ? '\uD83D\uDCC2 Buka' : '\u270E Edit / Buka', function () { openItem(p); });
    if (!it.d) add('\u2B07 Download', function () { downloadPath(p); });
    add('\u270F Rename', actRename);
    add('\u2398 Copy', actCopy);
    add('\u21AA Move', actMove);
    add('\uD83D\uDDDC Zip', actZip);
    if (!it.d && /\.(zip|tar|gz|tgz|bz2|tbz2)$/i.test(it.n)) add('\uD83D\uDCE6 Extract', actExtract);
    add('\u2699 Chmod', actChmod);
    add('\u2139 Info', actInfo);
    add('sep', null, 'sep');
    add('\uD83D\uDDD1 Hapus', actDelete);
  } else {
    add('\uD83D\uDCC1 Folder baru', actNewFolder);
    add('\uD83D\uDCC4 File baru', actNewFile);
    add('\u2B06 Upload', openUpload);
    add('\u21BB Refresh', refresh);
  }

  c.classList.add('on');
  var w = c.offsetWidth, h = c.offsetHeight;
  c.style.left = Math.min(x, window.innerWidth - w - 8) + 'px';
  c.style.top = Math.min(y, window.innerHeight - h - 8) + 'px';
}

/* ------------------------------------------------------------- actions */

function openItem(p) {
  var it = null;
  S.items.forEach(function (x) { if (itemPath(x) === p) it = x; });
  if (it && it.d) { cd(p); return; }
  if (it && /\.(png|jpe?g|gif|webp|bmp|svg|ico|avif|mp4|webm|mp3|wav|ogg|pdf)$/i.test(it.n)) {
    previewFile(p, it.n);
    return;
  }
  openEditor(p);
}

function previewFile(p, name) {
  var wrap = document.createElement('div');
  var src = '?a=raw&path=' + encodeURIComponent(p);
  var el;
  if (/\.(png|jpe?g|gif|webp|bmp|svg|ico|avif)$/i.test(name)) {
    el = document.createElement('img');
    el.src = src;
    el.style.maxWidth = '100%';
  } else if (/\.(mp4|webm)$/i.test(name)) {
    el = document.createElement('video');
    el.src = src; el.controls = true; el.style.maxWidth = '100%';
  } else if (/\.(mp3|wav|ogg)$/i.test(name)) {
    el = document.createElement('audio');
    el.src = src; el.controls = true; el.style.width = '100%';
  } else {
    el = document.createElement('iframe');
    el.src = src; el.style.width = '100%'; el.style.height = '65vh'; el.style.border = '0';
  }
  wrap.appendChild(el);
  modal('\uD83D\uDC41 ' + name, wrap, [{ t: 'Tutup' }, { t: '\u2B07 Download', cls: 'primary', fn: function () { downloadPath(p); } }], true);
}

function downloadPath(p) {
  var a = document.createElement('a');
  a.href = jpath(p);
  a.style.display = 'none';
  document.body.appendChild(a);
  a.click();
  setTimeout(function () { if (a.parentNode) a.parentNode.removeChild(a); }, 1000);
}

function downloadList(paths) {
  var i = 0;
  (function next() {
    if (i >= paths.length) { toast('Download dimulai (' + paths.length + ' file).', 'ok'); return; }
    var p = paths[i++];
    downloadPath(p);
    setTimeout(next, 700);
  })();
}

function actDownload() {
  var paths = selectedPaths();
  if (!paths.length) return;
  var dirs = selectedItems().filter(function (x) { return x.d; });
  if (!dirs.length) { downloadList(paths); return; }
  var files = selectedItems().filter(function (x) { return !x.d; }).map(itemPath);
  var i = 0;
  (function pack() {
    if (i >= dirs.length) { if (files.length) downloadList(files); return; }
    var d = dirs[i++];
    var dest = joinPath(S.path, d.n + '.zip');
    setLoading(true);
    api('zip', { items: [joinPath(S.path, d.n)], dest: dest }).then(function (r) {
      setLoading(false);
      if (!r.ok) { toast('Zip gagal: ' + r.error, 'err'); pack(); return; }
      files.push(dest);
      pack();
    }).catch(function (e) { setLoading(false); toast(e.message, 'err'); pack(); });
  })();
}

function actEdit() {
  var sel = selectedItems();
  if (sel.length !== 1) { toast('Pilih tepat satu file untuk diedit.', 'warn'); return; }
  if (sel[0].d) { toast('Folder tidak bisa diedit.', 'warn'); return; }
  openEditor(itemPath(sel[0]));
}

function actRename() {
  var sel = selectedItems();
  if (sel.length !== 1) { toast('Pilih tepat satu item untuk rename.', 'warn'); return; }
  var it = sel[0];
  var old = itemPath(it);
  var dir = old.lastIndexOf('/') > 0 ? old.substring(0, old.lastIndexOf('/')) : S.path;
  askDialog({
    title: 'Rename', label: 'Nama baru', value: it.n, ok: 'Rename',
    onOk: function (v) {
      v = v.trim();
      if (!v || v === it.n) return;
      setLoading(true);
      api('rename', { from: old, to: joinPath(dir, v) }).then(function (r) {
        setLoading(false);
        if (!r.ok) { toast(r.error, 'err'); return; }
        toast('Rename berhasil.', 'ok'); refresh();
      }).catch(function (e) { setLoading(false); toast(e.message, 'err'); });
    }
  });
}

function actDelete() {
  var paths = selectedPaths();
  if (!paths.length) return;
  var names = selectedItems().map(function (x) { return x.n; }).join('\n');
  confirmDialog('Hapus ' + paths.length + ' item?', 'Item berikut akan dihapus permanen:\n\n' + names, function () {
    setLoading(true);
    api('delete', { items: paths }).then(function (r) {
      setLoading(false);
      if (!r.ok) { toast(r.error, 'err'); return; }
      toast('Dihapus: ' + (r.deleted || []).length + ' item.', 'ok');
      S.sel = {}; refresh();
    }).catch(function (e) { setLoading(false); toast(e.message, 'err'); });
  });
}

function actNewFolder() {
  askDialog({
    title: 'Folder baru', label: 'Nama folder', value: 'folder_baru', ok: 'Buat',
    onOk: function (v) {
      if (!v.trim()) return;
      api('mkdir', { path: joinPath(S.path, v.trim()) }).then(function (r) {
        if (!r.ok) { toast(r.error, 'err'); return; }
        toast('Folder dibuat.', 'ok'); refresh();
      }).catch(function (e) { toast(e.message, 'err'); });
    }
  });
}

function actNewFile() {
  askDialog({
    title: 'File baru', label: 'Nama file', value: 'file.txt', ok: 'Buat',
    onOk: function (v) {
      if (!v.trim()) return;
      var p = joinPath(S.path, v.trim());
      api('newfile', { path: p }).then(function (r) {
        if (!r.ok) { toast(r.error, 'err'); return; }
        refresh();
        openEditor(p);
      }).catch(function (e) { toast(e.message, 'err'); });
    }
  });
}

function actCopy() {
  var paths = selectedPaths();
  if (!paths.length) return;
  S.clip = { mode: 'copy', items: paths };
  updatePasteBtn();
  toast(paths.length + ' item disalin ke clipboard. Masuk folder tujuan lalu Paste.', 'ok');
}

function actMove() {
  var paths = selectedPaths();
  if (!paths.length) return;
  S.clip = { mode: 'move', items: paths };
  updatePasteBtn();
  toast(paths.length + ' item siap dipindah. Masuk folder tujuan lalu Paste.', 'ok');
}

function doPaste() {
  if (!S.clip || !S.clip.items.length) return;
  setLoading(true);
  api(S.clip.mode, { items: S.clip.items, dest: S.path }).then(function (r) {
    setLoading(false);
    if (!r.ok) { toast(r.error, 'err'); return; }
    toast(S.clip.mode === 'copy' ? 'Paste selesai.' : 'Move selesai.', 'ok');
    S.clip = null; updatePasteBtn(); refresh();
  }).catch(function (e) { setLoading(false); toast(e.message, 'err'); });
}

function actZip() {
  var paths = selectedPaths();
  if (!paths.length) return;
  var def = (selectedItems().length === 1 ? selectedItems()[0].n : 'archive') + '.zip';
  askDialog({
    title: 'Buat arsip ZIP', label: 'Nama arsip', value: def, ok: 'Zip',
    hint: 'Arsip dibuat di folder saat ini.',
    onOk: function (v) {
      if (!v.trim()) return;
      if (!/\.zip$/i.test(v)) v += '.zip';
      setLoading(true);
      api('zip', { items: paths, dest: joinPath(S.path, v) }).then(function (r) {
        setLoading(false);
        if (!r.ok) { toast(r.error, 'err'); return; }
        toast('Arsip dibuat: ' + v, 'ok'); refresh();
      }).catch(function (e) { setLoading(false); toast(e.message, 'err'); });
    }
  });
}

function actExtract() {
  var sel = selectedItems();
  if (sel.length !== 1) { toast('Pilih satu file arsip.', 'warn'); return; }
  if (sel[0].d) { toast('Itu folder, bukan arsip.', 'warn'); return; }
  var it = sel[0];
  var p = itemPath(it);
  var base = it.n.replace(/\.(zip|tar\.gz|tgz|tar\.bz2|tbz2|tar|gz)$/i, '');
  askDialog({
    title: 'Extract arsip', label: 'Folder tujuan', value: joinPath(S.path, base), ok: 'Extract',
    hint: 'Akan dibuat otomatis jika belum ada.',
    onOk: function (v) {
      if (!v.trim()) return;
      setLoading(true);
      api('extract', { path: p, dest: v.trim() }).then(function (r) {
        setLoading(false);
        if (!r.ok) { toast(r.error, 'err'); return; }
        toast('Extract selesai.', 'ok'); cd(v.trim());
      }).catch(function (e) { setLoading(false); toast(e.message, 'err'); });
    }
  });
}

function actChmod() {
  var sel = selectedItems();
  if (sel.length !== 1) { toast('Pilih satu item.', 'warn'); return; }
  var p = itemPath(sel[0]);
  askDialog({
    title: 'Chmod', label: 'Mode octal', value: sel[0].p || '0644', ok: 'Terapkan',
    hint: 'Contoh: 644, 755, 0777. Tidak berlaku penuh di Windows.',
    onOk: function (v) {
      api('chmod', { path: p, mode: v.trim() }).then(function (r) {
        if (!r.ok) { toast(r.error, 'err'); return; }
        toast('Permission: ' + r.perm, 'ok'); refresh();
      }).catch(function (e) { toast(e.message, 'err'); });
    }
  });
}

function actInfo() {
  var sel = selectedItems();
  if (sel.length !== 1) { toast('Pilih satu item.', 'warn'); return; }
  var p = itemPath(sel[0]);
  api('info', { path: p }).then(function (r) {
    if (!r.ok) { toast(r.error, 'err'); return; }
    var t = document.createElement('table');
    t.className = 'kv';
    var rows = [
      ['Path', r.path], ['Tipe', r.dir ? 'Folder' : 'File'],
      ['Ukuran', r.size_h + ' (' + r.size + ' byte)'],
      ['Item', r.dir ? r.items + ' file' : '-'],
      ['MIME', r.mime || '-'], ['Perm', r.perm],
      ['Owner', r.owner || '-'], ['Group', r.group || '-'],
      ['Diubah', r.mtime], ['Akses', r.atime], ['Inode', r.inode],
      ['Symlink', r.link || '-'],
      ['Readable', r.readable ? 'ya' : 'tidak'], ['Writable', r.writable ? 'ya' : 'tidak'],
      ['Executable', r.executable ? 'ya' : 'tidak']
    ];
    Object.keys(r.hashes || {}).forEach(function (k) { rows.push([k.toUpperCase(), r.hashes[k]]); });
    rows.forEach(function (row) {
      var tr = document.createElement('tr');
      var a = document.createElement('td'); a.textContent = row[0];
      var b = document.createElement('td'); b.textContent = row[1];
      tr.appendChild(a); tr.appendChild(b); t.appendChild(tr);
    });
    modal('\u2139 Info: ' + r.name, t, [{ t: 'Tutup' }]);
  }).catch(function (e) { toast(e.message, 'err'); });
}

/* -------------------------------------------------------------- search */

function doSearch() {
  var q = $('search').value.trim();
  if (!q) { if (S.search) { S.search = null; cd(S.path); } return; }
  setLoading(true);
  api('search', {
    path: S.path || '/',
    q: q,
    content: $('searchContent').checked ? 1 : 0,
    limit: 300
  }).then(function (r) {
    setLoading(false);
    if (!r.ok) { toast(r.error, 'err'); return; }
    S.search = { q: q, items: r.items || [] };
    S.items = S.search.items;
    S.sel = {};
    sortItems(); render();
    $('stCount').textContent = S.items.length + ' hasil (scan ' + r.scanned + ')';
    $('stPath').textContent = 'Hasil: "' + q + '" di ' + S.path;
  }).catch(function (e) { setLoading(false); toast(e.message, 'err'); });
}

/* -------------------------------------------------------------- upload */

var UP = { rows: {}, total: 0, done: 0, active: 0, max: 3, queue: [] };

function openUpload() { $('filePick').value = ''; $('filePick').click(); }

function uploadPanel(files) {
  var wrap = document.createElement('div');
  var head = document.createElement('div');
  head.className = 'hint';
  head.style.marginBottom = '10px';
  head.textContent = 'Upload ke: ' + S.path + '  (' + files.length + ' file)';
  wrap.appendChild(head);
  var list = document.createElement('div');
  wrap.appendChild(list);

  UP = { rows: {}, total: files.length, done: 0, active: 0, max: 3, queue: [] };

  Array.prototype.forEach.call(files, function (f) {
    var row = document.createElement('div');
    row.className = 'prog';
    var nm = document.createElement('span');
    nm.className = 'nm';
    nm.textContent = f.name + '  (' + fmtSize(f.size) + ')';
    var pb = document.createElement('div');
    pb.className = 'pb';
    var pi = document.createElement('i');
    pb.appendChild(pi);
    var pc = document.createElement('span');
    pc.className = 'pc';
    pc.textContent = '0%';
    row.appendChild(nm); row.appendChild(pb); row.appendChild(pc);
    list.appendChild(row);
    UP.rows[f.name] = { bar: pi, pc: pc, row: row };
    UP.queue.push(f);
  });

  modal('Upload', wrap, [{ t: 'Tutup', fn: function () { if (UP.active === 0) closeModal(); else toast('Upload masih berjalan...', 'warn'); } }]);
}

function uploadFiles(files) {
  if (!files || !files.length) return;
  uploadPanel(files);
  pump();
}

function pump() {
  while (UP.active < UP.max && UP.queue.length) {
    var f = UP.queue.shift();
    UP.active++;
    uploadOne(f).then(function () {
      UP.active--; UP.done++;
      if (UP.done === UP.total) {
        toast('Upload selesai: ' + UP.total + ' file.', 'ok');
        setTimeout(closeModal, 400);
        refresh();
      }
      pump();
    }).catch(function (e) {
      UP.active--;
      toast('Upload gagal: ' + e.message, 'err');
      pump();
    });
  }
}

function uploadOne(file) {
  var chunk = 1024 * 1024;
  var offset = 0;
  var target = joinPath(S.path, file.name);
  var row = UP.rows[file.name];

  return new Promise(function (resolve, reject) {
    function step() {
      var slice = file.slice(offset, offset + chunk);
      var fr = new FileReader();
      fr.onload = function () {
        var b64 = String(fr.result);
        var i = b64.indexOf(',');
        b64 = i >= 0 ? b64.slice(i + 1) : b64;
        api('upload', { path: target, offset: offset, data: b64 }).then(function (r) {
          if (!r.ok) { reject(new Error(r.error || 'server menolak')); return; }
          offset += slice.size;
          var pct = file.size ? Math.min(100, Math.round(offset / file.size * 100)) : 100;
          if (row) { row.bar.style.width = pct + '%'; row.pc.textContent = pct + '%'; }
          if (offset < file.size) step(); else resolve();
        }).catch(reject);
      };
      fr.onerror = function () { reject(new Error('gagal membaca file')); };
      fr.readAsDataURL(slice);
    }
    if (file.size === 0) {
      api('upload', { path: target, offset: 0, data: '' }).then(function (r) {
        if (r.ok) resolve(); else reject(new Error(r.error));
      }).catch(reject);
    } else step();
  });
}

/* -------------------------------------------------------------- editor */

var ED = { path: null, orig: '' };

function openEditor(p) {
  setLoading(true);
  api('read', { path: p }).then(function (r) {
    setLoading(false);
    if (!r.ok) { toast(r.error, 'err'); return; }
    if (r.binary) {
      toast('File biner - dibuka sebagai preview.', 'warn');
      previewFile(p, p.split('/').pop());
      return;
    }
    ED.path = r.path;
    ED.orig = b64d(r.data);
    $('edPath').textContent = r.path;
    var ta = $('edtext');
    ta.value = ED.orig;
    $('edInfo').textContent = fmtSize(r.size) + '  ' + r.perm + '  ' + fmtDate(r.mtime);
    $('editor').classList.add('on');
    edDirty(false);
    edApplyWrap();
    updateGutter();
    setTimeout(function () { ta.focus(); ta.setSelectionRange(0, 0); ta.scrollTop = 0; }, 30);
  }).catch(function (e) { setLoading(false); toast(e.message, 'err'); });
}

function edDirty(on) {
  ED.dirty = on;
  $('edDirty').textContent = on ? '\u25CF belum disimpan' : '';
}

function edApplyWrap() {
  var ta = $('edtext');
  var w = $('edWrap').checked;
  ta.wrap = w ? 'soft' : 'off';
  ta.style.whiteSpace = w ? 'pre-wrap' : 'pre';
  ta.style.overflowX = w ? 'hidden' : 'auto';
}

function updateGutter() {
  var ta = $('edtext');
  var n = ta.value.split('\n').length;
  var g = [];
  for (var i = 1; i <= n; i++) g.push(i);
  $('gutter').textContent = g.join('\n');
  $('gutter').scrollTop = ta.scrollTop;
}

function edPos() {
  var ta = $('edtext');
  var upto = ta.value.substring(0, ta.selectionStart);
  var ln = upto.split('\n').length;
  var col = upto.length - upto.lastIndexOf('\n');
  $('edPos').textContent = 'Ln ' + ln + ', Col ' + col;
}

function edSave() {
  if (!ED.path) return;
  var ta = $('edtext');
  setLoading(true);
  api('save', { path: ED.path, data: b64e(ta.value) }).then(function (r) {
    setLoading(false);
    if (!r.ok) { toast(r.error, 'err'); return; }
    ED.orig = ta.value;
    edDirty(false);
    toast('Tersimpan: ' + r.path.split('/').pop() + ' (' + fmtSize(r.size) + ')', 'ok');
    refresh();
  }).catch(function (e) { setLoading(false); toast(e.message, 'err'); });
}

function edDownload() {
  if (ED.path) downloadPath(ED.path);
}

function edClose() {
  var ta = $('edtext');
  if (ta.value !== ED.orig) {
    confirmDialog('Tutup editor?', 'Ada perubahan yang belum disimpan. Tutup tanpa menyimpan?', function () {
      $('editor').classList.remove('on'); ED.path = null; ED.orig = '';
    });
    return;
  }
  $('editor').classList.remove('on');
  ED.path = null; ED.orig = '';
}

function edKey(e) {
  if (e.key === 'Tab') {
    e.preventDefault();
    var ta = e.target, s = ta.selectionStart, en = ta.selectionEnd;
    ta.value = ta.value.substring(0, s) + '    ' + ta.value.substring(en);
    ta.selectionStart = ta.selectionEnd = s + 4;
    updateGutter(); edDirty(true);
    return;
  }
  if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 's') {
    e.preventDefault(); edSave(); return;
  }
  if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'w') {
    e.preventDefault(); edClose(); return;
  }
}

/* ------------------------------------------------------------ terminal */

function toggleTerm(force) {
  var t = $('term');
  var on = (typeof force === 'boolean') ? force : !t.classList.contains('on');
  t.classList.toggle('on', on);
  if (on) {
    if (!S.term.cwd) {
      S.term.cwd = S.path || '/';
      termWrite('\u2500\u2500 terminal siap \u2500\u2500  ketik perintah lalu Enter. "cd" untuk pindah folder.\n', 'prompt');
    }
    termPrompt();
    $('tShell').textContent = S.os || '';
    setTimeout(function () { $('termCmd').focus(); }, 40);
  }
}

function termPrompt() {
  var p = S.term.cwd || S.path || '/';
  var short = p.length > 42 ? '\u2026' + p.slice(-41) : p;
  $('termPrompt').textContent = short + ' $';
}

function termWrite(text, cls) {
  var out = $('termOut');
  var d = document.createElement('div');
  if (cls) d.className = cls;
  d.textContent = text;
  out.appendChild(d);
  out.scrollTop = out.scrollHeight;
}

function termClear() { $('termOut').textContent = ''; }

function termSize() {
  var t = $('term');
  t.style.height = (t.style.height === '92vh') ? '46vh' : '92vh';
}

function termRun(cmd) {
  if (S.term.busy) { toast('Tunggu perintah sebelumnya selesai.', 'warn'); return; }
  if (!S.term.cwd) S.term.cwd = S.path || '/';
  termWrite((S.term.cwd || '') + ' $ ' + cmd, 'cmd');
  if (!cmd.trim()) return;
  S.term.hist.push(cmd);
  S.term.hi = S.term.hist.length;
  S.term.busy = true;
  api('terminal', { cmd: cmd, cwd: S.term.cwd }).then(function (r) {
    S.term.busy = false;
    if (!r.ok) { termWrite(r.error, 'errc'); return; }
    if (r.clear) { termClear(); return; }
    if (r.out) termWrite(r.out);
    if (r.cwd && r.cwd !== S.term.cwd) { S.term.cwd = r.cwd; }
    termPrompt();
    if (r.code && Number(r.code) !== 0) {
      var last = $('termOut').lastElementChild;
      if (last) last.className = 'errc';
    }
  }).catch(function (e) {
    S.term.busy = false;
    termWrite(e.message || 'error', 'errc');
  });
}

function termKey(e) {
  if (e.key === 'Enter') {
    e.preventDefault();
    var v = e.target.value;
    e.target.value = '';
    termRun(v);
    return;
  }
  if (e.key === 'ArrowUp') {
    if (S.term.hi > 0) { S.term.hi--; e.target.value = S.term.hist[S.term.hi] || ''; }
    e.preventDefault(); return;
  }
  if (e.key === 'ArrowDown') {
    if (S.term.hi < S.term.hist.length) {
      S.term.hi++;
      e.target.value = S.term.hist[S.term.hi] || '';
    }
    e.preventDefault(); return;
  }
  if (e.ctrlKey && e.key.toLowerCase() === 'l') { e.preventDefault(); termClear(); return; }
  if (e.ctrlKey && e.key.toLowerCase() === 'c') {
    e.preventDefault();
    termWrite('^C', 'errc');
    e.target.value = '';
    return;
  }
}

/* ---------------------------------------------------------------- init */

function init() {
  var ta = $('edtext');
  ta.addEventListener('input', function () { updateGutter(); edDirty(true); });
  ta.addEventListener('scroll', function () { $('gutter').scrollTop = ta.scrollTop; });
  ta.addEventListener('keydown', edKey);
  ta.addEventListener('keyup', edPos);
  ta.addEventListener('click', edPos);
  $('edWrap').addEventListener('change', edApplyWrap);

  $('termCmd').addEventListener('keydown', termKey);
  $('filePick').addEventListener('change', function () { if (this.files.length) uploadFiles(this.files); });

  var dragCount = 0;
  window.addEventListener('dragenter', function (e) {
    if (!e.dataTransfer || Array.prototype.indexOf.call(e.dataTransfer.types || [], 'Files') < 0) return;
    dragCount++; $('drop').classList.add('on');
  });
  window.addEventListener('dragover', function (e) { e.preventDefault(); });
  window.addEventListener('dragleave', function () {
    dragCount--; if (dragCount <= 0) { dragCount = 0; $('drop').classList.remove('on'); }
  });
  window.addEventListener('drop', function (e) {
    e.preventDefault();
    dragCount = 0; $('drop').classList.remove('on');
    if (e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files.length) uploadFiles(e.dataTransfer.files);
  });

  document.addEventListener('keydown', function (e) {
    if (e.key === 'F9') { e.preventDefault(); toggleTerm(); }
  });

  var start = '';
  try { start = decodeURIComponent((location.hash || '').replace(/^#/, '')); } catch (err) { start = ''; }
  cd(start || '');
  loadDrives();
}

window.addEventListener('hashchange', function () {
  var h = '';
  try { h = decodeURIComponent((location.hash || '').replace(/^#/, '')); } catch (e) {}
  if (h && h !== S.path) cd(h);
});
</script>
</body>
</html>
