// Generated automatically by Industrial UI Architecture Standard (Yeste.id)
// Preset: navy-industrial-default | Focal Accent: Amber (38°)
// Target Framework: shadcn/ui & Base UI (Tailwind CSS v4 + Semantic HSL Tokens)
// Active Add-ons: [none]

import React, { useState, useEffect, useRef, useCallback } from 'react';




// ============================================================================
// 1. TYPE DEFINITIONS & INTERFACES
// ============================================================================

export type ConfirmationLevel = 'L0_NONE' | 'L1_UNDO_TOAST' | 'L2_MODAL' | 'L3_HOLD_TO_EXECUTE' | 'L3_TYPED_ENTITY';

export interface ActionButtonConfig {
  id: string;
  label: string;
  icon?: string;
  variant: 'primary' | 'secondary' | 'ghost' | 'destructive' | 'hold';
  size?: 'dense' | 'regular' | 'large';
  confirmationLevel?: ConfirmationLevel;
  holdDurationMs?: number;
  entityNameToMatch?: string;
}

export interface StatCardData {
  id: string;
  title: string;
  value: string | number;
  unit?: string;
  secondaryLabel?: string;
  subtitle?: string;
  icon?: string;
  status?: 'normal' | 'optimal' | 'warning' | 'critical';
}

export interface TableColumn {
  key: string;
  label: string;
  align?: 'left' | 'center' | 'right';
  isMonospace?: boolean;
  isTabular?: boolean;
}

export interface LogRecord {
  timestamp: string;
  level: string;
  message: string;
  source: string;
  [key: string]: unknown;
}

export interface ToastState {
  id: number;
  message: string;
  onUndo?: () => void;
  durationMs?: number;
}

export interface ModalState {
  isOpen: boolean;
  title: string;
  body: string;
  confirmLabel: string;
  cancelLabel: string;
  onConfirm: () => void;
}

// ============================================================================
// 2. MAIN COMPONENT: ServerPerformanceDashboard
// ============================================================================

