import { demoFunc } from './dees-statsgrid.demo.js';
import * as plugins from '../00plugins.js';
import { cssGeistFontFamily } from '../00fonts.js';
import {
  customElement,
  html,
  DeesElement,
  property,
  state,
  css,
  unsafeCSS,
  cssManager,
} from '@design.estate/dees-element';
import type { TemplateResult } from '@design.estate/dees-element';

import '../dees-icon/dees-icon.js';
import '../dees-contextmenu/dees-contextmenu.js';
import '../00group-button/dees-button/dees-button.js';
import { themeDefaultStyles } from '../00theme.js';

declare global {
  interface HTMLElementTagNameMap {
    'dees-statsgrid': DeesStatsGrid;
  }
}

export interface ICpuCore {
  id: string | number;
  usage: number; // 0-100
  label?: string;
}

export interface IPartitionData {
  used: number;        // bytes
  total: number;       // bytes
  filesystem: string;  // e.g., 'ext4', 'NTFS', 'btrfs'
  mountPoint?: string; // e.g., '/', '/home', 'C:'
}

export interface IDiskData {
  capacity: number;    // bytes
  model?: string;      // e.g., 'Samsung 970 EVO Plus'
  type?: 'ssd' | 'hdd' | 'nvme';
  iops?: {
    read: number;
    write: number;
  };
  health?: number;     // 0-100 (100 = new, 0 = end of life)
}

export interface IStatsTile {
  id: string;
  title: string;
  value: number | string;
  unit?: string;
  type: 'number' | 'gauge' | 'percentage' | 'trend' | 'text' | 'multiPercentage' | 'cpuCores' | 'partition' | 'disk';

  // Layout options
  columnSpan?: number; // Number of columns to span (default: 1)

  // For gauge type
  gaugeOptions?: {
    min: number;
    max: number;
    thresholds?: Array<{value: number; color: string}>;
  };

  // For trend type
  trendData?: number[];

  // For multiPercentage type
  percentages?: Array<{
    label: string;
    value: number;
    color?: string;
  }>;

  // For cpuCores type
  coresData?: ICpuCore[];

  // For partition type
  partitionData?: IPartitionData;

  // For disk type
  diskData?: IDiskData;

  // Visual customization
  color?: string;
  icon?: string;
  description?: string;

  // Tile-specific actions
  actions?: plugins.tsclass.website.IMenuItem[];
}

@customElement('dees-statsgrid')
export class DeesStatsGrid extends DeesElement {
  public static demo = demoFunc;

  @property({ type: Array })
  accessor tiles: IStatsTile[] = [];

  @property({ type: Number })
  accessor minTileWidth: number = 250;

  @property({ type: Number })
  accessor gap: number = 16;

  @property({ type: Array })
  accessor gridActions: plugins.tsclass.website.IMenuItem[] = [];

  @state()
  accessor contextMenuVisible = false;

  @state()
  accessor contextMenuPosition = { x: 0, y: 0 };

  @state()
  accessor contextMenuActions: plugins.tsclass.website.IMenuItem[] = [];

