@extends('layouts.master')

@section('page-title', 'Proly - AI Legal Assistant')

@section('styles')
<style>
    /* ========================================
       PROLY AI LEGAL ASSISTANT - IMPROVED VERSION
       ======================================== */

    :root {
        /* Primary colors */
        --primary: #1e3a8a;
        --primary-dark: #1e40af;
        --primary-light: #3b82f6;
        --primary-bg: #dbeafe;
        
        /* Accent colors */
        --accent: #3b82f6;
        --accent-purple: #8b5cf6;
        --accent-gradient: linear-gradient(135deg, #1e3a8a 0%, #3b82f6 100%);
        
        /* Background colors */
        --bg-main: #f8fafc;
        --bg-card: #ffffff;
        --bg-secondary: #f1f5f9;
        --bg-tertiary: #e2e8f0;
        
        /* Text colors */
        --text-primary: #1e293b;
        --text-secondary: #64748b;
        --text-tertiary: #94a3b8;
        --text-inverse: #ffffff;
        
        /* Status colors */
        --success: #10b981;
        --success-light: #d1fae5;
        --warning: #f59e0b;
        --warning-light: #fef3c7;
        --danger: #ef4444;
        --danger-light: #fee2e2;
        --info: #06b6d4;
        --info-light: #cffafe;
        
        /* Border colors */
        --border: #e2e8f0;
        --border-light: #f1f5f9;
        --border-focus: #3b82f6;
        
        /* Shadows */
        --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
        --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
        --shadow-xl: 0 20px 25px -5px rgba(0, 0, 0, 0.1);
        
        /* Transitions */
        --transition-fast: 150ms ease;
        --transition-base: 200ms ease;
        --transition-slow: 300ms ease;
        
        /* Spacing */
        --space-xs: 0.25rem;
        --space-sm: 0.5rem;
        --space-md: 1rem;
        --space-lg: 1.5rem;
        --space-xl: 2rem;
        --space-2xl: 3rem;
        
        /* Border radius */
        --radius-sm: 0.375rem;
        --radius-md: 0.5rem;
        --radius-lg: 0.75rem;
        --radius-xl: 1rem;
        --radius-2xl: 1.5rem;
        --radius-full: 9999px;
    }

    /* Dark mode */
    .dark-mode {
        --bg-main: #0f172a;
        --bg-card: #1e293b;
        --bg-secondary: #334155;
        --bg-tertiary: #475569;
        --text-primary: #f1f5f9;
        --text-secondary: #cbd5e1;
        --text-tertiary: #94a3b8;
        --border: #334155;
        --border-light: #475569;
    }

    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }

    body {
        background: var(--bg-main);
        font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', sans-serif;
        color: var(--text-primary);
        transition: background var(--transition-base), color var(--transition-base);
    }

    /* ========================================
       MAIN CONTAINER
       ======================================== */

    .chat-container {
        max-width: 1400px;
        margin: 0 auto;
        padding: var(--space-lg);
        height: 100vh;
        display: flex;
        flex-direction: column;
        gap: 0;
    }

    /* ========================================
       HEADER
       ======================================== */

    .chat-header {
        background: var(--accent-gradient);
        padding: var(--space-lg) var(--space-xl);
        border-radius: var(--radius-2xl) var(--radius-2xl) 0 0;
        box-shadow: var(--shadow-lg);
        display: flex;
        align-items: center;
        justify-content: space-between;
        position: relative;
        overflow: hidden;
    }

    .chat-header::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: url('data:image/svg+xml,<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg"><defs><pattern id="grid" width="20" height="20" patternUnits="userSpaceOnUse"><path d="M 20 0 L 0 0 0 20" fill="none" stroke="white" stroke-width="0.5" opacity="0.1"/></pattern></defs><rect width="100" height="100" fill="url(%23grid)"/></svg>');
        opacity: 0.1;
        pointer-events: none;
    }

    .header-left {
        display: flex;
        align-items: center;
        gap: var(--space-lg);
        position: relative;
        z-index: 1;
    }

    .back-btn {
        display: inline-flex;
        align-items: center;
        gap: var(--space-sm);
        color: rgba(255, 255, 255, 0.9);
        text-decoration: none;
        font-size: 14px;
        font-weight: 600;
        padding: var(--space-sm) var(--space-md);
        border-radius: var(--radius-lg);
        transition: all var(--transition-fast);
        background: rgba(255, 255, 255, 0.1);
        backdrop-filter: blur(10px);
        border: 1px solid rgba(255, 255, 255, 0.2);
    }

    .back-btn:hover {
        background: rgba(255, 255, 255, 0.2);
        color: white;
        transform: translateX(-3px);
    }

    .header-title {
        display: flex;
        align-items: center;
        gap: var(--space-md);
    }

    .bot-icon {
        font-size: 42px;
        animation: float 3s ease-in-out infinite;
        filter: drop-shadow(0 4px 8px rgba(0, 0, 0, 0.2));
    }

    @keyframes float {
        0%, 100% { transform: translateY(0px) rotate(0deg); }
        50% { transform: translateY(-8px) rotate(5deg); }
    }

    .header-title-text h1 {
        color: white;
        font-size: 28px;
        font-weight: 700;
        margin-bottom: 4px;
        text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }

    .header-title-text p {
        color: rgba(255, 255, 255, 0.85);
        font-size: 14px;
        font-weight: 500;
    }

    .header-right {
        display: flex;
        align-items: center;
        gap: var(--space-md);
        position: relative;
        z-index: 1;
    }

    .status-indicator {
        display: flex;
        align-items: center;
        gap: var(--space-sm);
        background: rgba(255, 255, 255, 0.15);
        padding: var(--space-sm) var(--space-md);
        border-radius: var(--radius-full);
        backdrop-filter: blur(10px);
        border: 1px solid rgba(255, 255, 255, 0.2);
    }

    .status-dot {
        width: 10px;
        height: 10px;
        background: var(--success);
        border-radius: 50%;
        animation: pulse 2s ease-in-out infinite;
        box-shadow: 0 0 10px var(--success);
    }

    @keyframes pulse {
        0%, 100% { opacity: 1; transform: scale(1); }
        50% { opacity: 0.6; transform: scale(1.1); }
    }

    .status-text {
        color: white;
        font-size: 13px;
        font-weight: 600;
    }

    .header-actions {
        display: flex;
        gap: var(--space-sm);
    }

    .header-btn {
        width: 36px;
        height: 36px;
        display: flex;
        align-items: center;
        justify-content: center;
        background: rgba(255, 255, 255, 0.15);
        border: 1px solid rgba(255, 255, 255, 0.2);
        border-radius: var(--radius-lg);
        color: white;
        cursor: pointer;
        transition: all var(--transition-fast);
        backdrop-filter: blur(10px);
    }

    .header-btn:hover {
        background: rgba(255, 255, 255, 0.25);
        transform: translateY(-2px);
    }

    /* ========================================
       CHAT BODY
       ======================================== */

    .chat-body {
        background: var(--bg-card);
        flex: 1;
        overflow-y: auto;
        padding: var(--space-xl);
        border-left: 1px solid var(--border);
        border-right: 1px solid var(--border);
        position: relative;
    }

    .chat-body::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 40px;
        background: linear-gradient(to bottom, var(--bg-card), transparent);
        pointer-events: none;
        z-index: 1;
    }

    .chat-body::-webkit-scrollbar {
        width: 8px;
    }

    .chat-body::-webkit-scrollbar-track {
        background: transparent;
    }

    .chat-body::-webkit-scrollbar-thumb {
        background: var(--border-light);
        border-radius: var(--radius-full);
    }

    .chat-body::-webkit-scrollbar-thumb:hover {
        background: var(--border);
    }

    .chat-messages {
        max-width: 900px;
        margin: 0 auto;
        display: flex;
        flex-direction: column;
        gap: var(--space-lg);
        padding-bottom: var(--space-xl);
    }

    /* ========================================
       MESSAGES
       ======================================== */

    .message {
        display: flex;
        gap: var(--space-md);
        animation: slideIn 0.4s cubic-bezier(0.34, 1.56, 0.64, 1);
        opacity: 0;
        animation-fill-mode: forwards;
    }

    @keyframes slideIn {
        from {
            opacity: 0;
            transform: translateY(20px) scale(0.95);
        }
        to {
            opacity: 1;
            transform: translateY(0) scale(1);
        }
    }

    .message.user {
        flex-direction: row-reverse;
    }

    .message-avatar {
        width: 44px;
        height: 44px;
        border-radius: var(--radius-xl);
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 20px;
        flex-shrink: 0;
        box-shadow: var(--shadow-md);
        position: relative;
    }

    .message.bot .message-avatar {
        background: var(--accent-gradient);
        color: white;
    }

    .message.user .message-avatar {
        background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
        color: white;
    }

    .message-wrapper {
        display: flex;
        flex-direction: column;
        gap: var(--space-xs);
        max-width: 75%;
    }

    .message-header {
        display: flex;
        align-items: center;
        gap: var(--space-sm);
        padding: 0 var(--space-xs);
    }

    .message-sender {
        font-size: 12px;
        font-weight: 600;
        color: var(--text-secondary);
    }

    .message-time {
        font-size: 11px;
        color: var(--text-tertiary);
    }

    .message-content {
        background: var(--bg-secondary);
        padding: var(--space-md) var(--space-lg);
        border-radius: var(--radius-xl);
        box-shadow: var(--shadow-sm);
        position: relative;
        border: 1px solid var(--border-light);
    }

    .message.user .message-content {
        background: var(--accent-gradient);
        color: white;
        border: none;
    }

    .message.bot .message-content {
        background: white;
        border: 1px solid var(--border);
    }

    .dark-mode .message.bot .message-content {
        background: var(--bg-secondary);
    }

    .message-text {
        line-height: 1.7;
        margin: 0;
        font-size: 15px;
        word-wrap: break-word;
    }

    .message.user .message-text {
        color: white;
    }

    .message-actions {
        display: flex;
        gap: var(--space-sm);
        margin-top: var(--space-sm);
        padding: 0 var(--space-xs);
    }

    .message-action-btn {
        display: flex;
        align-items: center;
        gap: 4px;
        padding: 4px var(--space-sm);
        background: transparent;
        border: none;
        border-radius: var(--radius-sm);
        color: var(--text-tertiary);
        font-size: 12px;
        cursor: pointer;
        transition: all var(--transition-fast);
    }

    .message-action-btn:hover {
        background: var(--bg-tertiary);
        color: var(--text-secondary);
    }

    /* Typing indicator */
    .typing-indicator {
        display: flex;
        gap: 6px;
        padding: var(--space-md);
    }

    .typing-dot {
        width: 10px;
        height: 10px;
        background: var(--text-secondary);
        border-radius: 50%;
        animation: typing 1.4s ease-in-out infinite;
    }

    .typing-dot:nth-child(2) { animation-delay: 0.2s; }
    .typing-dot:nth-child(3) { animation-delay: 0.4s; }

    @keyframes typing {
        0%, 60%, 100% { 
            transform: translateY(0);
            opacity: 0.4;
        }
        30% { 
            transform: translateY(-12px);
            opacity: 1;
        }
    }

    /* ========================================
       SUGGESTIONS
       ======================================== */

    .suggestions-container {
        max-width: 900px;
        margin: var(--space-lg) auto 0;
        animation: fadeIn 0.5s ease-out;
    }

    @keyframes fadeIn {
        from { opacity: 0; }
        to { opacity: 1; }
    }

    .suggestions-title {
        font-size: 13px;
        font-weight: 600;
        color: var(--text-secondary);
        margin-bottom: var(--space-md);
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }

    .suggestions-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
        gap: var(--space-md);
    }

    .suggestion-card {
        background: white;
        border: 1px solid var(--border);
        border-radius: var(--radius-xl);
        padding: var(--space-lg);
        cursor: pointer;
        transition: all var(--transition-base);
        display: flex;
        flex-direction: column;
        gap: var(--space-sm);
    }

    .dark-mode .suggestion-card {
        background: var(--bg-secondary);
    }

    .suggestion-card:hover {
        transform: translateY(-4px);
        box-shadow: var(--shadow-lg);
        border-color: var(--primary-light);
    }

    .suggestion-icon {
        font-size: 24px;
        margin-bottom: var(--space-xs);
    }

    .suggestion-title {
        font-size: 15px;
        font-weight: 700;
        color: var(--text-primary);
        margin-bottom: 4px;
    }

    .suggestion-desc {
        font-size: 13px;
        color: var(--text-secondary);
        line-height: 1.5;
    }

    /* ========================================
       EMPTY STATE
       ======================================== */

    .empty-state {
        text-align: center;
        padding: var(--space-2xl) var(--space-lg);
        color: var(--text-secondary);
        animation: fadeIn 0.6s ease-out;
    }

    .empty-state-icon {
        font-size: 72px;
        margin-bottom: var(--space-lg);
        animation: float 3s ease-in-out infinite;
        filter: drop-shadow(0 4px 8px rgba(0, 0, 0, 0.1));
    }

    .empty-state h3 {
        font-size: 24px;
        color: var(--text-primary);
        margin-bottom: var(--space-sm);
        font-weight: 700;
    }

    .empty-state p {
        font-size: 15px;
        color: var(--text-secondary);
        max-width: 500px;
        margin: 0 auto var(--space-xl);
        line-height: 1.6;
    }

    .features-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: var(--space-lg);
        max-width: 800px;
        margin: var(--space-xl) auto 0;
    }

    .feature-item {
        text-align: center;
        padding: var(--space-lg);
        background: var(--bg-secondary);
        border-radius: var(--radius-xl);
        transition: all var(--transition-base);
    }

    .feature-item:hover {
        transform: translateY(-4px);
        box-shadow: var(--shadow-md);
    }

    .feature-icon {
        font-size: 32px;
        margin-bottom: var(--space-sm);
    }

    .feature-title {
        font-size: 14px;
        font-weight: 600;
        color: var(--text-primary);
        margin-bottom: 4px;
    }

    .feature-desc {
        font-size: 12px;
        color: var(--text-secondary);
    }

    /* ========================================
       FOOTER / INPUT AREA
       ======================================== */

    .chat-footer {
        background: var(--bg-card);
        padding: var(--space-lg) var(--space-xl);
        border-radius: 0 0 var(--radius-2xl) var(--radius-2xl);
        border: 1px solid var(--border);
        border-top: none;
        box-shadow: 0 -4px 12px rgba(0, 0, 0, 0.05);
    }

    .quick-actions {
        max-width: 900px;
        margin: 0 auto var(--space-lg);
        display: flex;
        gap: var(--space-sm);
        flex-wrap: wrap;
        justify-content: center;
    }

    .quick-action {
        padding: var(--space-sm) var(--space-md);
        background: white;
        border: 1px solid var(--border);
        border-radius: var(--radius-full);
        font-size: 13px;
        font-weight: 600;
        color: var(--text-primary);
        cursor: pointer;
        transition: all var(--transition-fast);
        display: flex;
        align-items: center;
        gap: var(--space-xs);
    }

    .dark-mode .quick-action {
        background: var(--bg-secondary);
    }

    .quick-action:hover {
        background: var(--accent-gradient);
        color: white;
        border-color: var(--primary);
        transform: translateY(-2px);
        box-shadow: var(--shadow-md);
    }

    .input-container {
        max-width: 900px;
        margin: 0 auto;
        display: flex;
        gap: var(--space-md);
        align-items: flex-end;
    }

    .input-wrapper {
        flex: 1;
        position: relative;
    }

    .input-helper {
        font-size: 11px;
        color: var(--text-tertiary);
        margin-bottom: var(--space-xs);
        display: flex;
        align-items: center;
        gap: var(--space-sm);
    }

    .char-counter {
        margin-left: auto;
    }

    #user-input {
        width: 100%;
        padding: var(--space-md) var(--space-lg);
        border: 2px solid var(--border);
        border-radius: var(--radius-xl);
        font-size: 15px;
        line-height: 1.6;
        resize: none;
        font-family: inherit;
        color: var(--text-primary);
        background: white;
        transition: all var(--transition-base);
        max-height: 150px;
    }

    .dark-mode #user-input {
        background: var(--bg-secondary);
    }

    #user-input:focus {
        outline: none;
        border-color: var(--accent);
        box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.1);
    }

    #user-input::placeholder {
        color: var(--text-tertiary);
    }

    .input-actions {
        display: flex;
        gap: var(--space-sm);
        flex-shrink: 0;
    }

    /* ========================================
       BUTTONS
       ======================================== */

    .btn {
        padding: var(--space-md) var(--space-lg);
        border: none;
        border-radius: var(--radius-xl);
        font-size: 15px;
        font-weight: 600;
        cursor: pointer;
        transition: all var(--transition-base);
        display: flex;
        align-items: center;
        gap: var(--space-sm);
        white-space: nowrap;
    }

    .btn-primary {
        background: var(--accent-gradient);
        color: white;
        box-shadow: var(--shadow-md);
    }

    .btn-primary:hover:not(:disabled) {
        transform: translateY(-3px);
        box-shadow: var(--shadow-xl);
    }

    .btn-primary:active:not(:disabled) {
        transform: translateY(-1px);
    }

    .btn-secondary {
        background: white;
        color: var(--text-primary);
        border: 2px solid var(--border);
    }

    .dark-mode .btn-secondary {
        background: var(--bg-secondary);
    }

    .btn-secondary:hover:not(:disabled) {
        background: var(--bg-tertiary);
        border-color: var(--border);
    }

    .btn:disabled {
        opacity: 0.5;
        cursor: not-allowed;
    }

    .btn-icon {
        width: 44px;
        height: 44px;
        padding: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: var(--radius-xl);
    }

    /* ========================================
       TOAST NOTIFICATIONS
       ======================================== */

    .toast {
        position: fixed;
        bottom: var(--space-xl);
        right: var(--space-xl);
        background: white;
        padding: var(--space-md) var(--space-lg);
        border-radius: var(--radius-xl);
        box-shadow: var(--shadow-xl);
        border: 1px solid var(--border);
        display: flex;
        align-items: center;
        gap: var(--space-md);
        animation: slideInRight 0.3s ease-out;
        z-index: 1000;
        max-width: 400px;
    }

    @keyframes slideInRight {
        from {
            transform: translateX(400px);
            opacity: 0;
        }
        to {
            transform: translateX(0);
            opacity: 1;
        }
    }

    .toast-icon {
        font-size: 24px;
        flex-shrink: 0;
    }

    .toast-content {
        flex: 1;
    }

    .toast-title {
        font-size: 14px;
        font-weight: 600;
        color: var(--text-primary);
        margin-bottom: 2px;
    }

    .toast-message {
        font-size: 13px;
        color: var(--text-secondary);
    }

    .toast-close {
        background: transparent;
        border: none;
        color: var(--text-tertiary);
        cursor: pointer;
        font-size: 20px;
        padding: 4px;
        line-height: 1;
    }

    /* ========================================
       MODAL
       ======================================== */

    .modal-overlay {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.5);
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 2000;
        animation: fadeIn 0.2s ease-out;
        backdrop-filter: blur(4px);
    }

    .modal {
        background: var(--bg-card);
        border-radius: var(--radius-2xl);
        padding: var(--space-xl);
        max-width: 500px;
        width: 90%;
        box-shadow: var(--shadow-xl);
        animation: scaleIn 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
    }

    @keyframes scaleIn {
        from {
            transform: scale(0.9);
            opacity: 0;
        }
        to {
            transform: scale(1);
            opacity: 1;
        }
    }

    .modal-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: var(--space-lg);
    }

    .modal-title {
        font-size: 20px;
        font-weight: 700;
        color: var(--text-primary);
    }

    .modal-close {
        background: transparent;
        border: none;
        font-size: 24px;
        color: var(--text-tertiary);
        cursor: pointer;
        padding: 4px;
        line-height: 1;
    }

    .modal-body {
        color: var(--text-secondary);
        line-height: 1.6;
        margin-bottom: var(--space-lg);
    }

    .modal-footer {
        display: flex;
        gap: var(--space-md);
        justify-content: flex-end;
    }

    /* ========================================
       RESPONSIVE DESIGN
       ======================================== */

    @media (max-width: 768px) {
        .chat-container {
            padding: var(--space-sm);
        }

        .chat-header {
            padding: var(--space-md);
            flex-direction: column;
            gap: var(--space-md);
            align-items: stretch;
        }

        .header-left {
            flex-direction: column;
            align-items: flex-start;
            gap: var(--space-md);
        }

        .header-right {
            justify-content: space-between;
        }

        .bot-icon {
            font-size: 32px;
        }

        .header-title-text h1 {
            font-size: 22px;
        }

        .chat-body {
            padding: var(--space-md);
        }

        .message-wrapper {
            max-width: 85%;
        }

        .suggestions-grid {
            grid-template-columns: 1fr;
        }

        .quick-actions {
            justify-content: flex-start;
        }

        .input-container {
            flex-direction: column;
            align-items: stretch;
        }

        .input-actions {
            width: 100%;
        }

        .btn {
            flex: 1;
        }

        .features-grid {
            grid-template-columns: 1fr;
        }

        .toast {
            left: var(--space-md);
            right: var(--space-md);
            bottom: var(--space-md);
        }
    }

    /* ========================================
       UTILITIES
       ======================================== */

    .hidden {
        display: none !important;
    }

    .sr-only {
        position: absolute;
        width: 1px;
        height: 1px;
        padding: 0;
        margin: -1px;
        overflow: hidden;
        clip: rect(0, 0, 0, 0);
        white-space: nowrap;
        border-width: 0;
    }

    /* Code block styling */
    .message-text code {
        background: rgba(0, 0, 0, 0.05);
        padding: 2px 6px;
        border-radius: 4px;
        font-family: 'Monaco', 'Courier New', monospace;
        font-size: 13px;
    }

    .message.user .message-text code {
        background: rgba(255, 255, 255, 0.2);
    }

    .message-text pre {
        background: rgba(0, 0, 0, 0.05);
        padding: var(--space-md);
        border-radius: var(--radius-md);
        overflow-x: auto;
        margin: var(--space-sm) 0;
    }

    .message-text pre code {
        background: transparent;
        padding: 0;
    }
