/**
 * MCP Apps renderer — reusable HTML/CSS component system for structuredContent.
 * Provides cards, tables, badges, sparklines, metrics, and layouts.
 */

// Color palette
const COLORS = {
  bg: '#0f1117',
  card: '#1a1d27',
  cardBorder: '#2a2d3a',
  primary: '#6366f1',
  primaryLight: '#818cf8',
  success: '#22c55e',
  warning: '#f59e0b',
  danger: '#ef4444',
  info: '#3b82f6',
  text: '#e2e8f0',
  textMuted: '#94a3b8',
  textDim: '#64748b',
  tableBorder: '#1e293b',
  tableHeader: '#1e2333',
  tableRowHover: '#1e2333',
};

/** Base CSS that all apps share */
export function baseStyles(): string {
  return `
    <style>
      * { margin: 0; padding: 0; box-sizing: border-box; }
      body { 
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
        background: ${COLORS.bg}; color: ${COLORS.text}; padding: 16px;
        font-size: 13px; line-height: 1.5;
      }
      .app-container { max-width: 800px; margin: 0 auto; }
      .app-title { 
        font-size: 18px; font-weight: 700; margin-bottom: 16px;
        display: flex; align-items: center; gap: 8px;
      }
      .app-subtitle { color: ${COLORS.textMuted}; font-size: 12px; margin-bottom: 16px; }
      
      /* Cards */
      .card {
        background: ${COLORS.card}; border: 1px solid ${COLORS.cardBorder};
        border-radius: 10px; padding: 16px; margin-bottom: 12px;
      }
      .card-header { font-size: 13px; font-weight: 600; margin-bottom: 8px; }
      .card-grid { display: grid; gap: 12px; }
      .card-grid-2 { grid-template-columns: 1fr 1fr; }
      .card-grid-3 { grid-template-columns: 1fr 1fr 1fr; }
      .card-grid-4 { grid-template-columns: 1fr 1fr 1fr 1fr; }
      
      /* Metric cards */
      .metric { text-align: center; padding: 12px; }
      .metric-value { font-size: 24px; font-weight: 700; }
      .metric-label { font-size: 11px; color: ${COLORS.textMuted}; margin-top: 4px; }
      .metric-change { font-size: 11px; margin-top: 2px; }
      .metric-change.up { color: ${COLORS.success}; }
      .metric-change.down { color: ${COLORS.danger}; }
      
      /* Tables */
      .table-wrap { overflow-x: auto; }
      table { width: 100%; border-collapse: collapse; font-size: 12px; }
      th { 
        text-align: left; padding: 8px 12px; font-weight: 600;
        background: ${COLORS.tableHeader}; color: ${COLORS.textMuted};
        border-bottom: 1px solid ${COLORS.tableBorder};
        font-size: 11px; text-transform: uppercase; letter-spacing: 0.5px;
      }
      td { 
        padding: 8px 12px; border-bottom: 1px solid ${COLORS.tableBorder};
      }
      tr:hover td { background: ${COLORS.tableRowHover}; }
      
      /* Badges */
      .badge {
        display: inline-block; padding: 2px 8px; border-radius: 9999px;
        font-size: 11px; font-weight: 600;
      }
      .badge-success { background: #16a34a22; color: ${COLORS.success}; }
      .badge-warning { background: #f59e0b22; color: ${COLORS.warning}; }
      .badge-danger { background: #ef444422; color: ${COLORS.danger}; }
      .badge-info { background: #3b82f622; color: ${COLORS.info}; }
      .badge-muted { background: #64748b22; color: ${COLORS.textDim}; }
      
      /* Status dots */
      .dot { 
        display: inline-block; width: 8px; height: 8px; border-radius: 50%;
        margin-right: 6px;
      }
      .dot-green { background: ${COLORS.success}; }
      .dot-yellow { background: ${COLORS.warning}; }
      .dot-red { background: ${COLORS.danger}; }
      .dot-blue { background: ${COLORS.info}; }
      .dot-gray { background: ${COLORS.textDim}; }
      
      /* Progress bar */
      .progress-bar {
        height: 6px; background: ${COLORS.cardBorder}; border-radius: 3px;
        overflow: hidden; margin-top: 6px;
      }
      .progress-fill { height: 100%; border-radius: 3px; transition: width 0.3s; }
      .progress-fill.green { background: ${COLORS.success}; }
      .progress-fill.yellow { background: ${COLORS.warning}; }
      .progress-fill.red { background: ${COLORS.danger}; }
      .progress-fill.blue { background: ${COLORS.info}; }
      
      /* Sparkline (CSS-only mini chart) */
      .sparkline { display: flex; align-items: flex-end; gap: 2px; height: 32px; }
      .spark-bar { 
        flex: 1; background: ${COLORS.primary}; border-radius: 2px 2px 0 0;
        min-width: 4px; opacity: 0.7;
      }
      .spark-bar:last-child { opacity: 1; }
      
      /* Chat bubbles (for conversation thread) */
      .chat-bubble {
        max-width: 70%; padding: 8px 12px; border-radius: 12px;
        margin-bottom: 6px; font-size: 13px;
      }
      .chat-outbound { 
        background: ${COLORS.primary}; margin-left: auto; 
        border-bottom-right-radius: 4px;
      }
      .chat-inbound { 
        background: ${COLORS.card}; border: 1px solid ${COLORS.cardBorder};
        border-bottom-left-radius: 4px;
      }
      .chat-meta { font-size: 10px; color: ${COLORS.textDim}; margin-top: 2px; }
      
      /* List items */
      .list-item {
        display: flex; align-items: center; gap: 12px;
        padding: 10px 12px; border-bottom: 1px solid ${COLORS.tableBorder};
      }
      .list-item:last-child { border-bottom: none; }
      
      /* Divider */
      .divider { border-top: 1px solid ${COLORS.tableBorder}; margin: 12px 0; }
      
      /* Muted text */
      .muted { color: ${COLORS.textMuted}; }
      .dim { color: ${COLORS.textDim}; }
      .small { font-size: 11px; }
      
      /* Flow diagram */
      .flow-node {
        background: ${COLORS.card}; border: 2px solid ${COLORS.cardBorder};
        border-radius: 8px; padding: 8px 14px; display: inline-block;
        margin: 4px; font-size: 12px;
      }
      .flow-node.active { border-color: ${COLORS.primary}; }
      .flow-arrow { color: ${COLORS.textDim}; padding: 0 4px; }
    </style>
  `;
}

