<?php
if (!defined('_GNUBOARD_')) exit; // 개별 페이지 접근 불가

add_stylesheet('<link rel="stylesheet" href="'.$member_skin_url.'/style.css">', 0);
add_stylesheet('<link rel="stylesheet" href="'.$member_skin_url.'/style.memo.css">', 0);

$recv_mb = get_member($me_recv_mb_id);
$p_icon = get_member_profile_img($me_recv_mb_id);

//쪽지알림 업데이트
$sql3 = " update `{$g5['member_table']}` set mb_memo_cnt = '".get_memo_not_read($member['mb_id'])."' where mb_id = '{$member['mb_id']}' ";
sql_query($sql3);

//대화창을 열면 기존 읽지 않은 쪽지를 업데이트 한다.
$aaa = "select * from {$g5['memo_table']} where me_recv_mb_id ='".$member['mb_id']."' and me_send_mb_id = '".$recv_mb['mb_id']."' and me_read_datetime = '0000-00-00 00:00:00'";
$bbb = sql_query($aaa);

//한개씩 읽은 날짜를 업데이트 해준다.
for($i=0;$ccc=sql_fetch_array($bbb);$i++) {
    $up = "update {$g5['memo_table']} set me_read_datetime = '".G5_TIME_YMDHIS."' where me_id = '".$ccc['me_id']."'";
    sql_query($up);
}

//가장 큰 결과 값을 구함
$que = "select max(me_id) as max from {$g5['memo_table']} where (me_recv_mb_id ='".$recv_mb['mb_id']."' and me_send_mb_id = '".$member['mb_id']."') or (me_recv_mb_id = '".$member['mb_id']."' and me_send_mb_id = '".$recv_mb['mb_id']."')";
$max = sql_fetch($que); 

//전체 카운터 
$que = "select count(me_id) as cnt from {$g5['memo_table']} where (me_recv_mb_id ='".$recv_mb['mb_id']."' and me_send_mb_id = '".$member['mb_id']."') or (me_recv_mb_id = '".$member['mb_id']."' and me_send_mb_id = '".$recv_mb['mb_id']."')";
$cnt = sql_fetch($que);
$total = $cnt['cnt']; //총갯수
$limit = 15; // 출력할 갯수
//$limit = $cnt['cnt']; // 출력할 갯수

$from_record = $total - $limit;
if($from_record < 0) {
    $limit_record = $limit_record + $from_record;
    $from_record = 0;
}

$sql = "select * from {$g5['memo_table']} where (me_send_mb_id ='".$recv_mb['mb_id']."' and me_recv_mb_id = '".$member['mb_id']."') or (me_send_mb_id = '".$member['mb_id']."' and me_recv_mb_id = '".$recv_mb['mb_id']."') order by me_send_datetime asc limit  {$from_record}, {$limit}";
$res = sql_query($sql);

// 날짜 계산 함수
/*
function passing_time($me_send_datetime) {
	$time_lag = time() - strtotime($me_send_datetime);
	
	if($time_lag < 60) {
		$posting_time = "방금";
	} else if($time_lag >= 60 and $time_lag < 3600) {
		$posting_time = floor($time_lag/60)."분 전";
	} else if($time_lag >= 3600 and $time_lag < 86400) {
		$posting_time = floor($time_lag/3600)."시간 전";
	} else if($time_lag >= 86400 and $time_lag < 2419200) {
		$posting_time = floor($time_lag/86400)."일 전";
	} else {
		$posting_time = date("y-m-d", strtotime($me_send_datetime));
	} 
	
	return $posting_time;
}
*/
include_once(G5_LIB_PATH.'/thumbnail.lib.php');
//회원정보 불러오기
$sql = " select * from $g5[member_table] group by mb_id order by mb_id asc"; 
$result = sql_query($sql); 
?>
<style>
#chat-body {
background-size: cover;
background-position: center;
}
.badge3 img {
width:40px;
height:40px;
border-radius:50%;
margin-right:15px
}
body {
background-color:#0000 !important;
}
.modal {
    display: none;
    position: fixed;
    z-index: 1;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    overflow: auto;
    background-color: rgba(0, 0, 0, 0.4);
}

.modal-content {
    background-color: #fefefe;
    margin: 15% auto;
    padding: 20px;
    border: 1px solid #888;
    width: 80%;
}