</style>
@endsection

@section('content')
<div class="chat-container">
    <!-- Header -->
    <div class="chat-header">
        <div class="header-left">
            <a href="{{ url()->previous() }}" class="back-btn">
                <span>←</span> Back to Dashboard
            </a>
            <div class="header-title">
                <div class="bot-icon">⚖️</div>
                <div class="header-title-text">
                    <h1>Proly Legal Assistant</h1>
                    <p>AI-powered legal consultation and document analysis</p>
                </div>
            </div>
        </div>
        <div class="header-right">
            <div class="status-indicator">
                <span class="status-dot"></span>
                <span class="status-text">Online & Ready</span>
            </div>
            <div class="header-actions">
                <button class="header-btn" id="darkModeToggle" title="Toggle dark mode">
                    🌙
                </button>
                <button class="header-btn" id="helpBtn" title="Help & Info">
                    ❓
                </button>
                <button class="header-btn" id="settingsBtn" title="Settings">
                    ⚙️
                </button>
            </div>
        </div>
    </div>

    <!-- Chat Body -->
    <div class="chat-body" id="chatBody">
        <div id="chat-messages" class="chat-messages">
            <!-- Empty State -->
            <div class="empty-state" id="emptyState">
                <div class="empty-state-icon">⚖️</div>
                <h3>Welcome to Proly Legal Assistant</h3>
                <p>I'm your AI-powered legal consultation partner. Ask me anything about legal matters, contracts, compliance, case law, or get help drafting legal documents.</p>
                
                <div class="features-grid">
                    <div class="feature-item">
                        <div class="feature-icon">📄</div>
                        <div class="feature-title">Document Analysis</div>
                        <div class="feature-desc">Review and analyze legal documents</div>
                    </div>
                    <div class="feature-item">
                        <div class="feature-icon">✓</div>
                        <div class="feature-title">Compliance</div>
                        <div class="feature-desc">Legal compliance guidance</div>
                    </div>
                    <div class="feature-item">
                        <div class="feature-icon">🔍</div>
                        <div class="feature-title">Research</div>
                        <div class="feature-desc">Case law and legal research</div>
                    </div>
                    <div class="feature-item">
                        <div class="feature-icon">📝</div>
                        <div class="feature-title">Drafting</div>
                        <div class="feature-desc">Draft legal documents</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Suggestions (shown after first interaction) -->
        <div class="suggestions-container hidden" id="suggestionsContainer">
            <div class="suggestions-title">💡 Suggested Actions</div>
            <div class="suggestions-grid" id="suggestionsGrid">
                <!-- Dynamically populated -->
            </div>
        </div>
    </div>

    <!-- Footer / Input Area -->
    <div class="chat-footer">
        <div class="quick-actions">
            <button class="quick-action" onclick="quickSend('📄 Explain contract terms', 'Can you explain common contract terms and clauses?')">
                <span>📄</span> Contract Terms
            </button>
            <button class="quick-action" onclick="quickSend('✓ Legal compliance', 'What are the key legal compliance requirements for my business?')">
                <span>✓</span> Compliance
            </button>
            <button class="quick-action" onclick="quickSend('📝 Draft document', 'Help me draft a non-disclosure agreement.')">
                <span>📝</span> Draft Document
            </button>
            <button class="quick-action" onclick="quickSend('🔍 Case research', 'How do I research relevant case law for my situation?')">
                <span>🔍</span> Case Research
            </button>
            <button class="quick-action" onclick="quickSend('⚖️ Legal advice', 'I need general legal advice on a contract dispute.')">
                <span>⚖️</span> Legal Advice
            </button>
        </div>
        
        <div class="input-container">
            <div class="input-wrapper">
                <div class="input-helper">
                    <span>💬 Press Enter to send, Shift+Enter for new line</span>
                    <span class="char-counter" id="charCounter">0 / 2000</span>
                </div>
                <textarea 
                    id="user-input" 
                    placeholder="Ask me anything about legal matters..." 
                    rows="1"
                    maxlength="2000"
                    onkeydown="handleKeyPress(event)"
                    oninput="updateCharCounter()"
                ></textarea>
            </div>
            <div class="input-actions">
                <button class="btn btn-secondary btn-icon" id="attachBtn" title="Attach file" onclick="attachFile()">
                    📎
                </button>
                <button class="btn btn-secondary" id="clearBtn" onclick="showClearModal()">
                    <span>🗑️</span> Clear
                </button>
                <button class="btn btn-primary" id="send-btn" onclick="sendMessage()">
                    <span>Send</span>
                    <span>→</span>
                </button>
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
(function() {
    'use strict';

    // ========================================
    // STATE & CONFIGURATION
    // ========================================

    const CONFIG = {
        maxMessageLength: 2000,
        typingDelay: 1500,
        apiEndpoint: '/proly/chat',
        autoSuggestions: true,
        darkMode: false
    };

    let state = {
        isProcessing: false,
        messageCount: 0,
        conversationHistory: [],
        currentSuggestions: []
    };

    // ========================================
    // DOM ELEMENTS
    // ========================================

    const elements = {
        chatMessages: document.getElementById('chat-messages'),
        chatBody: document.getElementById('chatBody'),
        userInput: document.getElementById('user-input'),
        sendBtn: document.getElementById('send-btn'),
        clearBtn: document.getElementById('clearBtn'),
        emptyState: document.getElementById('emptyState'),
        suggestionsContainer: document.getElementById('suggestionsContainer'),
        suggestionsGrid: document.getElementById('suggestionsGrid'),
        charCounter: document.getElementById('charCounter'),
        darkModeToggle: document.getElementById('darkModeToggle'),
        helpBtn: document.getElementById('helpBtn'),
        settingsBtn: document.getElementById('settingsBtn'),
        attachBtn: document.getElementById('attachBtn')
    };

    // ========================================
    // UTILITY FUNCTIONS
    // ========================================

    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    function getCurrentTime() {
        return new Date().toLocaleTimeString('en-US', { 
            hour: 'numeric', 
            minute: '2-digit',
            hour12: true 
        });
    }

    function formatText(text) {
        // Convert markdown-like formatting
        text = text.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
        text = text.replace(/\*(.*?)\*/g, '<em>$1</em>');
        text = text.replace(/`(.*?)`/g, '<code>$1</code>');
        
        // Convert URLs to links
        text = text.replace(/(https?:\/\/[^\s]+)/g, '<a href="$1" target="_blank" rel="noopener">$1</a>');
        
        // Convert line breaks
        text = text.replace(/\n/g, '<br>');
        
        return text;
    }

    function scrollToBottom(smooth = true) {
        if (smooth) {
            elements.chatBody.scrollTo({
                top: elements.chatBody.scrollHeight,
                behavior: 'smooth'
            });
        } else {
            elements.chatBody.scrollTop = elements.chatBody.scrollHeight;
        }
    }

    function updateCharCounter() {
        const length = elements.userInput.value.length;
        elements.charCounter.textContent = `${length} / ${CONFIG.maxMessageLength}`;
        
        if (length > CONFIG.maxMessageLength * 0.9) {
            elements.charCounter.style.color = 'var(--danger)';
        } else {
            elements.charCounter.style.color = 'var(--text-tertiary)';
        }
    }

    // ========================================
    // TOAST NOTIFICATIONS
    // ========================================

    function showToast(title, message, icon = '✓') {
        const toast = document.createElement('div');
        toast.className = 'toast';
        toast.innerHTML = `
            <div class="toast-icon">${icon}</div>
            <div class="toast-content">
                <div class="toast-title">${escapeHtml(title)}</div>
                <div class="toast-message">${escapeHtml(message)}</div>
            </div>
            <button class="toast-close" onclick="this.parentElement.remove()">×</button>
        `;
        
        document.body.appendChild(toast);
        
        setTimeout(() => {
            toast.style.animation = 'slideInRight 0.3s ease-out reverse';
            setTimeout(() => toast.remove(), 300);
        }, 3000);
    }

    // ========================================
    // MODAL FUNCTIONS
    // ========================================

    function showClearModal() {
        const overlay = document.createElement('div');
        overlay.className = 'modal-overlay';
        overlay.innerHTML = `
            <div class="modal">
                <div class="modal-header">
                    <h3 class="modal-title">Clear Conversation?</h3>
                    <button class="modal-close" onclick="this.closest('.modal-overlay').remove()">×</button>
                </div>
                <div class="modal-body">
                    Are you sure you want to clear the entire conversation? This action cannot be undone.
                </div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" onclick="this.closest('.modal-overlay').remove()">
                        Cancel
                    </button>
                    <button class="btn btn-primary" onclick="clearChat(); this.closest('.modal-overlay').remove();">
                        Clear Conversation
                    </button>
                </div>
            </div>
        `;
        
        document.body.appendChild(overlay);
        
        // Close on outside click
        overlay.addEventListener('click', (e) => {
            if (e.target === overlay) {
                overlay.remove();
            }
        });
    }

    function showHelpModal() {
        const overlay = document.createElement('div');
        overlay.className = 'modal-overlay';
        overlay.innerHTML = `
            <div class="modal">
                <div class="modal-header">
                    <h3 class="modal-title">Help & Information</h3>
                    <button class="modal-close" onclick="this.closest('.modal-overlay').remove()">×</button>
                </div>
                <div class="modal-body">
                    <h4 style="margin-bottom: 12px; color: var(--text-primary);">How to use Proly:</h4>
                    <ul style="margin-left: 20px; line-height: 1.8;">
                        <li>Ask questions about legal matters, contracts, or compliance</li>
                        <li>Request document drafting or analysis</li>
                        <li>Get guidance on case law research</li>
                        <li>Use quick actions for common requests</li>
                        <li>Attach documents for analysis (coming soon)</li>
                    </ul>
                    <p style="margin-top: 16px; padding-top: 16px; border-top: 1px solid var(--border);">
                        <strong>Note:</strong> This is an AI assistant and should not replace professional legal advice for important matters.
                    </p>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-primary" onclick="this.closest('.modal-overlay').remove()">
                        Got it!
                    </button>
                </div>
            </div>
        `;
        
        document.body.appendChild(overlay);
        overlay.addEventListener('click', (e) => {
            if (e.target === overlay) overlay.remove();
        });
    }

    // ========================================
    // MESSAGE FUNCTIONS
    // ========================================

    function addMessage(text, isUser = false, showActions = true) {
        // Remove empty state
        if (elements.emptyState && !elements.emptyState.classList.contains('hidden')) {
            elements.emptyState.classList.add('hidden');
        }

        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${isUser ? 'user' : 'bot'}`;
        
        const formattedText = isUser ? escapeHtml(text) : formatText(escapeHtml(text));
        
        messageDiv.innerHTML = `
            <div class="message-avatar">${isUser ? '👤' : '⚖️'}</div>
            <div class="message-wrapper">
                <div class="message-header">
                    <span class="message-sender">${isUser ? 'You' : 'Proly Assistant'}</span>
                    <span class="message-time">${getCurrentTime()}</span>
                </div>
                <div class="message-content">
                    <p class="message-text">${formattedText}</p>
                </div>
                ${!isUser && showActions ? `
                    <div class="message-actions">
                        <button class="message-action-btn" onclick="copyMessage(this)">
                            📋 Copy
                        </button>
                        <button class="message-action-btn" onclick="likeMessage(this)">
                            👍 Helpful
                        </button>
                        <button class="message-action-btn" onclick="reportMessage(this)">
                            ⚠️ Report
                        </button>
                    </div>
                ` : ''}
            </div>
        `;
        
        elements.chatMessages.appendChild(messageDiv);
        scrollToBottom();
        
        state.messageCount++;
        
        // Show suggestions after first bot response
        if (!isUser && state.messageCount === 2 && CONFIG.autoSuggestions) {
            showSuggestions();
        }
    }

    function showTypingIndicator() {
        const typingDiv = document.createElement('div');
        typingDiv.className = 'message bot';
        typingDiv.id = 'typing-indicator';
        typingDiv.innerHTML = `
            <div class="message-avatar">⚖️</div>
            <div class="message-wrapper">
                <div class="message-header">
                    <span class="message-sender">Proly Assistant</span>
                </div>
                <div class="message-content">
                    <div class="typing-indicator">
                        <span class="typing-dot"></span>
                        <span class="typing-dot"></span>
                        <span class="typing-dot"></span>
                    </div>
                </div>
            </div>
        `;
        elements.chatMessages.appendChild(typingDiv);
        scrollToBottom();
    }

    function removeTypingIndicator() {
        const typingIndicator = document.getElementById('typing-indicator');
        if (typingIndicator) {
            typingIndicator.remove();
        }
    }

    // ========================================
    // SUGGESTIONS
    // ========================================

    function showSuggestions() {
        const suggestions = [
            {
                icon: '📄',
                title: 'Review a Contract',
                description: 'Get detailed analysis of contract terms and conditions',
                query: 'Can you help me review a contract and identify potential issues?'
            },
            {
                icon: '⚖️',
                title: 'Legal Precedents',
                description: 'Find relevant case law and legal precedents',
                query: 'How can I find legal precedents relevant to my case?'
            },
            {
                icon: '✍️',
                title: 'Draft NDA',
                description: 'Create a non-disclosure agreement',
                query: 'Help me draft a comprehensive non-disclosure agreement.'
            },
            {
                icon: '🏢',
                title: 'Business Compliance',
                description: 'Understand regulatory compliance requirements',
                query: 'What compliance requirements should my business be aware of?'
            }
        ];

        elements.suggestionsGrid.innerHTML = suggestions.map(s => `
            <div class="suggestion-card" onclick="quickSend('${s.icon} ${s.title}', '${s.query}')">
                <div class="suggestion-icon">${s.icon}</div>
                <div class="suggestion-title">${s.title}</div>
                <div class="suggestion-desc">${s.description}</div>
            </div>
        `).join('');

        elements.suggestionsContainer.classList.remove('hidden');
    }

    // ========================================
    // MESSAGE ACTIONS
    // ========================================

    window.copyMessage = function(btn) {
        const messageText = btn.closest('.message-wrapper').querySelector('.message-text').textContent;
        navigator.clipboard.writeText(messageText).then(() => {
            showToast('Copied!', 'Message copied to clipboard', '📋');
            btn.innerHTML = '✓ Copied';
            setTimeout(() => {
                btn.innerHTML = '📋 Copy';
            }, 2000);
        });
    };

    window.likeMessage = function(btn) {
        showToast('Thank you!', 'Your feedback helps us improve', '👍');
        btn.innerHTML = '✓ Liked';
        btn.disabled = true;
    };

    window.reportMessage = function(btn) {
        showToast('Reported', 'Thank you for your feedback', '⚠️');
        btn.innerHTML = '✓ Reported';
        btn.disabled = true;
    };

    // ========================================
    // SEND MESSAGE
    // ========================================

    async function sendMessage() {
        const message = elements.userInput.value.trim();
        
        if (!message || state.isProcessing) return;
        
        if (message.length > CONFIG.maxMessageLength) {
            showToast('Message too long', `Please keep messages under ${CONFIG.maxMessageLength} characters`, '⚠️');
            return;
        }
        
        state.isProcessing = true;
        elements.sendBtn.disabled = true;
        elements.userInput.disabled = true;
        
        // Add user message
        addMessage(message, true);
        state.conversationHistory.push({ role: 'user', content: message });
        
        // Clear input
        elements.userInput.value = '';
        elements.userInput.style.height = 'auto';
        updateCharCounter();
        
        // Show typing indicator
        showTypingIndicator();
        
        try {
            const response = await fetch(CONFIG.apiEndpoint, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                },
                body: JSON.stringify({ 
                    message,
                    history: state.conversationHistory.slice(-10) // Last 10 messages for context
                })
            });
            
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            
            const data = await response.json();
            
            // Remove typing indicator
            removeTypingIndicator();
            
            // Add bot response
            const botResponse = data.response || 'I apologize, but I encountered an error. Please try again.';
            addMessage(botResponse, false);
            state.conversationHistory.push({ role: 'assistant', content: botResponse });
            
        } catch (error) {
            removeTypingIndicator();
            addMessage('I apologize, but I\'m having trouble connecting right now. Please try again later.', false, false);
            console.error('Error:', error);
            showToast('Connection Error', 'Unable to reach the server', '⚠️');
        } finally {
            state.isProcessing = false;
            elements.sendBtn.disabled = false;
            elements.userInput.disabled = false;
            elements.userInput.focus();
        }
    }

    window.sendMessage = sendMessage;

    // ========================================
    // QUICK SEND
    // ========================================

    window.quickSend = function(label, message) {
        elements.userInput.value = message || label;
        sendMessage();
    };

    // ========================================
    // CLEAR CHAT
    // ========================================

    function clearChat() {
        elements.chatMessages.innerHTML = `
            <div class="empty-state" id="emptyState">
                <div class="empty-state-icon">⚖️</div>
                <h3>Welcome to Proly Legal Assistant</h3>
                <p>I'm your AI-powered legal consultation partner. Ask me anything about legal matters, contracts, compliance, case law, or get help drafting legal documents.</p>
                
                <div class="features-grid">
                    <div class="feature-item">
                        <div class="feature-icon">📄</div>
                        <div class="feature-title">Document Analysis</div>
                        <div class="feature-desc">Review and analyze legal documents</div>
                    </div>
                    <div class="feature-item">
                        <div class="feature-icon">✓</div>
                        <div class="feature-title">Compliance</div>
                        <div class="feature-desc">Legal compliance guidance</div>
                    </div>
                    <div class="feature-item">
                        <div class="feature-icon">🔍</div>
                        <div class="feature-title">Research</div>
                        <div class="feature-desc">Case law and legal research</div>
                    </div>
                    <div class="feature-item">
                        <div class="feature-icon">📝</div>
                        <div class="feature-title">Drafting</div>
                        <div class="feature-desc">Draft legal documents</div>
                    </div>
                </div>
            </div>
        `;
        
        elements.emptyState = document.getElementById('emptyState');
        elements.suggestionsContainer.classList.add('hidden');
        state.conversationHistory = [];
        state.messageCount = 0;
        
        showToast('Chat Cleared', 'Conversation has been reset', '🗑️');
    }

    window.clearChat = clearChat;

    // ========================================
    // INPUT HANDLERS
    // ========================================

    window.handleKeyPress = function(event) {
        if (event.key === 'Enter' && !event.shiftKey) {
            event.preventDefault();
            sendMessage();
        }
    };

    // Auto-resize textarea
    elements.userInput.addEventListener('input', function() {
        this.style.height = 'auto';
        this.style.height = Math.min(this.scrollHeight, 150) + 'px';
    });

    // ========================================
    // DARK MODE
    // ========================================

    function toggleDarkMode() {
        CONFIG.darkMode = !CONFIG.darkMode;
        document.body.classList.toggle('dark-mode');
        elements.darkModeToggle.textContent = CONFIG.darkMode ? '☀️' : '🌙';
        localStorage.setItem('prolyDarkMode', CONFIG.darkMode);
        showToast(
            CONFIG.darkMode ? 'Dark Mode' : 'Light Mode',
            `Switched to ${CONFIG.darkMode ? 'dark' : 'light'} mode`,
            CONFIG.darkMode ? '🌙' : '☀️'
        );
    }

    elements.darkModeToggle.addEventListener('click', toggleDarkMode);

    // ========================================
    // OTHER ACTIONS
    // ========================================

    elements.helpBtn.addEventListener('click', showHelpModal);
    
    elements.settingsBtn.addEventListener('click', () => {
        showToast('Settings', 'Settings panel coming soon!', '⚙️');
    });

    window.attachFile = function() {
        showToast('Coming Soon', 'File attachment feature will be available soon!', '📎');
    };

    // ========================================
    // INITIALIZATION
    // ========================================

    function init() {
        // Load dark mode preference
        const savedDarkMode = localStorage.getItem('prolyDarkMode');
        if (savedDarkMode === 'true') {
            CONFIG.darkMode = true;
            document.body.classList.add('dark-mode');
            elements.darkModeToggle.textContent = '☀️';
        }

        // Focus input
        elements.userInput.focus();

        // Welcome message (optional)
        setTimeout(() => {
            if (state.messageCount === 0) {
                // Could show a welcome message here
            }
        }, 1000);

        console.log('✅ Proly Legal Assistant initialized successfully');
    }

    // Start the application
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }

})();
</script>
@endpush
</document_content>