@extends('layouts.app')

@section('title', __('whatsapp::lang.whatsapp') . ' — ' . __('whatsapp::lang.inbox_chat'))

@section('css')
<style>
    .wa-inbox { display:flex; height:72vh; border:1px solid #ddd; border-radius:6px; overflow:hidden; background:#fff; }
    .wa-list { width:320px; border-right:1px solid #eee; overflow-y:auto; }
    .wa-conv { padding:10px 12px; border-bottom:1px solid #f2f2f2; cursor:pointer; }
    .wa-conv:hover, .wa-conv.active { background:#eef7ee; }
    .wa-conv .nm { font-weight:600; }
    .wa-conv .ex { color:#888; font-size:12px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
    .wa-conv .badge { background:#25d366; }
    .wa-thread-wrap { flex:1; display:flex; flex-direction:column; background:#e5ddd5; }
    .wa-thread { flex:1; overflow-y:auto; padding:14px; }
    .wa-bubble { max-width:75%; padding:7px 10px; border-radius:7px; margin-bottom:8px; clear:both; font-size:14px; white-space:pre-wrap; word-wrap:break-word; }
    .wa-in  { background:#fff; float:left; }
    .wa-out { background:#dcf8c6; float:right; }
    .wa-bubble .mt { display:block; font-size:10px; color:#888; text-align:right; margin-top:2px; }
    .wa-out.ai { background:#d6eaff; }
    .wa-head { padding:8px 12px; background:#f5f5f5; border-bottom:1px solid #e3e3e3; display:flex; align-items:center; }
    .wa-compose { display:flex; padding:8px; background:#f0f0f0; border-top:1px solid #e3e3e3; }
    .wa-compose textarea { flex:1; resize:none; }
</style>
@endsection

@section('content')
<section class="content-header">
    <h1><i class="fab fa-whatsapp"></i> {{ __('whatsapp::lang.whatsapp') }}
        <small>{{ __('whatsapp::lang.inbox_chat') }}</small></h1>
</section>

<section class="content">
    @include('whatsapp::partials._nav')

    <div class="wa-inbox">
        <div class="wa-list" id="wa-list"></div>
        <div class="wa-thread-wrap">
            <div class="wa-head" id="wa-head"><span class="text-muted">{{ __('whatsapp::lang.select_conversation') }}</span></div>
            <div class="wa-thread" id="wa-thread"></div>
            <form class="wa-compose" id="wa-compose" style="display:none;flex-direction:column;">
                <select id="wa-quick" class="form-control input-sm" style="margin-bottom:6px;">
                    <option value="">— {{ __('whatsapp::lang.quick_reply') }} —</option>
                    @foreach($quickReplies as $qr)
                        <option value="{{ $qr->name }}" data-body="{{ e($qr->body) }}">{{ $qr->name }}</option>
                    @endforeach
                </select>
                <div style="display:flex;">
                    <textarea id="wa-reply" rows="2" class="form-control" placeholder="{{ __('whatsapp::lang.type_a_message') }}"></textarea>
                    <button class="btn btn-success" style="margin-left:6px;"><i class="fa fa-paper-plane"></i></button>
                </div>
            </form>
        </div>
    </div>
</section>
@endsection

@section('javascript')
<script>
(function(){
    var current = null;
    var routes = {
        list: "{{ route('whatsapp.inbox.list') }}",
        thread: function(id){ return "{{ url('whatsapp/inbox') }}/" + id + "/thread"; },
        reply: function(id){ return "{{ url('whatsapp/inbox') }}/" + id + "/reply"; },
        assign: function(id){ return "{{ url('whatsapp/inbox') }}/" + id + "/assign"; },
        release: function(id){ return "{{ url('whatsapp/inbox') }}/" + id + "/release"; },
        ai: function(id){ return "{{ url('whatsapp/inbox') }}/" + id + "/ai"; },
        close: function(id){ return "{{ url('whatsapp/inbox') }}/" + id + "/close"; },
        labels: function(id){ return "{{ url('whatsapp/inbox') }}/" + id + "/labels"; }
    };
    var csrf = "{{ csrf_token() }}";
    function post(url){ return fetch(url,{method:'POST',headers:{'X-CSRF-TOKEN':csrf,'X-Requested-With':'XMLHttpRequest'}}); }
    function esc(s){ var d=document.createElement('div'); d.textContent=s||''; return d.innerHTML; }

    function renderList(data){
        var el = document.getElementById('wa-list');
        var html = '';
        (data.conversations||[]).forEach(function(c){
            var unread = c.unread ? '<span class="badge pull-right">'+c.unread+'</span>' : '';
            var ai = c.ai ? '<i class="fa fa-robot text-blue" title="AI on"></i> ' : '';
            html += '<div class="wa-conv '+(current==c.id?'active':'')+'" data-id="'+c.id+'">'
                + '<div class="nm">'+ai+esc(c.name)+unread+'</div>'
                + '<div class="ex">'+(c.direction==='out'?'↩ ':'')+esc(c.excerpt||'')+'</div>'
                + '<div class="ex" style="color:#bbb;">'+esc(c.at||'')+(c.assigned?(' · '+esc(c.assigned)):'')+'</div>'
                + '</div>';
        });
        el.innerHTML = html || '<div class="text-muted" style="padding:14px;">{{ __('whatsapp::lang.no_conversations') }}</div>';
        Array.prototype.forEach.call(el.querySelectorAll('.wa-conv'), function(node){
            node.addEventListener('click', function(){ openThread(node.getAttribute('data-id')); });
        });
    }

    function renderThread(data){
        var c = data.conversation;
        document.getElementById('wa-compose').style.display = 'flex';
        var aiBtn = '<button class="btn btn-xs '+(c.ai?'btn-primary':'btn-default')+'" id="wa-ai-btn"><i class="fa fa-robot"></i> '+(c.ai?'AI on':'AI off')+'</button>';
        var claim = c.assigned_id
            ? '<button class="btn btn-xs btn-warning" id="wa-release-btn">Release ('+esc(c.assigned||'')+')</button>'
            : '<button class="btn btn-xs btn-default" id="wa-assign-btn">Claim</button>';
        var labels = (c.labels||[]).map(function(l){ return '<span class="label label-info" style="margin-left:3px;">'+esc(l)+'</span>'; }).join('');
        document.getElementById('wa-head').innerHTML =
            '<strong>'+esc(c.name)+'</strong> <small class="text-muted" style="margin-left:6px;">'+esc(c.wa_id)+'</small> '+labels
            + '<span class="pull-right">'+aiBtn+' '+claim
            + ' <button class="btn btn-xs btn-default" id="wa-label-btn"><i class="fa fa-tag"></i></button>'
            + ' <button class="btn btn-xs btn-default" id="wa-close-btn">Close</button></span>';

        var t = document.getElementById('wa-thread');
        var html = '';
        var mediaIcon = {image:'🖼️ Image',document:'📄 Document',audio:'🎧 Audio',video:'🎬 Video',location:'📍 Location',interactive:'🔘 Buttons',sticker:'🌟 Sticker'};
        (data.messages||[]).forEach(function(m){
            var cls = m.direction==='in' ? 'wa-in' : ('wa-out' + (m.source==='ai'?' ai':''));
            var tick = '';
            if (m.direction==='out'){
                tick = ({queued:'🕓',pending:'🕓',sent:'✓',delivered:'✓✓',read:'✓✓',failed:'⚠'})[m.status]||'';
            }
            var inner = '';
            if (m.type && m.type !== 'text' && mediaIcon[m.type]) {
                inner = '<em>'+mediaIcon[m.type]+'</em>' + (m.body ? '<br>'+esc(m.body) : '');
            } else {
                inner = esc(m.body);
            }
            html += '<div class="wa-bubble '+cls+'">'+inner+'<span class="mt">'+m.time+' '+tick+'</span></div>';
        });
        t.innerHTML = html + '<div style="clear:both;"></div>';
        t.scrollTop = t.scrollHeight;

        var b;
        if (b=document.getElementById('wa-ai-btn')) b.onclick=function(){ post(routes.ai(c.id)).then(function(){ openThread(c.id); }); };
        if (b=document.getElementById('wa-assign-btn')) b.onclick=function(){ post(routes.assign(c.id)).then(function(){ openThread(c.id); }); };
        if (b=document.getElementById('wa-release-btn')) b.onclick=function(){ post(routes.release(c.id)).then(function(){ openThread(c.id); }); };
        if (b=document.getElementById('wa-close-btn')) b.onclick=function(){ post(routes.close(c.id)).then(function(){ current=null; document.getElementById('wa-thread').innerHTML=''; document.getElementById('wa-compose').style.display='none'; document.getElementById('wa-head').innerHTML='<span class="text-muted">{{ __('whatsapp::lang.select_conversation') }}</span>'; refreshList(); }); };
        if (b=document.getElementById('wa-label-btn')) b.onclick=function(){
            var v = prompt('Labels (comma-separated):', (c.labels||[]).join(', '));
            if (v===null) return;
            var fd = new FormData(); fd.append('labels', v);
            fetch(routes.labels(c.id),{method:'POST',headers:{'X-CSRF-TOKEN':csrf,'X-Requested-With':'XMLHttpRequest'},body:fd}).then(function(){ openThread(c.id); });
        };
    }

    function openThread(id){ current=id; fetch(routes.thread(id),{headers:{'X-Requested-With':'XMLHttpRequest'}}).then(function(r){return r.json();}).then(renderThread).then(refreshList); }
    function refreshList(){ fetch(routes.list,{headers:{'X-Requested-With':'XMLHttpRequest'}}).then(function(r){return r.json();}).then(renderList).catch(function(){}); }

    document.getElementById('wa-compose').addEventListener('submit', function(e){
        e.preventDefault();
        if (!current) return;
        var ta = document.getElementById('wa-reply');
        var body = ta.value.trim(); if (!body) return;
        var fd = new FormData(); fd.append('body', body);
        fetch(routes.reply(current),{method:'POST',headers:{'X-CSRF-TOKEN':csrf,'X-Requested-With':'XMLHttpRequest'},body:fd})
            .then(function(){ ta.value=''; openThread(current); });
    });

    // Quick reply → insert template body into the compose box.
    var quick = document.getElementById('wa-quick');
    if (quick) quick.addEventListener('change', function(){
        var opt = quick.options[quick.selectedIndex];
        var body = opt ? opt.getAttribute('data-body') : '';
        if (body){ var ta=document.getElementById('wa-reply'); ta.value = ta.value.trim()? (ta.value.replace(/\s+$/,'')+"\n\n"+body) : body; ta.focus(); }
        quick.selectedIndex = 0;
    });

    refreshList();
    setInterval(refreshList, 6000);
    setInterval(function(){ if(current) openThread(current); }, 4000);
})();
</script>
@endsection
