@extends('layouts.app', [
    'navLinks' => [['label' => 'Dashboard', 'url' => '/dashboard', 'visibility' => 'auth'], ['label' => 'Inventory', 'url' => '/inventory', 'visibility' => 'auth'], ['label' => 'Projects', 'url' => '/projects', 'visibility' => 'auth'], ['label' => 'Profile', 'url' => '/profile', 'visibility' => 'auth'], ['label' => 'Settings', 'url' => '/settings', 'visibility' => 'auth']],
])
@section('title', $component['part_number'])
@section('meta_description', $component['description'])
@section('meta_image', '/image/' . $component['part_number'] . '?h=900&w=900')
@section('meta_keywords', implode(', ', [$component['mpn'], $component['part_number'], $component['manufacturer'],
    'PartSense', 'Components']))
    @push('link')
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    @endpush
    @push('styles')
        <style>
            body {
                line-height: 1.6;
            }

            .container {
                max-width: 1200px;
                margin: 0 auto;
                /* padding: 0 20px; */
            }

            .btn {
                background-color: var(--primary-color);
                color: white;
                padding: 10px 20px;
                border-radius: 5px;
                font-weight: 600;
                transition: background-color 0.3s ease;
            }

            .btn:hover {
                background-color: #2980b9;
            }

            /* Updated component details styles */
            .component-details {
                background-color: var(--card-background);
                border-radius: var(--border-radius);
                box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
                margin-top: 40px;
                margin-bottom: 20px;
                display: flex;
                flex-wrap: wrap;
            }

            .component-image {
                flex: 1;
                min-width: 300px;
                padding: 30px;
            }

            .component-image img {
                width: 100%;
                height: auto;
                object-fit: contain;
                border-radius: var(--border-radius);
            }

            .component-info {
                flex: 2;
                min-width: 300px;
                padding: 30px;
            }

            .component-info h1 {
                font-size: 28px;
                margin-bottom: 20px;
                color: var(--primary-color);
            }

            .component-info p {
                margin-bottom: 15px;
            }

            .component-info strong {
                font-weight: 600;
                color: var(--secondary-color);
            }

            .distributors {
                margin-top: 30px;
            }

            .distributor-card {
                background-color: var(--background-color);
                border-radius: var(--border-radius);
                padding: 20px;
                box-shadow: 0 2px 4px var(--shadow-color);
                margin-bottom: 20px;
                transition: box-shadow 0.3s ease;
            }

            .distributor-card:hover {
                box-shadow: 0 4px 8px var(--shadow-color);
            }

            .distributor-card h3 {
                font-size: 18px;
                margin-bottom: 10px;
                color: var(--primary-color);
            }

            .loading {
                text-align: center;
                padding: 40px;
                font-size: 18px;
                color: var(--secondary-color);
            }

            .error {
                color: #e74c3c;
                text-align: center;
                padding: 40px;
                font-size: 18px;
            }

            .add-to-inventory {
                background-color: var(--primary-color);
                color: white;
                border: none;
                padding: 10px 20px;
                border-radius: var(--border-radius);
                font-size: 16px;
                font-weight: 600;
                cursor: pointer;
                transition: background-color 0.3s ease;
                margin-top: 20px;
            }

            .add-to-inventory:hover {
                background-color: #2980b9;
            }

            .message {
                padding: 10px;
                border-radius: var(--border-radius);
                margin-top: 20px;
                font-weight: 600;
            }

            .success {
                background-color: #d4edda;
                color: #155724;
            }

            .error {
                background-color: #f8d7da;
                color: #721c24;
            }

            a {
                text-decoration: none;
                color: var(--text-color);
            }

            input[type="number"],
            textarea {
                width: 100%;
                padding: 12px;
                border-radius: var(--border-radius);
                border: 1px solid var(--input-border-color);
                font-size: 16px;
                margin-top: 8px;
                margin-bottom: 8px;
                box-sizing: border-box;
            }

            input[type="number"]:focus,
            textarea:focus {
                border-color: var(--input-focus-border-color);
                border-width: 1.5px;
                outline: none;
            }

            textarea {
                font-family: 'Inter', sans-serif;
                resize: none;
                min-height: 70px;
            }

            label {
                font-weight: 600;
                margin-bottom: 8px;
            }

            .info-container {
                position: relative;
                display: inline-block;
                cursor: pointer;
                margin: 20px;
                height: 20px;
            }

            .info-container .info-icon {
                width: 30px;
                height: 30px;
                background-color: #6c757d;
                /* Grey color */
                color: white;
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 18px;
                font-weight: bold;
                z-index: 1000;
                /* Ensure the icon is on top */
            }

            .info-container .info-message {
                visibility: hidden;
                width: 250px;
                /* Adjust width as needed */
                background-color: #333;
                /* Dark grey background for tooltip */
                color: #fff;
                text-align: center;
                border-radius: 6px;
                padding: 10px;
                position: absolute;
                z-index: 999;
                /* Ensure the tooltip is below the icon but above other content */
                bottom: -50px;
                /* Position the tooltip below the badge */
                left: 100%;
                /* Center the tooltip horizontally */
                transform: translateY(80px);
                /* Center the tooltip and offset it slightly below */
                opacity: 0;
                transition: opacity 0.3s;
            }

            .info-container:hover .info-message {
                visibility: visible;
                opacity: 1;
            }

            .info-container .info-message::after {
                content: "";
                position: absolute;
                top: -10px;
                /* Position the arrow above the tooltip */
                left: 100%;
                /* Center the arrow horizontally */
                transform: translateX(-100%);
                border-width: 10px;
                border-style: solid;
                border-color: transparent transparent #333 transparent;
                /* Arrow color matches tooltip background */
            }

            .discontinued {
                display: flex;
                align-items: center;
                background-color: #f8d7da;
                color: #721c24;
                padding: 10px 20px;
                border-radius: 8px;
                font-weight: bold;
                box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
                margin-bottom: 20px;
                border-left: 5px solid #dc3545;
            }

            .discontinued-icon {
                background-color: #dc3545;
                color: white;
                border-radius: 50%;
                width: 24px;
                height: 24px;
                display: flex;
                align-items: center;
                justify-content: center;
                margin-right: 10px;
                font-weight: bold;
            }

            .discontinued-text {
                flex: 1;
                font-size: 16px;
            }

            .component-parameters {
                margin-top: 20px;
            }

            .parameter-table {
                border-radius: 8px;
                /* Rounded corners for the table */
                overflow: hidden;
                /* Ensures corners are rounded properly */
                padding-bottom: 10px;
            }

            table {
                width: 100%;
                /* Full width of the parent */
                border-collapse: collapse;
                /* Collapse borders for a cleaner look */
            }

            th,
            td {
                padding: 12px;
                /* Padding for table cells */
                text-align: left;
                /* Align text to the left */
            }

            th {
                background-color: #f9f9f9;
                /* Light background for header */
                color: #333;
                /* Darker text for better readability */
            }

            tr:hover {
                background-color: #f1f1f1;
                /* Hover effect for rows */
            }



            /* Container styles */
            #recomendedComponentsContainer {
                display: grid;
                grid-auto-flow: column;
                gap: 20px;
                align-content: center;
                background-color: var(--card-background);
                border-radius: var(--border-radius);
                padding: 20px;
                overflow-x: auto;
                scrollbar-width: thin;
                scrollbar-color: #ccc transparent;
                box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            }

            /* Smooth scroll effect with rounded scrollbar */
            #recomendedComponentsContainer::-webkit-scrollbar {
                height: 8px;
            }

            #recomendedComponentsContainer::-webkit-scrollbar-thumb {
                background: #ccc;
                border-radius: 8px;
                /* Match border-radius to the scrollbar height */
            }

            /* Optional scrollbar track styling */
            #recomendedComponentsContainer::-webkit-scrollbar-track {
                background: transparent;
                border-radius: 8px;
                /* Rounded edges for track as well */
            }


            /* Component card styles */
            .recomendedComponents {
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: space-between;
                background-color: var(--background-color);
                padding: 20px;
                border-radius: var(--border-radius);
                box-shadow: 0px 4px 12px rgba(0, 0, 0, 0.1);
                transition: transform 0.3s ease, box-shadow 0.3s ease;
                width: 150px;
            }

            /* Hover effect for cards */
            .recomendedComponents:hover {
                transform: scale(1.05);
                box-shadow: 0px 6px 15px rgba(0, 0, 0, 0.15);
            }

            /* Image styling */
            .recommendedComponentsImg {
                width: 80px;
                height: 80px;
                object-fit: contain;
                margin-bottom: 10px;
            }

            /* Part number text styling */
            .recomendedComponentsPartNumber {
                font-size: 0.9em;
                font-weight: 600;
                color: #333;
                text-align: center;
                margin-top: 10px;
            }

            /* Breadcrumb Container */
            .breadcrumb {
                display: flex;
                align-items: center;
                font-size: 0.9em;
                color: #555;
                padding: 10px 0;
                gap: 5px;
            }

            .breadcrumb a {
                margin-left: 0;
                color: var(--primary-color);
                /* Link color */
                text-decoration: none;
                padding: 5px 10px;
                border-radius: 5px;
                transition: background-color 0.2s ease, color 0.2s ease;
            }

            .breadcrumb a:hover {
                background-color: #e7f1ff;
            }

            .breadcrumb span {
                color: #999;
                /* Separator color */
                font-size: 0.85em;
                padding: 0 5px;
            }

            /* Optional - Responsiveness for smaller screens */
            @media (max-width: 768px) {
                .breadcrumb {
                    font-size: 0.85em;
                    flex-wrap: wrap;
                }
            }

            .tabs-container {
                margin: 20px 0;
                border-radius: 8px;
                /* Rounded corners for the container */
                overflow: hidden;
                /* Ensures that the active tab has rounded corners */
                box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
                /* Soft shadow for depth */
            }

            .tabs {
                display: flex;
                /* Display tabs in a row */
                background-color: #fff;
                /* White background for the tabs */
                border-bottom: 2px solid var(--primary-color);
                /* Blue border for the bottom */
            }

            .tab {
                flex: 1;
                /* Equal width for each tab */
                padding: 15px 20px;
                /* Increased padding for better click area */
                background: transparent;
                /* Transparent background */
                border: none;
                /* Remove default button border */
                cursor: pointer;
                /* Pointer cursor on hover */
                font-size: 1em;
                /* Font size for tab text */
                color: #71717a;
                /* Blue text color for tabs */
                transition: background-color 0.3s, color 0.3s;
                /* Transition for hover effect */
                text-align: center;
                /* Center text in tabs */
            }

            .tab:hover {
                background-color: #e9ecef;
                /* Light gray background on hover */
            }

            .tab[aria-selected="true"] {
                background-color: #fff;
                /* Active tab background */
                color: var(--primary-color);
                /* Darker blue for active tab */
                border-bottom: 2px solid var(--primary-color);
                /* Blue underline for active tab */
                font-weight: bold;
                /* Bold font for active tab */
            }

            .tabpanel {
                margin-top: 0;
                /* No space above the content */
                padding: 20px;
                /* Padding for content */
                background-color: #fff;
                /* White background for content */
                border: 1px solid #e0e0e0;
                /* Light gray border for content area */
                border-radius: 0 0 var(--border-radius) var(--border-radius);
                /* Rounded corners at the bottom */
            }

            h3 {
                margin: 0 0 10px;
                /* Margin for headings */
                color: #333;
                /* Dark text color for headings */
            }

            p {
                margin: 0;
                /* Remove margin from paragraphs */
            }

            .parameter-table {
                margin-top: 20px;
                /* Space above the parameter table */
            }

            table {
                width: 100%;
                /* Full width for table */
                border-collapse: collapse;
                /* Collapse borders for cleaner look */
            }

            th,
            td {
                padding: 12px;
                /* Padding for table cells */
                text-align: left;
                /* Align text to the left */
                border-bottom: 1px solid #e0e0e0;
                /* Light gray bottom border */
            }

            th:last-child {
                border-bottom: none;
                /* Light gray bottom border */
            }

            th {
                background-color: #f8f9fa;
                /* Light background for table headers */
                font-weight: bold;
                /* Bold text for headers */
            }

            #datasheet-button {
                background-color: var(--primary-color);
                color: white;
                border: none;
                padding: 10px 20px;
                margin-right: 10px;
                border-radius: var(--border-radius);
                font-size: 16px;
                font-weight: 600;
                cursor: pointer;
                transition: background-color 0.3s ease;
                margin-top: 20px;
            }

            #datasheet-button:hover {
                background-color: #2980b9;
            }

            #inventory-container {
                margin-top: 10px;
            }

            i {
                padding-right: 8px
            }
        </style>
    @endpush
