import { LitElement, html, css } from "lit";
import { gameStateManager } from "../../core/GameStateManager.js";
import { theme, buttonStyles, cardStyles } from "../styles/theme.js";

/**
 * ResearchScreen.js
 * The Ancient Archive - Research facility UI component.
 * @class
 */
export class ResearchScreen extends LitElement {
  static get styles() {
    return [
      theme,
      buttonStyles,
      cardStyles,
      css`
        :host {
          display: block;
          background: var(--color-bg-secondary);
          border: var(--border-width-medium) solid var(--color-border-default);
          padding: var(--spacing-xl);
          max-width: 1600px;
          max-height: 85vh;
          overflow: hidden;
          color: var(--color-text-primary);
          font-family: var(--font-family);
          display: grid;
          grid-template-columns: 1fr 350px;
          grid-template-rows: auto 1fr;
          grid-template-areas:
            "header header"
            "trees inspector";
          gap: var(--spacing-lg);
        }

        .header {
          grid-area: header;
          display: flex;
          justify-content: space-between;
          align-items: center;
          border-bottom: var(--border-width-medium) solid
            var(--color-border-default);
          padding-bottom: var(--spacing-md);
        }

        .header h2 {
          margin: 0;
          color: var(--color-accent-cyan);
          font-size: var(--font-size-4xl);
        }

        .cores-display {
          display: flex;
          align-items: center;
          gap: var(--spacing-md);
          font-size: var(--font-size-2xl);
          color: var(--color-accent-gold);
        }

        .cores-icon {
          font-size: var(--font-size-3xl);
        }

        .close-button {
          position: absolute;
          top: var(--spacing-md);
          right: var(--spacing-md);
          background: transparent;
          border: var(--border-width-medium) solid var(--color-border-default);
          color: var(--color-text-primary);
          width: 40px;
          height: 40px;
          cursor: pointer;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: var(--font-size-xl);
          transition: all var(--transition-normal);
        }

        .close-button:hover {
          border-color: var(--color-accent-red);
          color: var(--color-accent-red);
          background: rgba(255, 102, 102, 0.1);
        }

        /* Trees Container */
        .trees-container {
          grid-area: trees;
          display: flex;
          flex-direction: column;
          gap: var(--spacing-xl);
          overflow-y: auto;
          padding-right: var(--spacing-sm);
        }

        .tree-section {
          display: flex;
          flex-direction: column;
          gap: var(--spacing-md);
        }

        .tree-header {
          display: flex;
          align-items: center;
          gap: var(--spacing-md);
          padding: var(--spacing-md);
          background: var(--color-bg-card);
          border: var(--border-width-medium) solid var(--color-border-default);
        }

        .tree-header.logistics {
          border-color: var(--color-accent-green);
        }

        .tree-header.intel {
          border-color: var(--color-accent-cyan);
        }

        .tree-header.field-ops {
          border-color: var(--color-accent-red);
        }

        .tree-title {
          font-size: var(--font-size-2xl);
          font-weight: var(--font-weight-bold);
          text-transform: uppercase;
        }

        .tree-title.logistics {
          color: var(--color-accent-green);
        }

        .tree-title.intel {
          color: var(--color-accent-cyan);
        }

        .tree-title.field-ops {
          color: var(--color-accent-red);
        }

        /* Tree View */
        .tree-view {
          position: relative;
          min-height: 300px;
          background: var(--color-bg-card);
          border: var(--border-width-medium) solid var(--color-border-default);
          padding: var(--spacing-lg);
          overflow-x: auto;
          overflow-y: visible;
        }

        .tree-svg {
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          pointer-events: none;
          z-index: 1;
        }

        .tree-svg path {
          fill: none;
          stroke-width: 2;
        }

        .tree-svg path.connection-line.locked {
          stroke: var(--color-border-dark);
          opacity: 0.3;
        }

        .tree-svg path.connection-line.available {
          stroke: var(--color-accent-cyan);
          opacity: 0.6;
        }

        .tree-svg path.connection-line.researched {
          stroke: var(--color-accent-gold);
          opacity: 0.8;
        }

        .tree-nodes {
          position: relative;
          display: flex;
          gap: var(--spacing-xl);
          align-items: flex-start;
          padding: var(--spacing-lg);
          min-width: fit-content;
        }

        .tier-column {
          display: flex;
          flex-direction: column;
          gap: var(--spacing-lg);
          align-items: center;
        }

        .tier-label {
          font-size: var(--font-size-sm);
          color: var(--color-text-secondary);
          text-transform: uppercase;
          margin-bottom: var(--spacing-sm);
        }

        /* Node */
        .node {
          position: relative;
          width: 80px;
          height: 80px;
          border: var(--border-width-medium) solid var(--color-border-default);
          background: var(--color-bg-panel);
          cursor: pointer;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          transition: all var(--transition-normal);
          z-index: 2;
        }

        .node:hover {
          transform: scale(1.1);
          box-shadow: 0 0 15px rgba(0, 255, 255, 0.5);
        }

        .node.locked {
          border-color: var(--color-border-dark);
          background: rgba(0, 0, 0, 0.5);
          opacity: 0.5;
          cursor: not-allowed;
        }

        .node.available {
          border-color: var(--color-accent-cyan);
          background: rgba(0, 255, 255, 0.1);
          box-shadow: 0 0 10px rgba(0, 255, 255, 0.3);
        }

        .node.researched {
          border-color: var(--color-accent-gold);
          background: rgba(255, 215, 0, 0.2);
          box-shadow: 0 0 15px rgba(255, 215, 0, 0.5);
        }

        .node-icon {
          font-size: var(--font-size-2xl);
          margin-bottom: var(--spacing-xs);
        }

        .node-cost {
          font-size: var(--font-size-xs);
          color: var(--color-accent-gold);
        }

        /* Inspector Panel */
        .inspector {
          grid-area: inspector;
          background: var(--color-bg-panel);
          border: var(--border-width-medium) solid var(--color-border-default);
          padding: var(--spacing-lg);
          display: flex;
          flex-direction: column;
          gap: var(--spacing-lg);
          overflow-y: auto;
        }

        .inspector-header {
          display: flex;
          flex-direction: column;
          gap: var(--spacing-md);
          border-bottom: var(--border-width-medium) solid
            var(--color-border-default);
          padding-bottom: var(--spacing-md);
        }

        .inspector-icon {
          width: 100px;
          height: 100px;
          border: var(--border-width-medium) solid var(--color-border-default);
          background: var(--color-bg-card);
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: var(--font-size-4xl);
          margin: 0 auto;
        }

        .inspector-name {
          font-size: var(--font-size-xl);
          font-weight: var(--font-weight-bold);
          text-align: center;
          color: var(--color-accent-cyan);
        }

        .inspector-description {
          color: var(--color-text-secondary);
          line-height: 1.5;
          text-align: center;
        }

        .inspector-details {
          display: flex;
          flex-direction: column;
          gap: var(--spacing-md);
        }

        .detail-row {
          display: flex;
          justify-content: space-between;
          padding: var(--spacing-sm);
          background: var(--color-bg-card);
          border: var(--border-width-thin) solid var(--color-border-default);
        }

        .detail-label {
          color: var(--color-text-secondary);
        }

        .detail-value {
          color: var(--color-text-primary);
          font-weight: var(--font-weight-bold);
        }

        .status-badge {
          padding: var(--spacing-xs) var(--spacing-sm);
          border-radius: var(--border-radius-sm);
          font-size: var(--font-size-xs);
          font-weight: var(--font-weight-bold);
          text-transform: uppercase;
          text-align: center;
        }

        .status-badge.locked {
          background: var(--color-border-dark);
          color: var(--color-text-secondary);
        }

        .status-badge.available {
          background: var(--color-accent-cyan);
          color: #000;
        }

        .status-badge.researched {
          background: var(--color-accent-gold);
          color: #000;
        }

        .research-button {
          width: 100%;
          padding: var(--spacing-md);
          font-size: var(--font-size-lg);
          font-weight: var(--font-weight-bold);
          text-transform: uppercase;
          background: var(--color-accent-cyan);
          color: #000;
          border: var(--border-width-medium) solid var(--color-accent-cyan);
          cursor: pointer;
          transition: all var(--transition-normal);
        }

        .research-button:hover:not(:disabled) {
          background: var(--color-accent-cyan-dark);
          box-shadow: 0 0 15px rgba(0, 255, 255, 0.5);
        }

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

        .empty-state {
          text-align: center;
          color: var(--color-text-secondary);
          padding: var(--spacing-xl);
        }
      `,
    ];
  }