  public static styles = [
    themeDefaultStyles,
    cssManager.defaultStyles,
    css`
      /* TODO: Migrate hardcoded values to --dees-* CSS variables */
      :host {
        display: block;
        width: 100%;
        font-family: ${cssGeistFontFamily};
      }

      /* CSS Variables for consistent spacing and sizing */
      :host {
        --grid-gap: 12px;
        --tile-padding: 16px;
        --header-spacing: 12px;
        --content-min-height: 40px;
        --value-font-size: 26px;
        --unit-font-size: 14px;
        --label-font-size: 12px;
        --title-font-size: 13px;
        --description-spacing: 8px;
        --border-radius: 6px;
        --transition-duration: 0.15s;
      }

      /* Grid Layout */
      .grid-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: calc(var(--grid-gap) * 1.5);
        min-height: 40px;
      }

      .grid-title {
        font-size: 16px;
        font-weight: 500;
        color: ${cssManager.bdTheme('#09090b', '#fafafa')};
        letter-spacing: -0.01em;
      }

      .grid-actions {
        display: flex;
        gap: 6px;
      }

      .grid-actions dees-button {
        font-size: var(--label-font-size);
      }

      .stats-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(${unsafeCSS(250)}px, 1fr));
        gap: ${unsafeCSS(16)}px;
        width: 100%;
      }

      /* Tile Base Styles */
      .stats-tile {
        background: ${cssManager.bdTheme('#ffffff', '#09090b')};
        border: 1px solid ${cssManager.bdTheme('#e0e0e0', '#202020')};
        border-radius: var(--border-radius);
        padding: var(--tile-padding);
        transition: all var(--transition-duration) ease;
        cursor: default;
        position: relative;
        overflow: hidden;
        display: flex;
        flex-direction: column;
      }

      .stats-tile:hover {
        background: ${cssManager.bdTheme('#fafafa', '#0d0d0d')};
        border-color: ${cssManager.bdTheme('#d0d0d0', '#2a2a2a')};
      }

      .stats-tile.clickable {
        cursor: pointer;
      }

      .stats-tile.clickable:hover {
        transform: translateY(-1px);
        box-shadow: 0 2px 6px ${cssManager.bdTheme('rgba(0,0,0,0.03)', 'rgba(0,0,0,0.15)')};
      }

      /* Tile Header */
      .tile-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: var(--header-spacing);
        flex-shrink: 0;
      }

      .tile-title {
        font-size: var(--title-font-size);
        font-weight: 500;
        color: ${cssManager.bdTheme('hsl(215.4 16.3% 46.9%)', 'hsl(215 20.2% 65.1%)')};
        margin: 0;
        letter-spacing: -0.01em;
        line-height: 1.2;
      }

      .tile-icon {
        opacity: 0.7;
        color: ${cssManager.bdTheme('hsl(215.4 16.3% 46.9%)', 'hsl(215 20.2% 65.1%)')};
        font-size: 16px;
        flex-shrink: 0;
      }

      /* Tile Content */
      .tile-content {
        min-height: var(--content-min-height);
        display: flex;
        flex-direction: column;
        flex: 1;
      }

      .tile-value {
        font-size: var(--value-font-size);
        font-weight: 600;
        color: ${cssManager.bdTheme('hsl(215.3 25% 8.8%)', 'hsl(210 40% 98%)')};
        line-height: 1.1;
        display: flex;
        align-items: baseline;
        gap: 4px;
        letter-spacing: -0.025em;
      }

      .tile-unit {
        font-size: var(--unit-font-size);
        font-weight: 400;
        color: ${cssManager.bdTheme('hsl(215.4 16.3% 46.9%)', 'hsl(215 20.2% 65.1%)')};
        letter-spacing: -0.01em;
      }

      .tile-description {
        font-size: var(--label-font-size);
        color: ${cssManager.bdTheme('hsl(215.4 16.3% 56.9%)', 'hsl(215 20.2% 55.1%)')};
        margin-top: var(--description-spacing);
        letter-spacing: -0.01em;
        flex-shrink: 0;
      }

      /* Gauge Styles */
      .gauge-wrapper {
        width: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
      }

      .gauge-container {
        width: 120px;
        height: 70px;
        position: relative;
        margin-top: -8px;
      }

      .gauge-svg {
        width: 100%;
        height: 100%;
      }

      .gauge-background {
        fill: none;
        stroke: ${cssManager.bdTheme('#e8e8e8', '#1a1a1a')};
        stroke-width: 6;
      }

      .gauge-fill {
        fill: none;
        stroke-width: 6;
        stroke-linecap: round;
        transition: stroke-dashoffset 0.6s cubic-bezier(0.4, 0, 0.2, 1);
      }

      .gauge-text {
        fill: ${cssManager.bdTheme('hsl(215.3 25% 8.8%)', 'hsl(210 40% 98%)')};
        font-family: ${cssGeistFontFamily};
        font-size: var(--value-font-size);
        font-weight: 600;
        text-anchor: middle;
        letter-spacing: -0.025em;
      }
      
      .gauge-unit {
        font-size: var(--unit-font-size);
        fill: ${cssManager.bdTheme('hsl(215.4 16.3% 46.9%)', 'hsl(215 20.2% 65.1%)')};
        font-weight: 400;
        font-family: ${cssGeistFontFamily};
      }

      /* Percentage Styles */
      .percentage-wrapper {
        width: 100%;
        position: relative;
        display: flex;
        flex-direction: column;
        flex: 1;
      }

      .percentage-value {
        font-size: var(--value-font-size);
        font-weight: 600;
        color: ${cssManager.bdTheme('hsl(215.3 25% 8.8%)', 'hsl(210 40% 98%)')};
        line-height: 1.1;
        letter-spacing: -0.025em;
        margin-bottom: 8px;
      }

      .percentage-bar {
        width: 100%;
        height: 6px;
        background: ${cssManager.bdTheme('#e8e8e8', '#1a1a1a')};
        border-radius: 3px;
        overflow: hidden;
        margin-top: auto;
      }

      .percentage-fill {
        height: 100%;
        background: ${cssManager.bdTheme('#333333', '#e0e0e0')};
        transition: width 0.6s cubic-bezier(0.4, 0, 0.2, 1);
        border-radius: 3px;
      }

      /* Multi Percentage Styles */
      .multi-percentage-wrapper {
        width: 100%;
        display: flex;
        flex-direction: column;
        flex: 1;
      }

      .multi-percentage-items {
        display: flex;
        flex-direction: column;
        gap: 12px;
        margin-top: auto;
      }

      .multi-percentage-item {
        display: flex;
        flex-direction: column;
        gap: 4px;
      }

      .multi-percentage-header {
        display: flex;
        justify-content: space-between;
        align-items: baseline;
      }

      .multi-percentage-label {
        font-size: 11px;
        font-weight: 500;
        color: ${cssManager.bdTheme('hsl(215.4 16.3% 46.9%)', 'hsl(215 20.2% 65.1%)')};
        letter-spacing: -0.01em;
      }

      .multi-percentage-value {
        font-size: 13px;
        font-weight: 600;
        color: ${cssManager.bdTheme('hsl(215.3 25% 8.8%)', 'hsl(210 40% 98%)')};
        letter-spacing: -0.01em;
      }

      .multi-percentage-bar {
        width: 100%;
        height: 4px;
        background: ${cssManager.bdTheme('#e8e8e8', '#1a1a1a')};
        border-radius: 2px;
        overflow: hidden;
      }

      .multi-percentage-fill {
        height: 100%;
        background: ${cssManager.bdTheme('#333333', '#e0e0e0')};
        transition: width 0.6s cubic-bezier(0.4, 0, 0.2, 1);
        border-radius: 2px;
      }

      /* CPU Cores Styles */
      .cpu-cores-wrapper {
        width: 100%;
        display: flex;
        flex-direction: column;
        flex: 1;
        min-height: 80px;
      }

      .cpu-cores-header {
        display: flex;
        align-items: baseline;
        gap: 8px;
        margin-bottom: 12px;
      }

      .cpu-cores-value {
        font-size: var(--value-font-size);
        font-weight: 600;
        color: ${cssManager.bdTheme('hsl(215.3 25% 8.8%)', 'hsl(210 40% 98%)')};
        line-height: 1.1;
        letter-spacing: -0.025em;
      }

      .cpu-cores-unit {
        font-size: var(--unit-font-size);
        font-weight: 400;
        color: ${cssManager.bdTheme('hsl(215.4 16.3% 46.9%)', 'hsl(215 20.2% 65.1%)')};
        letter-spacing: -0.01em;
      }

      .cpu-cores-label {
        font-size: var(--label-font-size);
        font-weight: 500;
        color: ${cssManager.bdTheme('hsl(215.4 16.3% 56.9%)', 'hsl(215 20.2% 55.1%)')};
        letter-spacing: -0.01em;
        margin-left: auto;
      }

      .cpu-cores-bars {
        display: flex;
        align-items: flex-end;
        gap: 3px;
        flex: 1;
        min-height: 60px;
        padding: 4px 0;
      }

      .cpu-cores-bars.centered {
        justify-content: center;
      }

      .cpu-core-bar-container {
        flex: 1;
        min-width: 6px;
        max-width: 24px;
        height: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 4px;
      }

      .cpu-core-bar-wrapper {
        flex: 1;
        width: 100%;
        background: ${cssManager.bdTheme('#e8e8e8', '#1a1a1a')};
        border-radius: 2px;
        position: relative;
        overflow: hidden;
        min-height: 40px;
      }

      .cpu-core-bar-fill {
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        width: 100%;
        background: ${cssManager.bdTheme('#666666', '#888888')};
        transition: height 0.3s cubic-bezier(0.4, 0, 0.2, 1), background-color 0.3s ease;
        border-radius: 2px 2px 0 0;
      }

      .cpu-core-bar-fill.low {
        background: ${cssManager.bdTheme('hsl(142.1 76.2% 36.3%)', 'hsl(142.1 70.6% 45.3%)')};
      }

      .cpu-core-bar-fill.medium {
        background: ${cssManager.bdTheme('hsl(45.4 93.4% 47.5%)', 'hsl(45.4 93.4% 47.5%)')};
      }

      .cpu-core-bar-fill.high {
        background: ${cssManager.bdTheme('hsl(0 84.2% 60.2%)', 'hsl(0 84.2% 60.2%)')};
      }

      .cpu-core-label {
        font-size: 9px;
        font-weight: 500;
        color: ${cssManager.bdTheme('hsl(215.4 16.3% 56.9%)', 'hsl(215 20.2% 55.1%)')};
        text-align: center;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        max-width: 100%;
      }

      /* Partition Styles */
      .partition-wrapper {
        width: 100%;
        display: flex;
        flex-direction: column;
        flex: 1;
        gap: 8px;
      }

      .partition-header {
        display: flex;
        align-items: baseline;
        gap: 8px;
      }

      .partition-percentage {
        font-size: var(--value-font-size);
        font-weight: 600;
        color: ${cssManager.bdTheme('hsl(215.3 25% 8.8%)', 'hsl(210 40% 98%)')};
        line-height: 1.1;
        letter-spacing: -0.025em;
      }

      .partition-bar {
        width: 100%;
        height: 6px;
        background: ${cssManager.bdTheme('#e8e8e8', '#1a1a1a')};
        border-radius: 3px;
        overflow: hidden;
      }

      .partition-bar-fill {
        height: 100%;
        background: ${cssManager.bdTheme('#333333', '#e0e0e0')};
        transition: width 0.6s cubic-bezier(0.4, 0, 0.2, 1);
        border-radius: 3px;
      }

      .partition-bar-fill.warning {
        background: ${cssManager.bdTheme('hsl(45.4 93.4% 47.5%)', 'hsl(45.4 93.4% 47.5%)')};
      }

      .partition-bar-fill.critical {
        background: ${cssManager.bdTheme('hsl(0 84.2% 60.2%)', 'hsl(0 84.2% 60.2%)')};
      }

      .partition-stats {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: auto;
      }

      .partition-stat {
        display: flex;
        flex-direction: column;
        gap: 2px;
      }

      .partition-stat-label {
        font-size: 10px;
        font-weight: 500;
        color: ${cssManager.bdTheme('hsl(215.4 16.3% 56.9%)', 'hsl(215 20.2% 55.1%)')};
        text-transform: uppercase;
        letter-spacing: 0.02em;
      }

      .partition-stat-value {
        font-size: 13px;
        font-weight: 600;
        color: ${cssManager.bdTheme('hsl(215.3 25% 8.8%)', 'hsl(210 40% 98%)')};
        letter-spacing: -0.01em;
      }

      .partition-meta {
        display: flex;
        align-items: center;
        gap: 6px;
        margin-top: 4px;
      }

      .partition-filesystem {
        font-size: 11px;
        font-weight: 500;
        color: ${cssManager.bdTheme('hsl(215.4 16.3% 46.9%)', 'hsl(215 20.2% 65.1%)')};
        background: ${cssManager.bdTheme('hsl(210 40% 96.1%)', 'hsl(215 20.2% 16.8%)')};
        padding: 2px 6px;
        border-radius: 3px;
      }

      .partition-mountpoint {
        font-size: 11px;
        color: ${cssManager.bdTheme('hsl(215.4 16.3% 56.9%)', 'hsl(215 20.2% 55.1%)')};
      }

      /* Disk Styles */
      .disk-wrapper {
        width: 100%;
        display: flex;
        flex-direction: column;
        flex: 1;
        gap: 8px;
      }

      .disk-capacity {
        font-size: var(--value-font-size);
        font-weight: 600;
        color: ${cssManager.bdTheme('hsl(215.3 25% 8.8%)', 'hsl(210 40% 98%)')};
        line-height: 1.1;
        letter-spacing: -0.025em;
      }

      .disk-model {
        font-size: 12px;
        color: ${cssManager.bdTheme('hsl(215.4 16.3% 46.9%)', 'hsl(215 20.2% 65.1%)')};
        display: flex;
        align-items: center;
        gap: 6px;
      }

      .disk-type-badge {
        font-size: 10px;
        font-weight: 600;
        text-transform: uppercase;
        color: ${cssManager.bdTheme('hsl(215.4 16.3% 46.9%)', 'hsl(215 20.2% 65.1%)')};
        background: ${cssManager.bdTheme('hsl(210 40% 96.1%)', 'hsl(215 20.2% 16.8%)')};
        padding: 2px 6px;
        border-radius: 3px;
      }

      .disk-metrics {
        display: flex;
        flex-direction: column;
        gap: 8px;
        margin-top: auto;
      }

      .disk-iops {
        display: flex;
        align-items: center;
        gap: 12px;
      }

      .disk-iops-item {
        display: flex;
        align-items: baseline;
        gap: 4px;
      }

      .disk-iops-label {
        font-size: 10px;
        font-weight: 500;
        color: ${cssManager.bdTheme('hsl(215.4 16.3% 56.9%)', 'hsl(215 20.2% 55.1%)')};
        text-transform: uppercase;
      }

      .disk-iops-value {
        font-size: 13px;
        font-weight: 600;
        color: ${cssManager.bdTheme('hsl(215.3 25% 8.8%)', 'hsl(210 40% 98%)')};
      }

      .disk-health {
        display: flex;
        flex-direction: column;
        gap: 4px;
      }

      .disk-health-header {
        display: flex;
        justify-content: space-between;
        align-items: baseline;
      }

      .disk-health-label {
        font-size: 10px;
        font-weight: 500;
        color: ${cssManager.bdTheme('hsl(215.4 16.3% 56.9%)', 'hsl(215 20.2% 55.1%)')};
        text-transform: uppercase;
      }

      .disk-health-value {
        font-size: 12px;
        font-weight: 600;
        color: ${cssManager.bdTheme('hsl(215.3 25% 8.8%)', 'hsl(210 40% 98%)')};
      }

      .disk-health-bar {
        width: 100%;
        height: 4px;
        background: ${cssManager.bdTheme('#e8e8e8', '#1a1a1a')};
        border-radius: 2px;
        overflow: hidden;
      }

      .disk-health-fill {
        height: 100%;
        transition: width 0.6s cubic-bezier(0.4, 0, 0.2, 1);
        border-radius: 2px;
      }

      .disk-health-fill.good {
        background: ${cssManager.bdTheme('hsl(142.1 76.2% 36.3%)', 'hsl(142.1 70.6% 45.3%)')};
      }

      .disk-health-fill.warning {
        background: ${cssManager.bdTheme('hsl(45.4 93.4% 47.5%)', 'hsl(45.4 93.4% 47.5%)')};
      }

      .disk-health-fill.critical {
        background: ${cssManager.bdTheme('hsl(0 84.2% 60.2%)', 'hsl(0 84.2% 60.2%)')};
      }

      /* Trend Styles */
      .trend-container {
        width: 100%;
        display: flex;
        flex-direction: column;
        gap: 8px;
        flex: 1;
      }

      .trend-header {
        display: flex;
        align-items: baseline;
        gap: 8px;
      }

      .trend-value {
        font-size: var(--value-font-size);
        font-weight: 600;
        color: ${cssManager.bdTheme('hsl(215.3 25% 8.8%)', 'hsl(210 40% 98%)')};
        line-height: 1.1;
        letter-spacing: -0.025em;
      }

      .trend-unit {
        font-size: var(--unit-font-size);
        font-weight: 400;
        color: ${cssManager.bdTheme('hsl(215.4 16.3% 46.9%)', 'hsl(215 20.2% 65.1%)')};
        letter-spacing: -0.01em;
      }

      .trend-label {
        font-size: var(--label-font-size);
        font-weight: 500;
        color: ${cssManager.bdTheme('hsl(215.4 16.3% 56.9%)', 'hsl(215 20.2% 55.1%)')};
        letter-spacing: -0.01em;
        margin-left: auto;
      }

      .trend-graph {
        width: 100%;
        height: 28px;
        position: relative;
        margin-top: auto;
      }

      .trend-svg {
        width: 100%;
        height: 100%;
        display: block;
      }

      .trend-line {
        fill: none;
        stroke: ${cssManager.bdTheme('#999999', '#666666')};
        stroke-width: 1.5;
        stroke-linejoin: round;
        stroke-linecap: round;
      }

      .trend-area {
        fill: ${cssManager.bdTheme('rgba(150, 150, 150, 0.08)', 'rgba(100, 100, 100, 0.08)')};
      }

      /* Text Value Styles */
      .text-value {
        font-size: var(--value-font-size);
        font-weight: 600;
        color: ${cssManager.bdTheme('hsl(215.3 25% 8.8%)', 'hsl(210 40% 98%)')};
        line-height: 1.1;
        letter-spacing: -0.025em;
      }

      /* Context Menu */
      dees-contextmenu {
        position: fixed;
        z-index: 1000;
      }
    `,
  ];

