import { LitElement, html, css } from "lit";
import { narrativeManager } from "../managers/NarrativeManager.js";
import { theme, buttonStyles, portraitStyles } from "./styles/theme.js";

export class DialogueOverlay extends LitElement {
  static get styles() {
    return [
      theme,
      buttonStyles,
      portraitStyles,
      css`
        :host {
          position: absolute;
          bottom: var(--spacing-lg);
          left: 50%;
          transform: translateX(-50%);
          width: 80%;
          max-width: 800px;
          z-index: var(--z-overlay);
          pointer-events: auto;
          font-family: var(--font-family);
        }

        .dialogue-box {
          background: var(--color-bg-tertiary);
          border: var(--border-width-medium) solid var(--color-accent-cyan);
          box-shadow: var(--shadow-glow-cyan);
          padding: var(--spacing-lg);
          display: flex;
          gap: var(--spacing-lg);
          animation: slideUp var(--transition-slow) ease-out;
        }

        .portrait {
          width: 100px;
          height: 100px;
          background: #222;
          border: var(--border-width-thin) solid var(--color-border-default);
          flex-shrink: 0;
        }

        .content {
          flex-grow: 1;
          display: flex;
          flex-direction: column;
        }

        .speaker {
          color: var(--color-accent-cyan);
          font-weight: var(--font-weight-bold);
          font-size: var(--font-size-xl);
          margin-bottom: var(--spacing-xs);
        }

        .text {
          color: var(--color-text-primary);
          font-size: var(--font-size-lg);
          line-height: 1.5;
          min-height: 3em;
        }

        .choices {
          margin-top: var(--spacing-md);
          display: flex;
          gap: var(--spacing-sm);
        }

        .choices button {
          background: #333;
          color: var(--color-text-primary);
          border: var(--border-width-thin) solid var(--color-border-default);
          padding: var(--spacing-sm) var(--spacing-lg);
          cursor: pointer;
          font-family: var(--font-family);
          text-transform: uppercase;
        }

        .choices button:hover {
          background: #444;
          border-color: var(--color-accent-cyan);
        }

        .next-indicator {
          align-self: flex-end;
          font-size: var(--font-size-sm);
          color: var(--color-text-tertiary);
          margin-top: var(--spacing-sm);
          animation: blink 1s infinite;
        }

        @keyframes slideUp {
          from {
            transform: translateY(var(--spacing-lg));
            opacity: 0;
          }
          to {
            transform: translateY(0);
            opacity: 1;
          }
        }

        @keyframes blink {
          50% {
            opacity: 0;
          }
        }

        /* Tutorial Style Override */
        .type-tutorial {
          border-color: var(--color-accent-green);
        }
        .type-tutorial .speaker {
          color: var(--color-accent-green);
        }
      `
    ];
  }

  static get properties() {
    return {
      activeNode: { type: Object },
      isVisible: { type: Boolean },
    };
  }

  constructor() {
    super();
    this.activeNode = null;
    this.isVisible = false;
    this._isProcessingClick = false; // Prevent rapid clicks
  }

  connectedCallback() {
    super.connectedCallback();
    // Subscribe to Manager Updates
    narrativeManager.addEventListener(
      "narrative-update",
      this._onUpdate.bind(this)
    );
    narrativeManager.addEventListener("narrative-end", this._onEnd.bind(this));

    // Allow clicking/spacebar to advance
    window.addEventListener("keydown", this._handleInput.bind(this));
  }

  disconnectedCallback() {
    super.disconnectedCallback();
    window.removeEventListener("keydown", this._handleInput.bind(this));
  }

  _onUpdate(e) {
    this.activeNode = e.detail.node;
    this.isVisible = e.detail.active;
    // Reset processing flag when a new node is shown
    // This ensures each message can be clicked independently
    this._isProcessingClick = false;
  }

  _onEnd() {
    this.isVisible = false;
    this.activeNode = null;
  }

  _handleInput(e) {
    if (!this.isVisible) return;
    if (e.code === "Space" || e.code === "Enter") {
      // Prevent rapid key presses
      if (this._isProcessingClick) {
        return;
      }
      
      // Only advance if no choices
      if (!this.activeNode.choices) {
        this._isProcessingClick = true;
        
        // Check if this is the last message
        const isLastMessage = !this.activeNode.next || this.activeNode.next === "END";
        
        if (isLastMessage) {
          narrativeManager.endSequence();
        } else {
          narrativeManager.next();
        }
        
        // Reset flag after a short delay
        setTimeout(() => {
          this._isProcessingClick = false;
        }, 300);
      }
    }
  }

  render() {
    if (!this.isVisible || !this.activeNode) return html``;

    return html`
      <div
        class="dialogue-box ${this.activeNode.type === "TUTORIAL"
          ? "type-tutorial"
          : ""}"
        @click="${(e) => {
          // Prevent event bubbling and default behavior
          e.stopPropagation();
          e.preventDefault();
          
          // Prevent rapid clicks
          if (this._isProcessingClick) {
            return;
          }
          
          // Only advance on click if there are no choices
          // Check if we're clicking on the content area (not buttons or other interactive elements)
          const isContentClick = e.target.closest('.content') && !e.target.closest('button');
          
          if (!this.activeNode.choices && isContentClick) {
            this._isProcessingClick = true;
            
            // Check if this is the last message (next === "END")
            const isLastMessage = !this.activeNode.next || this.activeNode.next === "END";
            
            if (isLastMessage) {
              // For the last message, close the dialogue
              narrativeManager.endSequence();
            } else {
              // For other messages, advance normally
              narrativeManager.next();
            }
            
            // Reset flag after a short delay to prevent double-clicks
            setTimeout(() => {
              this._isProcessingClick = false;
            }, 300);
          }
        }}"
      >
        ${this.activeNode.portrait
          ? html`
              <div class="portrait">
                <img
                  src="${this.activeNode.portrait}"
                  alt="${this.activeNode.speaker}"
                />
              </div>
            `
          : ""}

        <div class="content">
          <div class="speaker">${this.activeNode.speaker}</div>
          <div class="text">${this.activeNode.text}</div>

          ${this.activeNode.choices
            ? html`
                <div class="choices">
                  ${this.activeNode.choices.map(
                    (choice, index) => html`
                      <button
                        @click="${(e) => {
                          e.stopPropagation();
                          narrativeManager.makeChoice(index);
                        }}"
                      >
                        ${choice.text}
                      </button>
                    `
                  )}
                </div>
              `
            : html`<div class="next-indicator">
                ${!this.activeNode.next || this.activeNode.next === "END" 
                  ? "Press SPACE or click to close" 
                  : "Press SPACE to continue..."}
              </div>`}
        </div>
      </div>
    `;
  }
}

customElements.define("dialogue-overlay", DialogueOverlay);