.close-button {
    color: #aaa;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

.close-button:hover,
.close-button:focus {
    color: black;
    text-decoration: none;
    cursor: pointer;
}

/* 업로드 선택 모달*/
.file-preview-item {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
}

.file-preview-thumbnail {
    width: 100px;
    height: 100px;
    margin-right: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #f1f1f1;
    border-radius:10px
}

.file-preview-thumbnail img,
.thumbnail-size {
    max-width: 100%;
    width:100%;
    max-height: 100%;
    height:auto;
    border-radius:10px
}

.file-preview-info {
    flex-grow: 1;
}

.file-name {
    margin-top: 0;
}

.remove-file {
    background-color: #0bcdff;
    color: white;
    border: none;
    padding: 5px 10px;
    border-radius: 5px;
    cursor: pointer;
}
</style>

<div id="chat-header">
    <div>
        <div class="mo_bdgs">
            <a href="memo.php" id="btn_close2" onclick="memo.php">
                <i class="fa fa-arrow-left" style="color:#3a3a3a;font-size:20px;"></i>
            </a>
        </div>
        
        <div class="mo_nick">
        <a href="profile.php?mb_id=<?php echo $recv_mb['mb_id'];?>">
        <span class="badge3" id="profileImage" style="position: relative;">
        <?php echo get_member_profile_img($recv_mb['mb_id']); ?>
        </span>
        <span style="font-size:1em;font-weight:500;color:#3a3a3a">
        <?php echo $recv_mb['mb_nick'];?>
        </span>
        </a>
        </div>
        <!--
        <div style="clear:both"></div>
        -->

    </div>
</div>

<div id="chat-body">
    
    <?php
    if($total > $limit) { //총갯수가 출력할 갯수보다 많으면 이전 버튼을 만들어 준다
        echo '<div class="chat_history_div_wrap" id="chat_history_div_wrap">';
        echo '<div class="chat_history_div">';
        echo '<button type="button" id="chat-history">이전대화 10개 보기</button>';
        echo '</div>';
        echo '</div>';
    }
    ?>
    
    <ul id="chat-list">
        
    <?php if($total <= 0) { ?>
    <div class="chktotal" style="margin:auto;text-align:center;color:#cdcdcd;margin-top:20px;"><?php echo $recv_mb['mb_nick'];?>님과 대화를 시작해보세요!</div>
    <?php } ?>
        
        <?php
        for($i=0;$row=sql_fetch_array($res);$i++) {
            

            $newDate = substr($row['me_send_datetime'],0,10);
            
            if($row['me_send_mb_id'] == $member['mb_id']) {
                $cls = "recv";
                $cls_box = "bubble_recv";
                
            } else {
                $cls = "send";
                $cls_box = "bubble_send";
            }
            
            if($newDate != $chkDate) {
                echo '<li id="'.$newDate.'" class="chkdate">' . $newDate.'</li>';
            }
            echo '<li id="chat_list_'.$row['me_id'].'" class="'.$cls.'">';
            if($row['me_send_mb_id'] != $member['mb_id']) {
                
                if($recv_mb['mb_level'] == "10") { // 관리자의 경우는 프로필 볼 수 없도록 처리
                    echo '<span class="p_icon">'.$p_icon.'</span>';
                } else {
                    echo '<a href="'.G5_BBS_URL.'/profile.php?mb_id='.$recv_mb['mb_id'].'" target="_blank" class="p_icon win_profile">'.$p_icon.'</a>';
                }
                
                echo '<span class="p_nick"> '.$recv_mb['mb_nick'].'</span>';
            }

            echo '<div class="'.$cls_box.'">';
            echo $row['me_memo'];
            echo '</div>'; 
            
            echo '<div class="chat_time_'.$cls.'">';
            
            /* 수신확인 부분, 실시간 구현 필요 */
            if($row['me_send_mb_id'] == $member['mb_id']) {
                if(substr($row['me_read_datetime'],0,1) == 0) {
                    echo "<span id='am".$row["me_id"]."' style='color:#0b93fa; font-weight:bold;'>1</span>";
                } else {
                    echo "";
                }
            }
            /* 수신확인 실시간처리 구현필요 */ 

            echo substr($row['me_send_datetime'],10,6);
            echo '</div>';
            
            if($row['me_send_mb_id'] == $member['mb_id']) {
                
            echo '<div style="position: absolute; margin-top:-62px; margin-left:-20px;"><a href="'.G5_BBS_URL.'/ajax.memo_del.php?me_id='.$row['me_id'].'&del_id='.$recv_mb['mb_id'].'" class="chatroom-cnt2 badge3"><svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" class="feather feather-trash w-4 h-4 mr-2"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path></svg></a><div>';
                
            }
                       
            
            echo '</li>';
            

            
            $chkDate = $newDate;
            $pos_id = $row['me_id']; 
        }
        $toDate = date("Y-m-d");
        if($chkDate != $toDate) {
            echo '<li id="'.$toDate.'" class="chkdate">' . $toDate.'</li>';
        }
        ?>
    </ul>
</div>

<!-- 이모티콘 팝업{ -->
<div id="emoji-modal" style="display:none; position:fixed; bottom:70px; right:50px; background:white; border:1px solid black; padding:10px; z-index:1000;">
    <div id="emoji-container" style="display:flex; flex-wrap:wrap;"></div>
    <button id="close-modal">닫기</button>
</div>
<!-- }이모티콘 팝업 -->

<div id="chat-footer">
    <div class="chat_message_div">
        <textarea id="chat-message" name="cmt_text" placeholder="쪽지 보내기..."></textarea>
    </div>                
    <div class="chat_message_btn_div">

<!-- 안드로이드 자동 붙여넣기{ -->
<script>
// 기본 동작 허용
document.addEventListener('contextmenu', function(e) {
    // 기본 동작을 허용
});

// textarea에 대해서만 붙여넣기 메뉴 허용
const textarea = document.querySelector('textarea');
if (textarea) {
    textarea.addEventListener('contextmenu', function(e) {
        e.stopPropagation(); // 이벤트 전파를 막지 않음
    });
}
</script>
<!-- }붙여넣기 허용 끝 -->

<!--파일 첨부-->
<div id="chat_file_up">
    <div id="file_up">
        <div class="file_write">
            <div class="file-upload">
                <input type="file" id="file" class="file" name="bf_file" title="파일용량 : 7MB 이하만 가능" class="frm_file" multiple>
                <label for="file"><i class="fa fa-folder-o"></i></label>
            </div>
        </div>
    </div>
</div>

<div id="file-preview-modal" class="modal">
    <div class="modal-content" style="border-radius:15px;border:none;background-color: rgba(255, 255, 251, 0.55);-webkit-backdrop-filter: blur(17px);backdrop-filter: blur(17px);">
        <span class="close-button">&times;</span>
        <div id="file-preview-container">
            <div class="file-preview-item">
                <div class="file-preview-thumbnail">
                    <img src="#" alt="Thumbnail">
                </div>
                <div class="file-preview-info">
                    <h3 class="file-name">파일명</h3>
                    <button class="remove-file">선택 취소</button>
                </div>
            </div>
        </div>
        <button id="upload-button" style="background-color:#6a6a6a;padding:7px;border-radius:10px;border:none;color:#f9f9f9;font-size:1em;font-weight:520">업로드</button>
    </div>
</div>

<!-- 선택 취소 버튼 -->
<button id="cancel-btn" style="display: none; position: fixed; bottom: 80px; left: 50%; transform: translateX(-50%);border-radius:25px;background-color:#cdcdcd;border:1px solid #0000;color:#2a2a2a;padding:5px;font-size:1.2em;width:35px;height:35px">X</button>
                <!--이미지 첨부 끝-->

        <div id="btn-ref" title="이모티콘">
            <i class="fa fa-smile-o" aria-hidden="true"></i>
        </div>

        <div id="btn-chat" title="보내기">
            <i class="fa fa-paper-plane" aria-hidden="true"></i>
        </div>
    </div>
 
    <div style="clear:both"></div>
    
</div>

<script>
document.querySelector(".fas").addEventListener("click", function() {
  document.querySelector(".file").click();
});
</script>
<script>
var uploadedFiles = [];
var upload_time;
var baseDomain = <?php echo json_encode(G5_URL); ?>;

document.getElementById('file').addEventListener('change', function() {
    showFilePreviewModal(this.files);
});

function showFilePreviewModal(files) {
    var modal = document.getElementById("file-preview-modal");
    var closeButton = document.getElementsByClassName("close-button")[0];
    var uploadButton = document.getElementById("upload-button");
    var filePreviewContainer = document.getElementById("file-preview-container");

    // 새로운 업로드 세션 시작 시 이전 데이터 초기화
    uploadedFiles = [];
    clearPreviousUploadData();

    // 이미지 파일 선택 시점의 시간을 저장
    upload_time = new Date().toISOString().replace(/[^0-9]/g, '');

    // 현재 년월일 추출
    var currentDate = new Date();
    var year = currentDate.getFullYear();
    var month = String(currentDate.getMonth() + 1).padStart(2, '0');
    var day = String(currentDate.getDate()).padStart(2, '0');
    var hours = String(currentDate.getHours()).padStart(2, '0');
    var minutes = String(currentDate.getMinutes()).padStart(2, '0');
    var seconds = String(currentDate.getSeconds()).padStart(2, '0');
    var milliseconds = String(currentDate.getMilliseconds()).padStart(3, '0');

    upload_time = year + month + day + hours + minutes + seconds + milliseconds;
    var formattedDate = year + month + day;

    // 파일 미리보기 생성
    filePreviewContainer.innerHTML = "";

    // 현재 업로드 세션 ID 생성 및 저장
    const sessionId = 'upload_session_' + upload_time;
    localStorage.setItem('current_upload_session', sessionId);

    for (var i = 0; i < files.length; i++) {
        var fileType = files[i].type.split('/')[0];
        var originalExtension = files[i].name.split('.').pop().toLowerCase();
        var fileExtension = (fileType === 'image' && originalExtension !== 'gif') ? 'webp' : originalExtension;
        var new_file_name = '<?php echo $member['mb_id'];?>-<?php echo $recv_mb['mb_id'];?>/' + formattedDate + '/' + upload_time + '_' + i + '.' + fileExtension;

        // 이미지 파일인 경우 썸네일 생성 및 저장
        if (fileType === 'image') {
            createAndStoreImageThumbnail(files[i], new_file_name);
        }

        var filePreviewItem = document.createElement("div");
        filePreviewItem.classList.add("file-preview-item");

        var thumbnailContainer = document.createElement("div");
        thumbnailContainer.classList.add("file-preview-thumbnail");

        if (fileType === 'image') {
            var thumbnail = document.createElement("img");
            thumbnail.alt = "Thumbnail";
            var reader = new FileReader();
            reader.onload = (function(thumbnail) {
                return function(e) {
                    thumbnail.src = e.target.result;
                };
            })(thumbnail);
            reader.readAsDataURL(files[i]);
            thumbnail.classList.add("thumbnail-size");
            thumbnailContainer.appendChild(thumbnail);
        } else if (fileType === 'video') {
            var videoElement = document.createElement("video");
            videoElement.src = URL.createObjectURL(files[i]);
            videoElement.controls = true;
            videoElement.classList.add("thumbnail-size");
            thumbnailContainer.appendChild(videoElement);
        } else {
            var thumbnail = document.createElement("img");
            thumbnail.src = '<?php echo G5_THEME_IMG_URL ?>/twave/file.png';
            thumbnail.alt = "Default Thumbnail";
            thumbnail.classList.add("thumbnail-size");
            thumbnailContainer.appendChild(thumbnail);
        }

        var fileInfoContainer = document.createElement("div");
        fileInfoContainer.classList.add("file-preview-info");
        var fileName = document.createElement("h3");
        fileName.classList.add("file-name");
        if (files[i].name.length > 12) {
            fileName.textContent = files[i].name.slice(0, 12) + '...';
        } else {
            fileName.textContent = files[i].name;
        }

        var removeButton = document.createElement("button");
        removeButton.classList.add("remove-file");
        removeButton.textContent = "선택 취소";
        removeButton.addEventListener("click", function() {
            removeFileFromPreview(this);
            updateLocalStorage();
        });

        fileInfoContainer.appendChild(fileName);
        fileInfoContainer.appendChild(removeButton);
        filePreviewItem.appendChild(thumbnailContainer);
        filePreviewItem.appendChild(fileInfoContainer);
        filePreviewContainer.appendChild(filePreviewItem);

        // 업로드 파일 배열에 추가
        uploadedFiles.push({
            file: files[i],
            new_file_name: new_file_name,
            status: 'pending', // 업로드 상태 추가
            sessionId: sessionId
        });
    }

    // 로컬 스토리지에 업로드 정보 저장
    updateLocalStorage();

    modal.style.display = "block";

    closeButton.onclick = function() {
        modal.style.display = "none";
    };

    window.onclick = function(event) {
        if (event.target == modal) {
            modal.style.display = "none";
        }
    };

    uploadButton.onclick = function() {
        uploadFiles(uploadedFiles);
        var urls = uploadedFiles.map(function(item) {
            return baseDomain + '/chat_data/img_loader.php?id=' + item.new_file_name;
        });
        document.getElementById('chat-message').value = urls.join(' ');
        modal.style.display = "none";

        var sendButton = document.getElementById("btn-chat");
        sendButton.click();
    };
}

// 썸네일 생성 및 저장 함수
function createAndStoreImageThumbnail(file, filename) {
    const reader = new FileReader();
    reader.onload = function(e) {
        const img = new Image();
        img.onload = function() {
            // 캔버스 생성 및 크기 설정 (원본의 50%)
            const canvas = document.createElement('canvas');
            canvas.width = img.width * 0.5;
            canvas.height = img.height * 0.5;
            
            // 이미지 그리기
            const ctx = canvas.getContext('2d');
            ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
            
            // base64로 변환 및 저장
            const thumbnailBase64 = canvas.toDataURL('image/jpeg', 0.7);
            const thumbnailKey = `thumbnail_${filename}`;
            try {
                localStorage.setItem(thumbnailKey, thumbnailBase64);
            } catch (e) {
                console.warn('Local storage quota exceeded:', e);
            }
        };
        img.src = e.target.result;
    };
    reader.readAsDataURL(file);
}

function removeFileFromPreview(button) {
    var filePreviewItem = button.parentNode.parentNode;
    var fileIndex = Array.from(filePreviewItem.parentNode.children).indexOf(filePreviewItem);
    
    // 썸네일 제거
    if (uploadedFiles[fileIndex] && uploadedFiles[fileIndex].new_file_name) {
        const thumbnailKey = `thumbnail_${uploadedFiles[fileIndex].new_file_name}`;
        localStorage.removeItem(thumbnailKey);
    }
    
    uploadedFiles.splice(fileIndex, 1);
    filePreviewItem.remove();
    updateLocalStorage();

    if (uploadedFiles.length === 0) {
        var modal = document.getElementById("file-preview-modal");
        modal.style.display = "none";
    }
}

// 이전 업로드 데이터 정리 함수
function clearPreviousUploadData() {
    // 로컬 스토리지의 모든 키를 확인
    for (let i = 0; i < localStorage.length; i++) {
        const key = localStorage.key(i);
        // 이전 썸네일 및 업로드 세션 데이터 삭제
        if (key.startsWith('thumbnail_') || key.startsWith('upload_session_')) {
            localStorage.removeItem(key);
        }
    }
    // 이전 업로드 파일 정보 삭제
    localStorage.removeItem('uploadedFiles');
    localStorage.removeItem('current_upload_session');
}

function updateLocalStorage() {
    const currentSessionId = localStorage.getItem('current_upload_session');
    // 현재 세션의 파일들만 필터링하여 저장
    const currentSessionFiles = uploadedFiles.filter(file => file.sessionId === currentSessionId);
    localStorage.setItem('uploadedFiles', JSON.stringify(currentSessionFiles));
}

function uploadFiles(files) {
    if (files.length === 0) {
        alert('업로드할 파일이 없습니다.');
        return;
    }

    var uploadStatusPopup = document.createElement('div');
    uploadStatusPopup.id = 'upload-status-popup';
    uploadStatusPopup.style.position = 'fixed';
    uploadStatusPopup.style.top = '65px';
    uploadStatusPopup.style.left = '50%';
    uploadStatusPopup.style.transform = 'translateX(-50%)';
    uploadStatusPopup.style.padding = '10px';
    uploadStatusPopup.style.backgroundColor = 'rgba(255, 255, 255, 0.8)';
    uploadStatusPopup.style.borderRadius = '15px';
    uploadStatusPopup.style.border = '1px solid #ccc';
    uploadStatusPopup.style.backdropFilter = 'blur(10px)';
    uploadStatusPopup.style.boxShadow = '0 4px 8px rgba(0, 0, 0, 0.2)';
    uploadStatusPopup.style.zIndex = '999999999';
    document.body.appendChild(uploadStatusPopup);

    var estimatedTime = files.reduce((total, file) => total + (file.file.size / 1024 / 1024) * 0.5, 0);
    var remainingTime = Math.max(Math.round(estimatedTime), 0);

    uploadStatusPopup.innerText = `업로드 중... 예상 시간: ${remainingTime}초`;

    var intervalId = setInterval(function() {
        remainingTime--;

        if (remainingTime < 0) {
            remainingTime = 0;
        }

        uploadStatusPopup.innerText = `업로드 중... 예상 시간: ${remainingTime}초`;
        
        if (remainingTime === 0) {
            let dots = '.';
            let dotInterval = setInterval(function() {
                dots += '.';
                if (dots.length > 3) {
                    dots = '';
                }
                uploadStatusPopup.innerText = `대기중${dots}`;
            }, 500);

            function clearDotInterval() {
                clearInterval(dotInterval);
            }

            setTimeout(clearDotInterval, 2000);
        }
    }, 1000);

    function uploadFile(index) {
        if (index >= files.length) {
            // 모든 파일 업로드 완료 시
            const currentSessionId = localStorage.getItem('current_upload_session');
            uploadedFiles.forEach(file => {
                if (file.sessionId === currentSessionId) {
                    file.status = 'completed';
                    // 업로드 완료된 파일의 썸네일 삭제
                    const thumbnailKey = `thumbnail_${file.new_file_name}`;
                    localStorage.removeItem(thumbnailKey);
                }
            });
            
            updateLocalStorage();
            clearInterval(intervalId);
            uploadStatusPopup.innerText = '업로드가 완료되었습니다!';
            
            setTimeout(function() {
                document.body.removeChild(uploadStatusPopup);
                // 업로드 완료 후 세션 데이터 정리
                clearPreviousUploadData();
            }, 2000);
            return;
        }

        var file = files[index].file;
        var new_file_name = files[index].new_file_name;

        var formData = new FormData();
        formData.append('bf_file', file);
        formData.append('new_file_name', new_file_name);

        var xhr = new XMLHttpRequest();
        xhr.open('POST', <?php echo json_encode(G5_URL . '/chat_data/data.php'); ?>, true);

        xhr.onload = function() {
            if (xhr.status >= 200 && xhr.status < 300) {
                console.log('파일 업로드 성공: ' + new_file_name);
                uploadFile(index + 1);
            } else {
                handleUploadError(xhr.responseText);
            }
        };

        xhr.onerror = function() {
            handleUploadError('네트워크 오류가 발생했습니다.');
        };

        xhr.send(formData);
    }

    uploadFile(0);
}

function handleUploadError(errorMessage) {
    alert('파일 업로드 중 오류가 발생했습니다: ' + errorMessage);
}

function updateLocalStorage() {
    localStorage.setItem('uploadedFiles', JSON.stringify(uploadedFiles));
}

// 페이지 로드 시 초기화
window.onload = function() {
    const currentSessionId = localStorage.getItem('current_upload_session');
    if (!currentSessionId) {
        // 새로운 페이지 로드 시 이전 데이터 정리
        clearPreviousUploadData();
        return;
    }

    var storedFiles = JSON.parse(localStorage.getItem('uploadedFiles')) || [];
    // 현재 세션의 파일들만 복원
    storedFiles = storedFiles.filter(file => file.sessionId === currentSessionId);
    
    if (storedFiles.length > 0) {
        uploadedFiles = storedFiles;
        showFilePreviewModal(storedFiles.map(item => item.file));
    }
};

// 브라우저 탭/창이 닫힐 때 정리
window.addEventListener('unload', function() {
    clearPreviousUploadData();
});
</script>

<script>
var pos_id = "<?php echo $pos_id;?>";
var chkDate = "<?php echo $chkDate;?>";
var send_mb_id = "<?php echo $member['mb_id'];?>";
var recv_mb_id = "<?php echo $recv_mb['mb_id'];?>";
var max_id = "<?php echo $max['max'];?>";
//var limit_record = "<?php echo $total - $limit;;?>";
var limit_record = "<?php echo $limit;?>";
var from_record = "<?php echo $from_record;?>";
var p_icon = '<?php echo $p_icon;?>';
var p_nick = "<?php echo $recv_mb['mb_nick'];?>";

function chat_refresh() { 
	
    $.ajax({

        type: "POST",
        data: {act:'refresh',send_mb_id:send_mb_id,recv_mb_id:recv_mb_id,max_id:max_id},
        url: '<?php echo G5_BBS_URL; ?>/ajax.memo.php',
        success: function(data) {

            var html = ''; 

            $.each(data.data, function(i, $i) { 
                var html = '';
                if ($i.me_send_mb_id == send_mb_id) { 
                    var cls = "recv";
                    var cls_box = "bubble_recv"; 
                } else {
                    var cls = "send"; 
                    var cls_box = "bubble_send"; 
                }
                html +='<li id="chat_list_'+$i.me_id+'" class="'+cls+'">'; 
                if($i.me_send_mb_id != send_mb_id) { 
                    html += '<span class="p_icon">'+p_icon+'</span>'; 
                    html += '<span class="p_nick">'+p_nick+'</span>'; 
                }
                
                html += '<div class="'+cls_box+'">';
                html += $i.me_memo;
                html += '</div>';
                html += '<div class="chat_time2_'+cls+'">';
                
               
                if ($i.me_send_mb_id == send_mb_id) {
	                if($i.me_read_datetime.substr(0,1) == 0) {
					//if($i.me_send_datetime.substr(0,1) == 0) {
                        html += "<span id='bm"+$i.me_id+"' style='color:#e983ea; font-weight:bold;'>1</span>";
                    } else {
                        //html += '';
                    }
                }        
                
                
                html += $i.me_send_datetime.substr(10,6);
                html += '</div>';
                    
                if($i.me_send_mb_id == send_mb_id) {
                
                html += '<div class="del_div"><a href="<?php echo G5_BBS_URL ?>/ajax.memo_del.php?me_id='+$i.me_id+'&del_id=<?php echo $recv_mb['mb_id'] ?>" class="chatroom-cnt2 badge3"><svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" class="feather feather-trash w-4 h-4 mr-2"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path></svg></a><div>';

                }


                html += '</li>';

                $('#chat-list').append(html);
				//보낸사람 숫자1 없애기

				check_Read();
				
				//ajax read체크 
				//$("#am"+$i.me_id).html(""); 

                max_id = data.max.max;

                if ($i.me_id) {
                     move_page();
                }
            });
           
        }
    });
    return false;

}

$("#chat-history").click(function() {
    $.ajax({
        type: "POST",
        data: {act:'history',send_mb_id:send_mb_id,recv_mb_id:recv_mb_id,from_record:from_record,limit_record:limit_record},
        url: '<?php echo G5_BBS_URL; ?>/ajax.memo.php',
        success: function(data) {
            var html = '';
            $.each(data.data, function(i, $i) {
                pos_id = $i.me_id;
                newDate = $i.me_send_datetime.substr(0,10);
                if ($i.me_send_mb_id == send_mb_id) {
                    var cls = "recv";
                    var cls_box = "bubble_recv";
                } else {
                    var cls = "send";
                    var cls_box = "bubble_send";
                }
                if  (newDate != chkDate) {
                    if($('#'+newDate).length > 0) {
                        $('#'+newDate).remove();
                    }
                    html +='<li id="'+newDate+'" class="chkdate">'+newDate+'</li>';
                } else {
                    if($('#'+newDate).length > 0) {
                       $('#'+newDate).remove();
                       html +='<li id="'+newDate+'" class="chkdate">'+newDate+'</li>';
                    }
                }
                html +='<li id="chat_list_'+$i.me_id+'" class="'+cls+'">';
                if($i.me_send_mb_id != send_mb_id) {
                    html += '<span class="p_icon">'+p_icon+'</span>';
                    html += '<span class="p_nick">'+p_nick+'</span>';
                }
                html += '<div class="'+cls_box+'">';
                html += $i.me_memo;
                html += '</div>';
                html += '<div class="chat_time2_'+cls+'">'+$i.me_send_datetime.substr(10,6)+'</div>';
                
                if($i.me_send_mb_id == send_mb_id) {
                
                html += '<div class="del_div"><a href="<?php echo G5_BBS_URL; ?>/ajax.memo_del.php?me_id='+$i.me_id+'&del_id=<?php echo $recv_mb['mb_id'] ?>" class="chatroom-cnt2 badge3"><svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" class="feather feather-trash w-4 h-4 mr-2"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path></svg></a><div>';

                }
                
                html += '</li>';
                chkDate = newDate;
            });
            $('#chat-list').prepend(html);

			

            from_record = data.from_record; 
            if (from_record == 0) {
                //$('#chat-history').hide();
                $('#chat_history_div_wrap').hide();
            }
            movePos();
        }
    });
    return false;
});

    
$("#btn-chat").click(function() {
    $("#chat-message").focus();
    var message = $("#chat-message").val().trim(); // 앞뒤 공백 제거
    if (message === "") {
        alert('메세지를 입력하세요');
        return false;
    }
    $("#chat-message").val('');
    send_message(message);
});


//$("#btn-ref").click(function() {   
//    window.location.reload();
//});


function send_message(msg) {
    // 줄바꿈 문자를 [/br]로 변환
    msg = msg.replace(/\n/g, '[/br]');

    // 띄어쓰기가 두 번인 것을 [/amp]로 변환
   msg = msg.replace(/\s+/g, function(match) {
  return match.length > 1 ? '[/amp]'.repeat(match.split(' ').length - 1) : match;
});

    $.ajax({
        type: "POST",
        data: {act:'update',send_mb_id:send_mb_id,recv_mb_id:recv_mb_id,me_memo:msg,recv_mb_level:<?php echo $recv_mb['mb_level'];?>},
        url: '<?php echo G5_BBS_URL; ?>/ajax.memo.php',
        success: function(data) {
            if(data['error_msg'].length > 0) {
                var html = '';
                html +='<li class="">이용하실 수 없습니다.('+data['error_msg']+')</li>';
                $('#chat-list').append(html);
                return false;
            }
            chat_refresh(); 
        }
    });
}

//$(function() {
//    $('#chat-message').on('keydown', function(event) {
//        if (event.keyCode == 13)
//            if (!event.shiftKey){
//                event.preventDefault();
//                $('#btn-chat').trigger('click');
//            }
//    });
//});

//줄바꿈 인식{



/*
$('#chat-body').scroll(function() {
    if($('#chat-body').scrollTop() == 0) {
        $('#chat-history').trigger('click');
    }
});

function movePos(){
    var pos = pos_id;
    document.getElementById('chat_list_'+pos).scrollIntoView();
    
}
*/

function move_page() {
    $('#chat-body').animate({scrollTop:$('#chat-body')[0].scrollHeight}, 0);
}

window.onload = function () { 
    move_page();
};

function check_Read() 
{
	 //전체데이터 가져와서 처리
	  $.post("<?php echo G5_BBS_URL; ?>/ajax.memo_read.php", {sender: "<?php echo $recv_mb['mb_id'];?>",receiver: "<?php echo $member['mb_id'];?>",from_record:"<?php echo $from_record;?>"}, function(result){ 
			var dd=result.split("--");
			for (i = 0; i < dd.length; i++) {
				console.log( dd[i] ); 
				var rd=dd[i].split("|");
				//읽음
				if( rd[1]=="Y"){
					$("#am"+rd[0]).html("");
					$("#bm"+rd[0]).html("");					
				}
			}

			//location.reload();

	  });

}

setInterval( function() {
    chat_refresh();	
	check_Read(); 
	

}, 3500 ); //4.5초에 갱신

</script>

<script>
async function fetchMetaData(url, cache = {}) {
  const supportsLocalStorage = typeof localStorage !== "undefined";

  // Early cache checks
  if (cache[url]) return cache[url];
  
  const cachedData = supportsLocalStorage ? 
    JSON.parse(localStorage.getItem(url) || 'null') : 
    null;
  
  if (cachedData?.image && cachedData?.title && 
      cachedData?.description && cachedData?.url) {
    cache[url] = cachedData;
    return cachedData;
  }

  try {
    const parser = new DOMParser();
    const response = await fetch(url, { 
      headers: { 'Accept': 'text/html' },
      signal: AbortSignal.timeout(5000)
    });
    const text = await response.text();
    
    const doc = parser.parseFromString(text, 'text/html');
    const metaData = {
      image: doc.querySelector('meta[property="og:image"]')?.content || '',
      title: doc.querySelector('meta[property="og:title"]')?.content || '',
      description: doc.querySelector('meta[property="og:description"]')?.content || '',
      url: doc.querySelector('meta[property="og:url"]')?.content || url
    };

    cache[url] = metaData;
    
    if (supportsLocalStorage) {
      setTimeout(() => {
        try {
          localStorage.setItem(url, JSON.stringify(metaData));
        } catch (storageError) {
          console.warn('Storage quota exceeded', storageError);
        }
      }, 0);
    }

    return metaData;
  } catch (error) {
    console.error('Metadata fetch failed:', error);
    return { image: '', title: '', description: '', url: '' };
  }
}

function getLinkType(link) {
  const linkTypes = {
    audio: ['mp3', 'm4a', 'wav', 'ogg'],
    video: ['mp4', 'avi', 'webm', 'mov', 'mkv'],
    image: ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg'],
    txt: ['txt', 'log', 'md'],
    pdf: ['pdf'],
    zip: ['zip', 'rar', '7z', 'gz'],
    youtube: ['youtube.com', 'youtu.be']
  };

  const extension = link.split('.').pop().toLowerCase();
  
  // Check for YouTube links
  if (linkTypes.youtube.some(type => link.includes(type))) {
    return 'youtube';
  }

  for (let type in linkTypes) {
    if (linkTypes[type].includes(extension)) {
      return type;
    }
  }

  return /^(https?:\/\/|www\.|ftp:\/\/)/i.test(link) ? 'text' : null;
}

async function processLinkWithRetry(element, link, cache, maxRetries = 2) {
  const linkType = getLinkType(link);
  
  // 미디어 링크의 경우 메타데이터 처리 건너뛰기
  if (['audio', 'video', 'image', 'txt', 'pdf', 'zip'].includes(linkType)) {
    return createMediaHtml(linkType, link, '');
  }

  try {
    const metadata = await fetchMetaData(link, cache);
    
    // 메타데이터가 있는 경우에만 메타데이터 HTML 추가
    if (metadata.title || metadata.description || metadata.url) {
      return createMediaHtml(linkType, link, '') + createMetadataHtml(metadata);
    }
    
    return createMediaHtml(linkType, link, '');
  } catch (error) {
    console.error(`Failed to process link: ${link}`, error);
    return `<a href="${link}">${link}</a>`;
  }
}

function createMetadataHtml(metadata) {
  if (!metadata.image && !metadata.title && !metadata.description && !metadata.url) {
    return '';
  }

  let metadataHtml = `<div class="link_meta">`;
  if (metadata.image) {
    metadataHtml += `<img src="${metadata.image}" style="width:100%;max-width:600px;height:auto;border-radius:10px" alt="${metadata.title}" onError="this.style.display = 'none';">`;
  }
  if (metadata.title) {
    metadataHtml += `<div class="og_title">${metadata.title}</div>`;
  }
  if (metadata.description) {
    metadataHtml += `<div class="og_description">${metadata.description}</div>`;
  }
  if (metadata.url) {
    metadataHtml += `<div class="og_url">${metadata.url}</div>`;
  }
  metadataHtml += `</div>`;

  return metadataHtml;
}

function preprocessText(text) {
  // Replace [/amp] with &
  text = text.replace(/\[\/amp\]/g, '&nbsp;');
  
  // Replace [/br] with <br>
  text = text.replace(/\[\/br\]/g, '<br>');
  
  return text;
}

async function processLink(element, cache) {
  // Preprocess the text first
  const preprocessedText = preprocessText(element.textContent);
  
  // Enhanced regex to capture ALL links within text more comprehensively
  const urlPattern = /(https?:\/\/[^\s]+)/g;
  const processedContent = [];
  
  let match;
  let lastIndex = 0;

  while ((match = urlPattern.exec(preprocessedText)) !== null) {
    // Add text before the link
    if (match.index > lastIndex) {
      processedContent.push(preprocessedText.slice(lastIndex, match.index));
    }
    
    // Process each link
    const linkProcessedContent = await processLinkWithRetry(element, match[1], cache);
    processedContent.push(linkProcessedContent);
    
    lastIndex = match.index + match[1].length;
  }
  
  // Add remaining text after the last link
  if (lastIndex < preprocessedText.length) {
    processedContent.push(preprocessedText.slice(lastIndex));
  }

  // Update the element's content
  requestAnimationFrame(() => {
    element.innerHTML = processedContent.join('');
  });
}


function processLinkWithRetry(element, link, cache, maxRetries = 2) {
  const linkType = getLinkType(link);
  
  // Skip metadata processing for media files
  if (['audio', 'video', 'image', 'txt', 'pdf', 'zip'].includes(linkType)) {
    return createMediaHtml(linkType, link, '');
  }

  return fetchMetaData(link, cache)
    .then(metadata => {
      // Only add metadata HTML if meaningful content exists
      const metadataHtml = metadata.title || metadata.description || metadata.url 
        ? createMetadataHtml(metadata) 
        : '';
      
      return createMediaHtml(linkType, link, '') + metadataHtml;
    })
    .catch(error => {
      console.error(`Failed to process link: ${link}`, error);
      return `<a href="${link}">${link}</a>`;
    });
}

function createMediaHtml(linkType, mainLink, remainingText) {
  let mediaHtml = '';
  
  const fixedStyles = 'style="max-width: 100%; width: auto; height: auto; display: block;"';

  switch (linkType) {
    case 'audio':
      mediaHtml = `<audio class="mp3" controls ${fixedStyles}><source src="${mainLink}" type="audio/mpeg"></audio> ${remainingText}`;
      break;
    case 'video':
      mediaHtml = `<video class="mp4" poster="<?php echo G5_THEME_IMG_URL ?>/twave/poster.png" controls playsinline muted ${fixedStyles}>
                    <source src="${mainLink}" type="video/mp4">
                   </video> ${remainingText}`;
      break;
        case 'image':
            // 업로드된 파일 정보 확인
            const uploadedFiles = JSON.parse(localStorage.getItem('uploadedFiles') || '[]');
            const fileName = mainLink.split('/').pop();
            const uploadedFile = uploadedFiles.find(f => f.new_file_name.includes(fileName));

            if (uploadedFile && uploadedFile.status === 'pending') {
                // 업로드 진행 중인 경우 썸네일 사용
                const thumbnailKey = `thumbnail_${uploadedFile.new_file_name}`;
                const thumbnailBase64 = localStorage.getItem(thumbnailKey);
                
                if (thumbnailBase64) {
                    mediaHtml = `
                        <div class="image-container" style="position: relative; display: inline-block; width: 100%; max-width: 600px;">
                            <img 
                                src="${thumbnailBase64}" 
                                class="link_img" 
                                alt="uploading..." 
                                ${fixedStyles}
                                data-original-src="${mainLink}"
                                ondragstart="return false"
                                style="
                                    width: 100%;
                                    height: auto;
                                    border-radius: 12px;
                                    filter: blur(1px) grayscale(0.1);
                                "
                            >
                            <div style="
                                position: absolute;
                                top: 50%;
                                left: 50%;
                                transform: translate(-50%, -50%);
                                background-color: rgba(0, 0, 0, 0.5);
                                color: white;
                                padding: 8px 16px;
                                border-radius: 20px;
                                font-size: 14px;
                                pointer-events: none;
                                white-space: nowrap;
                            ">
                                업로드 중...
                            </div>
                        </div>`;
                } else {
                    // 썸네일이 없는 경우 기본 이미지 표시
                    mediaHtml = createDefaultImageHtml(mainLink, fixedStyles);
                }
            } else {
                // 업로드 완료 또는 다른 이미지의 경우 원본 표시
                mediaHtml = createDefaultImageHtml(mainLink, fixedStyles);
            }
            break;
    case 'youtube':
      mediaHtml = `<iframe 
    style="width: 100%; height: auto; aspect-ratio: 16 / 9; margin-top: 5px; border-radius: 10px;" 
    src="https://www.youtube.com/embed/${getYouTubeID(mainLink)}" 
    frameborder="0" 
    allowfullscreen>
</iframe> ${remainingText}`;
      break;
    case 'txt':
      mediaHtml = `<a href="${mainLink}" class="link_txt" alt="${mainLink}"><span>.txt &nbsp;</span><i class="fa fa-file-text-o"></i></a> ${remainingText}`;
      break;
    case 'zip':
      mediaHtml = `<a href="${mainLink}" class="link_zip" alt="${mainLink}"><span>.zip &nbsp;</span><i class="fa fa-file-zip-o"></i></a> ${remainingText}`;
      break;
    case 'pdf':
      mediaHtml = `<a href="${mainLink}" class="link_pdf" alt="${mainLink}"><span>.pdf &nbsp;</span><i class="fa fa-file-pdf-o"></i></a> ${remainingText}`;
      break;
    case 'text':
      mediaHtml = `<a href="${mainLink}" target="_blank">${mainLink}</a>${remainingText ? ' ' + remainingText : ''}`;
      break;
    default:
      mediaHtml = part;
  }
  
  return mediaHtml;
}

function createDefaultImageHtml(mainLink, fixedStyles) {
    return `<img 
        src="${mainLink}" 
        class="link_img" 
        alt="${mainLink}" 
        ${fixedStyles}
        ondragstart="return false" 
        onerror="this.onerror=null; this.src='<?php echo G5_THEME_IMG_URL ?>/twave/file_404.png';"
        style="background-color:#fff; width: 100%; max-width: 600px; height: auto; border-radius: 12px;">`;
}

function checkAndUpdateImages() {
    const imageContainers = document.querySelectorAll('.image-container');
    const uploadedFiles = JSON.parse(localStorage.getItem('uploadedFiles') || '[]');
    
    imageContainers.forEach(container => {
        const img = container.querySelector('.link_img');
        if (!img) return;
        
        const originalSrc = img.getAttribute('data-original-src');
        if (!originalSrc) return;
        
        const fileName = originalSrc.split('/').pop();
        const uploadedFile = uploadedFiles.find(f => f.new_file_name.includes(fileName));
        
        if (uploadedFile && uploadedFile.status === 'completed') {
            // 새 이미지를 미리 로드
            const tempImg = new Image();
            tempImg.onload = () => {
                // 기존 이미지의 위치와 크기 정보 저장
                const rect = img.getBoundingClientRect();
                const parentRect = container.getBoundingClientRect();
                
                // 새 이미지에 기존 이미지의 스타일 복사
                const computedStyle = window.getComputedStyle(img);
                const newImg = document.createElement('img');
                newImg.className = img.className;
                newImg.alt = originalSrc;
                newImg.setAttribute('ondragstart', 'return false');
                newImg.setAttribute('onerror', "this.onerror=null; this.src='<?php echo G5_THEME_IMG_URL ?>/twave/file_404.png';");
                
                // 기존 이미지의 스타일 유지
                newImg.style.cssText = computedStyle.cssText;
                newImg.style.position = 'absolute';
                newImg.style.top = `${rect.top - parentRect.top}px`;
                newImg.style.left = `${rect.left - parentRect.left}px`;
                newImg.style.width = `${rect.width}px`;
                newImg.style.height = `${rect.height}px`;
                
                // 새 이미지 소스 설정
                newImg.src = originalSrc;
                
                // 부드러운 전환을 위한 CSS
                newImg.style.transition = 'opacity 0.3s ease-in-out';
                newImg.style.opacity = '0';
                
                // 컨테이너에 상대 위치 설정
                container.style.position = 'relative';
                
                // 새 이미지 추가
                container.appendChild(newImg);
                
                // 강제 리플로우
                newImg.offsetHeight;
                
                // 페이드 인
                newImg.style.opacity = '1';
                
                // 이전 이미지 페이드 아웃 후 제거
                img.style.transition = 'opacity 0.3s ease-in-out';
                img.style.opacity = '0';
                
                setTimeout(() => {
                    img.remove();
                    newImg.style.position = 'relative';
                    newImg.style.top = '';
                    newImg.style.left = '';
                }, 300);
            };
            
            tempImg.src = originalSrc;
        }
    });
}

// 주기적으로 이미지 상태 체크
setInterval(checkAndUpdateImages, 1000);

function getYouTubeID(url) {
  // 다양한 유튜브 링크 형식을 지원하는 정규 표현식
  const regex = /(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|shorts\/|.*[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})/;
  const matches = url.match(regex);
  return matches ? matches[1] : null;
}

function processInBatches(elements, batchSize = 3, delay = 50) {
  const processBatch = () => {
    if (elements.length === 0) return;
    
    const batch = elements.splice(-batchSize);
    batch.reverse().forEach(element => {
      Promise.resolve().then(() => {
        observer.observe(element);
        element.classList.add('processed');
      });
    });

    if (elements.length > 0) {
      requestAnimationFrame(processBatch);
    }
  };

  requestAnimationFrame(processBatch);
}

function getClosestElementToMiddle(elements) {
  const middleY = window.innerHeight / 2;
  let closestElement = null;
  let closestDistance = Infinity;

  elements.forEach(element => {
    const rect = element.getBoundingClientRect();
    const elementMiddleY = rect.top + rect.height / 2;
    const distance = Math.abs(middleY - elementMiddleY);
    if (distance < closestDistance) {
      closestDistance = distance;
      closestElement = element;
    }
  });

  return closestElement;
}

let cache = {};
let observer = new IntersectionObserver(entries => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      processLink(entry.target, cache);
      observer.unobserve(entry.target);
    }
  });
});