  constructor() {
    super();
  }

  public render(): TemplateResult {
    return html`
      ${this.gridActions.length > 0 ? html`
        <div class="grid-header">
          <div class="grid-title"></div>
          <div class="grid-actions">
            ${this.gridActions.map(action => html`
              <dees-button 
                @clicked=${() => this.handleGridAction(action)}
                type="outline"
                size="sm"
              >
                ${action.iconName ? html`<dees-icon .icon=${action.iconName} size="small"></dees-icon>` : ''}
                ${action.name}
              </dees-button>
            `)}
          </div>
        </div>
      ` : ''}
      
      <div class="stats-grid" style="grid-template-columns: repeat(auto-fit, minmax(${this.minTileWidth}px, 1fr)); gap: ${this.gap}px;">
        ${this.tiles.map(tile => this.renderTile(tile))}
      </div>

      ${this.contextMenuVisible ? html`
        <dees-contextmenu
          .x=${this.contextMenuPosition.x}
          .y=${this.contextMenuPosition.y}
          .menuItems=${this.contextMenuActions as any}
          @clicked=${() => this.contextMenuVisible = false}
        ></dees-contextmenu>
      ` : ''}
    `;
  }

  private renderTile(tile: IStatsTile): TemplateResult {
    const hasActions = tile.actions && tile.actions.length > 0;
    const clickable = hasActions && tile.actions.length === 1;
    const columnSpan = tile.columnSpan && tile.columnSpan > 1 ? tile.columnSpan : undefined;

    return html`
      <div
        class="stats-tile ${clickable ? 'clickable' : ''}"
        style="${columnSpan ? `grid-column: span ${columnSpan}` : ''}"
        @click=${clickable ? () => this.handleTileAction(tile.actions![0], tile) : undefined}
        @contextmenu=${hasActions ? (e: MouseEvent) => this.showContextMenu(e, tile) : undefined}
      >
        <div class="tile-header">
          <h3 class="tile-title">${tile.title}</h3>
          ${tile.icon ? html`
            <dees-icon class="tile-icon" .icon=${tile.icon} size="small"></dees-icon>
          ` : ''}
        </div>
        
        <div class="tile-content">
          ${this.renderTileContent(tile)}
        </div>
        
        ${tile.description && tile.type !== 'trend' ? html`
          <div class="tile-description">${tile.description}</div>
        ` : ''}
      </div>
    `;
  }

