@extends('layouts.app')

@section('content')
<style>
    /* --- CSS TRUNCATE TEXT --- */
    .text-clamp-2 {
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    
    /* --- STYLING AVATAR --- */
    .msg-avatar {
        width: 48px; height: 48px; 
        object-fit: cover; 
        border-radius: 50%;
        border: 2px solid var(--border-color);
    }
    .msg-avatar-placeholder {
        width: 48px; height: 48px; 
        border-radius: 50%;
        display: flex; align-items: center; justify-content: center;
        font-weight: bold; font-size: 1.2rem;
        box-shadow: 0 4px 10px rgba(0,0,0,0.05);
    }

    /* --- MODERN CARD OVERRIDES --- */
    .modern-card {
        background-color: var(--bg-card);
        border: 1px solid var(--border-color);
        border-radius: 24px !important;
        box-shadow: 0 10px 30px rgba(0,0,0,0.02);
    }
    [data-bs-theme="dark"] .modern-card { box-shadow: 0 10px 40px rgba(0,0,0,0.1); }
    
    .msg-item {
        background-color: var(--bg-card) !important;
        border: 1px solid var(--border-color) !important;
        transition: all 0.3s ease;
        border-radius: 16px !important;
    }
    .msg-item:hover {
        transform: translateY(-3px);
        box-shadow: 0 8px 25px rgba(0,0,0,0.05) !important;
        border-color: var(--primary-color) !important;
    }
    [data-bs-theme="dark"] .msg-item:hover { box-shadow: 0 8px 25px rgba(0,0,0,0.2) !important; }
    
    /* --- CUSTOM TAB STYLING --- */
    .nav-tabs { border-bottom: 2px solid var(--border-color); }
    .nav-tabs .nav-link { 
        color: var(--text-muted); 
        border: none; 
        border-bottom: 3px solid transparent; 
        margin-bottom: -2px;
        transition: all 0.3s ease;
    }
    .nav-tabs .nav-link:hover { color: var(--text-main); border-color: transparent; }
    .nav-tabs .nav-link.active { 
        color: var(--primary-color) !important; 
        background: transparent !important; 
        border-color: var(--primary-color); 
    }

    .btn-pill { border-radius: 50rem !important; }
</style>

<div class="container-fluid py-4">
    
    {{-- Header --}}
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h3 class="fw-bold mb-0"><i class="bi bi-chat-square-text me-2 text-primary"></i>Pesan & Notifikasi</h3>
            <p class="text-muted small mb-0">Kelola pesan masuk dan pengumuman.</p>
        </div>
        <div>
            <button class="btn btn-primary btn-pill px-4 py-2 fw-bold shadow-sm" data-bs-toggle="modal" data-bs-target="#modalCompose">
                <i class="bi bi-pencil-square me-2"></i> Tulis Pesan
            </button>
        </div>
    </div>

    @if(session('success'))
        <div class="alert alert-success alert-dismissible fade show rounded-4 border-0 shadow-sm text-white bg-success bg-opacity-25 border-start border-success border-4">
            <i class="bi bi-check-circle-fill me-2"></i> {{ session('success') }} 
            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="alert"></button>
        </div>
    @endif

    <div class="card modern-card overflow-hidden" style="min-height: 600px;">
        <div class="card-header bg-transparent border-bottom px-4 pt-4 pb-0">
            <ul class="nav nav-tabs card-header-tabs" id="msgTabs" role="tablist">
                <li class="nav-item">
                    <button class="nav-link active fw-bold py-3 px-4" id="tab-inbox" data-bs-toggle="tab" data-bs-target="#content-inbox" type="button">
                        <i class="bi bi-inbox-fill me-2"></i> Kotak Masuk
                        @if($inbox->where('is_read', 0)->count() > 0)
                            <span class="badge bg-danger rounded-pill ms-2 shadow-sm">{{ $inbox->where('is_read', 0)->count() }}</span>
                        @endif
                    </button>
                </li>
                <li class="nav-item">
                    <button class="nav-link fw-bold py-3 px-4" id="tab-sent" data-bs-toggle="tab" data-bs-target="#content-sent" type="button">
                        <i class="bi bi-send-fill me-2"></i> Pesan Keluar
                    </button>
                </li>
            </ul>
        </div>

        <div class="card-body p-4" style="background-color: var(--bg-body);">
            <div class="tab-content" id="msgTabsContent">
                
                {{-- TAB 1: KOTAK MASUK --}}
                <div class="tab-pane fade show active" id="content-inbox">
                    <div class="list-group list-group-flush gap-3">
                        @forelse($inbox as $msg)
                            @php
                                $isOfficial = in_array($msg->sender->role, ['super_admin', 'admin_mapel', 'koordinator']);
                                $badgeColor = $isOfficial ? 'bg-warning text-dark' : 'bg-primary bg-opacity-10 text-primary border border-primary-subtle';
                                $badgeText  = $isOfficial ? '📢 Broadcast' : '💬 Pribadi';
                                $borderClass = !$msg->is_read ? 'border-start border-5 border-primary' : '';
                            @endphp

                            <div class="list-group-item list-group-item-action py-4 px-4 msg-item shadow-sm {{ $borderClass }}">
                                <div class="d-flex w-100 justify-content-between align-items-center mb-3">
                                    <div class="d-flex align-items-center">
                                        @if($msg->sender && $msg->sender->avatar)
                                            <img src="{{ asset('storage/' . $msg->sender->avatar) }}" class="msg-avatar me-3" alt="Foto">
                                        @else
                                            <div class="msg-avatar-placeholder me-3 {{ $isOfficial ? 'bg-warning text-dark' : 'bg-primary text-white border-0' }}">
                                                {{ substr($msg->sender->name ?? '?', 0, 1) }}
                                            </div>
                                        @endif
                                        <div>
                                            <div class="d-flex align-items-center gap-2 mb-1">
                                                <h6 class="mb-0 fw-bold">{{ $msg->sender->name ?? 'User Terhapus' }}</h6>
                                                <span class="badge rounded-pill {{ $badgeColor }}" style="font-size: 0.65rem;">{{ $badgeText }}</span>
                                            </div>
                                            <small class="text-muted fw-medium" style="font-size: 0.8rem;">
                                                <i class="bi bi-clock me-1"></i> {{ $msg->created_at->format('d M Y, H:i') }}
                                            </small>
                                        </div>
                                    </div>
                                    <div class="text-end">
                                        @if(!$msg->is_read)
                                            <a href="{{ route('message.read', $msg->id) }}" class="btn btn-sm btn-primary btn-pill px-4 shadow-sm mb-1 fw-bold">
                                                <i class="bi bi-check2-all me-1"></i> Tandai Dibaca
                                            </a>
                                        @endif
                                    </div>
                                </div>
                                
                                <div class="ps-5 ms-3">
                                    <p class="mb-2 text-clamp-2" style="font-size: 0.95rem; line-height: 1.6; color: var(--text-main);">
                                        {{ $msg->message }}
                                    </p>
                                    
                                    @if(strlen($msg->message) > 100)
                                        <button class="btn btn-link p-0 text-decoration-none small fw-bold mb-3 text-primary" 
                                                onclick="showFullMessage('{{ $msg->sender->name }}', '{{ $msg->created_at->format('d M Y, H:i') }}', `{{ $msg->message }}`)">
                                            Baca Selengkapnya...
                                        </button>
                                    @endif

                                    <div class="d-flex gap-2 mt-3 pt-3 border-top">
                                        <button onclick="openReplyModal('{{ $msg->sender_id }}', '{{ $msg->sender->name ?? '' }}', `{{ $msg->message }}`)" 
                                            class="btn btn-outline-primary btn-sm fw-bold btn-pill px-4">
                                            <i class="bi bi-reply-fill me-1"></i> Balas
                                        </button>

                                        <form action="{{ route('message.destroy', $msg->id) }}" method="POST" onsubmit="return confirm('Hapus pesan ini?')">
                                            @csrf @method('DELETE')
                                            <button class="btn btn-outline-danger btn-sm btn-pill px-3">
                                                <i class="bi bi-trash"></i>
                                            </button>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        @empty
                            <div class="text-center py-5 mt-4 border border-dashed rounded-4" style="background-color: var(--hover-bg);">
                                <i class="bi bi-inbox text-primary opacity-50 display-1"></i>
                                <h5 class="mt-3 fw-bold">Kotak Masuk Kosong</h5>
                                <p class="text-muted">Anda tidak memiliki pesan baru saat ini.</p>
                            </div>
                        @endforelse
                    </div>
                </div>

                {{-- TAB 2: PESAN KELUAR --}}
                <div class="tab-pane fade" id="content-sent">
                    <div class="list-group list-group-flush gap-3">
                        @forelse($sentMessages as $group)
                            @php
                                $firstMsg = $group->first();
                                $count = $group->count();
                                $isBroadcast = $count > 1;
                            @endphp

                            <div class="list-group-item msg-item py-4 px-4 shadow-sm">
                                <div class="d-flex w-100 justify-content-between align-items-center mb-3">
                                    <div class="d-flex align-items-center">
                                        @if($isBroadcast)
                                            <div class="msg-avatar-placeholder me-3 bg-warning text-dark border-0">
                                                <i class="bi bi-megaphone-fill"></i>
                                            </div>
                                        @elseif($firstMsg->receiver && $firstMsg->receiver->avatar)
                                            <img src="{{ asset('storage/' . $firstMsg->receiver->avatar) }}" class="msg-avatar me-3" alt="Foto">
                                        @else
                                            <div class="msg-avatar-placeholder me-3 bg-success text-white border-0">
                                                <i class="bi bi-person-fill"></i>
                                            </div>
                                        @endif

                                        <div>
                                            <h6 class="mb-1 fw-bold">
                                                @if($isBroadcast)
                                                    Broadcast <span class="badge bg-secondary rounded-pill ms-2">{{ $count }} Penerima</span>
                                                @else
                                                    Kepada: <span class="text-primary">{{ $firstMsg->receiver->name ?? 'User Terhapus' }}</span>
                                                @endif
                                            </h6>
                                            <small class="text-muted fw-medium" style="font-size: 0.8rem;">
                                                <i class="bi bi-clock me-1"></i> {{ $firstMsg->created_at->format('d M Y, H:i') }}
                                            </small>
                                        </div>
                                    </div>
                                </div>
                                <div class="ps-5 ms-3">
                                    <p class="mb-2 text-clamp-2" style="font-size: 0.95rem; line-height: 1.6; color: var(--text-main);">
                                        {{ $firstMsg->message }}
                                    </p>
                                    @if(strlen($firstMsg->message) > 100)
                                        <button class="btn btn-link p-0 text-decoration-none small fw-bold mb-3 text-primary" 
                                                onclick="showFullMessage('Anda ({{ $isBroadcast ? 'Broadcast' : 'Pribadi' }})', '{{ $firstMsg->created_at->format('d M Y, H:i') }}', `{{ $firstMsg->message }}`)">
                                            Baca Selengkapnya...
                                        </button>
                                    @endif
                                    <div class="mt-3 pt-3 border-top">
                                        <form action="{{ route('message.destroy', $firstMsg->id) }}" method="POST" onsubmit="return confirm('Hapus riwayat pesan ini?')">
                                            @csrf @method('DELETE')
                                            <button class="btn btn-outline-danger btn-sm btn-pill px-4 fw-bold">
                                                <i class="bi bi-trash me-1"></i> Hapus Riwayat
                                            </button>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        @empty
                            <div class="text-center py-5 mt-4 border border-dashed rounded-4" style="background-color: var(--hover-bg);">
                                <i class="bi bi-send text-primary opacity-50 display-1"></i>
                                <h5 class="mt-3 fw-bold">Pesan Keluar Kosong</h5>
                                <p class="text-muted">Belum ada riwayat pengiriman pesan.</p>
                            </div>
                        @endforelse
                    </div>
                </div>

            </div>
        </div>
    </div>
</div>

{{-- MODAL 1: BACA SELENGKAPNYA --}}
<div class="modal fade" id="modalReadMore" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
        <div class="modal-content shadow-lg rounded-4">
            <div class="modal-header border-bottom pb-3">
                <h5 class="modal-title fw-bold" id="readMoreSender">Pengirim</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body pt-3">
                <small class="text-primary fw-bold d-block mb-3" id="readMoreTime">Waktu</small>
                <div class="p-4 rounded-4 border" style="font-size: 1rem; line-height: 1.8; white-space: pre-line; background-color: var(--hover-bg); color: var(--text-main);" id="readMoreContent">
                    Isi Pesan...
                </div>
            </div>
            <div class="modal-footer border-0">
                <button type="button" class="btn btn-secondary btn-pill px-4" data-bs-dismiss="modal">Tutup</button>
            </div>
        </div>
    </div>
</div>

{{-- MODAL 2: TULIS PESAN BARU --}}
<div class="modal fade" id="modalCompose" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content shadow-lg rounded-4">
            <div class="modal-header bg-primary border-0 rounded-top-4 text-white">
                <h5 class="modal-title fw-bold"><i class="bi bi-pencil-square me-2"></i> Tulis Pesan</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form action="{{ route('message.store') }}" method="POST">
                @csrf
                <div class="modal-body p-4">
                    @if(in_array(Auth::user()->role, ['super_admin', 'admin_mapel', 'koordinator']))
                        <div class="d-flex align-items-center mb-4 p-3 rounded-4 border border-warning bg-warning bg-opacity-10">
                            <div class="form-check form-switch m-0">
                                <input class="form-check-input" type="checkbox" name="is_broadcast" value="1" id="broadcastSwitch" onchange="toggleReceiver()" style="cursor:pointer;">
                                <label class="form-check-label fw-bold ms-2 text-warning" for="broadcastSwitch" style="cursor:pointer;">Kirim Broadcast (Ke Semua User)</label>
                            </div>
                        </div>
                    @endif

                    <div class="mb-4" id="receiverContainer">
                        <label class="form-label small fw-bold text-muted text-uppercase">Kepada</label>
                        <select name="receiver_id" id="receiverSelect" class="form-select rounded-pill px-3 py-2" required>
                            <option value="" selected disabled>-- Pilih Penerima --</option>
                            @foreach($usersList as $u)
                                <option value="{{ $u->id }}">{{ $u->name }} ({{ ucfirst($u->role) }})</option>
                            @endforeach
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label small fw-bold text-muted text-uppercase">Pesan</label>
                        <textarea name="message" class="form-control rounded-4 p-3" rows="5" placeholder="Ketikan pesan Anda disini..." required></textarea>
                    </div>
                </div>
                <div class="modal-footer border-0 pt-0 px-4 pb-4 d-flex justify-content-end gap-2">
                    <button type="button" class="btn btn-outline-secondary btn-pill px-4" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-primary btn-pill px-5 fw-bold shadow-sm">Kirim <i class="bi bi-send ms-1"></i></button>
                </div>
            </form>
        </div>
    </div>
</div>

{{-- MODAL 3: BALAS PESAN --}}
<div class="modal fade" id="modalReply" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content shadow-lg rounded-4">
            <div class="modal-header border-bottom">
                <h5 class="modal-title fw-bold text-primary"><i class="bi bi-reply-fill me-2"></i> Balas Pesan</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form action="{{ route('message.store') }}" method="POST">
                @csrf
                <div class="modal-body p-4">
                    <input type="hidden" name="receiver_id" id="replyReceiverId">
                    <div class="mb-4 p-3 rounded-4 border border-start-0 border-end-0 border-top-0 border-primary border-4" style="background-color: var(--hover-bg);">
                        <small class="text-muted d-block fw-bold mb-2">Membalas pesan dari <span id="replyToName" class="text-primary">...</span>:</small>
                        <p class="small mb-0 fst-italic text-truncate" id="replyQuote" style="color: var(--text-main);">...</p>
                    </div>
                    <div class="mb-3">
                        <label class="form-label small fw-bold text-muted text-uppercase">Balasan Anda</label>
                        <textarea name="message" class="form-control rounded-4 p-3" rows="5" placeholder="Tulis balasan..." required autofocus></textarea>
                    </div>
                </div>
                <div class="modal-footer border-0 pt-0 px-4 pb-4">
                    <button type="button" class="btn btn-outline-secondary btn-pill px-4" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-primary btn-pill px-5 fw-bold shadow-sm">Kirim Balasan <i class="bi bi-send ms-1"></i></button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    function toggleReceiver() {
        const isBroadcast = document.getElementById('broadcastSwitch').checked;
        const container = document.getElementById('receiverContainer');
        const select = document.getElementById('receiverSelect');
        if (isBroadcast) {
            container.style.opacity = '0.5';
            container.style.pointerEvents = 'none';
            select.removeAttribute('required');
            select.value = ""; 
        } else {
            container.style.opacity = '1';
            container.style.pointerEvents = 'auto';
            select.setAttribute('required', 'required');
        }
    }

    function showFullMessage(sender, time, message) {
        document.getElementById('readMoreSender').innerText = sender;
        document.getElementById('readMoreTime').innerText = time;
        document.getElementById('readMoreContent').innerText = message;
        var myModal = new bootstrap.Modal(document.getElementById('modalReadMore'));
        myModal.show();
    }

    function openReplyModal(senderId, senderName, messagePreview) {
        document.getElementById('replyReceiverId').value = senderId;
        document.getElementById('replyToName').innerText = senderName;
        document.getElementById('replyQuote').innerText = '"' + messagePreview.substring(0, 80) + (messagePreview.length > 80 ? '...' : '') + '"';
        var myModal = new bootstrap.Modal(document.getElementById('modalReply'));
        myModal.show();
    }
</script>
@endsection