/** Wrap content in the base app layout */
export function appLayout(title: string, subtitle: string, content: string): string {
  return `<!DOCTYPE html><html><head><meta charset="utf-8">${baseStyles()}</head>
<body><div class="app-container">
  <div class="app-title">${title}</div>
  <div class="app-subtitle">${subtitle}</div>
  ${content}
</div></body></html>`;
}

/** Metric card component */
export function metricCard(value: string, label: string, change?: { value: string; direction: 'up' | 'down' }): string {
  const changeHtml = change
    ? `<div class="metric-change ${change.direction}">${change.direction === 'up' ? '↑' : '↓'} ${change.value}</div>`
    : '';
  return `<div class="card metric">
    <div class="metric-value">${value}</div>
    <div class="metric-label">${label}</div>
    ${changeHtml}
  </div>`;
}

/** Badge component */
export function badge(text: string, variant: 'success' | 'warning' | 'danger' | 'info' | 'muted' = 'muted'): string {
  return `<span class="badge badge-${variant}">${text}</span>`;
}

/** Status dot */
export function statusDot(color: 'green' | 'yellow' | 'red' | 'blue' | 'gray' = 'gray'): string {
  return `<span class="dot dot-${color}"></span>`;
}

/** Progress bar */
export function progressBar(percent: number, color: 'green' | 'yellow' | 'red' | 'blue' = 'blue'): string {
  return `<div class="progress-bar"><div class="progress-fill ${color}" style="width: ${Math.min(100, percent)}%"></div></div>`;
}

/** CSS-only sparkline from data points */
export function sparkline(values: number[]): string {
  const max = Math.max(...values, 1);
  const bars = values.map(v => `<div class="spark-bar" style="height: ${(v / max) * 100}%"></div>`).join('');
  return `<div class="sparkline">${bars}</div>`;
}

/** Table component */
export function table(headers: string[], rows: string[][]): string {
  const headerHtml = headers.map(h => `<th>${h}</th>`).join('');
  const rowsHtml = rows.map(row =>
    `<tr>${row.map(cell => `<td>${cell}</td>`).join('')}</tr>`
  ).join('');
  return `<div class="table-wrap"><table><thead><tr>${headerHtml}</tr></thead><tbody>${rowsHtml}</tbody></table></div>`;
}

/** Format a dollar amount */
export function formatMoney(cents: number): string {
  return `$${(cents / 100).toFixed(2)}`;
}

/** Format a phone number for display */
export function formatPhone(phone: string): string {
  const cleaned = phone.replace(/\D/g, '');
  if (cleaned.length === 11 && cleaned.startsWith('1')) {
    return `+1 (${cleaned.slice(1, 4)}) ${cleaned.slice(4, 7)}-${cleaned.slice(7)}`;
  }
  return phone;
}

/** Create a structured content result for MCP Apps */
export function appResult(html: string, textFallback: string): {
  content: Array<{ type: 'text'; text: string }>;
  structuredContent: { type: 'html'; html: string };
} {
  return {
    content: [{ type: 'text' as const, text: textFallback }],
    structuredContent: { type: 'html' as const, html },
  };
}