@section('content')

    <div class="container">
        <nav class="breadcrumb">
            <a href="#">Home</a>
            <span>&gt;</span>
            <a href="#">Category</a>
            <span>&gt;</span>
            <a href="#">Subcategory</a>
            <span>&gt;</span>
            <span>{{ $component['part_number'] }}</span>
        </nav>

        <div id="componentDetails" class="component-details">
            @if (isset($error))
                <div class="error">{{ $error }}</div>
            @else
                <div class="info-container">
                    <div class="info-icon">i</div>
                    <div class="info-message">
                        The images displayed are the property of their respective owners, including LCSC, Mouser, and
                        Digi-Key.
                    </div>
                </div>
                <div class="component-image">
                    <img src="/image/{{ $component['part_number'] }}?h=900&w=900"
                        onerror="this.onerror=null;this.src='Image_Not_Found.svg';" alt="{{ $component['part_number'] }}"
                        loading="lazy">
                </div>
                <div class="component-info">
                    <h1>{{ $component['part_number'] }}</h1>
                    @if ($component['is_discontinued'])
                        <div class="discontinued">
                            <div class="discontinued-icon">!</div>
                            <div class="discontinued-text">This product is discontinued</div>
                        </div>
                    @endif


                    <p><strong>Manufacturer:</strong> <a
                            href="/manufacturer/{{ $component['manufacturer'] }}">{{ $component['manufacturer'] }}</a></p>
                    <p><strong>MPN:</strong> {{ $component['mpn'] }}</p>
                    <p><strong>Description:</strong> {{ $component['description'] ?? 'N/A' }}</p>
                    @if (!empty($component['datasheet_link']))
                        <p><strong>Datasheet:</strong>
                            <a href="{{ $component['datasheet_link'] }}" target="_blank" rel="noopener noreferrer">
                                {{ $component['mpn'] ?? 'N/A' }}
                            </a>
                        </p>
                    @endif
                    <button id="datasheet-button"><i class="fa-solid fa-file-lines"></i> View Datasheet</button>

                    @auth
                        <div id="message"></div>

                        @if (!$component['user_inventory']['hasInInventory'])
                            <button class="add-to-inventory" onclick="addToInventory('{{ $component['part_number'] }}')">Add to
                                Inventory</button>
                        @else
                            <div id="inventory-container">
                                <div>
                                    <label for="quantity">Quantity:</label>
                                    <input type="number" id="quantity" name="quantity"
                                        value="{{ $component['user_inventory']['quantity'] }}">
                                </div>
                                <div>
                                    <label for="notes">Notes:</label>
                                    <textarea id="notes" name="notes" placeholder="Add any notes about this component...">{{ $component['user_inventory']['notes'] ?? '' }}</textarea>
                                </div>
                                <button class="add-to-inventory"
                                    onclick="updateComponent('{{ $component['part_number'] }}')">Save
                                    Changes</button>
                            </div>
                        @endif

                    @endauth


                    <div class="tabs-container">
                        <div class="tabs" role="tablist" aria-orientation="horizontal">
                            <button type="button" role="tab" aria-selected="true" id="tab-specifications"
                                class="tab" onclick="switchTab(event, 'specifications')">Specifications</button>
                            <button type="button" role="tab" aria-selected="false" id="tab-documents" class="tab"
                                onclick="switchTab(event, 'documents')">Documents</button>
                            <button type="button" role="tab" aria-selected="false" id="tab-compliance" class="tab"
                                onclick="switchTab(event, 'compliance')">Compliance</button>
                        </div>

                        <div id="content-specifications" class="tabpanel" role="tabpanel"
                            aria-labelledby="tab-specifications">
                            @if (isset($parameters) && $parameters->isNotEmpty())
                                <div class="component-parameters">
                                    <div class="parameter-table">
                                        <h3>Detailed Specifications</h3>
                                        <table>
                                            <thead>
                                                <tr>
                                                    <th>Parameter</th>
                                                    <th>Value</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                @foreach ($parameters as $paramName => $paramValue)
                                                    <tr>
                                                        <td>{{ $paramName }}</td>
                                                        <td>{{ $paramValue }}</td>
                                                    </tr>
                                                @endforeach
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            @endif
                        </div>
                        <div id="content-documents" class="tabpanel" role="tabpanel" aria-labelledby="tab-documents" hidden>
                            <h3>Documents</h3>
                            <p>Document details will be displayed in this section.</p>
                        </div>
                        <div id="content-compliance" class="tabpanel" role="tabpanel" aria-labelledby="tab-compliance"
                            hidden>
                            <h3>Compliance Information</h3>
                            <p>Compliance and certification details will be displayed in this section.</p>
                        </div>
                    </div>
                    <h2>Distributors</h2>
                    <div class="distributors">
                        @foreach ($component['distributors'] as $distributor => $info)
                            @if (!empty($info['part_number']))
                                @php
                                    $url = '';
                                    switch ($distributor) {
                                        case 'lcsc':
                                            $url = 'https://lcsc.com/search?q=' . urlencode($info['part_number']);
                                            break;
                                        case 'digikey':
                                            $url =
                                                'https://www.digikey.ca/en/products/result?keywords=' .
                                                urlencode($info['part_number']);
                                            break;
                                        case 'mouser':
                                            $url = 'https://www.mouser.com/c/?q=' . urlencode($info['part_number']);
                                            break;
                                    }
                                @endphp
                                @if ($url)
                                    <a href="{{ $url }}" target="_blank">
                                        <div class="distributor-card">
                                            <h3>{{ strtoupper($distributor) }}</h3>
                                            <p><strong>Part Number:</strong> {{ $info['part_number'] }}</p>
                                            <p><strong>Stock:</strong> {{ $info['stock'] ?? 'N/A' }}</p>
                                            <p><strong>Price:</strong> {{ $info['price'] ?? 'N/A' }}
                                                {{ $info['currency'] ?? 'N/A' }}</p>
                                        </div>
                                    </a>
                                @endif
                            @endif
                        @endforeach

                    </div>
                </div>
            @endif
        </div>
        <div id="recomendedComponentsContainer">
            <div class="recomendedComponents">
                <img src="" alt="Component Image" class="recommendedComponentsImg">
                <div class="recomendedComponentsPartNumber">Component 1</div>
            </div>
            <div class="recomendedComponents">
                <img src="" alt="Component Image" class="recommendedComponentsImg">
                <div class="recomendedComponentsPartNumber">Component 2</div>
            </div>
            <div class="recomendedComponents">
                <img src="" alt="Component Image" class="recommendedComponentsImg">
                <div class="recomendedComponentsPartNumber">Component 3</div>
            </div>
            <div class="recomendedComponents">
                <img src="" alt="Component Image" class="recommendedComponentsImg">
                <div class="recomendedComponentsPartNumber">Component 4</div>
            </div>
            <div class="recomendedComponents">
                <img src="" alt="Component Image" class="recommendedComponentsImg">
                <div class="recomendedComponentsPartNumber">Component 5</div>
            </div>
        </div>
    </div>

    @auth
        <script>
            window.userID = "{{ auth()->id() }}";
            window.csrf = "{{ csrf_token() }}";
        </script>
    @endauth