let initialBatchProcessed = false;

async function processNewElements() {
  const bubbleRecvElements = document.querySelectorAll('.bubble_recv:not(.processed)');
  const bubbleSendElements = document.querySelectorAll('.bubble_send:not(.processed)');
  const allElements = [...bubbleRecvElements, ...bubbleSendElements];

  processInBatches(allElements);
}

const mutationObserver = new MutationObserver(mutations => {
  mutations.forEach(mutation => {
    if (mutation.addedNodes.length) {
      processNewElements();
    }
  });
});

mutationObserver.observe(document.body, {
  childList: true, 
  subtree: true 
});

document.addEventListener('DOMContentLoaded', () => {
  processNewElements();
});
</script>


<!-- 이미지 더보기 탭{ -->
<script>
let currentModal = null;

// List of files to exclude from modal functionality
const excludedFiles = [
  'file_404.png',
  'file.png',
  'file2.png',
  'file3.png',
  'file4.png',
  'file5.png',
  'file6.png',
  'poster_lite.png',
  'poster_dark.png',
  'poster_gb.png',
  'poster_rb.png',
  'poster.png'
];

function showFloatingModal() {
  document.querySelectorAll('.bubble_recv img, .bubble_send img').forEach(function(element) {
    // Check if the image source contains any of the excluded files
    const imageName = element.src.split('/').pop();
    if (excludedFiles.includes(imageName)) {
      return; // Skip this image
    }

    element.addEventListener('click', function() {
      if (currentModal) {
        document.body.removeChild(currentModal);
        currentModal = null;
      }

      var modal = document.createElement('div');
      modal.classList.add('floating-modal');

      var closeButton = document.createElement('button');
      closeButton.classList.add('close-button');
      closeButton.innerHTML = '<i class="fa fa-close"></i>';
      closeButton.addEventListener('click', function() {
        document.body.removeChild(modal);
        currentModal = null;
      });

      var mediaElement = element.cloneNode(true);
      mediaElement.classList.add('floating-media');

      var menuContainer = document.createElement('div');
      menuContainer.classList.add('floating-menu');

      var saveButton = document.createElement('button');
      saveButton.classList.add('floating-menu-item');
      saveButton.textContent = '파일 다운로드';
      saveButton.addEventListener('click', function() {
        fetch(element.src)
          .then(response => {
            if (!response.ok) throw new Error('네트워크 응답이 좋지 않음');
            return response.blob();
          })
          .then(blob => {
            var downloadLink = document.createElement('a');
            var url = URL.createObjectURL(blob);
            downloadLink.href = url;
            downloadLink.download = element.src.split('/').pop();
            document.body.appendChild(downloadLink);
            downloadLink.click();
            document.body.removeChild(downloadLink);
            URL.revokeObjectURL(url);
          })
          .catch(err => {
            console.error('파일 다운로드 실패:', err);
            showFloatingMessage('파일 다운로드에 실패했습니다. URL_error');
          });
      });

      menuContainer.appendChild(saveButton);
      modal.appendChild(closeButton);
      modal.appendChild(mediaElement);
      modal.appendChild(menuContainer);
      document.body.appendChild(modal);
      currentModal = modal;

      modal.addEventListener('click', function(event) {
        if (event.target === modal) {
          document.body.removeChild(modal);
          currentModal = null;
        }
      });
    });
  });
}

function showFloatingMessage(message) {
  var messageElement = document.createElement('div');
  messageElement.classList.add('floating-message');
  messageElement.textContent = message;
  document.body.appendChild(messageElement);
  setTimeout(function() {
    document.body.removeChild(messageElement);
  }, 2500);
}

window.addEventListener('load', function() {
  showFloatingModal();
  setInterval(showFloatingModal, 550);
});
</script>

<!-- 이모티콘 전송 기능{ -->
<script>
// emoji.js

document.addEventListener('DOMContentLoaded', function() {
    const btnRef = document.getElementById('btn-ref');
    const btnChat = document.getElementById('btn-chat');
    const chatMessage = document.getElementById('chat-message');

    let currentModal = null;

    // 모달 생성 함수
    function createEmojiModal(groupedEmojis) {
        // 기존 모달이 있으면 제거
        const existingModal = document.getElementById('emoji-modal');
        if (existingModal) {
            existingModal.remove();
        }

        // 모달 백그라운드 생성
        const modalBackground = document.createElement('div');
        modalBackground.id = 'emoji-modal';
        modalBackground.style.position = 'fixed';
        modalBackground.style.left = '0';
        modalBackground.style.right = '0';
        modalBackground.style.bottom = '60px';
        modalBackground.style.width = '100%';
        modalBackground.style.backgroundColor = '#fff';
        modalBackground.style.borderTop = '1px solid #ccc';
        modalBackground.style.boxShadow = '0 -2px 10px rgba(0,0,0,0.1)';
        modalBackground.style.zIndex = '1000';
        modalBackground.style.display = 'flex';
        modalBackground.style.flexDirection = 'column';
        modalBackground.style.maxHeight = '30%';

        // 그룹 선택 메뉴 생성
        const groupMenu = document.createElement('div');
        groupMenu.style.display = 'flex';
        groupMenu.style.overflowX = 'auto';
        groupMenu.style.borderBottom = '1px solid #ccc';
        groupMenu.style.padding = '10px 0';
        groupMenu.style.backgroundColor = '#f9f9f9';
        groupMenu.style.minHeight = '50px';

        // 그룹 버튼 생성
        const groupKeys = Object.keys(groupedEmojis);
        groupKeys.forEach((groupKey, index) => {
            const groupBtn = document.createElement('button');
            groupBtn.innerText = `${groupKey}`;
            groupBtn.style.margin = '0 10px';
            groupBtn.style.padding = '5px 10px';
            groupBtn.style.border = 'none';
            groupBtn.style.backgroundColor = index === 0 ? '#007BFF' : '#e0e0e0';
            groupBtn.style.color = index === 0 ? '#fff' : '#000';
            groupBtn.style.borderRadius = '4px';
            groupBtn.style.cursor = 'pointer';
            groupBtn.dataset.groupKey = groupKey;

            groupBtn.addEventListener('click', () => {
                // 모든 버튼 스타일 초기화
                const allButtons = groupMenu.querySelectorAll('button');
                allButtons.forEach(btn => {
                    btn.style.backgroundColor = '#e0e0e0';
                    btn.style.color = '#000';
                });
                // 현재 버튼 스타일 변경
                groupBtn.style.backgroundColor = '#007BFF';
                groupBtn.style.color = '#fff';

                // 이미지 그리드 업데이트
                displayGroupImages(groupedEmojis[groupKey]);
            });

            groupMenu.appendChild(groupBtn);
        });

        modalBackground.appendChild(groupMenu);

        // 이미지 그리드 컨테이너 생성
        const imageGrid = document.createElement('div');
        imageGrid.id = 'emoji-image-grid';
        imageGrid.style.display = 'grid';
        imageGrid.style.gridTemplateColumns = 'repeat(auto-fill, minmax(50px, 1fr))';
        imageGrid.style.gap = '10px';
        imageGrid.style.padding = '10px';
        imageGrid.style.overflowY = 'auto';
        imageGrid.style.flexGrow = '1';

        modalBackground.appendChild(imageGrid);
        document.body.appendChild(modalBackground);
        currentModal = modalBackground;

        // 첫 번째 그룹의 이미지를 표시
        if (groupKeys.length > 0) {
            displayGroupImages(groupedEmojis[groupKeys[0]]);
        }

        // 모달 외부 클릭 시 모달 닫기
        setTimeout(() => { // setTimeout을 사용하여 현재 클릭 이벤트가 완료된 후에 이벤트 리스너 추가
            document.addEventListener('click', outsideClickListener);
        }, 0);
    }

    // 특정 그룹의 이미지를 표시하는 함수
    function displayGroupImages(images) {
        const imageGrid = document.getElementById('emoji-image-grid');
        imageGrid.innerHTML = ''; // 기존 이미지 제거

        images.forEach((emojiUrl) => {
            const img = document.createElement('img');
            img.src = emojiUrl;
            img.width = 50;
            img.height = 50;
            img.style.cursor = 'pointer';
            img.style.objectFit = 'cover';
            img.addEventListener('click', () => {
                // 텍스트 영역에 이미지 URL 삽입
                chatMessage.value += emojiUrl;
                // 보내기 버튼 클릭 처리
                btnChat.click();
            });
            imageGrid.appendChild(img);
        });
    }

    // 모달 외부 클릭 감지 함수
    function outsideClickListener(event) {
        if (currentModal && !currentModal.contains(event.target) && event.target !== btnRef) {
            currentModal.remove();
            currentModal = null;
            document.removeEventListener('click', outsideClickListener);
        }
    }

    // 이모티콘 모달 열기 함수
    function openEmojiModal() {
        fetch('<?php echo G5_URL ?>/chat_data/emoji/emoji.php')
            .then(response => response.json())
            .then(data => {
                createEmojiModal(data);
            })
            .catch(error => {
                console.error('이모티콘을 불러오는 중 오류 발생:', error);
            });
    }

    // 버튼 클릭 시 모달 열기
    btnRef.addEventListener('click', openEmojiModal);

    // 자동으로 모달을 삽입하고 클릭
    /*
    openEmojiModal();
    btnRef.click();
    */
});

</script>

<style>
#emoji-modal button {
    background-color: #e0e0e0;
    color: #000;
    border: none;
    border-radius: 4px;
    padding: 5px 10px;
    margin: 0 5px;
    cursor: pointer;
    flex-shrink: 0;
}

#emoji-modal button.active {
    background-color: #007BFF;
    color: #fff;
}

