﻿@extends('layouts.app')

@section('title', config('app.name') . " | " . request('jobTitle') . " | " . request('currency') . " | " . request('location'))

@section('content')

            <div class="max-w-7xl mx-auto mt-20 px-4 sm:px-6 lg:px-8 py-8">

                <a href="{{ route('see-salary') }}" class="text-sm text-gray-500 hover:underline flex items-center gap-1 mb-6">
                    <span>&larr;</span> See Salaries
                </a>

                {{-- Header: Job Title & Location --}}
                <div class="flex flex-col md:flex-row justify-between items-start mb-6 gap-4 md:gap-0">
                    <div class="flex items-center gap-3">
                        <img src="{{ $country_flag }}" class="w-10 h-10 object-cover rounded-full border border-gray-200">
                        @if($jobTitle || ($city || $state || $location))
                            @if($jobTitle)
                                <h1 class="text-2xl md:text-3xl font-semibold">{{ $jobTitle }}</h1>
                            @endif
                            @if($city || $state || $location)
                                                            @if($jobTitle)
                                                                <h4 class="text-base md:text-lg mt-2">
                                                            @else
                                                                    <h1 class="text-2xl md:text-3xl font-semibold">
                                                                @endif
                                                                    @php
        $locationParts = [];
        if ($city)
            $locationParts[] = $city;
        if ($state)
            $locationParts[] = $state;
        if ($location)
            $locationParts[] = $location;
        $locationString = implode(', ', $locationParts);
                                                                    @endphp
                                                                    {{ $locationString }}
                                                                    @if($jobTitle)
                                                                        </h4>
                                                                    @else
                                    </h1>
                                @endif
                            @endif
                        @endif
    </div>

    <div class="text-left md:text-right">
        <a href="{{ route('dashboard.job-experiences.create') }}"
            class="w-full sm:w-auto bg-[#2F3D7E] hover:bg-[#2F3D7E]/90 px-6 py-3 rounded-lg font-bold text-white transition-all shadow-lg shadow-blue-900/20 flex items-center justify-center gap-2">
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
            </svg>
            Contribute Salary
        </a><br>
        <p class="text-xs text-gray-400">Median total comp.</p>
        <p class="text-3xl font-bold text-[#2F3D7E]">
            {{ $currency ?? 'USD' }} {{ number_format($aiData['average'], 2) }} <small>{{ ucfirst($pay_frequency) }}</small>
        </p>
        </div>
        </div>

        {{-- ================= AI SALARY DISTRIBUTION ================= --}}
        @if(!empty($aiRecords))
            <div class="bg-white p-6 rounded-xl shadow-sm border mb-10">
                <h4 class="text-lg font-semibold mb-4 text-blue-600">
                    AI Salary Distribution Curve
                </h4>
                <div id="aiSalaryChart" class="w-full"></div>
            </div>
        @endif

        <div class="bg-white p-6 rounded-xl shadow-sm border mb-10">
            <div class="flex items-center justify-between mb-4">
                <h4 class="text-lg font-semibold text-indigo-600">
                    RateMyPay vs Community Salary Comparison
            </h4>
            @if(!empty($experienceData['companies']))
                <span class="text-sm text-gray-500">
                    Based on {{ $experienceData['companies'] }} company submissions
                </span>
            @endif
        </div>
        <div id="salaryComparisonChart" class="w-full"></div>
    </div>

    {{-- ================= INDIVIDUAL SUBMISSIONS TABLE ================= --}}
    <div class="bg-white rounded-xl shadow-sm border overflow-hidden">
        <div class="p-6">
            <h3>Individual Submissions ({{ $experiences->count() }})</h3>
        </div>

        <div class="overflow-x-auto">
            <table class="w-full text-left min-w-[900px]">
                <thead class="bg-gray-100 text-gray-600 text-sm">
                    <tr>
                        <th class="p-4 whitespace-nowrap">Name</th>
                        <th class="p-4 whitespace-nowrap">Company Name</th>
                        <th class="p-4 whitespace-nowrap">Job Title</th>
                        <th class="p-4 whitespace-nowrap">Location</th>
                        <th class="p-4 whitespace-nowrap">Experience</th>
                        <th class="p-4 whitespace-nowrap">Salary</th>
                        <th class="p-4 whitespace-nowrap">Equity</th>
                    </tr>
                </thead>
                <tbody class="text-gray-700">
                    @foreach ($experiences as $experience)
                        <tr class="border-t hover:bg-gray-50 text-sm md:text-base">
                            <td class="p-4 flex items-center gap-3 whitespace-nowrap">
                                <img src="/images/avatar.png" class="w-8 h-8 rounded-full bg-gray-200">
                                Anonymous
                            </td>
                            <td class="p-4 whitespace-nowrap">{{ $experience->company_name }}</td>
                            <td class="p-4 whitespace-nowrap">{{ $experience->job_title }}</td>
                            <td class="p-4 whitespace-nowrap">
                                {{ implode(', ', array_filter([$experience->city, $experience->state, $experience->post_code, $experience->country])) }}
                            </td>
                            <td class="p-4 whitespace-nowrap">
                                {{ $experience->years_of_experience . ' ' . Str::plural('Year', $experience->years_of_experience) }}
                            </td>
                            <td class="p-4 whitespace-nowrap font-medium text-gray-900">
                                {{ $experience->currency }}{{ number_format($experience->annual_base_salary, 0) }}
                            </td>
                            <td class="p-4 whitespace-nowrap">{{ $experience->equity }}%</td>
                        </tr>
                    @endforeach
                </tbody>
            </table>
        </div>

        {{-- Pagination Links --}}
        @if(method_exists($experiences, 'links'))
            <div class="px-4 py-3 border-t">
                {{ $experiences->links() }}
            </div>
        @endif
    </div>

    </div>

