@extends('layout.main')

@section('title', 'প্রার্থী প্রোফাইল')

@php
    $shareUrl = url()->current();
    $shareTitle = ($candidate->user->name ?? 'প্রার্থী') . ' | প্রার্থী প্রোফাইল';

    $manifestoText = trim((string) ($candidate->election_manifesto ?? ''));
    if ($manifestoText === '') {
        $manifestoText = trim((string) ($candidate->bio ?? ''));
    }
    if ($manifestoText === '') {
        $manifestoText = 'প্রার্থীর প্রোফাইল দেখুন';
    }

    $shareDescription = \Illuminate\Support\Str::limit(preg_replace('/\s+/', ' ', strip_tags($manifestoText)), 180);

    $shareImage = $candidate->photo
        ? asset('storage/' . $candidate->photo)
        : ($candidate->symbol_photo
            ? asset('storage/' . $candidate->symbol_photo)
            : asset('images/default-share.png'));

    $age = $candidate->date_of_birth ? \Carbon\Carbon::parse($candidate->date_of_birth)->age : null;

    $bnDigits =
        $age !== null
            ? strtr((string) $age, [
                '0' => '০',
                '1' => '১',
                '2' => '২',
                '3' => '৩',
                '4' => '৪',
                '5' => '৫',
                '6' => '৬',
                '7' => '৭',
                '8' => '৮',
                '9' => '৯',
            ])
            : '—';

    $dobBn = $candidate->date_of_birth
        ? \Carbon\Carbon::parse($candidate->date_of_birth)->locale('bn')->translatedFormat('d F Y')
        : '—';

    $dobBn = strtr($dobBn, [
        '0' => '০',
        '1' => '১',
        '2' => '২',
        '3' => '৩',
        '4' => '৪',
        '5' => '৫',
        '6' => '৬',
        '7' => '৭',
        '8' => '৮',
        '9' => '৯',
    ]);

    $ytId = $candidate->youtube_video_id ?? '6UCuWxWiMaQ';

    $nidEn = $candidate->nid_number_en ?? null;
    $nidBn = $candidate->nid_number_bn ?? null;

    $seatName = $candidate->seat?->name_bn ?? ($candidate->seat?->name_en ?? 'N/A');
    $seatCode = $candidate->seat?->seat_code ?? null;

    $seatDivision = $candidate->seat?->district?->division?->name_bn ?? null;
    $seatDistrict = $candidate->seat?->district?->name_bn ?? null;
    $seatUpazila = $candidate->seat?->upazila?->name_bn ?? null;
    $seatCity = $candidate->seat?->city?->name_bn ?? null;

    $statusLabel =
        $candidate->status == 'active' ? 'সক্রিয়' : ($candidate->status == 'inactive' ? 'নিষ্ক্রিয়' : 'অযোগ্য');
    $statusPill =
        $candidate->status == 'active'
            ? 'bg-emerald-100 text-emerald-500 ring-emerald-200'
            : ($candidate->status == 'inactive'
                ? 'bg-gray-100 text-gray-700 ring-gray-200'
                : 'bg-red-100 text-red-700 ring-red-200');

    $statusDot =
        $candidate->status == 'active'
            ? 'bg-emerald-500'
            : ($candidate->status == 'inactive'
                ? 'bg-gray-400'
                : 'bg-red-500');

    $mask = function ($value) {
        if (!$value || mb_strlen($value) < 2) {
            return '—';
        }
        $len = mb_strlen($value);
        return mb_substr($value, 0, 1) . str_repeat('*', $len - 2) . mb_substr($value, -1);
    };
@endphp

@push('meta')
    <meta property="og:url" content="{{ $shareUrl }}">
    <meta property="og:type" content="website">
    <meta property="og:title" content="{{ $shareTitle }}">
    <meta property="og:description" content="{{ $shareDescription }}">
    <meta property="og:image" content="{{ $shareImage }}">
    <meta property="og:image:secure_url" content="{{ $shareImage }}">
    <meta property="og:image:alt" content="{{ $candidate->user->name ?? 'প্রার্থী' }}">

    <meta name="twitter:card" content="summary_large_image">
    <meta name="twitter:title" content="{{ $shareTitle }}">
    <meta name="twitter:description" content="{{ $shareDescription }}">
    <meta name="twitter:image" content="{{ $shareImage }}">