#emoji-modal img:hover {
    transform: scale(1.1);
    transition: transform 0.2s;
}

#emoji-modal {
max-height: 150px;
}
</style>


<!-- 이미지 더보기 탭 스타일{ -->
<style>
  .floating-modal {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: rgba(255, 255, 251, 0.55);
    -webkit-backdrop-filter: blur(17px);
    backdrop-filter: blur(17px);
    padding: 20px 0;
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.3);
    z-index: 9999;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width:70%;
    min-width:300px;
    border-radius:10px
  }

  .floating-modal img {
    max-height:170px;
    height:100%;
    width:auto;
    max-width:250px !important;
    padding-bottom:10px;
    border-radius:10px
    }
  
  .close-button {
    position: absolute;
    top: 10px;
    right: 10px;
    background-color: transparent;
    border: none;
    font-size: 20px;
    cursor: pointer;
    color:rgba(0, 0, 0, 0.35);
  }

  .floating-media {
    max-width: 80%;
  max-height: 80%;
  margin-right: 20px;
  float: left;
  border-radius:10px
  }
  
  .floating-menu {
    display: flex;
    flex-direction: column;
    justify-content: center;
    margin-top: 10px;
    width:100%;
    border-top:1px solid #7a7a7a;
    padding-top:10px
  }

  .floating-menu-item {
    padding: 10px 15px;
    border: none;
    cursor: pointer;
    margin: 5px 0;
    background-color:#0000;
    color:#6a6a6a
  }
  
  .floating-message {
    position: fixed;
    bottom: 100px;
    left: 50%;
    transform: translateX(-50%);
    transform: translate(-50%, -50%);
    background-color: rgba(0, 0, 0, 0.35);
    -webkit-backdrop-filter: blur(17px);
    backdrop-filter: blur(17px);
    color: #fff;
    padding: 10px 20px;
    border-radius: 5px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
    z-index: 9999;
  }
  
  .bubble_recv .mansion {
  color:#d8e7ff !important
  }
  
  .bubble_recv .search_tag {
  color:#fd7B84 !important
  }
  
  .bubble_send .mansion {
  color:#feecb4 !important
  }
  
  .bubble_send .search_tag {
  color:#FFECC6 !important
  }
  
  .bubble_recv .mp3 {
  max-width:100%;
  }

  .bubble_recv .mp4 {
  max-width:100%;
  width:100%;
  min-width:200px;
  height:auto;
  border-radius:10px;
  margin-top:5px 0;
  object-fit: cover;
  }
  
  .bubble_recv .link_img {
  max-width:100%;
  width:100%;
  min-width:200px;
  height:auto;
  border-radius:10px;
  margin:5px 0
  }
  
  .bubble_send .mp3 {
  max-width:100%;
  }

  .bubble_send .mp4 {
  max-width:100%;
  width:100%;
  min-width:200px;
  height:auto;
  border-radius:10px;
  margin-top:5px 0
  }
  
  .bubble_send .link_img {
  max-width:100%;
  width:100%;
  min-width:200px;
  height:auto;
  border-radius:10px;
  margin:5px 0
  }
  
  .bubble_recv .link_meta {
  background-color:#f2f2f2;
  padding:12px;
  border-radius:15px;
  }

