<?php
$page_title = 'Tree of Life Directory | Herbal Wellness Care';
$page_description = 'Discover our wellness guardians through the sacred Baobab Tree of Life';
$page_content = function () { ?>

<section class="py-20 bg-gradient-to-br from-green-50 to-amber-50 min-h-screen">
    <div class="max-w-7xl mx-auto px-6">
        <!-- Header -->
        <div class="text-center mb-12">
            <h1 class="serif text-5xl md:text-6xl font-bold text-shining-green mb-6">The Baobab Tree of Life 🌳</h1>
            <p class="text-xl text-gray-700 max-w-3xl mx-auto mb-8">
                Our guardians are rooted in specialized fields of healing. Each branch represents a unique path of wisdom, 
                from ancestral knowledge in the roots to modern science in the leaves.
            </p>
            
            <!-- Search and Filters -->
            <div class="flex flex-wrap gap-4 justify-center mb-8">
                <input type="text" id="search-input" placeholder="Search coaches, specialties..." 
                       class="px-4 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent">
                <select id="specialty-filter" class="px-4 py-2 border border-gray-200 rounded-lg">
                    <option value="">All Specialties</option>
                </select>
                <select id="experience-filter" class="px-4 py-2 border border-gray-200 rounded-lg">
                    <option value="">Any Experience</option>
                </select>
                <select id="branch-filter" class="px-4 py-2 border border-gray-200 rounded-lg">
                    <option value="">All Branches</option>
                    <option value="roots">Roots (Ancestral)</option>
                    <option value="trunk">Trunk (Foundation)</option>
                    <option value="branches">Branches (Practice)</option>
                    <option value="leaves">Leaves (Modern)</option>
                    <option value="fruits">Fruits (Results)</option>
                </select>
                <button onclick="searchCoaches()" class="bg-shining-green text-white px-6 py-2 rounded-lg font-semibold hover:bg-green-700">
                    Search
                </button>
            </div>
        </div>

        <!-- Tree Container -->
        <div class="relative">
            <!-- Baobab Tree Background -->
            <div id="tree-container" class="relative mx-auto" style="width: 800px; height: 600px; background-image: url('https://images.unsplash.com/photo-1518709268805-4e9042af2176?w=800&h=600&fit=crop'); background-size: contain; background-repeat: no-repeat; background-position: center;">
                
                <!-- Coach Positions on Tree -->
                <div id="coach-markers" class="absolute inset-0">
                    <!-- Coach markers will be positioned here -->
                </div>
                
                <!-- Tree Legend -->
                <div class="absolute bottom-4 left-4 bg-white bg-opacity-90 p-4 rounded-lg shadow-lg">
                    <h4 class="font-bold mb-2">Tree Wisdom Levels</h4>
                    <div class="space-y-1 text-sm">
                        <div class="flex items-center gap-2">
                            <div class="w-3 h-3 bg-amber-600 rounded-full"></div>
                            <span>Roots: Ancestral Knowledge</span>
                        </div>
                        <div class="flex items-center gap-2">
                            <div class="w-3 h-3 bg-amber-700 rounded-full"></div>
                            <span>Trunk: Foundation Practices</span>
                        </div>
                        <div class="flex items-center gap-2">
                            <div class="w-3 h-3 bg-green-600 rounded-full"></div>
                            <span>Branches: Active Practice</span>
                        </div>
                        <div class="flex items-center gap-2">
                            <div class="w-3 h-3 bg-green-400 rounded-full"></div>
                            <span>Leaves: Modern Methods</span>
                        </div>
                        <div class="flex items-center gap-2">
                            <div class="w-3 h-3 bg-orange-500 rounded-full"></div>
                            <span>Fruits: Proven Results</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Selected Coach Profile -->
        <div id="coach-profile" class="mt-12 bg-white rounded-2xl shadow-xl p-8 hidden">
            <div class="flex flex-col md:flex-row gap-8">
                <div class="md:w-1/3">
                    <img id="profile-image" src="" alt="" class="w-full h-64 object-cover rounded-xl">
                </div>
                <div class="md:w-2/3">
                    <div class="flex items-center gap-4 mb-4">
                        <h2 id="profile-name" class="serif text-3xl font-bold text-gray-900"></h2>
                        <span id="profile-branch" class="px-3 py-1 rounded-full text-sm font-bold"></span>
                    </div>
                    
                    <p id="profile-bio" class="text-gray-700 mb-6 italic text-lg"></p>
                    
                    <div class="grid md:grid-cols-2 gap-6 mb-6">
                        <div>
                            <h4 class="font-bold text-gray-800 mb-2">Experience</h4>
                            <p id="profile-experience" class="text-gray-600"></p>
                        </div>
                        <div>
                            <h4 class="font-bold text-gray-800 mb-2">Sessions Completed</h4>
                            <p id="profile-sessions" class="text-gray-600"></p>
                        </div>
                    </div>
                    
                    <div class="mb-6">
                        <h4 class="font-bold text-gray-800 mb-2">Specialties</h4>
                        <div id="profile-specialties" class="flex flex-wrap gap-2"></div>
                    </div>
                    
                    <div class="mb-6">
                        <h4 class="font-bold text-gray-800 mb-2">Certifications</h4>
                        <div id="profile-certifications" class="space-y-1"></div>
                    </div>
                    
                    <div class="flex gap-4">
                        <button id="book-session-btn" onclick="bookCoach(0, '')" class="bg-shining-green text-white px-6 py-3 rounded-lg font-semibold hover:bg-green-700 transition-colors">
                            Book Session - $<span id="profile-rate">0</span>/hr
                        </button>
                        <button onclick="viewProducts(0)" class="bg-amber-600 text-white px-6 py-3 rounded-lg font-semibold hover:bg-amber-700 transition-colors">
                            View Products
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Coach Grid (Alternative View) -->
        <div id="coach-grid" class="mt-12 grid md:grid-cols-2 lg:grid-cols-3 gap-6">
            <!-- Coach cards will be populated here -->
        </div>
    </div>
</section>

<script>
let coaches = [];
let selectedCoach = null;

async function loadCoaches() {
    try {
        const params = new URLSearchParams();
        const search = document.getElementById('search-input').value;
        const specialty = document.getElementById('specialty-filter').value;
        const experience = document.getElementById('experience-filter').value;
        const branch = document.getElementById('branch-filter').value;
        
        if (search) params.append('search', search);
        if (specialty) params.append('specialty', specialty);
        if (experience) params.append('experience', experience);
        if (branch) params.append('branch', branch);
        
        const response = await fetch(`/atasteofafricanmarketplace/api/coaches/tree.php?${params}`);
        const data = await response.json();
        
        if (data.success) {
            coaches = data.coaches;
            
            // Populate filter options
            if (data.filters) {
                populateFilters(data.filters);
            }
            
            // Render coaches on tree and grid
            renderTreeMarkers();
            renderCoachGrid();
        }
    } catch (error) {
        console.error('Error loading coaches:', error);
    }
}

function populateFilters(filters) {
    // Populate specialty filter
    const specialtySelect = document.getElementById('specialty-filter');
    const currentSpecialty = specialtySelect.value;
    specialtySelect.innerHTML = '<option value="">All Specialties</option>';
    filters.specialties.forEach(specialty => {
        const option = document.createElement('option');
        option.value = specialty;
        option.textContent = specialty;
        if (specialty === currentSpecialty) option.selected = true;
        specialtySelect.appendChild(option);
    });
    
    // Populate experience filter
    const experienceSelect = document.getElementById('experience-filter');
    const currentExperience = experienceSelect.value;
    experienceSelect.innerHTML = '<option value="">Any Experience</option>';
    filters.experience_levels.forEach(level => {
        const option = document.createElement('option');
        option.value = level.value;
        option.textContent = level.label;
        if (level.value == currentExperience) option.selected = true;
        experienceSelect.appendChild(option);
    });
}

function renderTreeMarkers() {
    const markersContainer = document.getElementById('coach-markers');
    markersContainer.innerHTML = '';
    
    coaches.forEach(coach => {
        const marker = document.createElement('div');
        marker.className = 'absolute w-12 h-12 rounded-full border-4 border-white shadow-lg cursor-pointer transform hover:scale-110 transition-transform';
        marker.style.left = `${coach.tree_position_x}%`;
        marker.style.top = `${coach.tree_position_y}%`;
        marker.style.transform = 'translate(-50%, -50%)';
        
        // Set color based on branch
        const branchColors = {
            'roots': 'bg-amber-600',
            'trunk': 'bg-amber-700', 
            'branches': 'bg-green-600',
            'leaves': 'bg-green-400',
            'fruits': 'bg-orange-500'
        };
        marker.className += ` ${branchColors[coach.tree_branch] || 'bg-green-600'}`;
        
        // Add coach image
        const img = document.createElement('img');
        img.src = coach.profile_image_url || `https://i.pravatar.cc/150?u=${coach.first_name}`;
        img.alt = coach.display_name;
        img.className = 'w-full h-full rounded-full object-cover';
        marker.appendChild(img);
        
        // Add click handler
        marker.addEventListener('click', () => showCoachProfile(coach));
        
        // Add tooltip
        marker.title = `${coach.display_name}`;
        
        markersContainer.appendChild(marker);
    });
}

function renderCoachGrid() {
    const grid = document.getElementById('coach-grid');
    grid.innerHTML = coaches.map(coach => `
        <div class="bg-white rounded-2xl shadow-lg overflow-hidden hover:shadow-xl transition-shadow cursor-pointer" onclick="showCoachProfile(coaches.find(c => c.id == ${coach.id}))">
            <img src="${coach.profile_image_url || `https://i.pravatar.cc/300?u=${coach.first_name}`}" alt="${coach.display_name}" class="w-full h-48 object-cover">
            <div class="p-6">
                <div class="flex items-center gap-2 mb-2">
                    <h3 class="font-bold text-lg">${coach.display_name}</h3>
                    <span class="px-2 py-1 rounded-full text-xs font-bold ${getBranchColor(coach.tree_branch)}">${coach.tree_branch}</span>
                </div>
                <p class="text-gray-600 text-sm mb-3">${coach.years_experience} years experience</p>
                <div class="flex flex-wrap gap-1 mb-4">
                    ${coach.specialties.slice(0, 3).map(specialty => 
                        `<span class="bg-green-100 text-green-800 px-2 py-1 rounded text-xs">${specialty}</span>`
                    ).join('')}
                </div>
                <div class="flex justify-between items-center">
                    <span class="font-bold text-shining-green">$${coach.hourly_rate}/hr</span>
                    <button onclick="event.stopPropagation(); bookCoach(${coach.id}, '${coach.display_name}')" class="bg-shining-green text-white px-4 py-2 rounded-lg text-sm font-semibold hover:bg-green-700">
                        Book Now
                    </button>
                </div>
            </div>
        </div>
    `).join('');
}

function showCoachProfile(coach) {
    selectedCoach = coach;
    const profile = document.getElementById('coach-profile');
    
    // Populate profile data
    document.getElementById('profile-image').src = coach.profile_image_url || `https://i.pravatar.cc/300?u=${coach.first_name}`;
    document.getElementById('profile-name').textContent = coach.display_name;
    document.getElementById('profile-branch').textContent = coach.tree_branch;
    document.getElementById('profile-branch').className = `px-3 py-1 rounded-full text-sm font-bold ${getBranchColor(coach.tree_branch)}`;
    document.getElementById('profile-bio').textContent = coach.bio;
    document.getElementById('profile-experience').textContent = `${coach.years_experience} years of practice`;
    document.getElementById('profile-sessions').textContent = `${coach.total_sessions} completed sessions`;
    document.getElementById('profile-rate').textContent = coach.hourly_rate;
    
    // Populate specialties
    const specialtiesContainer = document.getElementById('profile-specialties');
    specialtiesContainer.innerHTML = coach.specialties.map(specialty => 
        `<span class="bg-green-100 text-green-800 px-3 py-1 rounded-full text-sm">${specialty}</span>`
    ).join('');
    
    // Populate certifications
    const certificationsContainer = document.getElementById('profile-certifications');
    certificationsContainer.innerHTML = coach.certifications.map(cert => 
        `<div class="flex items-center gap-2">
            <span class="w-2 h-2 bg-green-500 rounded-full"></span>
            <span class="text-gray-700">${cert}</span>
        </div>`
    ).join('');
    
    // Update book button
    document.getElementById('book-session-btn').onclick = () => bookCoach(coach.id, coach.display_name);
    
    // Show profile
    profile.classList.remove('hidden');
    profile.scrollIntoView({ behavior: 'smooth' });
}

function getBranchColor(branch) {
    const colors = {
        'roots': 'bg-amber-100 text-amber-800',
        'trunk': 'bg-amber-200 text-amber-900',
        'branches': 'bg-green-100 text-green-800',
        'leaves': 'bg-green-200 text-green-900',
        'fruits': 'bg-orange-100 text-orange-800'
    };
    return colors[branch] || 'bg-gray-100 text-gray-800';
}

function searchCoaches() {
    loadCoaches();
}

function bookCoach(coachId, coachName) {
    // Check if user is logged in
    fetch('/atasteofafricanmarketplace/api/auth/me.php')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                window.location.href = `/atasteofafricanmarketplace/book.php?coach=${encodeURIComponent(coachName)}`;
            } else {
                window.location.href = `/atasteofafricanmarketplace/login.php?return=${encodeURIComponent('/atasteofafricanmarketplace/book.php?coach=' + encodeURIComponent(coachName))}`;
            }
        })
        .catch(() => {
            window.location.href = `/atasteofafricanmarketplace/login.php?return=${encodeURIComponent('/atasteofafricanmarketplace/book.php?coach=' + encodeURIComponent(coachName))}`;
        });
}

function viewProducts(coachId) {
    window.location.href = `/atasteofafricanmarketplace/store.php?coach=${coachId}`;
}

// Initialize
loadCoaches();
</script>

<?php };
include __DIR__ . '/partials/layout.php';
?>