  private renderTileContent(tile: IStatsTile): TemplateResult {
    switch (tile.type) {
      case 'number':
        return html`
          <div class="tile-value" style="${tile.color ? `color: ${tile.color}` : ''}">
            <span>${tile.value}</span>
            ${tile.unit ? html`<span class="tile-unit">${tile.unit}</span>` : ''}
          </div>
        `;

      case 'gauge':
        return this.renderGauge(tile);

      case 'percentage':
        return this.renderPercentage(tile);

      case 'trend':
        return this.renderTrend(tile);

      case 'multiPercentage':
        return this.renderMultiPercentage(tile);

      case 'cpuCores':
        return this.renderCpuCores(tile);

      case 'partition':
        return this.renderPartition(tile);

      case 'disk':
        return this.renderDisk(tile);

      case 'text':
        return html`
          <div class="text-value" style="${tile.color ? `color: ${tile.color}` : ''}">
            ${tile.value}
          </div>
        `;

      default:
        return html`<div class="tile-value">${tile.value}</div>`;
    }
  }

  private renderGauge(tile: IStatsTile): TemplateResult {
    const value = typeof tile.value === 'number' ? tile.value : parseFloat(tile.value);
    const options = tile.gaugeOptions || { min: 0, max: 100 };
    const percentage = ((value - options.min) / (options.max - options.min)) * 100;

    // SVG dimensions and calculations
    const width = 120;
    const height = 70;
    const strokeWidth = 6;
    const padding = strokeWidth / 2 + 2;
    const radius = 40;
    const centerX = width / 2;
    const centerY = height - padding;
    
    // Arc path
    const startX = centerX - radius;
    const startY = centerY;
    const endX = centerX + radius;
    const endY = centerY;
    const arcPath = `M ${startX} ${startY} A ${radius} ${radius} 0 0 1 ${endX} ${endY}`;
    
    // Calculate stroke dasharray and dashoffset
    const circumference = Math.PI * radius;
    const strokeDashoffset = circumference - (circumference * percentage) / 100;

    let strokeColor = tile.color || cssManager.bdTheme('hsl(215.3 25% 28.8%)', 'hsl(210 40% 78%)');
    if (options.thresholds) {
      const sortedThresholds = [...options.thresholds].sort((a, b) => b.value - a.value);
      for (const threshold of sortedThresholds) {
        if (value >= threshold.value) {
          strokeColor = threshold.color;
          break;
        }
      }
    }

    return html`
      <div class="gauge-wrapper">
        <div class="gauge-container">
          <svg class="gauge-svg" viewBox="0 0 ${width} ${height}" preserveAspectRatio="xMidYMid meet">
            <!-- Background arc -->
            <path
              class="gauge-background"
              d="${arcPath}"
            />
            <!-- Filled arc -->
            <path
              class="gauge-fill"
              d="${arcPath}"
              stroke="${strokeColor}"
              stroke-dasharray="${circumference}"
              stroke-dashoffset="${strokeDashoffset}"
            />
            <!-- Value text -->
            <text class="gauge-text" x="${centerX}" y="${centerY - 8}" dominant-baseline="middle">
              <tspan>${value}</tspan>${tile.unit ? html`<tspan class="gauge-unit" dx="2" dy="0">${tile.unit}</tspan>` : ''}
            </text>
          </svg>
        </div>
      </div>
    `;
  }