.bubble_send .link_meta {
  background-color:#eee;
  padding:12px;
  border-radius:15px;
  }

  .bubble_recv .og_title,
  .bubble_send .og_title {
  padding-top:5px;
  padding-left:5px;
  color:#333;
  font-size:14px;
  font-weight:520
  }

  .bubble_recv .og_description,
  .bubble_send .og_description {
  padding-top:5px;
  padding-left:5px;
  color:#4a4a4a;
  font-size:12px;
  font-weight:500
  }

  .bubble_recv .og_url,
  .bubble_send .og_url {
  padding-top:5px;
  padding-left:5px;
  color:#7a7a7a;
  font-size:10px;
  font-weight:520;
  text-align:right
  }

  .bubble_send .og_url {
  padding-top:5px;
  padding-left:5px;
  color:#7a7a7a;
  font-size:10px;
  font-weight:520;
  text-align:left
  }

  .link_txt {
  background-color:#a9a9a;
  padding:10px;
  color:#3a3a3a;
  font-size: 20px;
  bord-radius:10px;
  }
  
  .link_pdf {
  background-color:#a9a9a;
  padding:10px;
  color:#3a3a3a;
  font-size: 20px;
  bord-radius:10px;
  }
  
  .link_zip {
  padding:10px;
  color:#3a3a3a;
  font-size: 20px;
  bord-radius:10px;
  }
