@extends('front_end.pages.settings.layout')

@section('title', 'Notification Settings - Socialink')

@push('styles')
<style>
    .section-divider {
        height: 1px;
        background-color: #e9ecef;
        margin: 2rem 0;
    }

    .settings-section {
        margin-bottom: 2.5rem;
    }

    .settings-section-header {
        font-weight: 700;
        margin-bottom: 1.5rem;
        color: #1a1a1a;
        display: flex;
        align-items: center;
        gap: 12px;
        font-size: 1.1rem;
        padding-bottom: 0.75rem;
        border-bottom: 2px solid #f0f0f0;
    }

    .settings-section-header svg {
        width: 22px;
        height: 22px;
        color: #2196F3;
    }

    .form-table-row {
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        background: linear-gradient(135deg, #ffffff 0%, #fafafa 100%);
        border: 1px solid #e8e8e8 !important;
    }

    .form-table-row:hover {
        transform: translateY(-3px);
        box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
        border-color: #2196F3 !important;
        background: linear-gradient(135deg, #ffffff 0%, #f5f9ff 100%);
    }

    .badge-enabled {
        background-color: #e6f7ee;
        color: #0d9a5d;
        font-size: 0.75rem;
        padding: 0.25rem 0.5rem;
        border-radius: 4px;
    }

    .save-button {
        background: linear-gradient(135deg, #2196F3 0%, #1976D2 100%);
        border: none;
        padding: 12px 32px;
        font-weight: 600;
        letter-spacing: 0.5px;
        transition: all 0.3s ease;
        box-shadow: 0 4px 12px rgba(33, 150, 243, 0.3);
    }

    .save-button:hover {
        background: linear-gradient(135deg, #1976D2 0%, #1565C0 100%);
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(33, 150, 243, 0.4);
    }

    .save-button:disabled {
        opacity: 0.7;
        cursor: not-allowed;
        transform: none;
    }

    .card {
        border-radius: 16px !important;
        overflow: hidden;
    }

    .card-header.with-icon {
        background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
        border-bottom: 2px solid #f0f0f0;
    }

    .main-icon svg {
        filter: drop-shadow(0 2px 4px rgba(33, 150, 243, 0.2));
    }

    .notification-alert {
        border-radius: 12px;
        animation: slideDown 0.3s ease;
    }

    @keyframes slideDown {
        from {
            opacity: 0;
            transform: translateY(-10px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }
</style>
@endpush

@section('settings_content')
<div class="card mb-4 border-0 shadow-sm">
    <div class="card-header with-icon p-4 bg-white">
        <div class="d-flex align-items-center">
            <div class="main-icon">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 371.263 371.263" width="32" height="32"><path d="M353.12 277.369c-2.036-21.198-20.958-37.845-42.995-37.845a4.703 4.703 0 0 1-4.731-4.731v-70.54c0-52.396-33.533-98.085-79.702-115.151.539-2.695.838-5.449.838-8.204C226.531 18.324 208.208 0 185.632 0s-40.899 18.324-40.899 40.899c0 2.695.299 5.389.778 7.964-15.868 5.629-30.539 14.551-43.054 26.647-23.593 22.755-36.587 53.354-36.587 86.169v73.115c0 2.575-2.096 4.731-4.731 4.731-22.096 0-40.959 16.647-42.995 37.845-1.138 11.797 2.755 23.533 10.719 32.276 7.904 8.683 19.222 13.713 31.018 13.713h72.217c2.994 26.887 25.869 47.905 53.534 47.905s50.54-21.018 53.534-47.905h72.217c11.797 0 23.114-5.03 31.018-13.713 7.904-8.744 11.857-20.48 10.719-32.277zM185.632 23.952c9.341 0 16.946 7.605 16.946 16.946 0 .778-.12 1.497-.24 2.275-4.072-.599-8.204-1.018-12.336-1.138-7.126-.24-14.132.24-21.078 1.198-.12-.778-.24-1.497-.24-2.275.002-9.401 7.607-17.006 16.948-17.006zm0 323.358c-14.431 0-26.527-10.3-29.342-23.952h58.683c-2.813 13.653-14.909 23.952-29.341 23.952zm139.044-53.773c-3.473 3.773-8.144 5.868-13.294 5.868h-251.5c-5.15 0-9.82-2.096-13.294-5.868-3.473-3.772-5.09-8.743-4.551-13.892.838-9.042 9.282-16.168 19.162-16.168 15.809 0 28.683-12.874 28.683-28.683v-73.115c0-26.228 10.419-50.719 29.282-68.923 17.964-17.425 41.438-26.887 66.468-26.887 1.198 0 2.335 0 3.533.06 50.839 1.796 92.277 45.929 92.277 98.325v70.54c0 15.809 12.874 28.683 28.683 28.683 9.88 0 18.324 7.126 19.162 16.168.479 5.149-1.138 10.06-4.611 13.892z" fill="currentColor"/></svg>
            </div>
            <h5 class="mb-0 ms-3 fw-bold">Notification Settings</h5>
        </div>
    </div>
    <div class="card-body p-4">
        @if(session('success'))
            <div class="alert alert-success mb-4 d-flex align-items-center">
                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="me-2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path><polyline points="22 4 12 14.01 9 11.01"></polyline></svg>
                <div>{{ session('success') }}</div>
            </div>
        @endif

        @if(session('error'))
            <div class="alert alert-danger mb-4 d-flex align-items-center">
                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="me-2"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="8" x2="12" y2="12"></line><line x1="12" y1="16" x2="12.01" y2="16"></line></svg>
                <div>{{ session('error') }}</div>
            </div>
        @endif

        @php
            $defaultNotificationSettings = [
                'notify_like' => 1,
                'notify_comment' => 1,
                'notify_share_post' => 1,
                'notify_accept_request' => 1,
                'notify_liked_page' => 1,
                'notify_joined_group' => 1,
                'notify_view_story' => 1,
                'notify_visited_my_profile' => 0,
                'notify_mentioned_me' => 1,
                'notify_message' => 1,
                'notify_friends_newpost' => 1,
                'notify_profile_visit' => 1,
                'notify_send_request' => 1,
            ];

            $rawNotificationSettings = auth()->user()->notification_setting ?? [];

            if (is_string($rawNotificationSettings)) {
                $cleanJson = preg_replace('/[^\x20-\x7E]/', '', $rawNotificationSettings);
                $parsedNotificationSettings = json_decode($cleanJson, true) ?: [];
            } elseif (is_array($rawNotificationSettings)) {
                $parsedNotificationSettings = $rawNotificationSettings;
            } elseif ($rawNotificationSettings instanceof \Illuminate\Support\Collection) {
                $parsedNotificationSettings = $rawNotificationSettings->toArray();
            } else {
                $parsedNotificationSettings = [];
            }

            $notificationSettings = array_merge($defaultNotificationSettings, $parsedNotificationSettings);

            $notificationSections = [
                'Post Activity' => [
                    'icon' => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 8.5a5.5 5.5 0 0 0-11 0V9H4.5A2.5 2.5 0 0 0 2 11.5v7A2.5 2.5 0 0 0 4.5 21H13v-7.5l8 8V8.5z"></path></svg>',
                    'options' => [
                        'notify_like' => [
                            'label' => 'Post Likes',
                            'description' => 'Receive alerts when someone likes your posts.',
                        ],
                        'notify_comment' => [
                            'label' => 'Post Comments',
                            'description' => 'Be notified when someone comments on your posts.',
                        ],
                        'notify_share_post' => [
                            'label' => 'Post Shares',
                            'description' => 'Know when someone shares your posts.',
                        ],
                        'notify_friends_newpost' => [
                            'label' => "Friends' New Posts",
                            'description' => 'Get notified when friends publish something new.',
                        ],
                    ],
                ],
                'Connections & Messages' => [
                    'icon' => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path></svg>',
                    'options' => [
                        'notify_send_request' => [
                            'label' => 'Friend Requests Sent',
                            'description' => 'Updates when your friend requests are sent.',
                        ],
                        'notify_accept_request' => [
                            'label' => 'Friend Requests Accepted',
                            'description' => 'Alerts when someone accepts your friend request.',
                        ],
                        'notify_message' => [
                            'label' => 'Direct Messages',
                            'description' => 'Receive notifications for new direct messages.',
                        ],
                    ],
                ],
                'Community Activity' => [
                    'icon' => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M8 21h8"></path><path d="M12 17v4"></path><path d="M7 21h10"></path><path d="M5 11a7 7 0 0 1 14 0v5H5v-5z"></path></svg>',
                    'options' => [
                        'notify_liked_page' => [
                            'label' => 'Page Activity',
                            'description' => 'Stay updated when pages you like have new activity.',
                        ],
                        'notify_joined_group' => [
                            'label' => 'Group Membership',
                            'description' => 'Get alerts when someone joins your groups.',
                        ],
                        'notify_view_story' => [
                            'label' => 'Story Views',
                            'description' => 'See who viewed your stories.',
                        ],
                    ],
                ],
                'Profile & Mentions' => [
                    'icon' => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 12a5 5 0 1 0-5-5 5 5 0 0 0 5 5z"></path><path d="M20 21a8 8 0 1 0-16 0"></path></svg>',
                    'options' => [
                        'notify_mentioned_me' => [
                            'label' => 'Mentions',
                            'description' => 'Be notified when someone mentions you.',
                        ],
                        'notify_profile_visit' => [
                            'label' => 'Profile Visits',
                            'description' => 'Alerts when other members view your profile.',
                        ],
                        'notify_visited_my_profile' => [
                            'label' => 'Share My Visits',
                            'description' => 'Notify others when you visit their profile.',
                        ],
                    ],
                ],
            ];
        @endphp

        <p class="text-muted mb-4" style="font-size: 0.95rem; line-height: 1.6;">
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="16" height="16" style="display: inline-block; vertical-align: middle; margin-right: 6px; color: #2196F3;"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="16" x2="12" y2="12"></line><line x1="12" y1="8" x2="12.01" y2="8"></line></svg>
            Choose when and how you want to receive notifications about activity on Socialink. You can update these settings anytime.
        </p>

        <form id="notification-settings-form" action="{{ route('webapi.profile.update-notification-setting') }}" method="POST">
            @csrf

            <div id="notification-alert" class="alert d-none mb-4 notification-alert" role="alert" tabindex="-1"></div>

            @foreach($notificationSections as $sectionTitle => $sectionData)
                <div class="settings-section">
                    <h6 class="settings-section-header">
                        {!! $sectionData['icon'] !!}
                        {{ $sectionTitle }}
                    </h6>
                    <div class="ps-0 ps-md-3">
                        @foreach($sectionData['options'] as $field => $meta)
                            <div class="form-table-row mb-3 p-3 border rounded">
                                <div class="row align-items-center">
                                    <div class="col">
                                        <div class="form-label h6 mb-1" style="font-weight: 600; color: #2c3e50;">{{ $meta['label'] }}</div>
                                        @if(!empty($meta['description']))
                                            <div class="form-text d-none d-sm-block" style="font-size: 0.875rem; color: #6c757d; line-height: 1.5;">{{ $meta['description'] }}</div>
                                        @endif
                                    </div>
                                    <div class="col-auto text-end">
                                        <label class="switch" for="{{ $field }}">
                                            <input
                                                type="checkbox"
                                                id="{{ $field }}"
                                                name="{{ $field }}"
                                                value="1"
                                                {{ (int) ($notificationSettings[$field] ?? 0) === 1 ? 'checked' : '' }}
                                            >
                                            <span class="slider round"></span>
                                        </label>
                                    </div>
                                </div>
                            </div>
                        @endforeach
                    </div>
                </div>
            @endforeach

            <div class="mt-4 text-end">
                <button type="submit" class="btn btn-primary save-button">
                    <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="me-2"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"></path><polyline points="17 21 17 13 7 13 7 21"></polyline><polyline points="7 3 7 8 15 8"></polyline></svg>
                    Save Settings
                </button>
            </div>
        </form>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function () {
        const form = document.getElementById('notification-settings-form');
        if (!form) {
            return;
        }

        const endpoint = form.getAttribute('action');
        const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
        const alertBox = document.getElementById('notification-alert');
        const submitButton = form.querySelector('button[type="submit"]');

        function showAlert(type, message) {
            if (!alertBox) {
                return;
            }

            alertBox.classList.remove('d-none', 'alert-success', 'alert-danger');
            alertBox.classList.add(type === 'success' ? 'alert-success' : 'alert-danger');
            alertBox.textContent = message;
        }

        form.addEventListener('submit', async function (event) {
            event.preventDefault();

            if (!csrfToken) {
                showAlert('danger', 'Missing CSRF token.');
                return;
            }

            const payload = {};
            form.querySelectorAll('input[type="checkbox"]').forEach((input) => {
                payload[input.name] = input.checked ? 1 : 0;
            });

            if (submitButton) {
                submitButton.disabled = true;
                submitButton.dataset.originalText = submitButton.dataset.originalText || submitButton.innerHTML;
                submitButton.innerHTML = 'Saving...';
            }

            try {
                const response = await fetch(endpoint, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': csrfToken,
                        'Accept': 'application/json',
                    },
                    body: JSON.stringify(payload),
                });

                const data = await response.json().catch(() => ({}));

                if (response.ok && data.success) {
                    showAlert('success', data.message || 'Notification settings updated successfully.');
                    setTimeout(() => {
                        alertBox?.classList.add('d-none');
                    }, 4000);
                } else if (response.status === 422 && data.errors) {
                    const firstError = Object.values(data.errors)[0];
                    const errorMessage = Array.isArray(firstError) ? firstError[0] : firstError;
                    showAlert('danger', errorMessage || 'Please review the highlighted fields.');
                } else {
                    showAlert('danger', data.message || 'Unable to update notification settings.');
                }
            } catch (error) {
                showAlert('danger', 'Something went wrong. Please try again.');
            } finally {
                if (submitButton) {
                    submitButton.disabled = false;
                    submitButton.innerHTML = submitButton.dataset.originalText || 'Save Settings';
                }
            }
        });
    });
</script>
@endsection