  private renderPercentage(tile: IStatsTile): TemplateResult {
    const value = typeof tile.value === 'number' ? tile.value : parseFloat(tile.value);
    const percentage = Math.min(100, Math.max(0, value));

    return html`
      <div class="percentage-wrapper">
        <div class="percentage-value">${percentage}%</div>
        <div class="percentage-bar">
          <div 
            class="percentage-fill" 
            style="width: ${percentage}%; ${tile.color ? `background: ${tile.color}` : ''}"
          ></div>
        </div>
      </div>
    `;
  }

  private renderTrend(tile: IStatsTile): TemplateResult {
    if (!tile.trendData || tile.trendData.length < 2) {
      return html`<div class="tile-value">${tile.value}</div>`;
    }

    const data = tile.trendData;
    const max = Math.max(...data);
    const min = Math.min(...data);
    const range = max - min || 1;
    const width = 300;
    const height = 32;
    
    // Add padding to prevent clipping
    const padding = 2;
    const points = data.map((value, index) => {
      const x = (index / (data.length - 1)) * width;
      const y = padding + (height - 2 * padding) - ((value - min) / range) * (height - 2 * padding);
      return `${x},${y}`;
    }).join(' ');

    const areaPoints = `0,${height} ${points} ${width},${height}`;

    return html`
      <div class="trend-container">
        <div class="trend-header">
          <span class="trend-value">${tile.value}</span>
          ${tile.unit ? html`<span class="trend-unit">${tile.unit}</span>` : ''}
          ${tile.description ? html`<span class="trend-label">${tile.description}</span>` : ''}
        </div>
        <div class="trend-graph">
          <svg class="trend-svg" viewBox="0 0 ${width} ${height}" preserveAspectRatio="none">
            <polygon class="trend-area" points="${areaPoints}" />
            <polyline class="trend-line" points="${points}" />
          </svg>
        </div>
      </div>
    `;
  }

