import { css, html, LitElement } from "lit";
import { customElement, property } from "lit/decorators.js";
import { ifDefined } from "lit/directives/if-defined.js";

@customElement("text-input")
export class TextInput extends LitElement {
  @property({ type: String }) value = "";
  @property({ type: String }) placeholder = "";
  @property({ type: String }) name = "";
  @property({ type: String }) autocomplete = "";
  @property({ type: Boolean }) password = false;
  @property({ type: Boolean }) disabled = false;
  @property({ attribute: false }) onValueChange?: (value: string) => void;

  static styles = css`
    :host {
      display: block;
    }

    input {
      display: block;
      width: 100%;
      box-sizing: border-box;
      padding: 0.625rem 0.875rem;
      background-color: var(--color-bg, #fff);
      color: var(--color-text, #111);
      border: 1.5px solid var(--color-border-strong, #aaa);
      border-radius: 0.375rem;
      font-family: "Inter", system-ui, sans-serif;
      font-size: var(--font-size-base, 0.9375rem);
      font-weight: var(--font-weight-normal, 400);
      outline: none;
      transition: border-color 0.2s ease, box-shadow 0.2s ease;
    }

    input::placeholder {
      color: var(--color-text-muted, #999);
    }

    input:focus {
      border-color: var(--color-accent, #2b6cb0);
      box-shadow: 0 0 0 3px color-mix(in srgb, var(--color-accent, #2b6cb0) 20%, transparent);
    }

    input:disabled {
      opacity: 0.45;
      cursor: not-allowed;
    }
  `;

  private _handleInput(e: Event) {
    const input = e.target as HTMLInputElement;
    this.value = input.value;
    this.onValueChange?.(this.value);
  }

  render() {
    return html`
      <input
        .value=${this.value}
        type=${this.password ? "password" : "text"}
        placeholder=${this.placeholder}
        name=${ifDefined(this.name || undefined)}
        autocomplete=${ifDefined(this.autocomplete || undefined)}
        ?disabled=${this.disabled}
        @input=${this._handleInput}
      />
    `;
  }
}