@endsection
    @section('scripts')
        <script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>

            <script>
                document.addEventListener('DOMContentLoaded', function () {

                    const aiData = @json($aiData ?? null);
                    const experienceData = @json($experienceData ?? null);
                    const currencySymbol = "{{ $currency }}";

                    if (!aiData) return;

                    // ===============================
                    // SAFE NUMBER PARSER
                    // ===============================

                    const parseNumber = (value) => {
                        if (!value) return 0;
                        return Number(value);
                    };

                    // ===============================
                    // CATEGORIES
                    // ===============================

                    const categories = ['Min', 'Average', 'Max'];

                    // ===============================
                    // DATA PREPARATION
                    // ===============================

                    const aiValues = [
                        parseNumber(aiData.min),
                        parseNumber(aiData.average),
                        parseNumber(aiData.max)
                    ];

                    const experienceValues = experienceData
                        ? [
                            parseNumber(experienceData.min),
                            parseNumber(experienceData.average),
                            parseNumber(experienceData.max)
                        ]
                        : aiValues;

                    // ===============================
                    // FORMATTERS
                    // ===============================

                    const axisFormatter = (value) => {
                        if (value >= 1000000)
                            return currencySymbol + (value / 1000000).toFixed(1).replace(/\.0$/, '') + 'M';
                        if (value >= 1000)
                            return currencySymbol + Math.round(value / 1000) + 'k';
                        return currencySymbol + value;
                    };

                    const tooltipFormatter = (value) =>
                        currencySymbol + " " + new Intl.NumberFormat('en-US').format(value);

                    // ===============================
                    // CHART CONFIG
                    // ===============================

                    const options = {
                        chart: {
                            height: 420,
                            type: 'line',
                            stacked: false,
                            toolbar: { show: false },
                            fontFamily: 'Inter, sans-serif'
                        },

                        series: [
                            {
                                name: 'RateMyPay',
                                type: 'column',
                                data: aiValues
                            },
                            {
                                name: 'Community',
                                type: 'line',
                                data: experienceValues
                            }
                        ],

                        colors: [
                            '#EF4444', // red (min)
                            '#2563EB',

                        ],

                        stroke: {
                            width: [0, 4],
                            curve: 'smooth'
                        },

                        plotOptions: {
                            bar: {
                                distributed: false,
                                columnWidth: '40%',
                                borderRadius: 6,
                                dataLabels: {
                                    position: 'center' // puts text inside bar
                                }
                            }
                        },

                        markers: {
                            size: 6
                        },

                        dataLabels: {
                            enabled: true,
                            formatter: function (val, opts) {
                                return axisFormatter(val);
                            },
                            style: {
                                fontSize: '13px',
                                fontWeight: 600,
                                colors: ['#000000']
                            },

                            background: {
                                enabled: true
                            }
                        },

                        xaxis: {
                            categories: categories,
                            labels: {
                                style: {
                                    fontSize: '14px'
                                }
                            }
                        },

                        yaxis: {
                            labels: {
                                formatter: axisFormatter
                            }
                        },

                        tooltip: {
                            shared: true,
                            intersect: false,
                            y: {
                                formatter: tooltipFormatter
                            }
                        },

                        grid: {
                            borderColor: '#E5E7EB'
                        },

                        legend: {
                            position: 'bottom'
                        }
                    };

                    const chart = new ApexCharts(
                        document.querySelector("#salaryComparisonChart"),
                        options
                    );

                    chart.render();
                });
            </script>
    @endsect