  static get properties() {
    return {
      selectedNodeId: { type: String },
      availableCores: { type: Number },
    };
  }

  constructor() {
    super();
    this.selectedNodeId = null;
    this.availableCores = 0;
    this.researchManager = null;
    this._boundHandleResearchComplete = this._handleResearchComplete.bind(this);
    this._boundHandleWalletUpdate = this._handleWalletUpdate.bind(this);
  }

  connectedCallback() {
    super.connectedCallback();
    this._loadData();
    window.addEventListener("research-complete", this._boundHandleResearchComplete);
    window.addEventListener("wallet-updated", this._boundHandleWalletUpdate);
  }

  disconnectedCallback() {
    super.disconnectedCallback();
    window.removeEventListener("research-complete", this._boundHandleResearchComplete);
    window.removeEventListener("wallet-updated", this._boundHandleWalletUpdate);
  }

  async _loadData() {
    // Get research manager from gameStateManager
    if (gameStateManager.researchManager) {
      this.researchManager = gameStateManager.researchManager;
      await this.researchManager.load();
      this._updateAvailableCores();
      this.requestUpdate();
      // Update connections after render
      this.updateComplete.then(() => {
        this._updateConnections();
      });
    }
  }

  _updateAvailableCores() {
    if (gameStateManager.hubStash) {
      this.availableCores =
        gameStateManager.hubStash.currency.ancientCores || 0;
      if (this.researchManager) {
        this.researchManager.updateAvailableCores(this.availableCores);
      }
    }
  }