</style>

<!-- 접속 중인지 출력{ -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
    // 현재 페이지의 mb_id 파라미터 가져오기
    const urlParams = new URLSearchParams(window.location.search);
    const currentMbId = urlParams.get('me_recv_mb_id');

    function fetchData() {
        // AJAX 요청
        $.ajax({
            url: `<?php echo G5_BBS_URL ?>/ajax_connect-info.php`, // 현재 도메인을 사용
            type: 'GET',
            dataType: 'json',
            success: function(data) {
                // 동그라미 색상 기본 설정
                let circleColor = '#8c8c8c'; // 기본 색상 (회원 아님)

                // 접속 중인 회원 목록(data)에서 currentMbId가 있는지 확인
                if (data.includes(currentMbId)) {
                    circleColor = '#4895ff'; // 회원일 경우 색상 변경
                }

                // 동그라미 생성
                const circle = $('<div></div>')
                    .css({
                        width: '15px',
                        height: '15px',
                        backgroundColor: circleColor,
                        borderRadius: '50%',
                        position: 'absolute',
                        bottom: '-13px',
                        right: '13px',
                        margin: '5px',
                        border: '2px solid #f9f9f9'
                    });

                // 이전 동그라미 제거 (중복 방지)
                $('#profileImage').find('div').remove();
                
                // 프로필 이미지에 동그라미 추가
                $('#profileImage').append(circle);
            },
            error: function() {
                console.error('AJAX 요청 실패');
            }
        });
    }
    
    // 처음 데이터 가져오기
    fetchData();
    
    // 1분(60000ms)마다 데이터 가져오기
    setInterval(fetchData, 60000);
});
</script>


