import{a as E}from"./bootstrap.esm-Bb7dPm-H.js";import{i as B}from"./tooltip-manager-D9RaGGY4.js";import{g,r as v}from"./api-DZ3cXm1m.js";function w(d){const e=document.createElement("div");return e.textContent=d,e.innerHTML}class k{constructor(){this.uploadArea=document.getElementById("uploadArea"),this.fileInput=document.getElementById("fileInput"),this.uploadProgress=document.getElementById("uploadProgress"),this.attachmentsList=document.getElementById("attachmentsList"),this.config=window.uploadConfig,this.uploadedAttachments=[],this.uploadedAttachmentsData=[],this.init()}init(){this.setupDragAndDrop(),this.setupFileInput(),this.setupFileSelectButton()}setupDragAndDrop(){this.uploadArea&&(this.uploadArea.addEventListener("dragover",e=>{e.preventDefault(),this.uploadArea.classList.add("border-primary")}),this.uploadArea.addEventListener("dragleave",e=>{e.preventDefault(),this.uploadArea.classList.remove("border-primary")}),this.uploadArea.addEventListener("drop",e=>{e.preventDefault(),this.uploadArea.classList.remove("border-primary");const t=e.dataTransfer.files;this.handleFiles(t)}))}setupFileInput(){this.fileInput&&this.fileInput.addEventListener("change",e=>{const t=e.target.files;this.handleFiles(t)})}setupFileSelectButton(){const e=document.getElementById("fileSelectBtn");e&&this.fileInput&&e.addEventListener("click",()=>{this.fileInput.click()})}handleFiles(e){Array.from(e).forEach(t=>{this.uploadFile(t)})}async uploadFile(e){var n,r,m,h,c,p,s,i,l;if(e.size>10*1024*1024){this.showAlert("error",((m=(r=(n=window.translations)==null?void 0:n.tickets)==null?void 0:r.upload)==null?void 0:m.file_too_large)||"File size too large");return}if(!["application/pdf","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","text/plain","image/jpeg","image/jpg","image/png","image/gif"].includes(e.type)){this.showAlert("error",((p=(c=(h=window.translations)==null?void 0:h.tickets)==null?void 0:c.upload)==null?void 0:p.invalid_file_type)||"Invalid file type");return}const a=new FormData;a.append("file",e),a.append("uploadable_type",this.config.uploadableType),a.append("uploadable_id",""),a.append("upload_source",this.config.uploadSource);try{this.showProgress();const o=await fetch(window.routes.upload.store,{method:"POST",headers:{Accept:"application/json",Authorization:`Bearer ${g()}`},body:a});if(o.status===401){if(await v())return this.uploadFile(e);this.showAlert("error","Authentication failed");return}if(!o.ok){const f=await o.text();console.error("Upload error:",o.status,f),this.showAlert("error","Upload failed: "+o.status);return}const u=await o.json();u.success?(this.uploadedAttachments.push(u.data.id),this.uploadedAttachmentsData.push(u.data),this.showAlert("success",u.message),this.renderAttachments()):this.showAlert("error",u.message||"Upload failed")}catch(o){console.error("Upload error:",o),this.showAlert("error",((l=(i=(s=window.translations)==null?void 0:s.tickets)==null?void 0:i.upload)==null?void 0:l.upload_error)||"Upload error")}finally{this.hideProgress()}}renderAttachments(){if(this.uploadedAttachmentsData.length===0){this.attachmentsList.innerHTML='<p class="text-muted text-center small">No files uploaded yet.</p>';return}const e=this.uploadedAttachmentsData.map(t=>`
            <div class="attachment-item d-flex align-items-center justify-content-between p-2 border rounded mb-2" data-attachment-id="${t.id}">
                <div class="d-flex align-items-center">
                    <i class="fas fa-file me-2 text-muted"></i>
                    <div>
                        <div class="fw-bold small">${w(t.original_name)}</div>
                        <small class="text-muted">${w(t.file_size)}</small>
                    </div>
                </div>
                <div class="d-flex gap-1">
                    <button type="button" class="btn btn-sm btn-outline-danger delete-attachment"
                            data-id="${t.id}" title="Delete">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            </div>
        `).join("");this.attachmentsList.innerHTML=e,this.setupDeleteButtons()}setupDeleteButtons(){document.querySelectorAll(".delete-attachment").forEach(e=>{e.addEventListener("click",async t=>{const a=t.target.closest(".delete-attachment").dataset.id;await this.deleteAttachment(a)})})}async deleteAttachment(e){try{const t=await fetch(window.routes.upload.destroy.replace(":id",e),{method:"DELETE",headers:{Accept:"application/json",Authorization:`Bearer ${g()}`}});if(t.status===401){if(await v())return this.deleteAttachment(e);this.showAlert("error","Authentication failed");return}if(!t.ok){this.showAlert("error","Delete failed: "+t.status);return}const a=await t.json();a.success?(this.uploadedAttachments=this.uploadedAttachments.filter(n=>n!=e),this.uploadedAttachmentsData=this.uploadedAttachmentsData.filter(n=>n.id!=e),this.showAlert("success",a.message),this.renderAttachments()):this.showAlert("error",a.message)}catch(t){console.error("Delete error:",t),this.showAlert("error","Delete error")}}showProgress(){this.uploadProgress&&(this.uploadProgress.style.display="block")}hideProgress(){this.uploadProgress&&(this.uploadProgress.style.display="none")}showAlert(e,t){window.toastr?e==="error"?window.toastr.error(t):window.toastr.success(t):e==="error"?(console.error(t),window.showError(t)):console.log(t)}getUploadedAttachmentIds(){return this.uploadedAttachments}}let y;document.addEventListener("DOMContentLoaded",function(){B(),y=new k;const d=document.getElementById("replyForm"),e=document.getElementById("replyMessage");d&&d.addEventListener("submit",b),e&&(e.addEventListener("input",function(){this.style.height="auto",this.style.height=this.scrollHeight+"px"}),e.addEventListener("keydown",function(s){s.ctrlKey&&s.key==="Enter"&&(s.preventDefault(),b())})),document.querySelectorAll('[data-bs-toggle="tab"]').forEach(s=>{s.addEventListener("click",function(i){document.querySelectorAll(".nav-link").forEach(o=>{o.classList.remove("active")}),this.classList.add("active");const l=this.getAttribute("data-bs-target");document.querySelectorAll(".tab-pane").forEach(o=>{o.classList.remove("show","active")}),document.querySelector(l).classList.add("show","active")})}),document.addEventListener("keydown",function(s){s.ctrlKey&&s.key==="Enter"&&document.getElementById("replyForm")&&document.activeElement===document.getElementById("replyMessage")&&(s.preventDefault(),b())});const a=document.getElementById("predefinedReplyBtn"),n=document.getElementById("predefinedReplyDropdown"),r=document.getElementById("predefinedReplySearch"),m=document.getElementById("predefinedReplyResults");let h=[];if(a&&n){let s=null;a.addEventListener("click",i=>{i.preventDefault(),i.stopPropagation();const l=n.style.display!=="none";n.style.display=l?"none":"block",l||(r.focus(),c(""))}),r.addEventListener("input",()=>{clearTimeout(s),s=setTimeout(()=>{c(r.value)},300)}),document.addEventListener("click",i=>{!n.contains(i.target)&&i.target!==a&&!a.contains(i.target)&&(n.style.display="none")})}async function c(s){try{const i=new URL(window.routes.predefinedReplies.search,window.location.origin);s&&i.searchParams.set("q",s);const l=await fetch(i,{headers:{Authorization:`Bearer ${g()}`,Accept:"application/json"}});if(l.status===401&&await v())return c(s);const o=await l.json();p(o.data||[])}catch(i){console.error("Predefined reply search error:",i)}}function p(s){var i,l;if(h=s,s.length===0){m.innerHTML=`<div class="text-muted text-center small py-2">${w(((l=(i=window.translations)==null?void 0:i.predefinedReplies)==null?void 0:l.no_results)||"No predefined replies found.")}</div>`;return}m.innerHTML=s.map((o,u)=>`<div class="predefined-reply-item" data-index="${u}">
                <i class="fas fa-file-alt me-1 text-muted"></i>${w(o.title)}
            </div>`).join(""),m.querySelectorAll(".predefined-reply-item").forEach(o=>{o.addEventListener("click",()=>{const u=parseInt(o.dataset.index),f=h[u];if(f&&e){const A=e.value;e.value=A?A+`

`+f.content:f.content,e.dispatchEvent(new Event("input")),n.style.display="none",r.value="",e.focus()}})})}});async function b(d){d&&d.preventDefault(),document.getElementById("replyForm");const e=document.getElementById("replyMessage"),t=document.getElementById("replyStatus");if(!e||!e.value.trim()){window.toastr?window.toastr.warning("Please enter a message."):window.bootstrap&&window.bootstrap.Toast?new E(document.getElementById("warningToast")).show():window.showWarning("Please enter a message.");return}const a=new FormData;a.append("message",e.value.trim()),a.append("status_id",t?t.value:""),a.append("content_format",e.dataset.contentFormat||"plain"),y&&y.getUploadedAttachmentIds().length>0&&y.getUploadedAttachmentIds().forEach(n=>{a.append("attachment_ids[]",n)});try{let n=await fetch(window.routes.tickets.reply,{method:"POST",headers:{Authorization:`Bearer ${g()}`},body:a});n.status===401&&await v()&&(n=await fetch(window.routes.tickets.reply,{method:"POST",headers:{Authorization:`Bearer ${g()}`},body:a}));const r=await n.json();r.success?(L(r.data.reply),e.value="",e.style.height="auto",e.dispatchEvent(new Event("input",{bubbles:!0})),y&&(y.uploadedAttachments=[],y.uploadedAttachmentsData=[],y.renderAttachments()),window.toastr?window.toastr.success(r.message):window.showSuccess(r.message)):window.toastr?window.toastr.error("Error: "+r.message):window.showError(r.message)}catch(n){window.toastr?window.toastr.error("An error occurred: "+n.message):window.showError("An error occurred: "+n.message)}}function L(d){var m,h,c;const e=document.querySelector(".replies-container");if(!e)return;const r=`
        <div class="reply-item mb-4 ${e.querySelectorAll(".reply-item").length%2===0?"bg-body":"bg-body-tertiary"}">
            <div class="row g-0">
                <!-- Kişi Bilgileri - Sol Taraf -->
                <div class="col-md-3">
                    <div class="sender-info p-3 border rounded-start h-100 bg-primary-subtle">
                        <div class="text-center mb-3">
                            <div class="fw-bold fs-5">${w(d.author_name)}</div>
                            <span class="badge bg-primary">ADMIN</span>
                        </div>
                        
                        <div class="d-flex justify-content-center gap-2">
                            <button type="button" class="btn btn-sm btn-outline-secondary">
                                <i class="fas fa-edit"></i> Edit
                            </button>
                            <button type="button" class="btn btn-sm btn-outline-danger">
                                <i class="fas fa-trash"></i> Delete
                            </button>
                        </div>
                    </div>
                </div>
                
                <!-- Mesaj İçeriği - Sağ Taraf -->
                <div class="col-md-9">
                    <div class="message-content p-3 border border-start-0 rounded-end h-100 bg-primary-subtle">
                        <!-- Mesaj Başlığı -->
                        <div class="d-flex justify-content-between align-items-start mb-3">
                            <div>
                                <small class="text-muted">
                                    Posted on ${new Date(d.created_at).toLocaleDateString("en-US",{weekday:"long",year:"numeric",month:"long",day:"numeric"})} at ${new Date(d.created_at).toLocaleTimeString()}
                                </small>
                                <br>
                                <small class="text-muted">
                                    Just now
                                </small>
                            </div>
                            <div>
                                <button type="button" class="btn btn-sm btn-outline-primary" title="Reply">
                                    <i class="fas fa-comment"></i>
                                </button>
                            </div>
                        </div>
                        
                        <!-- Mesaj İçeriği -->
                        <div class="message-body mb-3">
                            ${w(d.message).replace(/\n/g,"<br>")}
                        </div>
                        
                        ${d.attachments&&d.attachments.length>0?`
                            <!-- Attachments -->
                            <div class="attachments mb-2">
                                <small class="text-muted d-block mb-1">
                                    <i class="fas fa-paperclip me-1"></i>${((c=(h=(m=window.translations)==null?void 0:m.tickets)==null?void 0:h.conversation)==null?void 0:c.attachments)||"Attachments"}
                                </small>
                                <div class="d-flex flex-wrap gap-2">
                                    ${d.attachments.map(p=>{const s=w(p.original_name),i=w(p.file_size),l=s.length>25?s.substring(0,25)+"...":s;return`
                                        <a href="${p.url}" target="_blank"
                                           class="btn btn-sm btn-outline-secondary text-truncate"
                                           style="max-width: 200px;"
                                           data-bs-toggle="tooltip"
                                           title="${s} (${i})">
                                            <i class="fas fa-file me-1"></i>${l}
                                        </a>
                                        `}).join("")}
                                </div>
                            </div>
                        `:""}
                    </div>
                </div>
            </div>
        </div>
    `;e.insertAdjacentHTML("beforeend",r)}(function(){const e=document.getElementById("editCcBtn"),t=document.getElementById("saveCcBtn"),a=document.getElementById("cancelCcBtn"),n=document.getElementById("ccDisplay"),r=document.getElementById("ccEditForm"),m=document.getElementById("ccEmailsInput");if(!e)return;e.addEventListener("click",()=>{n.style.display="none",e.style.display="none",r.style.display="block",m.focus()}),a.addEventListener("click",()=>{r.style.display="none",n.style.display="block",e.style.display="block"}),t.addEventListener("click",async()=>{const c=m.value.trim();t.disabled=!0;try{const p=await fetch(window.routes.tickets.updateCc,{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${g()}`},body:JSON.stringify({cc_emails:c})});if(p.status===401){const s=await v();if(s){const i=await fetch(window.routes.tickets.updateCc,{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({cc_emails:c})});return h(await i.json())}}h(await p.json())}catch(p){window.toastr&&window.toastr.error(p.message)}finally{t.disabled=!1}});function h(c){var p,s,i,l;if(c.success){const o=c.cc_emails;if(o){const u=o.split(",").map(f=>f.trim()).filter(Boolean);n.innerHTML=u.map(f=>`<small class="d-block text-truncate" title="${w(f)}">${w(f)}</small>`).join("")}else{const u=((s=(p=window.translations)==null?void 0:p.cc)==null?void 0:s.none)||"-";n.innerHTML=`<small class="text-muted">${w(u)}</small>`}r.style.display="none",n.style.display="block",e.style.display="block",window.toastr&&window.toastr.success(((l=(i=window.translations)==null?void 0:i.cc)==null?void 0:l.updated)||"CC updated")}else window.toastr&&window.toastr.error(c.message)}})();