@endpush

@section('content')
    <div class="min-h-screen bg-gray-50">

        <!-- COVER -->
        <header class="relative">
            <div class="relative w-full h-[240px] sm:h-[320px] lg:h-[300px] bg-black overflow-hidden">
                <iframe id="ytBannerFrame" class="absolute inset-0 w-full h-full pointer-events-none"
                    src="https://www.youtube.com/embed/{{ $ytId }}?autoplay=1&mute=0&loop=1&playlist={{ $ytId }}&rel=0&modestbranding=1&playsinline=1&controls=0"
                    title="YouTube video player" frameborder="0"
                    allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
                    referrerpolicy="strict-origin-when-cross-origin" allowfullscreen>
                </iframe>

                <div class="absolute inset-0 bg-gradient-to-b from-black/30 via-black/10 to-black/40"></div>

                <div class="absolute top-4 left-4 right-4 z-10 flex items-center justify-between gap-2">
                    <a href="{{ route('candidates.index') }}"
                        class="inline-flex items-center gap-2 rounded-full bg-white/15 px-4 py-2 text-xs font-bold text-white ring-1 ring-white/25 backdrop-blur hover:bg-white/20 transition">
                        <i class="fas fa-arrow-left"></i>
                        তালিকা
                    </a>

                    <div class="flex items-center gap-2">
                        <span
                            class="hidden sm:inline-flex items-center gap-2 rounded-full px-3 py-2 text-xs font-extrabold ring-1 bg-white/15 text-white ring-white/25 backdrop-blur">
                            <span
                                class="h-2 w-2 rounded-full {{ $candidate->status == 'active' ? 'bg-emerald-400' : ($candidate->status == 'inactive' ? 'bg-gray-300' : 'bg-red-400') }}"></span>
                            {{ $statusLabel }}
                        </span>

                        <a href="{{ route('candidates.edit', $candidate) }}"
                            class="inline-flex items-center gap-2 rounded-full bg-white/15 px-4 py-2 text-xs font-bold text-white ring-1 ring-white/25 backdrop-blur hover:bg-white/20 transition">
                            <i class="fas fa-edit"></i>
                            এডিট
                        </a>
                    </div>
                </div>
            </div>

            <!-- Profile bar -->
            <div class="bg-white border-b border-gray-200">
                <div class="mx-auto max-w-6xl px-4">
                    <div class="relative">
                        <div
                            class="absolute -top-12 sm:-top-14 lg:-top-16 left-1/2 -translate-x-1/2 lg:left-0 lg:translate-x-0">
                            <div class="relative">
                                <div
                                    class="h-24 w-24 sm:h-28 sm:w-28 lg:h-32 lg:w-32 rounded-full overflow-hidden bg-gray-100 ring-4 ring-white shadow-lg">
                                    @if ($candidate->photo)
                                        <img src="{{ asset('storage/' . $candidate->photo) }}"
                                            alt="{{ $candidate->user->name }}" class="h-full w-full object-cover">
                                    @else
                                        <div class="h-full w-full grid place-items-center text-gray-400">
                                            <i class="fas fa-user text-4xl"></i>
                                        </div>
                                    @endif
                                </div>

                                @if ($candidate->symbol_photo)
                                    <div
                                        class="absolute -bottom-1 -right-1 h-11 w-11 lg:h-12 lg:w-12 rounded-full bg-white ring-2 ring-white shadow p-1">
                                        <img src="{{ asset('storage/' . $candidate->symbol_photo) }}"
                                            alt="{{ $candidate->symbol_name }}" class="h-full w-full object-contain">
                                    </div>
                                @endif
                            </div>
                        </div>

                        <div class="pt-14 sm:pt-16 lg:pt-6 pb-4 lg:pb-5">
                            <div class="flex flex-col lg:flex-row lg:items-end lg:justify-between gap-4">
                                <div class="text-center lg:text-left lg:pl-36">
                                    <h1 class="text-2xl sm:text-3xl font-extrabold text-gray-900">
                                        {{ $candidate->user->name ?? 'N/A' }}
                                    </h1>

                                    <p class="mt-1 text-sm text-gray-600 font-semibold">
                                        {{ $candidate->party_name ?? '—' }}
                                        <span class="mx-2 text-gray-300">|</span>
                                        {{ $seatName }}@if ($seatCode)
                                            <span class="text-gray-500 font-bold">({{ $seatCode }})</span>
                                        @endif
                                    </p>

                                    @if ($seatDivision || $seatDistrict || $seatCity || $seatUpazila)
                                        <p class="mt-1 text-xs text-gray-500 font-bold">
                                            {{ $seatDivision ?? '—' }}{{ $seatDistrict ? ', ' . $seatDistrict : '' }}
                                            @if ($seatCity)
                                                , {{ $seatCity }}
                                            @elseif($seatUpazila)
                                                , {{ $seatUpazila }}
                                            @endif
                                        </p>
                                    @endif

                                    <div
                                        class="mt-3 inline-flex items-center gap-2 rounded-full px-3 py-1.5 text-xs font-extrabold ring-1 {{ $statusPill }}">
                                        <span class="h-2 w-2 rounded-full {{ $statusDot }}"></span>
                                        {{ $statusLabel }}
                                    </div>
                                </div>

                                <div class="flex flex-wrap justify-center lg:justify-end gap-2">
                                    <button id="fbShareBtn" type="button"
                                        class="inline-flex items-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-sm font-extrabold text-white hover:bg-blue-700 transition">
                                        <i class="fab fa-facebook-f"></i>
                                        Facebook এ শেয়ার
                                    </button>

                                    <button id="waShareBtn" type="button"
                                        class="inline-flex items-center gap-2 rounded-lg bg-emerald-600 px-4 py-2 text-sm font-extrabold text-white hover:bg-emerald-700 transition">
                                        <i class="fab fa-whatsapp"></i>
                                        WhatsApp
                                    </button>

                                    <button id="copyLinkBtn" type="button"
                                        class="inline-flex items-center gap-2 rounded-lg bg-gray-900 px-4 py-2 text-sm font-extrabold text-white hover:bg-black transition">
                                        <i class="fas fa-link"></i>
                                        লিংক কপি
                                    </button>

                                    <span id="shareCountBadge"
                                        class="hidden items-center gap-2 rounded-lg bg-gray-100 px-4 py-2 text-sm font-extrabold text-gray-800 ring-1 ring-gray-200">
                                        <i class="fas fa-share-alt text-gray-500"></i>
                                        <span id="shareCountText">0</span> শেয়ার
                                    </span>
                                </div>
                            </div>
                        </div>
                    </div>
                    <!-- Removed tabs completely -->
                </div>
            </div>
        </header>

        <!-- BODY -->
        <main class="mx-auto max-w-6xl px-4 py-6">
            <div class="grid grid-cols-1 lg:grid-cols-12 gap-6">

                <!-- Left: Intro -->
                <aside class="lg:col-span-4 space-y-6 ">
                    <div class="rounded-2xl bg-emerald-600 shadow-sm ring-1 ring-gray-200 overflow-hidden">
                        <div class="px-5 py-4 border-b border-gray-100">
                            <h3 class="text-base font-extrabold text-white">পরিচিতি</h3>
                            <p class="mt-1 text-sm text-white">প্রার্থীর মূল তথ্য</p>
                        </div>

                        <div class="p-5 space-y-4">
                            <div class="flex items-start gap-3">
                                <div
                                    class="h-10 w-10 rounded-xl bg-gray-50 ring-1 ring-gray-200 grid place-items-center text-gray-700">
                                    <i class="fas fa-landmark"></i>
                                </div>
                                <div class="min-w-0">
                                    <p class="text-xs font-extrabold text-white">রাজনৈতিক দল</p>
                                    <p class="text-sm font-extrabold text-white break-words">
                                        {{ $candidate->party_name ?? '—' }}</p>
                                </div>
                            </div>

                            <div class="flex items-start gap-3">
                                <div
                                    class="h-10 w-10 rounded-xl bg-gray-50 ring-1 ring-gray-200 grid place-items-center text-gray-700">
                                    <i class="fas fa-chair"></i>
                                </div>
                                <div class="min-w-0">
                                    <p class="text-xs font-extrabold text-white">সীট</p>
                                    <p class="text-sm font-extrabold text-white break-words">
                                        {{ $seatName }}@if ($seatCode)
                                            <span class="text-white font-bold">({{ $seatCode }})</span>
                                        @endif
                                    </p>
                                    @if ($seatDivision || $seatDistrict || $seatCity || $seatUpazila)
                                        <p class="mt-1 text-xs text-white font-bold break-words">
                                            {{ $seatDivision ?? '—' }}{{ $seatDistrict ? ', ' . $seatDistrict : '' }}
                                            @if ($seatCity)
                                                , {{ $seatCity }}
                                            @elseif($seatUpazila)
                                                , {{ $seatUpazila }}
                                            @endif
                                        </p>
                                    @endif
                                </div>
                            </div>

                            <div class="flex items-start gap-3">
                                <div
                                    class="h-10 w-10 rounded-xl bg-gray-50 ring-1 ring-gray-200 grid place-items-center text-gray-700">
                                    <i class="fas fa-flag"></i>
                                </div>
                                <div class="min-w-0">
                                    <p class="text-xs font-extrabold text-white">প্রতীক</p>
                                    <p class="text-sm font-extrabold text-white break-words">
                                        {{ $candidate->symbol_name ?? '—' }} মার্কা</p>
                                </div>
                            </div>

                            <div class="flex items-start gap-3">
                                <div
                                    class="h-10 w-10 rounded-xl bg-gray-50 ring-1 ring-gray-200 grid place-items-center text-gray-700">
                                    <i class="fas fa-fingerprint"></i>
                                </div>
                                <div class="min-w-0">
                                    <p class="text-xs font-extrabold text-white">এনআইডি (EN/BN)</p>
                                    <p class="font-mono text-sm font-extrabold text-white break-all">
                                        {{ $mask($nidEn ?? null) }}</p>
                                    <p class="font-mono text-xs font-bold text-white break-all">
                                        {{ $mask($nidBn ?? null) }}</p>
                                </div>
                            </div>

                            {{-- <div class="grid grid-cols-2 gap-3">
                            <div class="rounded-2xl bg-gray-50 p-4 ring-1 ring-gray-200">
                                <p class="text-[11px] font-extrabold text-gray-500">বয়স</p>
                                <p class="mt-1 text-sm font-extrabold text-gray-900">{{ $bnDigits }}</p>
                            </div>
                            <div class="rounded-2xl bg-gray-50 p-4 ring-1 ring-gray-200">
                                <p class="text-[11px] font-extrabold text-gray-500">জন্মতারিখ</p>
                                <p class="mt-1 text-sm font-extrabold text-gray-900">{{ $dobBn }}</p>
                            </div>
                        </div> --}}

                            @if ($candidate->bio)
                                <article class="rounded-2xl bg-white shadow-sm ring-1 ring-gray-200 overflow-hidden">
                                    <div class="px-5 py-4 border-b border-gray-100">
                                        <h2 class="text-base font-extrabold text-gray-900">বিবরণ</h2>
                                        <p class="mt-1 text-sm text-gray-500">প্রার্থীর সংক্ষিপ্ত পরিচিতি</p>
                                    </div>
                                    <div class="p-5">
                                        <p class="text-gray-800 leading-relaxed whitespace-pre-line text-sm  ">
                                            {{ $candidate->bio }}
                                        </p>
                                    </div>
                                </article>
                            @endif

                            <article
                                class="rounded-2xl bg-white shadow-sm ring-1 ring-gray-200 overflow-hidden hidden lg:block md:block">
                                <div class="px-5 py-4 border-b border-gray-100">
                                    <h2 class="text-base font-extrabold text-gray-900">প্রার্থী অবস্থা</h2>
                                    <p class="mt-1 text-sm text-gray-500">বর্তমান স্ট্যাটাস ও বেসিক তথ্য</p>
                                </div>

                                <div class="p-5">
                                    <div class="flex items-center gap-2">
                                        <span
                                            class="inline-flex items-center rounded-full px-3 py-1.5 text-sm font-extrabold ring-1 {{ $statusPill }}">
                                            {{ $statusLabel }}
                                        </span>
                                        <span class="h-2.5 w-2.5 rounded-full {{ $statusDot }}"></span>
                                    </div>

                                    <div class="mt-4 grid grid-cols-1 sm:grid-cols-2 gap-4">
                                        <div class="rounded-2xl bg-gray-50 p-4 ring-1 ring-gray-200">
                                            <p class="text-xs font-extrabold text-gray-500">দল</p>
                                            <p class="mt-1 text-sm font-bold text-gray-900">
                                                {{ $candidate->party_name ?? '—' }}</p>
                                        </div>

                                        <div class="rounded-2xl bg-gray-50 p-4 ring-1 ring-gray-200">
                                            <p class="text-xs font-extrabold text-gray-500">প্রতীক</p>
                                            <p class="mt-1 text-sm font-bold text-gray-900">
                                                {{ $candidate->symbol_name ?? '—' }} মার্কা</p>
                                        </div>
                                    </div>
                                </div>
                            </article>
                        </div>
                    </div>
                </aside>

                <!-- Right: Feed -->
                <section class="lg:col-span-8 space-y-6">

                    @if ($candidate->election_manifesto)
                        <article class="rounded-2xl bg-white shadow-sm ring-1 ring-gray-200 overflow-hidden">
                            <div class="px-5 py-4 border-b border-gray-100 flex items-center justify-between gap-3">
                                <div>
                                    <h2 class="text-base font-extrabold text-gray-900">ইশতেহার</h2>
                                    <p class="mt-1 text-sm text-gray-500">প্রার্থীর প্রতিশ্রুতি ও পরিকল্পনা</p>
                                </div>
                                <span
                                    class="text-[11px] font-extrabold text-rose-700 bg-rose-50 px-3 py-1.5 rounded-full ring-1 ring-rose-200">
                                    গুরুত্বপূর্ণ
                                </span>
                            </div>
                            <div class="p-5">
                                @php
                                    $raw = trim((string) $candidate->election_manifesto);

                                    // Split into lines and remove empty ones
                                    $lines = preg_split("/\r\n|\n|\r/", $raw);
                                    $lines = array_values(array_filter(array_map('trim', $lines)));

                                    // Remove the title line if present (📜 নির্বাচনী ইশতেহার)
                                    if (
                                        !empty($lines) &&
                                        (str_contains($lines[0], '📜') || str_contains($lines[0], 'নির্বাচনী ইশতেহার'))
                                    ) {
                                        array_shift($lines);
                                    }

                                    // Intro paragraph = first line after title
                                    $intro = $lines[0] ?? '';

                                    // Bullets = rest of the lines
                                    $bullets = array_slice($lines, 1);

                                    // Final short appeal (display-only text)
                                    $finalAppeal =
                                        'আপনার মূল্যবান ভোট ও সমর্থন কামনা করছি — চলুন একসাথে উন্নয়ন ও সেবামুখী নেতৃত্ব গড়ে তুলি।';
                                @endphp

                                {{-- Intro paragraph --}}
                                @if ($intro)
                                    <p class="text-gray-800 leading-relaxed text-sm   font-semibold">
                                        {{ $intro }}
                                    </p>
                                @endif

                                {{-- Bullet points as table --}}