<!-- 보안을 위한 개발자 도구 제한{ -->
<?php
// 개발자 도구 사용 감지
if (isset($_SERVER['HTTP_USER_AGENT']) && stripos($_SERVER['HTTP_USER_AGENT'], 'Chrome') !== false && stripos($_SERVER['HTTP_USER_AGENT'], 'Edg') === false && stripos($_SERVER['HTTP_USER_AGENT'], 'Firefox') === false && stripos($_SERVER['HTTP_USER_AGENT'], 'Safari') === false) {
    // 개발자 도구 사용 시 오류 메시지 출력
    http_response_code(403);
    echo "개발자 도구 사용이 금지얀.";
    exit;
}
?>
<script>
// F12 키 막기
document.addEventListener('keydown', function(event) {
  if (event.keyCode == 123) {
    event.preventDefault();
    return false;
  }
});

// 개발자 도구 열기 막기
document.addEventListener('contextmenu', function(e) {
  e.preventDefault();
});

// 개발자 도구 콘솔 막기
if (window.console) {
  console.log = function() {};
  console.error = function() {};
  console.warn = function() {};
  console.info = function() {};
  console.debug = function() {};
}
</script>
<?php
// 브라우저에서 JavaScript 사용 여부 확인
if (!isset($_SERVER['HTTP_USER_AGENT']) || !preg_match('/(?i)msie|trident|firefox|safari|opera|chrome/', $_SERVER['HTTP_USER_AGENT'])) {
    // JavaScript를 사용하지 않는 경우 리다이렉트
    header('Location: ' . G5_URL);
    exit;
}
?>
<!-- 이미지 보안 처리{ -->
<script>
// 이미지 복사 및 URL 복사를 차단하는 함수
document.addEventListener('contextmenu', function(e) {
    e.preventDefault(); // 오른쪽 클릭 메뉴 차단
});

// 드래그 시작 차단
document.addEventListener('dragstart', function(e) {
    e.preventDefault();
});

// 키보드 단축키 차단
document.addEventListener('keydown', function(e) {
    // Ctrl+C, Ctrl+U, Ctrl+S, Ctrl+A 등 차단
    if (e.ctrlKey && (e.key === 'c' || e.key === 'u' || e.key === 's' || e.key === 'a')) {
        e.preventDefault();
    }
});

// 모든 이미지에 대해 복사 방지 적용
const images = document.querySelectorAll('img');
images.forEach(img => {
    img.addEventListener('dragstart', function(e) {
        e.preventDefault(); // 특정 이미지 드래그 방지
    });

    // 모바일에서의 터치 이벤트 차단
    img.addEventListener('touchstart', function(e) {
        e.preventDefault(); // 터치 시작 차단
    });
});
</script>
<style>
body {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
</style>
<script>
// 모든 이미지에 대해 터치 호출 비활성화
document.querySelectorAll('img').forEach(img => {
    img.style.webkitTouchCallout = 'none'; // 터치 호출 비활성화
    img.style.userSelect = 'none'; // 선택 방지
});

// 추가로 오른쪽 클릭 메뉴 차단
document.addEventListener('contextmenu', function(e) {
    e.preventDefault(); // 오른쪽 클릭 메뉴 차단
});
</script>
<script>
document.addEventListener('contextmenu', function(e) {
    e.preventDefault(); // 기본 컨텍스트 메뉴 차단
});

const images = document.querySelectorAll('img');
images.forEach(image => {
    image.addEventListener('touchstart', function(e) {
        e.preventDefault(); // 터치 시작 시 기본 동작 차단
    });
});
</script>
<script type="text/javascript">/*<![CDATA[*/
document.addEventListener("contextmenu",function(e){"IMG"===e.target.nodeName&&e.preventDefault()},!1);/*]]>*/</script>
    <script>
        document.addEventListener('copy', function(e) {
            e.preventDefault(); // 복사 이벤트 차단
            alert('복사가 싫오싫오.');
        });

        document.addEventListener('paste', function(e) {
            // 붙여넣기 이벤트 처리 (필요시 추가 로직 구현 가능)
        });
    </script>
<script>
//안드로이드 우측 버튼 비활성
    $(document).bind("contextmenu", function(e) {
        return false;
     });
    
    //pc F12 개발자도구 비활성
    $(document).bind('keydown',function(e){
        if ( e.keyCode == 123) {
            e.preventDefault();
            e.returnValue = false;
        }
    });
</script>
<script>
$(".leftBtn").on("touchstart",function(e){
  e.preventDefault();
  _this.leftDownHandler();
 }).on("touchend",function(e){
  e.preventDefault();
  _this.leftUpHandler();
 }).on("touchmove",function(e){
  e.preventDefault();
  //_this.rightDownHandler();
})
</script>
<script>
class ImageProtector {

  protect = (img) => {
      img.addEventListener('contextmenu', this.onContextMenu);
  };

  unprotect = (img) => {
      img.removeEventListener('contextmenu', this.onContextMenu);
  };

  onContextMenu = (e) => {
      e.preventDefault();
      e.stopPropagation();
      // alert("저작권 보호를 위해서 복사는 금지되어 있습니다.");
  };
}

export default new ImageProtector();
</script>
<script>
$(document).ready(function() {
$(document).bind("contextmenu", function(e) {
return false;
});
});
$(document).bind('selectstart',function() {return false;}); 
$(document).bind('dragstart',function(){return false;}); 
</script>
<script>
document.addEventListener("DOMContentLoaded", function() {
    // 브라우저 User-Agent 확인
    const userAgent = navigator.userAgent;
    const isUnsupportedBrowser = /Chrome|Safari|Opera|Edg/.test(userAgent);

    if (!isUnsupportedBrowser) {
        // referer 확인
        const referer = document.referrer;
        const validUrl = "<?php echo G5_BBS_URL ?>/memo_form.php";

        // referer가 없거나 유효하지 않은 경우
        if (!referer || referer !== validUrl) {
            // 모든 이미지에 pointer-events: none 적용
            const style = document.createElement('style');
            style.innerHTML = "img { pointer-events: none; }";
            document.head.appendChild(style);
        }
    }
});
</script>
<!-- 최소한의 보안?{ -->
<script>
(function() {
    const checkDevTools = setInterval(() => {
        const devtools = /./;
        devtools.toString = function() {
            clearInterval(checkDevTools);
            alert("개발자 모드는 금지양.");
            window.location.href = "<?php echo G5_URL ?>";
        };
        console.log('%c', devtools);
    }, 1000);
})();
</script>

<!-- 이미지/동영상 아닌 파일 썸네일 기본 제공 테마
1. twave테마경로/img/twave/file.png (기본 설정)
2. twave테마경로/img/twave/file2.png
3. twave테마경로/img/twave/file3.png
4. twave테마경로/img/twave/file4.png 
5. twave테마경로/img/twave/file5.png
6. twave테마경로/img/twave/file6.png
-->

<!-- 동영상 로드되기 전 썸네일 기본 제공 테마
1. twave테마경로/img/twave/poster_lite.png (화이트 테마)
2. twave테마경로/img/twave/poster_dark.png (다크 테마)
3. twave테마경로/img/twave/poster_gb.png (그레이/베이지)
4. twave테마경로/img/twave/poster_rb.png (그레이/루비)
5. (기본/dsclub) twave테마경로/img/twave/poster.png (권장 안함)
-->
