<div class="container chat-wrapper">

  <!-- ── Chat Interface ────────────────────────────────────────────────────── -->
  <div class="chat-layout">

      <!-- Chat panel -->
      <div class="chat-panel glass-panel">
        <div class="chat-header">
          <span class="chat-title">PALM OIL <span class="accent-gold">INTELLIGENCE</span></span>
          <div class="chat-header-actions">
            <span class="chat-lego">Lego 03 · 06</span>
            <button class="btn btn-outline chat-clear-btn" (click)="onClearChat()">Clear Chat</button>
          </div>
        </div>

        <!-- Message list -->
        <div class="message-list" #messageList>
          @for (msg of messages(); track msg.timestamp) {
            <div class="message" [class]="'message--' + msg.role">
              <div class="message-bubble">
                <p class="message-text">{{ msg.text }}</p>
                <div class="message-meta">
                  <span class="message-time">{{ formatTime(msg.timestamp) }}</span>
                  @if (msg.durationMs) {
                    <span class="message-latency">{{ msg.durationMs }}ms</span>
                  }
                </div>
              </div>
            </div>
          }

          @if (loading()) {
            <div class="message message--bot">
              <div class="message-bubble">
                <div class="thinking-dots">
                  <span></span><span></span><span></span>
                </div>
                <p class="thinking-label">Agent is typing...</p>
              </div>
            </div>
          }
        </div>

        <!-- NestJS offline banner — socket proxy unavailable -->
        @if (surveillance.nestStatus() === 'OFFLINE') {
          <div class="n8n-offline-banner">
            🔴 NestJS offline — chat proxy unavailable. Restore the backend to send messages.
          </div>
        }

        <!-- Input row -->
        <div class="chat-input-row">
          <textarea
            class="chat-input"
            [(ngModel)]="inputText"
            (keydown)="onEnter($event)"
            placeholder="Ask about palm oil ripeness, site data, operational reports..."
            rows="2"
            [disabled]="loading() || chatSocket.sending() || surveillance.nestStatus() === 'OFFLINE'">
          </textarea>
          <button
            class="btn btn-primary send-btn"
            (click)="sendMessage()"
            [disabled]="!inputText.trim() || loading() || chatSocket.sending() || surveillance.nestStatus() === 'OFFLINE'">
            {{ chatSocket.sending() ? '...' : 'Send' }}
          </button>
        </div>

        <div class="chat-hint">Enter to send · Shift+Enter for new line · Socket → NestJS → n8n</div>
      </div>

  </div>

</div>
