@php
    $avatarDirs = array_values(array_unique([
        file_exists(base_path('index.php')) ? base_path('support-avatar') : public_path('support-avatar'),
        public_path('support-avatar'),
        base_path('support-avatar'),
    ]));
    $avatarFiles = [];
    foreach ($avatarDirs as $avatarDir) {
        $matches = glob($avatarDir . DIRECTORY_SEPARATOR . 'support-avatar.*') ?: [];
        if (count($matches)) {
            $avatarFiles = $matches;
            break;
        }
    }
    $supportAvatarUrl = count($avatarFiles) ? asset('support-avatar/' . basename($avatarFiles[0])) . '?v=' . filemtime($avatarFiles[0]) : '';
@endphp

@include('partials.brand-colors-css')

@if($settings->whatsapp)
<script type="text/javascript">
    (function () {
        var options = {
            whatsapp: "{{$settings->whatsapp}}",
            call_to_action: "Message us",
            position: "left",
            pre_filled_message: "Hello I am",
        };
        var proto = document.location.protocol, host = "getbutton.io", url = proto + "//static." + host;
        var s = document.createElement('script'); s.type = 'text/javascript'; s.async = true; s.src = url + '/widget-send-button/js/init.js';
        s.onload = function () { WhWidgetSendButton.init(host, proto, options); };
        var x = document.getElementsByTagName('script')[0]; x.parentNode.insertBefore(s, x);
    })();
</script>
@endif

