<?php

use Livewire\Component;
use App\Models\TaxRefund;
use Illuminate\Support\Facades\Mail;
use App\Mail\TaxRefundReceiptMail;
use Illuminate\Support\Facades\URL;

new class extends Component {
    public TaxRefund $refund;

    public array $timeline = [];
    public array $timelineColors = [];
    public array $statusMap = [];
    public int $currentStep = 0;
    public float $progressHeight = 0;

    public function mount($filing_number = null)
    {
        if (!$filing_number) {
            return redirect()
                ->route('user.tax.refund.track')
                ->with([
                    'message' => 'Filing number is required.',
                    'type' => 'info',
                ]);
        }

        try {
            $this->refund = TaxRefund::with('statusHistories')
                ->where('filing_number', $filing_number)
                ->where('user_id', auth()->id())
                ->firstOrFail();
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return redirect()
                ->route('user.tax.refund.track')
                ->with([
                    'message' => 'Filing number not found.',
                    'type' => 'error',
                ]);
        }

        // Status to index mapping
        $this->statusMap = [
            'pending' => 0,
            'in_review' => 1,
            'on_hold' => 2,
            'approved' => 3,
            'processed' => 4,
            'rejected' => 5,
            'failed' => 6,
        ];

        // Timeline dot colors
        $this->timelineColors = [
            'pending' => 'bg-yellow-500 dark:bg-yellow-700',
            'in_review' => 'bg-indigo-500 dark:bg-indigo-700',
            'on_hold' => 'bg-purple-500 dark:bg-purple-700',
            'approved' => 'bg-green-500 dark:bg-green-600',
            'processed' => 'bg-sky-500 dark:bg-sky-700',
            'rejected' => 'bg-red-500 dark:bg-red-600',
            'failed' => 'bg-gray-500 dark:bg-gray-700',
        ];

        // Build timeline only from actual status histories
        $this->timeline = $this->refund->statusHistories
            ->sortBy(fn($h) => $this->statusMap[$h->status] ?? 0) // Optional: sort by workflow
            ->map(
                fn($history) => [
                    'status' => $history->status,
                    'label' => match ($history->status) {
                        'pending' => 'Filing Received',
                        'in_review' => 'Under Review',
                        'on_hold' => 'On Hold',
                        'approved' => 'Refund Approved',
                        'processed' => 'Refund Processed',
                        'rejected' => 'Refund Rejected',
                        'failed' => 'Refund Failed',
                        default => ucwords(str_replace('_', ' ', $history->status)),
                    },
                    'date' => $history->changed_at?->format('M d, Y') ?? $history->created_at->format('M d, Y'),
                    'notes' => $history->notes,
                ],
            )
            ->toArray();

        // Current step is the last status in the timeline
        $this->currentStep = count($this->timeline) - 1;
        $this->progressHeight = ($this->currentStep / max(count($this->timeline) - 1, 1)) * 100;
    }

    /**
     * Download receipt via controller route (PDF/CSV) or send by email.
     */
    public function downloadReceipt(string $format)
    {
        if (!$this->refund) {
            $this->addError('error', 'Refund not found.');
            return;
        }

        $user = auth()->user();

        // Generate signed URL to the controller
        $downloadUrl = URL::signedRoute('user.tax.refund.download', [
            'refund' => $this->refund->id,
            'format' => $format,
        ]);

        switch ($format) {
            case 'pdf':
            case 'csv':
                return redirect()->away($downloadUrl);

            case 'email':
                Mail::to($user->email)->send(new TaxRefundReceiptMail($this->refund, $downloadUrl, $user));
                $this->dispatch('showToast', message: 'Receipt emailed successfully', type: 'success');
                return;

            default:
                $this->addError('error', 'Invalid format selected.');
                return;
        }
    }
};
?>

 <?php $__env->slot('title', null, []); ?> 
    <?php echo e(config('app.name')); ?> || Tax Refund Status
 <?php $__env->endSlot(); ?>

