<?php $__env->startSection('title', 'FamilyTree · Dashboard'); ?>
<?php $__env->startSection('page-title', 'Activity Feed'); ?>

<?php $__env->startSection('sidebar-left'); ?>
    <section class="glass-card rounded-2xl shadow-card p-6 border border-white/60">
        <div class="flex items-center gap-4">
            <img src="<?php echo e($user['avatar']); ?>" alt="Profile" class="h-16 w-16 rounded-xl object-cover">
            <div>
                <p class="text-sm text-slate-500"><?php echo e($user['role']); ?></p>
                <h2 class="text-lg font-semibold text-ink"><?php echo e($user['name']); ?></h2>
            </div>
        </div>
        <div class="mt-6 grid grid-cols-2 gap-4 text-center">
            <div class="rounded-xl bg-white/70 px-3 py-2">
                <p class="text-xs uppercase tracking-wider text-slate-400">Following</p>
                <p class="text-xl font-semibold text-ink"><?php echo e($user['following']); ?></p>
            </div>
            <div class="rounded-xl bg-white/70 px-3 py-2">
                <p class="text-xs uppercase tracking-wider text-slate-400">Followers</p>
                <p class="text-xl font-semibold text-ink"><?php echo e($user['followers']); ?></p>
            </div>
        </div>
        <div class="mt-6">
            <h3 class="text-sm font-semibold text-slate-500 mb-3">Family Spaces</h3>
            <div class="space-y-3">
                <?php $__empty_1 = true; $__currentLoopData = $families; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $family): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                    <article class="flex gap-3">
                        <img src="<?php echo e($family['cover']); ?>" alt="<?php echo e($family['name']); ?>" class="h-14 w-14 rounded-lg object-cover">
                        <div>
                            <p class="text-sm font-semibold text-ink"><?php echo e($family['name']); ?></p>
                            <p class="text-xs text-slate-500"><?php echo e($family['members']); ?> members</p>
                        </div>
                    </article>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                    <div>
                        <p class="text-sm text-slate-400 mb-3">Create your first family space to start documenting shared history.</p>
                        <a href="<?php echo e(route('families.create')); ?>" class="inline-flex items-center gap-2 bg-primary text-white px-3 py-2 rounded-xl text-sm">
                            <span class="material-symbols-rounded text-base">diversity_3</span>
                            Create family
                        </a>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </section>

    <section class="glass-card rounded-2xl shadow-card p-6 border border-white/60">
        <div class="flex items-center justify-between">
            <h3 class="text-sm font-semibold text-ink">People you may know</h3>
            <button type="button" class="text-xs text-primary font-medium" aria-label="View all connection suggestions">View all</button>
        </div>
        <div class="mt-5 space-y-4">
            <?php $__empty_1 = true; $__currentLoopData = $suggestions; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $person): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                <div class="flex items-center justify-between gap-3">
                    <div class="flex items-center gap-3">
                        <img src="<?php echo e($person['avatar']); ?>" alt="<?php echo e($person['name']); ?>" class="h-10 w-10 rounded-full object-cover">
                        <div>
                            <p class="text-sm font-medium text-ink"><?php echo e($person['name']); ?></p>
                            <p class="text-xs text-slate-500"><?php echo e($person['relationship']); ?></p>
                        </div>
                    </div>
                    <?php ($relUrl = !empty($postFamilyId) ? (route('families.relationships.manage.index', $postFamilyId) . '?related_person_id=' . $person['id']) : route('families.index')); ?>
                    <a href="<?php echo e($relUrl); ?>" class="text-xs font-semibold text-accent">Connect</a>
                </div>
            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                <p class="text-sm text-slate-400">Check back soon to discover new family connections.</p>
            <?php endif; ?>
        </div>
    </section>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('content'); ?>
    <?php if(auth()->guard()->check()): ?>
    <section class="glass-card rounded-2xl shadow-card border border-white/60 p-6">
        <form id="postComposer" class="space-y-3" onsubmit="return false;">
            <div class="flex items-start gap-3">
                <img src="<?php echo e($user['avatar']); ?>" alt="Avatar" class="h-10 w-10 rounded-full object-cover">
                <div class="flex-1 relative">
                    <textarea id="composerText" rows="3" placeholder="Share what's on your mind, <?php echo e(explode(' ', $user['name'])[0]); ?>..." class="w-full rounded-xl border border-slate-200 bg-white/80 px-4 py-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/50"></textarea>
                    <input type="hidden" id="composerFamilyId" value="<?php echo e($postFamilyId); ?>">
                    <div id="mentionResults" class="absolute left-0 right-0 top-full mt-1 bg-white border border-slate-200 rounded-xl shadow hidden max-h-64 overflow-auto z-20"></div>
                    <div id="locationBadge" class="mt-2 text-xs text-slate-500"></div>
                </div>
            </div>
            <div class="flex items-center justify-between">
                <div class="flex items-center gap-1 text-slate-500">
                    <label class="p-2 rounded-lg hover:bg-primary/10 text-primary cursor-pointer" aria-label="Add photo or video">
                        <input id="composerFiles" type="file" multiple class="hidden" accept="image/*,video/*">
                        <span class="material-symbols-rounded">image</span>
                    </label>
                    <button type="button" id="composerTag" class="p-2 rounded-lg hover:bg-slate-100" title="Tag people"><span class="material-symbols-rounded">person_add</span></button>
                    <button type="button" id="composerEmoji" class="p-2 rounded-lg hover:bg-slate-100" title="Add emoji"><span class="material-symbols-rounded">mood</span></button>
                    <button type="button" id="composerLocation" class="p-2 rounded-lg hover:bg-slate-100" title="Add location"><span class="material-symbols-rounded">location_on</span></button>
                    <button type="button" id="composerGif" class="p-2 rounded-lg hover:bg-slate-100" title="Add GIF"><span class="material-symbols-rounded">gif</span></button>
                </div>
                <div>
                    <button type="button" id="composerSubmit" class="px-4 py-2 rounded-xl bg-primary text-white text-sm font-medium">Post</button>
                </div>
            </div>
            <div id="uploadPreview" class="grid grid-cols-3 gap-2"></div>
        </form>
    </section>
    <?php endif; ?>

    <div class="space-y-6">
        <?php $__empty_1 = true; $__currentLoopData = $feed; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $item): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
            <article class="glass-card rounded-2xl shadow-card border border-white/60 overflow-hidden">
                <header class="p-6 flex items-start gap-3">
                    <img src="<?php echo e($item['avatar']); ?>" alt="<?php echo e($item['author']); ?>" class="h-12 w-12 rounded-xl object-cover">
                    <div class="flex-1">
                        <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between">
                            <div>
                                <p class="font-semibold text-ink"><?php echo e($item['author']); ?></p>
                                <p class="text-xs text-slate-500 flex items-center gap-2">
                                    <?php echo e($item['time']); ?> · <?php echo e($item['privacy']); ?>

                                </p>
                            </div>
                            <button class="text-slate-400 hover:text-primary" aria-label="More options">
                                <span class="material-symbols-rounded">more_horiz</span>
                            </button>
                        </div>
                        <p class="mt-3 text-sm text-slate-600 leading-relaxed"><?php echo e($item['content']); ?></p>
                    </div>
                </header>

                <?php if(!empty($item['media_list'])): ?>
                    <div class="px-6 pb-4 grid sm:grid-cols-2 gap-3">
                        <?php $__currentLoopData = $item['media_list']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $m): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <?php if(($m['type'] ?? '') === 'image'): ?>
                                <img src="<?php echo e($m['url'] ?? ''); ?>" alt="Media" class="w-full max-h-[360px] object-cover rounded-lg">
                            <?php elseif(($m['type'] ?? '') === 'video'): ?>
                                <video src="<?php echo e($m['url'] ?? ''); ?>" controls class="w-full rounded-lg"></video>
                            <?php else: ?>
                                <a href="<?php echo e($m['url'] ?? ''); ?>" class="text-sm text-primary underline" target="_blank" rel="noopener"><?php echo e($m['name'] ?? 'File'); ?></a>
                            <?php endif; ?>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </div>
                <?php endif; ?>

                <footer class="px-6 py-4 border-t border-white/70">
                    <div class="flex flex-wrap items-center justify-between gap-4 text-sm text-slate-500">
                        <div class="flex items-center gap-3">
                            <span class="flex items-center gap-1 text-primary"><span class="material-symbols-rounded text-base">favorite</span><?php echo e($item['likes']); ?></span>
                            <span class="flex items-center gap-1 text-accent"><span class="material-symbols-rounded text-base">forum</span><?php echo e($item['comments']); ?></span>
                            <span class="flex items-center gap-2">
                                <?php $__currentLoopData = $item['reactions']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $emoji): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <span class="text-lg"><?php echo e($emoji); ?></span>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </span>
                        </div>
                        <div class="flex items-center gap-3 text-slate-400">
                            <button class="hover:text-primary flex items-center gap-1" data-action="like" data-post-id="<?php echo e($item['id']); ?>" data-family-id="<?php echo e($item['family_id']); ?>"><span class="material-symbols-rounded text-base">thumb_up</span>Like</button>
                            <button class="hover:text-primary flex items-center gap-1" data-action="comment-toggle" data-post-id="<?php echo e($item['id']); ?>" data-family-id="<?php echo e($item['family_id']); ?>"><span class="material-symbols-rounded text-base">chat</span>Comment</button>
                            <button class="hover:text-primary flex items-center gap-1" data-action="share" data-post-id="<?php echo e($item['id']); ?>"><span class="material-symbols-rounded text-base">share</span>Share</button>
                        </div>
                    </div>
                </footer>
                <div id="comments-<?php echo e($item['id']); ?>" class="hidden border-t border-slate-100 px-6 py-4">
                    <div class="space-y-3" data-role="comments-list"></div>
                    <?php if(auth()->guard()->check()): ?>
                    <div class="mt-3 flex items-center gap-2">
                        <input type="text" class="flex-1 rounded-xl border border-slate-200 px-3 py-2 text-sm" placeholder="Write a comment…" data-role="comment-input">
                        <button class="px-3 py-2 rounded-xl bg-primary text-white text-sm" data-action="comment-submit" data-post-id="<?php echo e($item['id']); ?>" data-family-id="<?php echo e($item['family_id']); ?>">Send</button>
                    </div>
                    <?php endif; ?>
                </div>
            </article>
        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
            <article class="glass-card rounded-2xl shadow-card border border-white/60 p-6 text-center text-sm text-slate-500">
                <p>No activity yet. Start a post or invite family members to see shared moments here.</p>
            </article>
        <?php endif; ?>
    </div>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('sidebar-right'); ?>
    <section class="glass-card rounded-2xl shadow-card p-6 border border-white/60">
        <div class="flex items-center justify-between mb-4">
            <h3 class="text-sm font-semibold text-ink">Complete your profile</h3>
            <a href="<?php echo e(route('settings')); ?>#profile" class="text-xs text-primary font-medium">Open Settings</a>
        </div>
        <div class="flex items-center gap-4">
            <div class="relative h-20 w-20">
                <svg viewBox="0 0 36 36" class="h-full w-full">
                    <path class="text-slate-200" stroke-width="3.5" stroke="currentColor" fill="transparent" stroke-linecap="round"
                          d="M18 2.5a15.5 15.5 0 1 1 0 31 15.5 15.5 0 0 1 0-31" />
                    <path class="text-primary" stroke-width="3.5" stroke="currentColor" fill="transparent" stroke-linecap="round"
                          stroke-dasharray="<?php echo e($user['completion']); ?>, 100" d="M18 2.5a15.5 15.5 0 1 1 0 31 15.5 15.5 0 0 1 0-31" />
                </svg>
                <span class="absolute inset-0 flex items-center justify-center text-lg font-semibold text-ink"><?php echo e($user['completion']); ?>%</span>
            </div>
            <div class="flex-1 space-y-3">
                <?php $__currentLoopData = $user['completion_breakdown']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $step): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    <a href="<?php echo e(route('settings')); ?>#profile" class="block group">
                        <p class="text-xs font-medium text-slate-500 group-hover:text-primary"><?php echo e($step['label']); ?></p>
                        <div class="mt-1 h-2 rounded-full bg-slate-100">
                            <div class="h-full rounded-full bg-primary" style="width: <?php echo e(round(($step['completed'] / max(1, ($step['total'] ?? 1))) * 100)); ?>%"></div>
                        </div>
                    </a>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            </div>
        </div>
    </section>

    <?php if(!empty($canSeeOps)): ?>
        <section class="glass-card rounded-2xl shadow-card p-6 border border-white/60">
            <h3 class="text-sm font-semibold text-ink mb-4">Operations snapshot</h3>
            <div class="space-y-4">
                <?php $__empty_1 = true; $__currentLoopData = $metrics; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $metric): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm font-medium text-ink"><?php echo e($metric['label']); ?></p>
                            <p class="text-xs text-slate-500">vs last month</p>
                        </div>
                        <div class="text-right">
                            <p class="text-lg font-semibold text-ink"><?php echo e($metric['value']); ?></p>
                            <p class="text-xs font-semibold text-emerald-500"><?php echo e($metric['change']); ?></p>
                        </div>
                    </div>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                    <p class="text-sm text-slate-400">Analytics will appear here after the first week of activity.</p>
                <?php endif; ?>
            </div>
        </section>
    <?php endif; ?>

    <section class="glass-card rounded-2xl shadow-card p-6 border border-white/60">
        <h3 class="text-sm font-semibold text-ink mb-4">Latest platform activity</h3>
        <ul class="space-y-3 text-sm text-slate-600">
            <?php $__empty_1 = true; $__currentLoopData = $timeline; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $event): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                <li class="flex items-center gap-3">
                    <span class="h-10 w-10 rounded-full bg-primary/10 text-primary flex items-center justify-center">
                        <span class="material-symbols-rounded"><?php echo e($event['icon']); ?></span>
                    </span>
                    <div>
                        <p class="font-medium text-ink"><?php echo e($event['label']); ?></p>
                        <p class="text-xs text-slate-500"><?php echo e($event['time']); ?></p>
                    </div>
                </li>
            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                <li class="text-sm text-slate-400">Once families start engaging, the latest highlights will appear here.</li>
            <?php endif; ?>
        </ul>
    </section>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('head'); ?>
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Rounded:opsz,wght,FILL,GRAD@24,400,0,0" />
<?php $__env->stopPush(); ?>