  private renderMultiPercentage(tile: IStatsTile): TemplateResult {
    if (!tile.percentages || tile.percentages.length === 0) {
      return html`<div class="tile-value">${tile.value}</div>`;
    }

    // Limit to 3 percentages
    const items = tile.percentages.slice(0, 3);

    return html`
      <div class="multi-percentage-wrapper">
        <div class="multi-percentage-items">
          ${items.map(item => {
            const percentage = Math.min(100, Math.max(0, item.value));
            return html`
              <div class="multi-percentage-item">
                <div class="multi-percentage-header">
                  <span class="multi-percentage-label">${item.label}</span>
                  <span class="multi-percentage-value">${percentage}%</span>
                </div>
                <div class="multi-percentage-bar">
                  <div
                    class="multi-percentage-fill"
                    style="width: ${percentage}%; ${item.color ? `background: ${item.color}` : ''}"
                  ></div>
                </div>
              </div>
            `;
          })}
        </div>
      </div>
    `;
  }

  private renderCpuCores(tile: IStatsTile): TemplateResult {
    if (!tile.coresData || tile.coresData.length === 0) {
      return html`<div class="tile-value">${tile.value}</div>`;
    }

    const cores = tile.coresData;
    const avgUsage = Math.round(cores.reduce((sum, core) => sum + core.usage, 0) / cores.length);

    // Determine color class based on usage
    const getColorClass = (usage: number): string => {
      if (usage < 50) return 'low';
      if (usage < 80) return 'medium';
      return 'high';
    };

    // Calculate if bars should be centered (when they take up less than 66.6% of available width)
    // Max bar width = cores * 24px + (cores - 1) * 3px gap
    const maxBarsWidth = cores.length * 24 + (cores.length - 1) * 3;
    // Estimate tile content width based on columnSpan and minTileWidth (subtract padding)
    const columnSpan = tile.columnSpan || 1;
    const estimatedTileWidth = (this.minTileWidth * columnSpan) + ((columnSpan - 1) * this.gap) - 32; // 32px for padding
    const shouldCenter = maxBarsWidth < estimatedTileWidth * 0.666;

    return html`
      <div class="cpu-cores-wrapper">
        <div class="cpu-cores-header">
          <span class="cpu-cores-value">${avgUsage}</span>
          <span class="cpu-cores-unit">%</span>
          <span class="cpu-cores-label">${cores.length} cores</span>
        </div>
        <div class="cpu-cores-bars ${shouldCenter ? 'centered' : ''}">
          ${cores.map(core => {
            const usage = Math.min(100, Math.max(0, core.usage));
            const colorClass = getColorClass(usage);
            return html`
              <div class="cpu-core-bar-container" title="Core ${core.label || core.id}: ${usage}%">
                <div class="cpu-core-bar-wrapper">
                  <div
                    class="cpu-core-bar-fill ${colorClass}"
                    style="height: ${usage}%"
                  ></div>
                </div>
                ${cores.length <= 16 ? html`
                  <span class="cpu-core-label">${core.label || core.id}</span>
                ` : ''}
              </div>
            `;
          })}
        </div>
      </div>
    `;
  }