<div class="py-3">
    <?php echo $__env->make('partials.errors', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>

    <!-- Header -->
    <header class="max-w-4xl mx-auto text-center mb-6 px-4 sm:px-6 lg:px-8">
        <div class="flex flex-col items-center justify-center space-x-3">
            <div
                class="w-12 h-12 flex items-center justify-center rounded-full aspect-square bg-sky-600/30 backdrop-blur-md">
                <?php if (isset($component)) { $__componentOriginalc459039abf56f83b43258829ddb861ca = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginalc459039abf56f83b43258829ddb861ca = $attributes; } ?>
<?php $component = Illuminate\View\AnonymousComponent::resolve(['view' => 'e60dd9d2c3a62d619c9acb38f20d5aa5::icon.receipt-percent','data' => ['variant' => 'solid','class' => 'w-6 h-6 text-white']] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('flux::icon.receipt-percent'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\Illuminate\View\AnonymousComponent::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes(['variant' => 'solid','class' => 'w-6 h-6 text-white']); ?>
<?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::processComponentKey($component); ?>

<?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginalc459039abf56f83b43258829ddb861ca)): ?>
<?php $attributes = $__attributesOriginalc459039abf56f83b43258829ddb861ca; ?>
<?php unset($__attributesOriginalc459039abf56f83b43258829ddb861ca); ?>
<?php endif; ?>
<?php if (isset($__componentOriginalc459039abf56f83b43258829ddb861ca)): ?>
<?php $component = $__componentOriginalc459039abf56f83b43258829ddb861ca; ?>
<?php unset($__componentOriginalc459039abf56f83b43258829ddb861ca); ?>
<?php endif; ?>
            </div>

            <h1 class="text-base md:text-lg uppercase font-extrabold text-gray-900 dark:text-white">
                Tax Refund Status Portal
            </h1>
        </div>

        <p class="mt-2 text-gray-600 dark:text-gray-300 text-xs md:text-sm max-w-2xl mx-auto">
            Your Filing ID has been received. Check below for the current status of your refund.
        </p>
    </header>

    <!-- Main Content -->
    <main
        class="max-w-3xl mx-auto bg-white dark:bg-gray-800 shadow-xl rounded-lg border border-gray-200 dark:border-gray-700 p-8 transition-colors duration-300">

        <!-- Filing Info & Current Status -->
        <div class="flex flex-col md:flex-row items-start md:items-center justify-between gap-6 mb-10">
            <div>
                <h2 class="text-gray-700 dark:text-gray-300 font-semibold mb-3">Filing Information</h2>
                <p class="text-gray-900 dark:text-white mb-1">
                    <span class="font-medium">Filing ID:</span> <?php echo e($refund->filing_number ?? 'N/A'); ?>

                </p>
            </div>

            <div>
                <h2 class="text-gray-700 dark:text-gray-300 font-semibold mb-3">Current Status</h2>

                <span
                    class="inline-block px-5 py-2 rounded-full text-sm font-semibold shadow-sm transition-all duration-300 hover:scale-105 <?php echo e($refund->status_color); ?>">
                    <?php echo e($refund->status_label); ?>

                </span>
            </div>
        </div>

        <!-- Timeline -->
        <section class="mb-10">
            <h2 class="text-gray-700 dark:text-gray-300 font-semibold mb-5">Processing Timeline</h2>

            <ol class="relative border-l-2 border-gray-300 dark:border-gray-600 pl-0">
                <div class="absolute left-3 w-1 bg-blue-500 dark:bg-blue-400 rounded z-0 timeline-line"
                    style="height: <?php echo e($progressHeight); ?>%;">
                </div>

                <style>
                    .timeline-line {
                        top: 1rem;
                        bottom: 0;
                        transform-origin: top;
                    }
                </style>

                <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::openLoop(); ?><?php endif; ?><?php $__currentLoopData = $timeline; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $step): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::startLoop($loop->index); ?><?php endif; ?>
                    <?php
                        $stepIndex = $statusMap[$step['status']] ?? 0;
                        $isActive = $stepIndex <= $currentStep;

                        $bg = $isActive
                            ? $timelineColors[$step['status']] ?? 'bg-gray-300'
                            : 'bg-gray-200 dark:bg-gray-700';
                    ?>

                    <li class="mb-8 relative pl-12 z-10">
                        <span
                            class="absolute left-0 top-0 flex items-center justify-center w-8 h-8 rounded-full border-2 border-white dark:border-gray-800 transition-all duration-300 <?php echo e($bg); ?>">
                            <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($isActive): ?>
                                <svg class="w-4 h-4 text-white animate-pulse" fill="currentColor" viewBox="0 0 20 20">
                                    <path fill-rule="evenodd"
                                        d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-10.707a1 1 0 00-1.414-1.414L9 9.586 7.707 8.293a1 1 0 00-1.414 1.414L9 12.414l4.707-4.707z"
                                        clip-rule="evenodd" />
                                </svg>
                            <?php else: ?>
                                <svg class="w-4 h-4 text-white opacity-40" fill="currentColor" viewBox="0 0 20 20">
                                    <path fill-rule="evenodd"
                                        d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-10.707a1 1 0 00-1.414-1.414L9 9.586 7.707 8.293a1 1 0 00-1.414 1.414L9 12.414l4.707-4.707z"
                                        clip-rule="evenodd" />
                                </svg>
                            <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                        </span>

                        <h3 class="font-medium text-gray-700 dark:text-gray-300">
                            <?php echo e($step['label']); ?>

                        </h3>

                        <time class="block text-sm text-gray-500 dark:text-gray-400">
                            <?php echo e($step['date']); ?>

                        </time>

                        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if(!empty($step['notes'])): ?>
                            <p class="mt-2 text-sm text-gray-600 dark:text-gray-300 leading-relaxed">
                                <span class="font-semibold">Note:</span> <?php echo e($step['notes']); ?>

                            </p>
                        <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                    </li>
                <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::endLoop(); ?><?php endif; ?><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::closeLoop(); ?><?php endif; ?>
            </ol>
        </section>

        <!-- Refund Amount & Actions -->
        <div class="flex flex-wrap items-center justify-between gap-4 mb-6">
            <p class="text-gray-900 dark:text-white">
                <span class="font-medium">Refund Amount:</span> <?php echo e($refund->formattedAmount(true)); ?>

            </p>

            <a href="<?php echo e(route('user.tax.refund.index')); ?>"
                class="px-5 py-2 rounded-md border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 transition-all duration-200">
                Back
            </a>
        </div>

        <!-- Receipt Actions -->
        <div class="mb-6">
            <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if(in_array($refund->status ?? '', ['approved', 'processed'])): ?>
                <div class="flex space-x-3">
                    <?php if (isset($component)) { $__componentOriginalc04b147acd0e65cc1a77f86fb0e81580 = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginalc04b147acd0e65cc1a77f86fb0e81580 = $attributes; } ?>