<?php $__env->startPush('scripts'); ?>
<script>
document.addEventListener('DOMContentLoaded', function(){
    var csrf = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
    var txt = document.getElementById('composerText');
    var files = document.getElementById('composerFiles');
    var preview = document.getElementById('uploadPreview');
    var submit = document.getElementById('composerSubmit');
    var familyIdInput = document.getElementById('composerFamilyId');
    var tagBtn = document.getElementById('composerTag');
    var emojiBtn = document.getElementById('composerEmoji');
    var gifBtn = document.getElementById('composerGif');
    var locBtn = document.getElementById('composerLocation');
    var mentionBox = document.getElementById('mentionResults');
    var locationBadge = document.getElementById('locationBadge');
    var uploadedMedia = [];
    var uploadingCount = 0;
    var composerMentions = [];
    var composerLocation = null;

    function renderPreview(){
        if (!preview) return;
        var html = '';
        if (uploadedMedia.length){
            html += uploadedMedia.map(function(f){
            if (f.type === 'image') {
                return '<img src="'+ encodeURI(f.url) +'" alt="upload" class="w-full h-24 object-cover rounded-lg">';
            } else if (f.type === 'video') {
                return '<video src="'+ encodeURI(f.url) +'" class="w-full h-24 object-cover rounded-lg" controls muted></video>';
            }
            return '<div class="h-24 rounded-lg bg-slate-100 flex items-center justify-center text-xs text-slate-500">'+ (f.name || 'file') +'</div>';
            }).join('');
        }
        if (uploadingCount > 0) {
            html += '<div class="h-24 rounded-lg bg-slate-50 border border-dashed border-slate-300 flex items-center justify-center text-xs text-slate-500">Uploading…</div>';
        }
        preview.innerHTML = html;
    }

    if (files) {
        files.addEventListener('change', function(){
            if (!files.files || !files.files.length) return;
            var selectedCount = files.files.length;
            uploadingCount += selectedCount;
            renderPreview();
            var fd = new FormData();
            Array.prototype.forEach.call(files.files, function(file){
                fd.append('files[]', file);
            });
            fetch('<?php echo e(url('/uploads')); ?>', {
                method: 'POST',
                headers: { 'X-CSRF-TOKEN': csrf, 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json' },
                credentials: 'same-origin',
                body: fd
            })
            .then(function(r){ if (!r.ok) throw new Error('Upload failed'); return r.json(); })
            .then(function(data){
                if (data && Array.isArray(data.files)) {
                    uploadedMedia = uploadedMedia.concat(data.files.map(function(f){ return { type: f.type, url: f.url, name: f.name, mime: f.mime }; }));
                }
            })
            .catch(function(err){ alert('Could not upload files. Please try again.'); })
            .finally(function(){ files.value = ''; uploadingCount = Math.max(0, uploadingCount - selectedCount); renderPreview(); });
        });
    }

    if (submit) {
        submit.addEventListener('click', function(){
            var familyId = familyIdInput ? familyIdInput.value : '';
            var content = txt ? (txt.value || '').trim() : '';
            if (!familyId) { alert('Select a family to post to.'); return; }
            if (!content && uploadedMedia.length === 0) { alert('Write something or add media.'); return; }

            submit.disabled = true; submit.classList.add('opacity-60');
            var payload = { content: content, media: uploadedMedia, meta: { mentions: composerMentions, location: composerLocation } };
            function resolveMentionsFromText(text){
                var tokens = (text.match(/@([A-Za-z][A-Za-z0-9_\- ]{0,40})/g) || []).map(function(t){ return t.slice(1).trim(); });
                var unique = Array.from(new Set(tokens)).filter(Boolean);
                if (!unique.length) return Promise.resolve([]);
                return Promise.all(unique.map(function(name){
                    var url = new URL(window.location.origin + '/people/search');
                    url.searchParams.set('q', name);
                    if (familyId) url.searchParams.set('family_id', familyId);
                    return fetch(url.toString(), { headers: { 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json' }})
                        .then(function(r){ return r.json(); })
                        .then(function(list){
                            var exact = (list || []).find(function(i){ return (i.name||'').toLowerCase() === name.toLowerCase(); });
                            return exact ? exact.id : null;
                        })
                        .catch(function(){ return null; });
                })).then(function(ids){ return ids.filter(function(id){ return id !== null; }); });
            }

            resolveMentionsFromText(content).then(function(autoIds){
                var allMentions = Array.from(new Set([].concat(composerMentions, autoIds).filter(Boolean)));
                var payload = { content: content, media: uploadedMedia, meta: { mentions: allMentions, location: composerLocation } };
                return fetch('/families/' + encodeURIComponent(familyId) + '/posts', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': csrf,
                    'X-Requested-With': 'XMLHttpRequest',
                    'Accept': 'application/json'
                },
                credentials: 'same-origin',
                body: JSON.stringify(payload)
            });
            })
            .then(function(r){ if (!r.ok) throw new Error('Failed to post'); return r.json(); })
            .then(function(){
                // Reset and reload feed
                if (txt) txt.value = '';
                uploadedMedia = []; renderPreview();
                composerMentions = [];
                composerLocation = null; if (locationBadge) locationBadge.textContent = '';
                location.reload();
            })
            .catch(function(){ alert('Unable to create post. Please try again.'); })
            .finally(function(){ submit.disabled = false; submit.classList.remove('opacity-60'); });
        });
    }

    // Mentions: inline @ search limited to selected family
    function uniquePush(arr, val){ if (arr.indexOf(val) === -1) arr.push(val); }
    function openMentionBox(list, atPos){
        if (!mentionBox) return;
        if (!list.length){ mentionBox.classList.add('hidden'); mentionBox.innerHTML = ''; return; }
        var html = list.map(function(u){
            return '<button type="button" class="w-full text-left flex items-center gap-2 px-3 py-2 hover:bg-slate-50" data-id="'+u.id+'" data-name="'+escapeHtml(u.name)+'" data-avatar="'+(u.avatar||'')+'">\
                <img src="'+ (u.avatar||'') +'" class="h-7 w-7 rounded-full object-cover" alt="">\
                <span class="text-sm">'+ escapeHtml(u.name) +'</span>\
            </button>';
        }).join('');
        mentionBox.innerHTML = html;
        mentionBox.classList.remove('hidden');
        // Click handler
        mentionBox.querySelectorAll('button').forEach(function(btn){
            btn.addEventListener('click', function(){
                var name = this.getAttribute('data-name');
                var id = this.getAttribute('data-id');
                insertMention(atPos, '@'+name+' ');
                uniquePush(composerMentions, parseInt(id));
                mentionBox.classList.add('hidden');
                mentionBox.innerHTML = '';
                txt.focus();
            });
        });
    }
    function insertMention(atIndex, textToInsert){
        var start = txt.selectionStart;
        var end = txt.selectionEnd;
        // replace from atIndex to current caret with mention text
        var before = txt.value.slice(0, atIndex);
        var after = txt.value.slice(end);
        txt.value = before + textToInsert + after;
        var newPos = (before + textToInsert).length;
        txt.setSelectionRange(newPos, newPos);
    }
    function escapeHtml(str){
        return String(str)
            .replaceAll('&','&amp;')
            .replaceAll('<','&lt;')
            .replaceAll('>','&gt;')
            .replaceAll('"','&quot;')
            .replaceAll("'",'&#39;');
    }
    function fetchPeople(q){
        var familyId = familyIdInput ? familyIdInput.value : '';
        var url = new URL(window.location.origin + '/people/search');
        url.searchParams.set('q', q);
        if (familyId) url.searchParams.set('family_id', familyId);
        return fetch(url.toString(), { headers: { 'X-Requested-With': 'XMLHttpRequest' }})
            .then(function(r){ return r.json(); });
    }
    var lastAtPos = -1;
    function handleMentionLookup(){
        var caret = txt.selectionStart;
        var upto = txt.value.slice(0, caret);
        var at = upto.lastIndexOf('@');
        if (at === -1 || (at > 0 && /\S/.test(upto[at-1]))) { mentionBox && mentionBox.classList.add('hidden'); return; }
        var query = upto.slice(at+1);
        if (query.length < 1) { mentionBox && mentionBox.classList.add('hidden'); return; }
        lastAtPos = at;
        fetchPeople(query).then(function(list){ openMentionBox(list, at); });
    }
    if (txt) {
        txt.addEventListener('keyup', handleMentionLookup);
        txt.addEventListener('input', handleMentionLookup);
    }
    document.addEventListener('click', function(e){ if (mentionBox && !mentionBox.contains(e.target) && e.target !== txt) { mentionBox.classList.add('hidden'); } });
    if (tagBtn) {
        tagBtn.addEventListener('click', function(){
            if (!txt) return;
            txt.focus();
            // insert '@' at caret
            var start = txt.selectionStart, end = txt.selectionEnd;
            txt.setRangeText('@', start, end, 'end');
        });
    }

    // Emoji picker (lightweight):
    var emojiSet = ['😀','😂','😍','👍','🙏','🎉','😢','🔥','💯','👏'];
    var emojiMenu;
    function ensureEmojiMenu(){
        if (emojiMenu) return emojiMenu;
        emojiMenu = document.createElement('div');
        emojiMenu.className = 'absolute mt-1 bg-white border border-slate-200 rounded-xl shadow z-20 p-2 grid grid-cols-5 gap-1';
        emojiSet.forEach(function(em){
            var b = document.createElement('button');
            b.type = 'button'; b.className = 'text-xl p-1 hover:bg-slate-50 rounded'; b.textContent = em;
            b.addEventListener('click', function(){
                if (!txt) return;
                var s = txt.selectionStart, e = txt.selectionEnd;
                txt.setRangeText(em, s, e, 'end');
                emojiMenu.classList.add('hidden');
                txt.focus();
            });
            emojiMenu.appendChild(b);
        });
        (txt.parentElement || document.body).appendChild(emojiMenu);
        return emojiMenu;
    }
    if (emojiBtn) {
        emojiBtn.addEventListener('click', function(){
            var menu = ensureEmojiMenu();
            menu.style.left = '0px';
            menu.style.top = '100%';
            menu.classList.toggle('hidden');
        });
        document.addEventListener('click', function(e){ if (emojiMenu && !emojiMenu.contains(e.target) && e.target !== emojiBtn) emojiMenu.classList.add('hidden'); });
    }

    // GIF: quick add by URL (temporary lightweight picker)
    if (gifBtn) {
        gifBtn.addEventListener('click', function(){
            var url = prompt('Paste GIF image URL');
            if (!url) return;
            uploadedMedia.push({ type: 'image', url: url, name: 'GIF' });
            renderPreview();
        });
    }

    // Location: request geolocation and attach to meta
    if (locBtn) {
        locBtn.addEventListener('click', function(){
            if (!navigator.geolocation || (!window.isSecureContext && location.hostname !== 'localhost' && location.hostname !== '127.0.0.1')) { alert('Geolocation requires HTTPS or localhost.'); return; }
            locBtn.disabled = true;
            navigator.geolocation.getCurrentPosition(function(pos){
                composerLocation = { lat: pos.coords.latitude, lon: pos.coords.longitude, accuracy: pos.coords.accuracy };
                if (locationBadge) locationBadge.textContent = 'Location attached ('+composerLocation.lat.toFixed(4)+', '+composerLocation.lon.toFixed(4)+')';
                locBtn.disabled = false;
            }, function(){ locBtn.disabled = false; alert('Unable to fetch location'); }, { maximumAge: 600000, timeout: 7000 });
        });
    }
});
</script>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('layouts.app', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH C:\xampp\htdocs\familytree\api\resources\views/dashboard.blade.php ENDPATH**/ ?>