  _handleWalletUpdate() {
    this._updateAvailableCores();
    this.requestUpdate();
  }

  _handleResearchComplete() {
    this._updateAvailableCores();
    this.requestUpdate();
    // Update connections after state change
    this.updateComplete.then(() => {
      this._updateConnections();
    });
  }

  _selectNode(nodeId) {
    this.selectedNodeId = nodeId;
    this.requestUpdate();
  }

  _dispatchClose() {
    this.dispatchEvent(new CustomEvent("close"));
  }

  async _researchNode() {
    if (!this.selectedNodeId || !this.researchManager) return;

    const result = await this.researchManager.unlockNode(
      this.selectedNodeId,
      this.availableCores
    );

    if (result.success) {
      // Deduct cores from hub stash
      if (gameStateManager.hubStash) {
        const node = this.researchManager.getNode(this.selectedNodeId);
        gameStateManager.hubStash.currency.ancientCores -= node.cost;
        await gameStateManager._saveHubStash();
        this._updateAvailableCores();

        // Dispatch event to update wallet display
        window.dispatchEvent(
          new CustomEvent("wallet-updated", {
            detail: { wallet: gameStateManager.hubStash.currency },
          })
        );
      }

      // Dispatch research event
      window.dispatchEvent(
        new CustomEvent("research-complete", {
          detail: { nodeId: this.selectedNodeId },
        })
      );
    } else {
      alert(result.error || "Failed to research node");
    }
  }

  _updateConnections() {
    if (!this.researchManager) return;

    const trees = ["LOGISTICS", "INTEL", "FIELD_OPS"];
    trees.forEach((treeType) => {
      const treeView = this.shadowRoot?.querySelector(
        `.tree-view[data-tree="${treeType}"]`
      );
      if (!treeView) return;

      const svg = treeView.querySelector(".tree-svg");
      if (!svg) return;

      // Clear existing paths
      svg.innerHTML = "";

      const nodes = this.researchManager.getNodesByTree(treeType);
      const containerRect = treeView.getBoundingClientRect();

      // Draw connections for each node to its prerequisites
      nodes.forEach((node) => {
        if (node.prerequisites.length === 0) return;

        const nodeElement = this.shadowRoot?.querySelector(
          `[data-node-id="${node.id}"]`
        );
        if (!nodeElement) return;

        const nodeRect = nodeElement.getBoundingClientRect();
        const nodeCenter = {
          x: nodeRect.left + nodeRect.width / 2 - containerRect.left,
          y: nodeRect.top + nodeRect.height / 2 - containerRect.top,
        };

        node.prerequisites.forEach((prereqId) => {
          const prereqElement = this.shadowRoot?.querySelector(
            `[data-node-id="${prereqId}"]`
          );
          if (!prereqElement) return;

          const prereqRect = prereqElement.getBoundingClientRect();
          const prereqCenter = {
            x: prereqRect.left + prereqRect.width / 2 - containerRect.left,
            y: prereqRect.top + prereqRect.height / 2 - containerRect.top,
          };

          // Determine line style based on node status
          const status = this.researchManager.getNodeStatus(node.id);
          const pathClass = `connection-line ${status.toLowerCase()}`;

          // Create horizontal connection with vertical offset
          const midY = (prereqCenter.y + nodeCenter.y) / 2;
          const pathData = `M ${prereqCenter.x} ${prereqCenter.y} L ${prereqCenter.x} ${midY} L ${nodeCenter.x} ${midY} L ${nodeCenter.x} ${nodeCenter.y}`;

          const path = document.createElementNS(
            "http://www.w3.org/2000/svg",
            "path"
          );
          path.setAttribute("d", pathData);
          path.setAttribute("class", pathClass);
          svg.appendChild(path);
        });
      });
    });
  }