<?php $component = Illuminate\View\AnonymousComponent::resolve(['view' => 'e60dd9d2c3a62d619c9acb38f20d5aa5::button.index','data' => ['variant' => 'primary','type' => 'button','wire:click' => 'downloadReceipt(\'pdf\')','wire:loading.attr' => 'disabled','class' => 'bg-sky-500 hover:bg-sky-700 text-white px-5 py-2 rounded-md transition-all duration-200']] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('flux::button'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\Illuminate\View\AnonymousComponent::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes(['variant' => 'primary','type' => 'button','wire:click' => 'downloadReceipt(\'pdf\')','wire:loading.attr' => 'disabled','class' => 'bg-sky-500 hover:bg-sky-700 text-white px-5 py-2 rounded-md transition-all duration-200']); ?>
<?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::processComponentKey($component); ?>

                        Download PDF
                     <?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginalc04b147acd0e65cc1a77f86fb0e81580)): ?>
<?php $attributes = $__attributesOriginalc04b147acd0e65cc1a77f86fb0e81580; ?>
<?php unset($__attributesOriginalc04b147acd0e65cc1a77f86fb0e81580); ?>
<?php endif; ?>
<?php if (isset($__componentOriginalc04b147acd0e65cc1a77f86fb0e81580)): ?>
<?php $component = $__componentOriginalc04b147acd0e65cc1a77f86fb0e81580; ?>
<?php unset($__componentOriginalc04b147acd0e65cc1a77f86fb0e81580); ?>
<?php endif; ?>

                    <?php if (isset($component)) { $__componentOriginalc04b147acd0e65cc1a77f86fb0e81580 = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginalc04b147acd0e65cc1a77f86fb0e81580 = $attributes; } ?>