<style>
    .fc-live-support-widget{position:fixed;right:20px;bottom:24px;z-index:1061;display:flex;flex-direction:column;align-items:flex-end;gap:7px;font-family:inherit}.fc-live-support-btn{border:0;border-radius:999px;background:var(--brand-gradient,linear-gradient(135deg,#f7931a,#155c9d,#0f766e));color:#fff;padding:13px 18px;font-weight:800;box-shadow:0 16px 32px rgba(0,0,0,.24);cursor:pointer;position:relative}.fc-live-support-badge{position:absolute;top:-8px;right:-8px;min-width:22px;height:22px;border-radius:999px;background:#ef4444;color:#fff;border:2px solid #fff;display:none;align-items:center;justify-content:center;font-size:11px;font-weight:900;line-height:1;box-shadow:0 8px 18px rgba(239,68,68,.35)}.fc-live-support-badge.is-visible{display:flex}.fc-live-support-meta{font-size:11px;color:#fff;background:var(--brand-dark,#102033);border:1px solid rgba(255,255,255,.18);border-radius:999px;padding:4px 9px}.fc-live-chat-modal{position:fixed;inset:0;z-index:1062;display:none}.fc-live-chat-modal.is-open{display:block}.fc-live-chat-overlay{position:absolute;inset:0;background:rgba(2,6,23,.45)}.fc-live-chat-dialog{position:absolute;right:18px;bottom:24px;width:min(400px,calc(100vw - 24px));max-height:min(620px,calc(100vh - 48px));background:#fff;border-radius:18px;box-shadow:0 28px 70px rgba(15,23,42,.34);overflow:hidden;display:flex;flex-direction:column;border:1px solid color-mix(in srgb,var(--brand-primary,#f7931a) 20%,#fff)}.fc-live-chat-head{padding:15px 16px;background:var(--brand-gradient,linear-gradient(135deg,#f7931a,#155c9d,#0f766e));color:#fff;display:flex;justify-content:space-between;gap:12px;align-items:flex-start}.fc-live-chat-head-title{font-size:16px;font-weight:800;color:#fff}.fc-live-chat-head-sub{font-size:12px;opacity:.9;margin-top:3px;color:#fff}.fc-live-chat-close{border:0;background:transparent;color:#fff;font-size:24px;line-height:1;cursor:pointer}.fc-live-chat-body{padding:14px;overflow:auto;background:linear-gradient(180deg,#fff,var(--brand-light,#fff7ed))}.fc-live-chat-form .form-control{width:100%;border-radius:10px;border:1px solid #d7e2e8;font-size:13px;padding:10px;margin-bottom:8px}.fc-live-chat-form .form-control:focus,.fc-live-chat-reply textarea:focus{border-color:var(--brand-primary,#f7931a)!important;box-shadow:0 0 0 .16rem rgba(15,23,42,.08)!important;outline:0}.fc-live-chat-actions{display:grid;grid-template-columns:1fr 1fr;gap:8px}.fc-live-chat-actions button,.fc-live-chat-send-btn{border:0;border-radius:10px;background:var(--brand-primary,#f7931a);color:#fff;font-size:13px;font-weight:800;padding:10px;cursor:pointer}.fc-live-chat-actions button[type=button]{background:var(--brand-light,#fff7ed);color:var(--brand-dark,#102033);border:1px solid color-mix(in srgb,var(--brand-primary,#f7931a) 25%,#fff)}.fc-live-chat-result{min-height:18px;font-size:12px;color:#64748b;margin:7px 0}.fc-live-chat-thread{display:none}.fc-live-chat-thread.is-active{display:block}.fc-live-chat-ticket{display:flex;align-items:center;justify-content:space-between;gap:8px;color:#53636b;font-size:12px;margin-bottom:8px}.fc-live-chat-new-btn{border:1px solid color-mix(in srgb,var(--brand-secondary,#155c9d) 22%,#d7e2e8);background:#fff;color:var(--brand-secondary,#155c9d);border-radius:8px;height:30px;padding:0 10px;font-size:12px;font-weight:700;cursor:pointer}.fc-live-chat-stream{display:flex;flex-direction:column;gap:9px;max-height:270px;overflow:auto;padding:4px 2px 10px}.fc-live-chat-row{display:flex;align-items:flex-end;gap:8px}.fc-live-chat-row--user{justify-content:flex-start}.fc-live-chat-row--support{justify-content:flex-end}.fc-live-chat-avatar{width:30px;height:30px;border-radius:999px;display:flex;align-items:center;justify-content:center;font-size:11px;font-weight:800;flex:0 0 auto;overflow:hidden}.fc-live-chat-avatar img{width:100%;height:100%;object-fit:cover}.fc-live-chat-avatar--user{background:var(--brand-light,#fff7ed);color:var(--brand-dark,#102033);border:1px solid color-mix(in srgb,var(--brand-primary,#f7931a) 22%,#fff)}.fc-live-chat-avatar--support{background:var(--brand-secondary,#155c9d);color:#fff}.fc-live-chat-bubble-wrap{max-width:78%}.fc-live-chat-bubble{border-radius:14px;padding:9px 11px;font-size:13px;line-height:1.45;word-break:break-word}.fc-live-chat-bubble.is-user{background:#fff;border:1px solid color-mix(in srgb,var(--brand-primary,#f7931a) 20%,#dbe5ef);color:var(--brand-dark,#102033)}.fc-live-chat-bubble.is-support{background:linear-gradient(135deg,var(--brand-secondary,#155c9d),var(--brand-accent,#0f766e));border:1px solid transparent;color:#fff}.fc-live-chat-b-meta{font-size:11px;opacity:.72;margin-top:5px}.fc-live-chat-reply{display:grid;grid-template-columns:38px 1fr 72px;gap:8px;align-items:end;margin-top:8px}.fc-live-chat-reply textarea{min-height:48px;max-height:100px;resize:vertical;border-radius:10px;font-size:13px;border:1px solid #d7e2e8;padding:8px;background:#fff;color:var(--brand-dark,#102033)}.fc-live-chat-attach-btn{width:38px;height:38px;border-radius:10px;border:1px solid color-mix(in srgb,var(--brand-primary,#f7931a) 25%,#d7e2e8);background:#fff;color:var(--brand-primary,#f7931a);display:flex;align-items:center;justify-content:center;cursor:pointer;position:relative;overflow:hidden}.fc-live-chat-file-hit{position:absolute;inset:0;opacity:0;cursor:pointer}.fc-live-chat-hp{position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden}.fc-reply-attachment{margin-top:7px}.fc-reply-attachment a{font-size:12px;font-weight:800;color:var(--brand-primary,#f7931a)!important}@supports not (color:color-mix(in srgb,#fff,#000)){.fc-live-chat-dialog,.fc-live-chat-actions button[type=button],.fc-live-chat-new-btn,.fc-live-chat-avatar--user,.fc-live-chat-bubble.is-user,.fc-live-chat-attach-btn{border-color:#d7e2e8}}@media (max-width:560px){.fc-live-support-widget{right:14px;bottom:16px}.fc-live-chat-dialog{right:8px;bottom:8px;width:calc(100vw - 16px);max-height:calc(100vh - 16px)}.fc-live-chat-actions{grid-template-columns:1fr}.fc-live-chat-reply{grid-template-columns:34px 1fr}.fc-live-chat-send-btn{grid-column:1 / -1}}
</style>

<div class="fc-live-support-widget">
    <div class="fc-live-support-meta">Support usually replies quickly</div>
    <button type="button" class="fc-live-support-btn" id="fcLiveSupportOpen">Live Support <span class="fc-live-support-badge" id="fcLiveSupportBadge">0</span></button>
</div>

<div class="fc-live-chat-modal" id="fcLiveSupportModal" aria-hidden="true">
    <div class="fc-live-chat-overlay" data-fc-close></div>
    <div class="fc-live-chat-dialog" role="dialog" aria-modal="true" aria-label="Live support chat">
        <div class="fc-live-chat-head">
            <div>
                <div class="fc-live-chat-head-title">Live Support</div>
                <div class="fc-live-chat-head-sub">Start a ticket or continue your chat.</div>
            </div>
            <button type="button" class="fc-live-chat-close" data-fc-close>&times;</button>
        </div>
        <div class="fc-live-chat-body">
            <form class="fc-live-chat-form" id="fcLiveCreateForm">
                <input type="text" name="website" class="fc-live-chat-hp" tabindex="-1" autocomplete="off">
                <input class="form-control" name="name" placeholder="Your name" required>
                <input class="form-control" type="email" name="email" placeholder="Email address" required>
                <select class="form-control" name="department">
                    <option>General Enquiry</option>
                    <option>Customer Services Department</option>
                    <option>Shipment Department</option>
                    <option>Payment Department</option>
                </select>
                <textarea class="form-control" name="message" rows="3" placeholder="How can we help?" required></textarea>
                <div class="fc-live-chat-actions">
                    <button type="submit">Start Chat</button>
                    <button type="button" id="fcLiveContinue">Continue Last Chat</button>
                </div>
            </form>
            <div class="fc-live-chat-result" id="fcLiveResult"></div>
            <div class="fc-live-chat-thread" id="fcLiveThread">
                <div class="fc-live-chat-ticket">
                    <span id="fcLiveTicketLabel"></span>
                    <button class="fc-live-chat-new-btn" type="button" id="fcLiveNew">New chat</button>
                </div>
                <div class="fc-live-chat-stream" id="fcLiveStream"></div>
                <div class="fc-live-chat-reply">
                    <label class="fc-live-chat-attach-btn" title="Attach file">📎<input class="fc-live-chat-file-hit" type="file" id="fcLiveAttachment" accept=".pdf,.png,.jpg,.jpeg,.gif,.webp,.txt,.doc,.docx,.xls,.xlsx,.csv,.zip"></label>
                    <textarea id="fcLiveReply" placeholder="Type your reply"></textarea>
                    <button class="fc-live-chat-send-btn" type="button" id="fcLiveSend">Send</button>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
(function(){
    var modal=document.getElementById('fcLiveSupportModal'),openBtn=document.getElementById('fcLiveSupportOpen'),badge=document.getElementById('fcLiveSupportBadge'),createForm=document.getElementById('fcLiveCreateForm'),thread=document.getElementById('fcLiveThread'),stream=document.getElementById('fcLiveStream'),result=document.getElementById('fcLiveResult'),ticketLabel=document.getElementById('fcLiveTicketLabel'),reply=document.getElementById('fcLiveReply'),attach=document.getElementById('fcLiveAttachment'),send=document.getElementById('fcLiveSend'),supportAvatar=@json($supportAvatarUrl),activeTicket=localStorage.getItem('fc_live_ticket')||'',pollTimer=null,csrf=(document.querySelector('meta[name="csrf-token"]')||{}).content||'',lastSupportCount=null,soundUnlocked=false;
    function esc(v){return String(v||'').replace(/[&<>"']/g,function(m){return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'}[m];});}
    function storageKey(){return 'fc_live_seen_support_'+activeTicket;}
    function seenSupportCount(){try{return parseInt(localStorage.getItem(storageKey())||'0',10)||0;}catch(e){return 0;}}
    function setSeenSupportCount(count){try{localStorage.setItem(storageKey(),String(count));}catch(e){}}
    function setBadge(count){if(!badge)return;badge.textContent=count>99?'99+':count;badge.classList.toggle('is-visible',count>0);}
    function unlockSound(){soundUnlocked=true;}
    function playTone(){if(!soundUnlocked)return;try{var C=window.AudioContext||window.webkitAudioContext;if(!C)return;var ctx=new C(),osc=ctx.createOscillator(),gain=ctx.createGain();osc.type='sine';osc.frequency.setValueAtTime(880,ctx.currentTime);osc.frequency.setValueAtTime(660,ctx.currentTime+.12);gain.gain.setValueAtTime(.0001,ctx.currentTime);gain.gain.exponentialRampToValueAtTime(.08,ctx.currentTime+.02);gain.gain.exponentialRampToValueAtTime(.0001,ctx.currentTime+.32);osc.connect(gain);gain.connect(ctx.destination);osc.start();osc.stop(ctx.currentTime+.34);}catch(e){}}
    function open(){unlockSound();modal.classList.add('is-open');modal.setAttribute('aria-hidden','false');if(activeTicket){loadThread(true);}}
    function close(){modal.classList.remove('is-open');modal.setAttribute('aria-hidden','true');}
    function showThread(){createForm.style.display='none';thread.classList.add('is-active');startPoll();}
    function showCreate(){thread.classList.remove('is-active');createForm.style.display='block';stopPoll();}
    function stopPoll(){if(pollTimer){clearInterval(pollTimer);pollTimer=null;}}
    function startPoll(){stopPoll();pollTimer=setInterval(function(){loadThread(false);},4000);}
    function avatar(side){if(side==='support'&&supportAvatar){return '<div class="fc-live-chat-avatar fc-live-chat-avatar--support"><img src="'+esc(supportAvatar)+'" alt=""></div>';}return '<div class="fc-live-chat-avatar fc-live-chat-avatar--'+(side==='support'?'support':'user')+'">'+(side==='support'?'CC':'YU')+'</div>';}
    function render(data){if(!data||!data.success)return;activeTicket=data.ticket.ticket_id;supportAvatar=data.support_avatar_url||supportAvatar;localStorage.setItem('fc_live_ticket',activeTicket);ticketLabel.textContent='Ticket '+activeTicket+' - '+data.ticket.status;var supportCount=(data.rows||[]).filter(function(row){return row.side==='support';}).length;if(lastSupportCount!==null&&supportCount>lastSupportCount&&!modal.classList.contains('is-open'))playTone();lastSupportCount=supportCount;if(modal.classList.contains('is-open'))setSeenSupportCount(supportCount);setBadge(Math.max(0,supportCount-seenSupportCount()));stream.innerHTML=(data.rows||[]).map(function(row){var sup=row.side==='support',att=row.attachment_url?'<div class="fc-reply-attachment"><a href="'+esc(row.attachment_url)+'" target="_blank">Attachment'+(row.attachment_ext?' ('+esc(row.attachment_ext.toUpperCase())+')':'')+'</a></div>':'';return '<div class="fc-live-chat-row '+(sup?'fc-live-chat-row--support':'fc-live-chat-row--user')+'">'+(!sup?avatar('user'):'')+'<div class="fc-live-chat-bubble-wrap"><div class="fc-live-chat-bubble '+(sup?'is-support':'is-user')+'">'+esc(row.message)+att+'<div class="fc-live-chat-b-meta">'+esc(row.author)+' - '+esc(row.datecreated)+'</div></div></div>'+(sup?avatar('support'):'')+'</div>';}).join('')||'<div class="fc-live-chat-bubble is-support">No messages yet.</div>';stream.scrollTop=stream.scrollHeight;showThread();}
    function loadThread(noise){if(!activeTicket)return;fetch('{{ route('live-support.thread') }}?ticket_id='+encodeURIComponent(activeTicket),{headers:{'Accept':'application/json'}}).then(function(r){return r.json();}).then(render).catch(function(){if(noise)result.textContent='Could not load the chat.';});}
    openBtn.addEventListener('click',open);['click','keydown','touchstart'].forEach(function(evt){document.addEventListener(evt,unlockSound,{once:true,passive:true});});modal.querySelectorAll('[data-fc-close]').forEach(function(el){el.addEventListener('click',close);});
    document.getElementById('fcLiveNew').addEventListener('click',function(){activeTicket='';localStorage.removeItem('fc_live_ticket');setBadge(0);showCreate();});
    document.getElementById('fcLiveContinue').addEventListener('click',function(){unlockSound();activeTicket=localStorage.getItem('fc_live_ticket')||'';activeTicket?loadThread(true):(result.textContent='No previous chat found.');});
    createForm.addEventListener('submit',function(e){e.preventDefault();result.textContent='Creating ticket...';fetch('{{ route('live-support.create') }}',{method:'POST',headers:{'X-CSRF-TOKEN':csrf,'Accept':'application/json'},body:new FormData(createForm)}).then(function(r){return r.json();}).then(function(data){if(!data.success){result.textContent=data.error||'Could not create ticket.';return;}createForm.reset();result.textContent='Ticket created.';render(data.thread);}).catch(function(){result.textContent='Could not create ticket.';});});
    send.addEventListener('click',function(){if(!activeTicket)return;var fd=new FormData();fd.append('ticket_id',activeTicket);fd.append('message',reply.value||'');if(attach.files[0])fd.append('attachment',attach.files[0]);send.disabled=true;fetch('{{ route('live-support.send') }}',{method:'POST',headers:{'X-CSRF-TOKEN':csrf,'Accept':'application/json'},body:fd}).then(function(r){return r.json();}).then(function(data){if(!data.success){result.textContent=data.error||'Send failed.';return;}reply.value='';attach.value='';render(data.thread);}).catch(function(){result.textContent='Send failed.';}).finally(function(){send.disabled=false;});});
    if(activeTicket){loadThread(false);startPoll();}
})();
</script>
