@extends('layouts.app')

@section('title', 'Family Tree · FamilyTree')
@section('page-title', 'Family Tree')

@section('content')
    <section class="space-y-6">
        <div class="glass-card rounded-2xl border border-white/60 shadow-card p-6 print:hidden">
            <div class="flex flex-col md:flex-row md:items-end gap-4 md:justify-between">
                <div>
                    <h2 class="text-base font-semibold text-slate-800">{{ $family->name }}</h2>
                    <p class="text-xs text-slate-500">Center the tree on a person</p>
                </div>
                <div class="flex items-end gap-3">
                    <div>
                        <label class="block text-xs text-slate-500">Centered person</label>
                        <select id="centerPerson" class="rounded-xl border-slate-200">
                            <option value="">— Select member —</option>
                            @foreach($members as $m)
                                <option value="{{ $m['id'] }}" @selected((int)($center?->id ?? 0) === (int)$m['id'])>{{ $m['name'] }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div>
                        <label class="block text-xs text-slate-500">Depth (generations)</label>
                        <select id="depthSelect" class="rounded-xl border-slate-200">
                            @for($i=1; $i<=5; $i++)
                                <option value="{{ $i }}" @selected((int)($depth ?? 2) === $i)>{{ $i }}</option>
                            @endfor
                        </select>
                    </div>
                    <button id="printBtn" class="inline-flex items-center gap-1 text-sm bg-slate-100 text-slate-700 px-3 py-2 rounded-xl hover:bg-slate-200">
                        <span class="material-symbols-rounded text-base">print</span>
                        Print
                    </button>
                    <button id="exportBtn" class="inline-flex items-center gap-1 text-sm bg-slate-100 text-slate-700 px-3 py-2 rounded-xl hover:bg-slate-200">
                        <span class="material-symbols-rounded text-base">download</span>
                        Export PNG
                    </button>
                    @if(!empty($canManage))
                        <a href="{{ route('families.relationships.manage.index', $family) }}" class="inline-flex items-center gap-1 text-sm bg-slate-100 text-slate-700 px-3 py-2 rounded-xl hover:bg-slate-200">
                            <span class="material-symbols-rounded text-base">link</span>
                            Manage Relationships
                        </a>
                    @endif
                    <a href="{{ route('families.index') }}" class="inline-flex items-center gap-1 text-sm bg-slate-100 text-slate-700 px-3 py-2 rounded-xl hover:bg-slate-200">
                        <span class="material-symbols-rounded text-base">chevron_left</span>
                        Back to directory
                    </a>
                </div>
            </div>
        </div>

        @if(!$center)
            <div class="rounded-2xl border border-slate-100 bg-white p-10 text-center text-slate-500">
                <p class="mb-3">No members found in this family yet.</p>
                <p class="text-xs">Add members and relationships to visualize the family tree.</p>
            </div>
        @else
            <div id="treeContainer" class="grid grid-cols-1 gap-6">
                @if(!empty($ancestors))
                    <div class="rounded-2xl border border-slate-100 bg-white p-6">
                        <h3 class="text-sm font-semibold text-slate-700 mb-3">Ancestors (up to {{ $depth }} generations)</h3>
                        @forelse($ancestors as $levelIndex => $level)
                            <div class="mb-3">
                                <div class="text-xs text-slate-500 mb-2">Generation {{ $levelIndex + 1 }}</div>
                                <div class="flex flex-wrap gap-3">
                                    @forelse($level as $p)
                                        @php($name = trim(($p->first_name ?? '').' '.($p->last_name ?? '')) ?: 'Ancestor')
                                        <div class="flex items-center gap-3 px-3 py-2 rounded-xl border border-slate-200">
                                            <img src="{{ $p->photo_url ?: 'https://ui-avatars.com/api/?name='.urlencode($name) }}" alt="{{ $name }}" class="h-8 w-8 rounded-full object-cover">
                                            <div class="text-sm text-slate-700">{{ $name }}</div>
                                            <button type="button" data-center-person="{{ $p->id }}" class="ml-2 text-xs px-2 py-1 rounded-lg bg-slate-100 text-slate-700 hover:bg-slate-200">Center</button>
                                        </div>
                                    @empty
                                        <p class="text-sm text-slate-400">— None</p>
                                    @endforelse
                                </div>
                            </div>
                        @empty
                            <p class="text-sm text-slate-400">— None</p>
                        @endforelse
                    </div>
                @endif
                <div class="rounded-2xl border border-slate-100 bg-white p-6">
                    <h3 class="text-sm font-semibold text-slate-700 mb-3">Parents</h3>
                    <div class="flex flex-wrap gap-3">
                        @forelse($parents as $p)
                            @php($name = trim(($p->first_name ?? '').' '.($p->last_name ?? '')) ?: 'Parent')
                            <div class="flex items-center gap-3 px-3 py-2 rounded-xl border border-slate-200">
                                <img src="{{ $p->photo_url ?: 'https://ui-avatars.com/api/?name='.urlencode($name) }}" alt="{{ $name }}" class="h-10 w-10 rounded-full object-cover">
                                <div class="text-sm text-slate-700">{{ $name }}</div>
                                <button type="button" data-center-person="{{ $p->id }}" class="ml-2 text-xs px-2 py-1 rounded-lg bg-slate-100 text-slate-700 hover:bg-slate-200">Center</button>
                            </div>
                        @empty
                            <p class="text-sm text-slate-400">— None listed</p>
                        @endforelse
                    </div>
                </div>

                <div class="rounded-2xl border border-slate-100 bg-white p-6">
                    <h3 class="text-sm font-semibold text-slate-700 mb-4">Centered person</h3>
                    @php($cname = trim(($center->first_name ?? '').' '.($center->last_name ?? '')) ?: 'Member')
                    <div class="flex items-center gap-4">
                        <img src="{{ $center->photo_url ?: 'https://ui-avatars.com/api/?name='.urlencode($cname) }}" alt="{{ $cname }}" class="h-16 w-16 rounded-full object-cover">
                        <div>
                            <div class="text-base font-semibold text-slate-800">{{ $cname }}</div>
                            @if((int)($family->head_person_id ?? 0) === (int)$center->id)
                                <div class="inline-flex items-center gap-1 text-xs bg-primary/10 text-primary px-2 py-0.5 rounded-full mt-1">
                                    <span class="material-symbols-rounded text-sm">military_tech</span>
                                    Head of family
                                </div>
                            @endif
                        </div>
                    </div>
                </div>

                <div class="rounded-2xl border border-slate-100 bg-white p-6">
                    <h3 class="text-sm font-semibold text-slate-700 mb-3">Spouse(s)</h3>
                    <div class="flex flex-wrap gap-3">
                        @forelse($spouses as $p)
                            @php($name = trim(($p->first_name ?? '').' '.($p->last_name ?? '')) ?: 'Spouse')
                            <div class="flex items-center gap-3 px-3 py-2 rounded-xl border border-slate-200">
                                <img src="{{ $p->photo_url ?: 'https://ui-avatars.com/api/?name='.urlencode($name) }}" alt="{{ $name }}" class="h-10 w-10 rounded-full object-cover">
                                <div class="text-sm text-slate-700">{{ $name }}</div>
                                <button type="button" data-center-person="{{ $p->id }}" class="ml-2 text-xs px-2 py-1 rounded-lg bg-slate-100 text-slate-700 hover:bg-slate-200">Center</button>
                            </div>
                        @empty
                            <p class="text-sm text-slate-400">— None listed</p>
                        @endforelse
                    </div>
                </div>

                <div class="rounded-2xl border border-slate-100 bg-white p-6">
                    <h3 class="text-sm font-semibold text-slate-700 mb-3">Children</h3>
                    <div class="flex flex-wrap gap-3">
                        @forelse($children as $p)
                            @php($name = trim(($p->first_name ?? '').' '.($p->last_name ?? '')) ?: 'Child')
                            <div class="flex items-center gap-3 px-3 py-2 rounded-xl border border-slate-200">
                                <img src="{{ $p->photo_url ?: 'https://ui-avatars.com/api/?name='.urlencode($name) }}" alt="{{ $name }}" class="h-10 w-10 rounded-full object-cover">
                                <div class="text-sm text-slate-700">{{ $name }}</div>
                                <button type="button" data-center-person="{{ $p->id }}" class="ml-2 text-xs px-2 py-1 rounded-lg bg-slate-100 text-slate-700 hover:bg-slate-200">Center</button>
                            </div>
                        @empty
                            <p class="text-sm text-slate-400">— None listed</p>
                        @endforelse
                    </div>
                </div>

                <div class="rounded-2xl border border-slate-100 bg-white p-6">
                    <h3 class="text-sm font-semibold text-slate-700 mb-3">Siblings</h3>
                    <div class="flex flex-wrap gap-3">
                        @forelse($siblings as $p)
                            @php($name = trim(($p->first_name ?? '').' '.($p->last_name ?? '')) ?: 'Sibling')
                            <div class="flex items-center gap-3 px-3 py-2 rounded-xl border border-slate-200">
                                <img src="{{ $p->photo_url ?: 'https://ui-avatars.com/api/?name='.urlencode($name) }}" alt="{{ $name }}" class="h-10 w-10 rounded-full object-cover">
                                <div class="text-sm text-slate-700">{{ $name }}</div>
                                <button type="button" data-center-person="{{ $p->id }}" class="ml-2 text-xs px-2 py-1 rounded-lg bg-slate-100 text-slate-700 hover:bg-slate-200">Center</button>
                            </div>
                        @empty
                            <p class="text-sm text-slate-400">— None listed</p>
                        @endforelse
                    </div>
                </div>
                @if(!empty($descendants))
                    <div class="rounded-2xl border border-slate-100 bg-white p-6">
                        <h3 class="text-sm font-semibold text-slate-700 mb-3">Descendants (up to {{ $depth }} generations)</h3>
                        @forelse($descendants as $levelIndex => $level)
                            <div class="mb-3">
                                <div class="text-xs text-slate-500 mb-2">Generation {{ $levelIndex + 1 }}</div>
                                <div class="flex flex-wrap gap-3">
                                    @forelse($level as $p)
                                        @php($name = trim(($p->first_name ?? '').' '.($p->last_name ?? '')) ?: 'Descendant')
                                        <div class="flex items-center gap-3 px-3 py-2 rounded-xl border border-slate-200">
                                            <img src="{{ $p->photo_url ?: 'https://ui-avatars.com/api/?name='.urlencode($name) }}" alt="{{ $name }}" class="h-8 w-8 rounded-full object-cover">
                                            <div class="text-sm text-slate-700">{{ $name }}</div>
                                            <button type="button" data-center-person="{{ $p->id }}" class="ml-2 text-xs px-2 py-1 rounded-lg bg-slate-100 text-slate-700 hover:bg-slate-200">Center</button>
                                        </div>
                                    @empty
                                        <p class="text-sm text-slate-400">— None</p>
                                    @endforelse
                                </div>
                            </div>
                        @empty
                            <p class="text-sm text-slate-400">— None</p>
                        @endforelse
                    </div>
                @endif
            </div>
        @endif
    </section>
@endsection

@push('head')
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Rounded:opsz,wght,FILL,GRAD@24,400,0,0" />
    <style>
        @media print {
            .print\:hidden { display: none !important; }
            .glass-card, .shadow-card { box-shadow: none !important; }
            a[href]:after { content: '' !important; }
            body { background: #ffffff !important; }
        }
    </style>
@endpush

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js"></script>
<script>
    // Change centered person via selector
    const centerEl = document.getElementById('centerPerson');
    if (centerEl) {
        centerEl.addEventListener('change', function(){
            const id = centerEl.value || '';
            const url = new URL(window.location.href);
            if (id) { url.searchParams.set('person_id', id); } else { url.searchParams.delete('person_id'); }
            window.location.href = url.toString();
        });
    }

    // Change depth (generations)
    const depthEl = document.getElementById('depthSelect');
    if (depthEl) {
        depthEl.addEventListener('change', function(){
            const url = new URL(window.location.href);
            url.searchParams.set('depth', depthEl.value);
            window.location.href = url.toString();
        });
    }

    // Re-center on any person via inline Center buttons
    document.querySelectorAll('[data-center-person]').forEach(btn => {
        btn.addEventListener('click', () => {
            const id = btn.getAttribute('data-center-person');
            const url = new URL(window.location.href);
            url.searchParams.set('person_id', id);
            window.location.href = url.toString();
        });
    });

    // Print current tree
    const printBtn = document.getElementById('printBtn');
    if (printBtn) {
        printBtn.addEventListener('click', () => window.print());
    }

    // Export current tree as PNG using html2canvas
    const exportBtn = document.getElementById('exportBtn');
    if (exportBtn) {
        exportBtn.addEventListener('click', async () => {
            const container = document.getElementById('treeContainer');
            if (!container) return;
            try {
                window.scrollTo(0,0);
                const canvas = await html2canvas(container, {backgroundColor: '#ffffff', scale: 2});
                const link = document.createElement('a');
                link.download = 'family-tree.png';
                link.href = canvas.toDataURL('image/png');
                link.click();
            } catch (e) {
                alert('Unable to export PNG at the moment.');
            }
        });
    }
</script>
@endpush