  private formatBytes(bytes: number): string {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
  }

  private renderPartition(tile: IStatsTile): TemplateResult {
    if (!tile.partitionData) {
      return html`<div class="tile-value">${tile.value}</div>`;
    }

    const { used, total, filesystem, mountPoint } = tile.partitionData;
    const percentage = Math.min(100, Math.max(0, (used / total) * 100));
    const free = total - used;

    // Determine color class based on usage
    const getColorClass = (): string => {
      if (percentage >= 90) return 'critical';
      if (percentage >= 75) return 'warning';
      return '';
    };

    return html`
      <div class="partition-wrapper">
        <div class="partition-header">
          <span class="partition-percentage">${Math.round(percentage)}%</span>
        </div>
        <div class="partition-bar">
          <div
            class="partition-bar-fill ${getColorClass()}"
            style="width: ${percentage}%"
          ></div>
        </div>
        <div class="partition-stats">
          <div class="partition-stat">
            <span class="partition-stat-label">Used</span>
            <span class="partition-stat-value">${this.formatBytes(used)}</span>
          </div>
          <div class="partition-stat">
            <span class="partition-stat-label">Free</span>
            <span class="partition-stat-value">${this.formatBytes(free)}</span>
          </div>
        </div>
        <div class="partition-meta">
          <span class="partition-filesystem">${filesystem}</span>
          ${mountPoint ? html`<span class="partition-mountpoint">${mountPoint}</span>` : ''}
        </div>
      </div>
    `;
  }