export const ServerPerformanceDashboard: React.FC = () => {
  // --- DEFENSIVE UX STATE ---
  const [toasts, setToasts] = useState<ToastState[]>([]);
  const [modal, setModal] = useState<ModalState>({
    isOpen: false,
    title: '',
    body: '',
    confirmLabel: 'Confirm',
    cancelLabel: 'Cancel',
    onConfirm: () => {}
  });

  // Hold-to-Execute Button State (L3)
  const [holdProgress, setHoldProgress] = useState<{ [buttonId: string]: number }>({});
  const holdAnimRef = useRef<{ [buttonId: string]: number | null }>({});

  // Table Roving Tabindex State
  const [activeRowIndex, setActiveRowIndex] = useState<number>(0);

  // Search query state
  const [searchQuery, setSearchQuery] = useState<string>('');

  // --- DEFENSIVE TOAST TRIGGER (L1) ---
  const showToast = useCallback((message: string, onUndo?: () => void, durationMs = 5000) => {
    const id = Date.now();
    setToasts(prev => [...prev, { id, message, onUndo, durationMs }]);

    setTimeout(() => {
      setToasts(prev => prev.filter(t => t.id !== id));
    }, durationMs);
  }, []);

  // --- DEFENSIVE MODAL TRIGGER (L2) ---
  const showModal = useCallback((title: string, body: string, onConfirm: () => void) => {
    setModal({
      isOpen: true,
      title,
      body,
      confirmLabel: 'Proceed',
      cancelLabel: 'Cancel',
      onConfirm: () => {
        onConfirm();
        setModal(prev => ({ ...prev, isOpen: false }));
      }
    });
  }, []);

  // --- HOLD TO EXECUTE HANDLER (L3) ---
  const startHold = useCallback((buttonId: string, durationMs = 2500, onComplete: () => void) => {
    const startTime = performance.now();

    const update = (now: number) => {
      const elapsed = now - startTime;
      const progress = Math.min(elapsed / durationMs, 1);
      setHoldProgress(prev => ({ ...prev, [buttonId]: progress * 100 }));

      if (progress >= 1) {
        onComplete();
        setTimeout(() => {
          setHoldProgress(prev => ({ ...prev, [buttonId]: 0 }));
        }, 600);
        return;
      }

      holdAnimRef.current[buttonId] = requestAnimationFrame(update);
    };

    holdAnimRef.current[buttonId] = requestAnimationFrame(update);
  }, []);

  const cancelHold = useCallback((buttonId: string) => {
    if (holdAnimRef.current[buttonId]) {
      cancelAnimationFrame(holdAnimRef.current[buttonId]!);
      holdAnimRef.current[buttonId] = null;
    }
    setHoldProgress(prev => ({ ...prev, [buttonId]: 0 }));
  }, []);

  // --- ACTION BUTTON DISPATCHER ---
  const handleActionClick = useCallback((action: ActionButtonConfig) => {
    const level = action.confirmationLevel || 'L0_NONE';

    if (level === 'L1_UNDO_TOAST') {
      showToast(`Action "${action.label}" executed.`, () => {
        showToast(`Undo: Action "${action.label}" was reverted.`, undefined, 3000);
      });
    } else if (level === 'L2_MODAL') {
      showModal(
        `Confirm ${action.label}`,
        `Are you sure you want to proceed with "${action.label}"? This will apply system updates.`,
        () => {
          showToast(`Confirmed: "${action.label}" completed.`, undefined, 4000);
        }
      );
    } else if (level === 'L3_TYPED_ENTITY') {
      const entity = action.entityNameToMatch || 'NODE-007';
      const typed = window.prompt(`⚠️ CRITICAL IRREVERSIBLE ACTION\n\nType "${entity}" to execute:`);
      if (typed === entity) {
        showToast(`🚨 Entity "${entity}" verified. Action completed!`, undefined, 5000);
      } else if (typed !== null) {
        alert('❌ Mismatch! Action aborted.');
      }
    }
  }, [showToast, showModal]);

  const statCards: StatCardData[] = [
  {
    "componentType": "StatCard",
    "id": "cpu-usage-card",
    "title": "CPU USAGE",
    "value": "78.2",
    "unit": "%",
    "secondaryLabel": "16 Cores",
    "subtitle": "Threshold: 85% (Warning)",
    "icon": "fa-microchip",
    "status": "warning",
    "type": "StatCard"
  },
  {
    "componentType": "StatCard",
    "id": "memory-usage-card",
    "title": "MEMORY USAGE",
    "value": "45.1",
    "unit": "GB",
    "secondaryLabel": "64 GB Total",
    "subtitle": "Available: 18.9 GB",
    "icon": "fa-memory",
    "status": "normal",
    "type": "StatCard"
  },
  {
    "componentType": "StatCard",
    "id": "network-latency-card",
    "title": "NETWORK LATENCY",
    "value": "12.7",
    "unit": "ms",
    "secondaryLabel": "Avg. Last 5 min",
    "subtitle": "Status: Optimal",
    "icon": "fa-network-wired",
    "status": "optimal",
    "type": "StatCard"
  }
];
  const logTableData = {
  "componentType": "DataTable",
  "id": "system-logs-table",
  "title": "Recent System Events",
  "badge": "124 Active",
  "enableRovingTabindex": true,
  "columns": [
    {
      "key": "timestamp",
      "label": "TIMESTAMP",
      "align": "left",
      "isMonospace": true,
      "isTabular": true
    },
    {
      "key": "level",
      "label": "LEVEL",
      "align": "left"
    },
    {
      "key": "source",
      "label": "SOURCE",
      "align": "left"
    },
    {
      "key": "message",
      "label": "MESSAGE",
      "align": "left"
    }
  ],
  "rows": [
    {
      "timestamp": "2023-10-27T10:30:01Z",
      "level": "INFO",
      "source": "kernel",
      "message": "System heartbeat detected."
    },
    {
      "timestamp": "2023-10-27T10:29:45Z",
      "level": "WARNING",
      "source": "cpu-monitor",
      "message": "CPU load exceeded 75% for 30s."
    },
    {
      "timestamp": "2023-10-27T10:29:30Z",
      "level": "ERROR",
      "source": "disk-io",
      "message": "Disk I/O bottleneck detected on /dev/sda1."
    },
    {
      "timestamp": "2023-10-27T10:29:15Z",
      "level": "INFO",
      "source": "network",
      "message": "Connection established to primary gateway."
    }
  ],
  "actions": [
    "View Details"
  ],
  "type": "DataTable"
};

  return (
    <div className="bg-surface-0 text-text-high font-sans text-sm leading-normal antialiased min-h-screen flex flex-col select-none">
      
      {/* 1. TOP GLOBAL UTILITY SWITCHER */}
      <nav className="h-9 bg-surface-1 border-b border-surface-2 px-4 flex items-center justify-between text-xs text-text-med shrink-0 z-30">
        <div className="flex items-center gap-3">
          <div className="flex items-center gap-1.5 font-mono text-[11px] text-text-high font-semibold">
            <span className="w-2 h-2 rounded-full bg-focal-core animate-pulse" />
            <span>SHADCN INDUSTRIAL CONSOLE</span>
          </div>
          <span className="text-surface-3">|</span>
          <span className="text-[11px] text-text-low font-mono">navy-industrial-default (shadcn)</span>
        </div>
        <div className="flex items-center gap-2">
          
          
          <span className="text-[10px] font-mono px-2 py-0.5 rounded bg-surface-2 text-text-med">React v19 TSX</span>
        </div>
      </nav>

      {/* 2. Z1 WORKSPACE HEADER */}
      <header className="h-14 bg-surface-1 shadow-edge flex items-center justify-between px-6 shrink-0 border-b border-surface-2">
        <div className="flex items-center gap-3">
          <div className="w-3 h-3 bg-focal-core shadow-focal rounded-sm shrink-0" />
          <h1 className="text-sm font-semibold tracking-wider uppercase text-text-high m-0">
            Server Performance Overview
          </h1>
        </div>

        {/* Search Input */}
        <div className="relative flex items-center flex-1 max-w-md mx-6">
          <i className="fas fa-magnifying-glass text-text-low absolute left-3 text-xs pointer-events-none" />
          <input
            type="text"
            value={searchQuery}
            onChange={e => setSearchQuery(e.target.value)}
            placeholder="Search server logs or metrics..."
            className="w-full h-9 bg-surface-0 text-text-high placeholder-text-low pl-9 pr-3 rounded-base outline-none focus:ring-1 focus:ring-focal-core focus:shadow-focal text-xs font-mono transition-shadow shadow-inner border-0"
          />
        </div>

        {/* Header Actions */}
        <div className="flex items-center gap-2">
          
          <button
            onClick={() => handleActionClick({"id":"refresh-data","label":"Refresh Data","icon":"fa-sync-alt","variant":"ghost","size":"regular","confirmationLevel":"L0_NONE","type":"ActionButton"})}
            className="btn h-8 px-2.5 rounded-base bg-surface-3 text-text-high hover:bg-surface-2 text-xs font-semibold shadow-edge transition-all border-0 cursor-pointer inline-flex items-center gap-1.5"
          >
            <i className="fas fa-arrows-rotate text-xs" />
            <span>Refresh Data</span>
          </button>
          
          
        </div>
      </header>

      {/* 3. Z0 MAIN WORKSPACE CANVAS */}
      <main className="flex-1 p-5 overflow-y-auto max-w-[1400px] w-full mx-auto flex flex-col gap-4">
        
        {/* ALERT BANNER */}
        
        <div className="bg-surface-2 shadow-edge rounded-base py-2.5 px-3.5 flex items-center gap-3">
          <div className="w-2 h-2 rounded-full bg-focal-core shadow-focal-sm shrink-0" />
          <div className="text-text-high text-xs sm:text-sm font-medium">
            <span className="font-semibold text-text-high">Degraded Performance Detected: </span>
            <span className="text-text-med">High CPU load on Node-003. Review logs for anomalies.</span>
          </div>
        </div>
        

        {/* SECTION: METRIC CARDS (Z2) */}
        <section className="flex flex-col gap-2.5">
          <h2 className="text-xs font-semibold text-text-med uppercase tracking-wider flex items-center gap-1.5">
            <span className="w-1.5 h-1.5 rounded-full bg-focal-core" />
            Telemetry Metrics
          </h2>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
            {statCards.map((card) => (
              <article key={card.id} className="bg-surface-2 shadow-edge rounded-base p-3.5 flex flex-col gap-2 relative overflow-hidden">
                
                <div className="flex justify-between items-center">
                  <span className="text-xs font-medium text-text-med uppercase tracking-wider flex items-center gap-1.5">
                    
                    {card.title}
                  </span>
                  {card.secondaryLabel && (
                    <span className="text-xs text-text-med tabular-num font-mono">{card.secondaryLabel}</span>
                  )}
                </div>
                <div className="text-3xl font-semibold text-text-high leading-none tabular-num my-1">
                  {card.value} {card.unit && <span className="text-sm font-normal text-text-med">{card.unit}</span>}
                </div>
                {card.subtitle && <div className="text-xs text-text-med">{card.subtitle}</div>}
              </article>
            ))}
          </div>
        </section>

        

        {/* SECTION: DATA TABLE (Z2 with Keyboard Roving Tabindex) */}
        <section className="flex flex-col gap-2.5">
          <div className="bg-surface-2 shadow-edge rounded-base overflow-hidden">
            <div className="px-3.5 py-2.5 border-b border-surface-3 flex justify-between items-center">
              <div className="flex items-center gap-2">
                <span className="text-xs font-semibold text-text-high uppercase tracking-wider">{logTableData.title}</span>
                {logTableData.badge && (
                  <span className="px-1.5 py-0.5 rounded-sm bg-surface-3 text-[10px] font-mono text-text-med">{logTableData.badge}</span>
                )}
              </div>
              <div className="text-[11px] text-text-low font-mono">
                Keyboard: <kbd className="px-1 bg-surface-3 rounded">J</kbd>/<kbd className="px-1 bg-surface-3 rounded">K</kbd> row navigate
              </div>
            </div>
            <div className="overflow-x-auto">
              <table 
                className="w-full border-collapse text-left"
              >
                <thead>
                  <tr>
                    {logTableData.columns?.map((col: TableColumn) => (
                      <th key={col.key} className="px-3.5 py-2.5 text-xs font-medium text-text-med uppercase tracking-wider border-b border-surface-3">
                        {col.label}
                      </th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {logTableData.rows?.map((row: LogRecord, idx: number) => (
                    <tr 
                      key={idx}
                      onClick={() => setActiveRowIndex(idx)}
                      className={`hover:bg-surface-3 transition-colors cursor-pointer ${activeRowIndex === idx ? 'bg-surface-3 ring-1 ring-focal-core/40' : ''}`}
                    >
                      {logTableData.columns?.map((col: TableColumn) => (
                        <td key={col.key} className="px-3.5 py-2 text-text-high border-b border-surface-1 text-sm font-mono">
                          {String(row[col.key] ?? '-')}
                        </td>
                      ))}
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        </section>

        {/* SECTION: CRITICAL ACTIONS (Hold-to-Execute L3) */}
        <section className="flex flex-col gap-2.5">
          <h2 className="text-xs font-semibold text-text-med uppercase tracking-wider flex items-center gap-1.5">
            <span className="w-1.5 h-1.5 rounded-full bg-focal-core" />
            Critical Actions (Defensive UX)
          </h2>
          <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-3 bg-surface-2 p-3.5 rounded-base shadow-edge">
            
            {/* L3 Hold Button */}
            <div className="flex flex-col gap-1">
              <button
                onPointerDown={() => startHold('btn-clear-cache', 2500, () => showToast('🚨 Cache cleared completely!'))}
                onPointerUp={() => cancelHold('btn-clear-cache')}
                onPointerLeave={() => cancelHold('btn-clear-cache')}
                className="relative overflow-hidden h-10 px-4 rounded-base bg-surface-3 text-red-400 hover:bg-red-950/50 border border-red-900/40 text-xs font-semibold shadow-edge transition-all border-0 cursor-pointer flex items-center justify-center gap-2"
              >
                <div 
                  className="absolute inset-0 bg-red-600/30 transition-all duration-75"
                  style={{ width: `${holdProgress['btn-clear-cache'] || 0}%` }}
                />
                <span className="relative z-10 flex items-center gap-1.5">
                  
                  Hold to Clear System Cache
                </span>
              </button>
              <div className="text-[10px] text-text-low font-mono flex justify-between px-1">
                <span>Level: L3_HOLD_TO_EXECUTE</span>
                <span>Hold 2.5s</span>
              </div>
            </div>

            {/* L3 Typed Confirmation Button */}
            <div className="flex flex-col gap-1">
              <button
                onClick={() => handleActionClick({
                  id: 'btn-restart-server',
                  label: 'Restart Server Node',
                  variant: 'destructive',
                  confirmationLevel: 'L3_TYPED_ENTITY',
                  entityNameToMatch: 'NODE-007'
                })}
                className="h-10 px-4 rounded-base bg-surface-3 text-red-400 hover:bg-red-950/50 border border-red-900/40 text-xs font-semibold shadow-edge transition-all border-0 cursor-pointer flex items-center justify-center gap-2"
              >
                
                <span>Restart Server Node</span>
              </button>
              <div className="text-[10px] text-text-low font-mono flex justify-between px-1">
                <span>Level: L3_TYPED_ENTITY</span>
                <span>Entity: NODE-007</span>
              </div>
            </div>

          </div>
        </section>

      </main>

      {/* 4. DEFENSIVE MODAL COMPONENT (L2) */}
      {modal.isOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/65 backdrop-blur-sm p-4">
          <div className="bg-surface-2 border border-surface-3 rounded-base shadow-2xl max-w-md w-full p-4 flex flex-col gap-3">
            <h3 className="text-sm font-semibold text-text-high m-0">{modal.title}</h3>
            <p className="text-xs text-text-med leading-relaxed m-0">{modal.body}</p>
            <div className="flex justify-end gap-2 mt-2">
              <button
                onClick={() => setModal(prev => ({ ...prev, isOpen: false }))}
                className="h-8 px-3 rounded-base bg-surface-3 text-text-high text-xs font-medium hover:bg-surface-1 border-0 cursor-pointer"
              >
                {modal.cancelLabel}
              </button>
              <button
                onClick={modal.onConfirm}
                className="h-8 px-3 rounded-base bg-focal-core text-black text-xs font-semibold shadow-focal hover:opacity-90 border-0 cursor-pointer"
              >
                {modal.confirmLabel}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 5. TOAST NOTIFICATIONS CONTAINER (L1) */}
      <div className="fixed bottom-4 right-4 z-50 flex flex-col gap-2">
        {toasts.map(toast => (
          <div key={toast.id} className="bg-surface-3 border border-surface-2 shadow-lg rounded-base px-3.5 py-2.5 flex items-center gap-3 text-xs text-text-high font-medium">
            <span>{toast.message}</span>
            {toast.onUndo && (
              <button
                onClick={toast.onUndo}
                className="text-focal-core hover:underline font-mono text-[11px] bg-transparent border-0 cursor-pointer p-0"
              >
                Undo
              </button>
            )}
          </div>
        ))}
      </div>

    </div>
  );
};

export default ServerPerformanceDashboard;
