import { html, LitElement } from "lit";
import { customElement, state } from "lit/decorators.js";

interface TokenPrice {
  symbol: string;
  price: number;
  change24h: number;
  loading: boolean;
}

@customElement("jae-crypto-ticker")
export class JaeCryptoTicker extends LitElement {
  @state() private tokens: TokenPrice[] = [
    { symbol: "VVV", price: 0, change24h: 0, loading: true },
    { symbol: "DIEM", price: 0, change24h: 0, loading: true },
  ];

  private interval: ReturnType<typeof setInterval> | null = null;

  protected override createRenderRoot() { return this; }

  override connectedCallback() {
    super.connectedCallback();
    this.fetchPrices();
    this.interval = setInterval(() => this.fetchPrices(), 30000);
  }

  override disconnectedCallback() {
    super.disconnectedCallback();
    if (this.interval) clearInterval(this.interval);
  }

  private async fetchPrices() {
    try {
      // Try CoinGecko for VVV (Venice Token)
      const vvvRes = await fetch("https://api.coingecko.com/api/v3/simple/price?ids=venice-token&vs_currencies=usd&include_24hr_change=true");
      if (vvvRes.ok) {
        const data = await vvvRes.json();
        const vt = data["venice-token"];
        if (vt) {
          this.tokens = this.tokens.map(t =>
            t.symbol === "VVV" ? { ...t, price: vt.usd || 0, change24h: vt.usd_24h_change || 0, loading: false } : t
          );
        }
      }
    } catch {
      this.tokens = this.tokens.map(t => t.symbol === "VVV" ? { ...t, loading: false } : t);
    }

    try {
      // Try CoinGecko for DIEM
      const diemRes = await fetch("https://api.coingecko.com/api/v3/simple/price?ids=venice-diem&vs_currencies=usd&include_24hr_change=true");
      if (diemRes.ok) {
        const data = await diemRes.json();
        const dt = data["venice-diem"];
        if (dt) {
          this.tokens = this.tokens.map(t =>
            t.symbol === "DIEM" ? { ...t, price: dt.usd || 0, change24h: dt.usd_24h_change || 0, loading: false } : t
          );
        }
      }
    } catch {
      this.tokens = this.tokens.map(t => t.symbol === "DIEM" ? { ...t, loading: false } : t);
    }

    this.requestUpdate();
  }

  private formatPrice(price: number): string {
    if (price === 0) return "--";
    if (price < 0.01) return `$${price.toFixed(6)}`;
    if (price < 1) return `$${price.toFixed(4)}`;
    return `$${price.toFixed(2)}`;
  }

  private formatChange(change: number): string {
    const sign = change >= 0 ? "+" : "";
    return `${sign}${change.toFixed(1)}%`;
  }

  override render() {
    return html`
      <div class="px-2 py-1.5 flex items-center gap-2 text-[10px]" style="font-variant-numeric:tabular-nums">
        ${this.tokens.map(t => html`
          <div class="flex items-center gap-1.5 px-2 py-1 rounded-lg transition-all duration-300"
            style="background:rgba(255,255,255,0.03);border:1px solid rgba(255,255,255,0.06)">
            <span class="font-bold" style="color:var(--color-card-foreground, hsl(0 0% 90%))">${t.symbol}</span>
            ${t.loading ? html`
              <span class="jae-ticker-pulse" style="color:var(--color-muted-foreground, hsl(0 0% 55%))">...</span>
            ` : html`
              <span style="color:var(--color-card-foreground, hsl(0 0% 90%))">${this.formatPrice(t.price)}</span>
              <span class="font-medium" style="color:${t.change24h >= 0 ? "rgb(34,197,94)" : "rgb(239,68,68)"}">${this.formatChange(t.change24h)}</span>
            `}
          </div>
        `)}
      </div>
    `;
  }
}