@if (!empty($bullets))
    <div class="mt-4 overflow-x-auto">
        <table class="w-full border border-emerald-600 rounded-lg overflow-hidden text-sm">
            <thead class="bg-gray-50">
                <tr>
                    <th class="w-12 px-3 py-2 text-left font-bold text-gray-700 border-b bg-emerald-100">
                        #
                    </th>
                    <th class="px-3 py-2 text-left font-bold text-gray-700 border-b  bg-emerald-100">
                        প্রতিশ্রুতি / পরিকল্পনা
                    </th>
                </tr>
            </thead>
            <tbody>
                @foreach ($bullets as $index => $line)
                    <tr class="odd:bg-white even:bg-emerald-50">
                        <td class="px-3 py-2 border-b text-gray-600 font-semibold">
                            {{ $index + 1 }}
                        </td>
                        <td class="px-3 py-2 border-b text-gray-800 leading-relaxed">
                            {{ $line }}
                        </td>
                    </tr>
                @endforeach
            </tbody>
        </table>
    </div>
@endif

                                {{-- Final appeal --}}
                                <p class="mt-5 text-gray-900 text-sm   font-extrabold">
                                    {{ $finalAppeal }}
                                </p>
                            </div>

                        </article>
                    @endif




                </section>
            </div>
        </main>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const shareUrl = @json($shareUrl);
            const shareTitle = @json(($candidate->user->name ?? 'প্রার্থী') . ' | প্রার্থী প্রোফাইল');

            const shareCountBadge = document.getElementById('shareCountBadge');
            const shareCountText = document.getElementById('shareCountText');

            const getShareCounts = () => {
                try {
                    const key = 'share_counts:' + shareUrl;
                    const raw = localStorage.getItem(key);
                    if (!raw) return {
                        fb: 0,
                        wa: 0,
                        copy: 0,
                        total: 0
                    };
                    const parsed = JSON.parse(raw);
                    const fb = Number(parsed.fb || 0);
                    const wa = Number(parsed.wa || 0);
                    const copy = Number(parsed.copy || 0);
                    return {
                        fb,
                        wa,
                        copy,
                        total: fb + wa + copy
                    };
                } catch (e) {
                    return {
                        fb: 0,
                        wa: 0,
                        copy: 0,
                        total: 0
                    };
                }
            };

            const setShareCounts = (counts) => {
                const key = 'share_counts:' + shareUrl;
                localStorage.setItem(key, JSON.stringify({
                    fb: counts.fb || 0,
                    wa: counts.wa || 0,
                    copy: counts.copy || 0
                }));
            };

            const renderShareCount = () => {
                const counts = getShareCounts();
                if (shareCountText && shareCountBadge) {
                    shareCountText.textContent = String(counts.total || 0);
                    shareCountBadge.classList.remove('hidden');
                    shareCountBadge.classList.add('inline-flex');
                }
            };

            const bumpCount = (type) => {
                const counts = getShareCounts();
                counts[type] = (counts[type] || 0) + 1;
                setShareCounts(counts);
                renderShareCount();
            };

            renderShareCount();

            const fbBtn = document.getElementById('fbShareBtn');
            if (fbBtn) {
                fbBtn.addEventListener('click', function() {
                    const url = encodeURIComponent(shareUrl);
                    const fbShareUrl = `https://www.facebook.com/sharer/sharer.php?u=${url}`;
                    window.open(fbShareUrl, 'fb-share-dialog', 'width=626,height=436');
                    bumpCount('fb');
                });
            }

            const waBtn = document.getElementById('waShareBtn');
            if (waBtn) {
                waBtn.addEventListener('click', function() {
                    const text = encodeURIComponent(`${shareTitle}\n${shareUrl}`);
                    const waShareUrl = `https://wa.me/?text=${text}`;
                    window.open(waShareUrl, '_blank');
                    bumpCount('wa');
                });
            }

            const copyBtn = document.getElementById('copyLinkBtn');

            const showToast = (msg) => {
                const toast = document.createElement('div');
                toast.className =
                    'fixed bottom-6 left-1/2 -translate-x-1/2 z-[9999] ' +
                    'rounded-full bg-gray-900 text-white text-sm font-extrabold px-5 py-3 shadow-lg ring-1 ring-white/10';
                toast.textContent = msg;
                document.body.appendChild(toast);

                setTimeout(() => {
                    toast.style.opacity = '0';
                    toast.style.transition = 'opacity 250ms ease';
                }, 1200);

                setTimeout(() => toast.remove(), 1600);
            };

            const doCopy = async () => {
                try {
                    if (navigator.clipboard && window.isSecureContext) {
                        await navigator.clipboard.writeText(shareUrl);
                    } else {
                        const temp = document.createElement('textarea');
                        temp.value = shareUrl;
                        temp.style.position = 'fixed';
                        temp.style.left = '-9999px';
                        temp.style.top = '-9999px';
                        document.body.appendChild(temp);
                        temp.focus();
                        temp.select();
                        document.execCommand('copy');
                        temp.remove();
                    }
                    showToast('লিংক কপি হয়েছে!');
                    bumpCount('copy');
                } catch (e) {
                    showToast('কপি করা যায়নি');
                }
            };

            if (copyBtn) {
                copyBtn.addEventListener('click', function() {
                    doCopy();
                });
            }
        });
    </script>
@endsection