@endsection
@push('scripts')
    @auth
        <script>
            function addToInventory(partNumber) {

                fetch('/inventory/add', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({
                            part_number: partNumber,
                            user_id: window.userID,
                            _token: window.csrf,
                            quantity: 0,
                            notes: null
                        }),
                    })
                    .then(response => {
                        if (!response.ok) {
                            return response.json().then(err => {
                                throw err;
                            });
                        }
                        return response.json();
                    })
                    .then(data => {
                        if (data.message) {
                            showMessage(data.message, 'success');
                        } else {
                            showMessage('{{ __('Component added to inventory successfully!') }}', 'success');
                        }
                        // Find the element with class 'add-to-inventory'
                        const addToInventoryElement = document.querySelector('.add-to-inventory');

                        if (addToInventoryElement) {
                            // Create the new HTML structure as a string
                            const newHTML = `
        <div>
            <label for="quantity">Quantity:</label>
            <input type="number" id="quantity" name="quantity"
                value="{{ $component['user_inventory']['quantity'] }}">
        </div>
        <div>
            <label for="notes">Notes:</label>
            <textarea id="notes" name="notes">{{ $component['user_inventory']['notes'] ?? '' }}</textarea>
        </div>
        <button class="add-to-inventory" onclick="updateComponent('{{ $component['part_number'] }}')">
            Save Changes
        </button>
    `;

                            // Replace the existing element's HTML content
                            addToInventoryElement.outerHTML = newHTML;
                        }
                    })
                    .catch(error => {
                        if (error.message) {
                            showMessage('Error: ' + error.message, 'error');
                        } else {
                            showMessage('{{ __('Error: Failed to add component to inventory') }}', 'error');
                        }
                    });
            }

            function updateComponent(partNumber) {
                const quantity = document.getElementById('quantity').value;
                const notes = document.getElementById('notes').value;

                fetch('/inventory/update', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({
                            part_number: partNumber,
                            user_id: window.userID,
                            _token: window.csrf,
                            quantity: quantity,
                            notes: notes
                        }),
                    })
                    .then(response => {
                        if (!response.ok) {
                            return response.json().then(err => {
                                throw err;
                            });
                        }
                        return response.json();
                    })
                    .then(data => {
                        if (data.message) {
                            showMessage(data.message, 'success');
                        } else {
                            showMessage('{{ __('Component updated successfully!') }}', 'success');
                        }
                    })
                    .catch(error => {
                        if (error.message) {
                            showMessage('Error: ' + error.message, 'error');
                        } else {
                            showMessage('{{ __('Error: Failed to update component') }}', 'error');
                        }
                    });
            }

            function showMessage(message, type) {
                const messageElement = document.getElementById('message');
                messageElement.textContent = message;
                messageElement.className = `message ${type}`;

                // Hide the message after 5 seconds
                setTimeout(() => {
                    messageElement.textContent = '';
                    messageElement.className = '';
                }, 5000);
            }
        </script>
    @endauth
    <script>
        function switchTab(event, tabName) {
            const tabs = document.querySelectorAll('.tab');
            const tabPanels = document.querySelectorAll('.tabpanel');

            tabs.forEach(tab => {
                tab.setAttribute('aria-selected', 'false');
            });

            tabPanels.forEach(panel => {
                panel.hidden = true;
            });

            event.currentTarget.setAttribute('aria-selected', 'true');
            document.getElementById(`content-${tabName}`).hidden = false;
        }
    </script>
@endpush