  _renderTree(treeType) {
    if (!this.researchManager) return html``;

    const nodes = this.researchManager.getNodesByTree(treeType);
    const nodesByTier = {};
    nodes.forEach((node) => {
      if (!nodesByTier[node.tier]) {
        nodesByTier[node.tier] = [];
      }
      nodesByTier[node.tier].push(node);
    });

    const treeClass = treeType.toLowerCase().replace("_", "-");

    return html`
      <div class="tree-section">
        <div class="tree-header ${treeClass}">
          <h3 class="tree-title ${treeClass}">${treeType.replace("_", " ")}</h3>
        </div>
        <div class="tree-view" data-tree="${treeType}">
          <svg class="tree-svg"></svg>
          <div class="tree-nodes">
            ${Object.keys(nodesByTier)
              .sort((a, b) => Number(a) - Number(b))
              .map(
                (tier) => html`
                  <div class="tier-column">
                    <div class="tier-label">Tier ${tier}</div>
                    ${nodesByTier[tier].map(
                      (node) => this._renderNode(node, treeClass)
                    )}
                  </div>
                `
              )}
          </div>
        </div>
      </div>
    `;
  }

  _renderNode(node, treeClass) {
    const status = this.researchManager
      ? this.researchManager.getNodeStatus(node.id)
      : "LOCKED";
    const isSelected = this.selectedNodeId === node.id;

    return html`
      <button
        class="node ${status.toLowerCase()} ${isSelected ? "selected" : ""}"
        data-node-id="${node.id}"
        @click=${() => this._selectNode(node.id)}
        ?disabled=${status === "LOCKED"}
      >
        <div class="node-icon">⚙️</div>
        <div class="node-cost">${node.cost}</div>
      </button>
    `;
  }

  _renderInspector() {
    if (!this.selectedNodeId || !this.researchManager) {
      return html`
        <div class="inspector">
          <div class="empty-state">
            <p>Select a research node to view details</p>
          </div>
        </div>
      `;
    }

    const node = this.researchManager.getNode(this.selectedNodeId);
    if (!node) {
      return html`
        <div class="inspector">
          <div class="empty-state">
            <p>Node not found</p>
          </div>
        </div>
      `;
    }

    const status = this.researchManager.getNodeStatus(node.id);
    const canResearch =
      status === "AVAILABLE" && this.availableCores >= node.cost;

    return html`
      <div class="inspector">
        <div class="inspector-header">
          <div class="inspector-icon">⚙️</div>
          <div class="inspector-name">${node.name}</div>
          <div class="inspector-description">${node.description}</div>
        </div>
        <div class="inspector-details">
          <div class="detail-row">
            <span class="detail-label">Cost:</span>
            <span class="detail-value">${node.cost} Ancient Cores</span>
          </div>
          <div class="detail-row">
            <span class="detail-label">Status:</span>
            <span class="status-badge ${status.toLowerCase()}">${status}</span>
          </div>
          ${node.prerequisites.length > 0
            ? html`
                <div class="detail-row">
                  <span class="detail-label">Requires:</span>
                  <span class="detail-value"
                    >${node.prerequisites.length} prerequisite(s)</span
                  >
                </div>
              `
            : ""}
        </div>
        <button
          class="research-button"
          @click=${this._researchNode}
          ?disabled=${!canResearch}
        >
          ${status === "RESEARCHED" ? "RESEARCHED" : "RESEARCH"}
        </button>
      </div>
    `;
  }

  render() {
    return html`
      <div class="header">
        <h2>Ancient Archive</h2>
        <div class="cores-display">
          <span class="cores-icon">⚙️</span>
          <span>${this.availableCores} Ancient Cores</span>
        </div>
        <button class="close-button" @click=${this._dispatchClose} aria-label="Close">
          ✕
        </button>
      </div>
      <div class="trees-container">
        ${this._renderTree("LOGISTICS")} ${this._renderTree("INTEL")}
        ${this._renderTree("FIELD_OPS")}
      </div>
      ${this._renderInspector()}
    `;
  }

  updated(changedProperties) {
    super.updated(changedProperties);
    if (changedProperties.has("selectedNodeId") || changedProperties.has("availableCores")) {
      this.updateComplete.then(() => {
        this._updateConnections();
      });
    }
  }
}

customElements.define("research-screen", ResearchScreen);