  private renderDisk(tile: IStatsTile): TemplateResult {
    if (!tile.diskData) {
      return html`<div class="tile-value">${tile.value}</div>`;
    }

    const { capacity, model, type, iops, health } = tile.diskData;

    // Determine health color class (inverted - high is good)
    const getHealthClass = (value: number): string => {
      if (value >= 70) return 'good';
      if (value >= 30) return 'warning';
      return 'critical';
    };

    return html`
      <div class="disk-wrapper">
        <div class="disk-capacity">${this.formatBytes(capacity)}</div>
        ${model || type ? html`
          <div class="disk-model">
            ${model ? html`<span>${model}</span>` : ''}
            ${type ? html`<span class="disk-type-badge">${type}</span>` : ''}
          </div>
        ` : ''}
        <div class="disk-metrics">
          ${iops ? html`
            <div class="disk-iops">
              <div class="disk-iops-item">
                <span class="disk-iops-label">Read</span>
                <span class="disk-iops-value">${iops.read.toLocaleString()}</span>
              </div>
              <div class="disk-iops-item">
                <span class="disk-iops-label">Write</span>
                <span class="disk-iops-value">${iops.write.toLocaleString()}</span>
              </div>
            </div>
          ` : ''}
          ${health !== undefined ? html`
            <div class="disk-health">
              <div class="disk-health-header">
                <span class="disk-health-label">Health</span>
                <span class="disk-health-value">${health}%</span>
              </div>
              <div class="disk-health-bar">
                <div
                  class="disk-health-fill ${getHealthClass(health)}"
                  style="width: ${health}%"
                ></div>
              </div>
            </div>
          ` : ''}
        </div>
      </div>
    `;
  }

  private async handleGridAction(action: plugins.tsclass.website.IMenuItem) {
    if (action.action) {
      await action.action();
    }
  }

  private async handleTileAction(action: plugins.tsclass.website.IMenuItem, _tile: IStatsTile) {
    if (action.action) {
      await action.action();
    }
    // Note: tile data is available through closure when defining actions
  }

  private showContextMenu(event: MouseEvent, tile: IStatsTile) {
    if (!tile.actions || tile.actions.length === 0) return;
    
    event.preventDefault();
    this.contextMenuPosition = { x: event.clientX, y: event.clientY };
    this.contextMenuActions = tile.actions;
    this.contextMenuVisible = true;

    // Close context menu on click outside
    const closeHandler = () => {
      this.contextMenuVisible = false;
      document.removeEventListener('click', closeHandler);
    };
    setTimeout(() => {
      document.addEventListener('click', closeHandler);
    }, 100);
  }
}