@extends('layouts.user')

@section('title', 'AI Skin Checker | Smart Dermatology')

@push('styles')
    <style>
        .upload-container { border: 3px dashed rgba(246, 144, 166, 0.4); border-radius: 30px; padding: 50px; text-align: center; background: rgba(255,255,255,0.8); transition: 0.3s; cursor: pointer; position: relative; }
        .upload-container:hover, .upload-container.dragover { background: rgba(246, 144, 166, 0.05); border-color: var(--brand-pink); }
        #imagePreview { max-width: 100%; max-height: 400px; border-radius: 20px; display: none; margin: 20px auto; box-shadow: 0 10px 20px rgba(0,0,0,0.1); }
        .result-box { background: white; border-radius: 25px; padding: 40px; box-shadow: 0 15px 35px rgba(0,0,0,0.05); border-top: 5px solid var(--brand-pink); }
        .loader { display: none; border: 5px solid #f3f3f3; border-top: 5px solid var(--brand-pink); border-radius: 50%; width: 50px; height: 50px; animation: spin 1s linear infinite; margin: 20px auto; }
        .history-card { border: 0; border-radius: 20px; box-shadow: 0 12px 30px rgba(15, 23, 42, 0.06); }
        @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
    </style>
@endpush

@section('content')
    <section class="hero-mini" style="height: 70vh; background: linear-gradient(rgba(0,0,0,0.6), rgba(0,0,0,0.6)), url('https://images.unsplash.com/photo-1576091160550-2173dba999ef?auto=format&fit=crop&w=1350&q=80'); background-size: cover; background-position: center; display: flex; align-items: center; justify-content: center; color: white;">
        <div class="text-center pt-5">
            <h1 class="display-4 fw-bold animate__animated animate__fadeIn">AI Skin <span style="color: var(--brand-pink);">Analyzer</span></h1>
            <p>Upload a photo for instant dermatological insights.</p>
        </div>
    </section>

    <section class="py-5 bg-light">
        <div class="container">
            @if (session('status'))
                <div class="alert alert-success rounded-4">{{ session('status') }}</div>
            @endif
            <div class="row justify-content-center">
                <div class="col-lg-8 text-center">
                    @auth
                        <form method="POST" action="{{ route('checker.analyze') }}" enctype="multipart/form-data" id="checkerForm">
                            @csrf
                            <div class="upload-container animate__animated animate__zoomIn" id="dropZone">
                                <div id="uploadPlaceholder" style="{{ session('analysis_result') ? 'display:none;' : '' }}">
                                    <i class="fas fa-cloud-upload-alt fa-4x mb-3" style="color: var(--brand-pink);"></i>
                                    <h3>Drag & Drop Image</h3>
                                    <p class="text-muted">or click to browse from your device</p>
                                </div>
                                <img id="imagePreview" src="{{ session('analysis_result.image_url', '#') }}" alt="Skin Preview" style="{{ session('analysis_result') ? 'display:block;' : '' }}">
                                <input type="file" id="fileInput" name="file" hidden accept="image/*">
                            </div>

                            @error('file')
                                <div class="text-danger text-start mt-3">{{ $message }}</div>
                            @enderror

                            <div class="mt-4">
                                <button type="button" class="btn btn-pink btn-lg px-5 shadow-sm" id="analyzeBtn" disabled>Analyze Image</button>
                                <button type="button" class="btn btn-outline-secondary btn-lg ms-2 rounded-pill px-4" id="resetBtn" style="{{ session('analysis_result') ? 'display:inline-block;' : 'display:none;' }}">Reset</button>
                            </div>

                            <div class="loader" id="aiLoader"></div>
                        </form>
                    @else
                        <div class="result-box text-center">
                            <h3 class="fw-bold mb-3">Sign in to analyze and save history</h3>
                            <p class="text-muted mb-4">Each image is linked to your account so you and the admin panel can review past results later.</p>
                            <a href="{{ route('login') }}" class="btn btn-pink btn-lg">Login to Continue</a>
                        </div>
                    @endauth

                    @if (session('analysis_result'))
                        <div class="result-box mt-5 animate__animated animate__fadeInUp" id="resultSection">
                            <h2 class="fw-bold mb-4">Analysis Results</h2>
                            <div class="row align-items-center">
                                <div class="col-md-6 text-md-start">
                                    <h4 class="text-muted">Predicted Condition:</h4>
                                    <h2 id="predictedClass" style="color: var(--brand-pink);">{{ str_replace('_', ' ', session('analysis_result.disease')) }}</h2>
                                    <p>Confidence Score: <span id="confidence" class="fw-bold">{{ number_format(session('analysis_result.confidence') * 100, 2) }}%</span></p>
                                </div>
                                <div class="col-md-6">
                                    <div class="p-3 rounded-4" style="background: #fff0f3; text-align: left;">
                                        <h6 class="fw-bold"><i class="fas fa-info-circle me-2"></i>AI Note:</h6>
                                        <p class="small mb-0">This is an AI-assisted screening result. Please use it as guidance and consult a medical professional for diagnosis and treatment.</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    @endif
                </div>
            </div>

            @auth
                <div class="row justify-content-center mt-5">
                    <div class="col-lg-10">
                        <div class="card history-card p-4">
                            <div class="d-flex justify-content-between align-items-center flex-wrap gap-2 mb-4">
                                <div>
                                    <h4 class="fw-bold mb-1">Recent Analysis History</h4>
                                    <p class="text-muted mb-0">Your latest saved predictions.</p>
                                </div>
                                <a href="{{ route('user.history') }}" class="btn btn-outline-secondary rounded-pill">View Full History</a>
                            </div>
                            <div class="table-responsive">
                                <table class="table align-middle mb-0">
                                    <thead class="table-light">
                                        <tr>
                                            <th>Image</th>
                                            <th>Predicted Disease</th>
                                            <th>Confidence</th>
                                            <th>Date</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        @forelse ($analyses as $analysis)
                                            <tr>
                                                <td><img src="{{ asset($analysis->image_path) }}" alt="Analyzed image" class="rounded-3" style="width:64px;height:64px;object-fit:cover;"></td>
                                                <td class="text-capitalize">{{ str_replace('_', ' ', $analysis->disease) }}</td>
                                                <td>{{ number_format($analysis->confidence * 100, 2) }}%</td>
                                                <td>{{ $analysis->created_at?->format('d M Y h:i A') }}</td>
                                            </tr>
                                        @empty
                                            <tr>
                                                <td colspan="4" class="text-center text-muted py-4">No analysis history yet.</td>
                                            </tr>
                                        @endforelse
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            @endauth
        </div>
    </section>
@endsection

@push('scripts')
    <script>
        const dropZone = document.getElementById('dropZone');
        const fileInput = document.getElementById('fileInput');
        const imagePreview = document.getElementById('imagePreview');
        const placeholder = document.getElementById('uploadPlaceholder');
        const analyzeBtn = document.getElementById('analyzeBtn');
        const resetBtn = document.getElementById('resetBtn');
        const loader = document.getElementById('aiLoader');
        const checkerForm = document.getElementById('checkerForm');

        if (dropZone && fileInput) {
            dropZone.onclick = () => fileInput.click();
            fileInput.onchange = (event) => handleFiles(event.target.files);
            dropZone.ondragover = (event) => { event.preventDefault(); dropZone.classList.add('dragover'); };
            dropZone.ondragleave = () => dropZone.classList.remove('dragover');
            dropZone.ondrop = (event) => {
                event.preventDefault();
                dropZone.classList.remove('dragover');
                fileInput.files = event.dataTransfer.files;
                handleFiles(event.dataTransfer.files);
            };
        }

        function handleFiles(files) {
            if (!files.length) return;
            const reader = new FileReader();
            reader.onload = (event) => {
                imagePreview.src = event.target.result;
                imagePreview.style.display = 'block';
                placeholder.style.display = 'none';
                analyzeBtn.disabled = false;
                resetBtn.style.display = 'inline-block';
            };
            reader.readAsDataURL(files[0]);
        }

        if (analyzeBtn && checkerForm) {
            analyzeBtn.onclick = () => {
                analyzeBtn.disabled = true;
                loader.style.display = 'block';
                checkerForm.submit();
            };
        }

        if (resetBtn) {
            resetBtn.onclick = () => window.location.href = "{{ route('checker') }}";
        }
    </script>
@endpush