<?php $component = Illuminate\View\AnonymousComponent::resolve(['view' => 'e60dd9d2c3a62d619c9acb38f20d5aa5::button.index','data' => ['variant' => 'primary','type' => 'button','wire:click' => 'downloadReceipt(\'csv\')','wire:loading.attr' => 'disabled','class' => 'bg-emerald-500 hover:bg-emerald-700 text-white px-5 py-2 rounded-md transition-all duration-200']] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('flux::button'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\Illuminate\View\AnonymousComponent::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes(['variant' => 'primary','type' => 'button','wire:click' => 'downloadReceipt(\'csv\')','wire:loading.attr' => 'disabled','class' => 'bg-emerald-500 hover:bg-emerald-700 text-white px-5 py-2 rounded-md transition-all duration-200']); ?>
<?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::processComponentKey($component); ?>

                        Download CSV
                     <?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginalc04b147acd0e65cc1a77f86fb0e81580)): ?>
<?php $attributes = $__attributesOriginalc04b147acd0e65cc1a77f86fb0e81580; ?>
<?php unset($__attributesOriginalc04b147acd0e65cc1a77f86fb0e81580); ?>
<?php endif; ?>
<?php if (isset($__componentOriginalc04b147acd0e65cc1a77f86fb0e81580)): ?>
<?php $component = $__componentOriginalc04b147acd0e65cc1a77f86fb0e81580; ?>
<?php unset($__componentOriginalc04b147acd0e65cc1a77f86fb0e81580); ?>
<?php endif; ?>

                    <?php if (isset($component)) { $__componentOriginalc04b147acd0e65cc1a77f86fb0e81580 = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginalc04b147acd0e65cc1a77f86fb0e81580 = $attributes; } ?>
<?php $component = Illuminate\View\AnonymousComponent::resolve(['view' => 'e60dd9d2c3a62d619c9acb38f20d5aa5::button.index','data' => ['variant' => 'primary','type' => 'button','wire:click' => 'downloadReceipt(\'email\')','wire:loading.attr' => 'disabled','class' => 'bg-indigo-500 hover:bg-indigo-700 text-white px-5 py-2 rounded-md transition-all duration-200']] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('flux::button'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\Illuminate\View\AnonymousComponent::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes(['variant' => 'primary','type' => 'button','wire:click' => 'downloadReceipt(\'email\')','wire:loading.attr' => 'disabled','class' => 'bg-indigo-500 hover:bg-indigo-700 text-white px-5 py-2 rounded-md transition-all duration-200']); ?>
<?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::processComponentKey($component); ?>

                        Email Receipt
                     <?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginalc04b147acd0e65cc1a77f86fb0e81580)): ?>
<?php $attributes = $__attributesOriginalc04b147acd0e65cc1a77f86fb0e81580; ?>
<?php unset($__attributesOriginalc04b147acd0e65cc1a77f86fb0e81580); ?>
<?php endif; ?>
<?php if (isset($__componentOriginalc04b147acd0e65cc1a77f86fb0e81580)): ?>
<?php $component = $__componentOriginalc04b147acd0e65cc1a77f86fb0e81580; ?>
<?php unset($__componentOriginalc04b147acd0e65cc1a77f86fb0e81580); ?>
<?php endif; ?>
                </div>
            <?php else: ?>
                <p class="text-gray-500 text-sm mt-2">
                    Receipt will be available once your refund is processed.
                </p>
            <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
        </div>

        <!-- Contact / Support -->
        <?php echo $__env->make('partials.contact-card', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
    </main>
</div>
<?php /**PATH /Users/macuser/Herd/Novabank/resources/views/pages/user/⚡view-tax-refund.blade.php ENDPATH**/ ?>