export function formatPreview(design) {
  const { meta, colors, typography, spacing, shadows, borders, accessibility, components, componentScreenshots } = design;

  return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Design Language: ${esc(meta.title)}</title>
<style>
  * { margin: 0; padding: 0; box-sizing: border-box; }
  :root {
    --bg: #0a0a0a; --bg-card: #141414; --border: #222; --text: #e5e5e5; --text-heading: #fff;
    --text-muted: #666; --text-sub: #a0a0a0; --text-dim: #444; --text-faint: #555; --row-border: #1a1a1a;
  }
  [data-theme="light"] {
    --bg: #f5f5f5; --bg-card: #fff; --border: #ddd; --text: #333; --text-heading: #111;
    --text-muted: #888; --text-sub: #666; --text-dim: #999; --text-faint: #aaa; --row-border: #e5e5e5;
  }
  body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; background: var(--bg); color: var(--text); line-height: 1.6; }
  .container { max-width: 1200px; margin: 0 auto; padding: 40px 24px; }
  .header-row { display: flex; align-items: center; justify-content: space-between; gap: 16px; flex-wrap: wrap; }
  .theme-toggle { background: var(--bg-card); border: 1px solid var(--border); color: var(--text); padding: 6px 14px; border-radius: 8px; cursor: pointer; font-size: 13px; white-space: nowrap; }
  h1 { font-size: 36px; font-weight: 700; margin-bottom: 8px; color: var(--text-heading); }
  h2 { font-size: 24px; font-weight: 600; margin: 48px 0 20px; color: var(--text-heading); border-bottom: 1px solid var(--border); padding-bottom: 12px; }
  h3 { font-size: 16px; font-weight: 600; margin: 24px 0 12px; color: var(--text-sub); text-transform: uppercase; letter-spacing: 0.05em; }
  .meta { color: var(--text-muted); font-size: 14px; margin-bottom: 32px; }
  .meta span { margin-right: 16px; }
  .grid { display: grid; gap: 12px; }
  .grid-2 { grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); }
  .grid-3 { grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); }
  .grid-4 { grid-template-columns: repeat(auto-fill, minmax(120px, 1fr)); }
  @media (max-width: 600px) {
    .grid-2, .grid-3, .grid-4 { grid-template-columns: 1fr 1fr; }
    h1 { font-size: 24px; }
    .container { padding: 20px 12px; }
  }
  @media (max-width: 380px) {
    .grid-2, .grid-3, .grid-4 { grid-template-columns: 1fr; }
  }

  /* Color swatches */
  .swatch { border-radius: 12px; overflow: hidden; background: var(--bg-card); border: 1px solid var(--border); cursor: pointer; position: relative; }
  .swatch-color { height: 80px; position: relative; }
  .swatch-info { padding: 10px 12px; font-size: 13px; }
  .swatch-hex { font-weight: 600; font-family: monospace; color: var(--text-heading); }
  .swatch-label { font-size: 11px; color: var(--text-muted); margin-top: 2px; }
  .swatch-role { display: inline-block; font-size: 10px; background: var(--border); color: var(--text-sub); padding: 2px 8px; border-radius: 4px; margin-top: 4px; }
  .copied-tip { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background: rgba(0,0,0,0.8); color: #fff; padding: 4px 12px; border-radius: 6px; font-size: 12px; pointer-events: none; opacity: 0; transition: opacity 0.2s; }
  .copied-tip.show { opacity: 1; }

  /* Type scale */
  .type-row { display: flex; align-items: baseline; gap: 16px; padding: 12px 0; border-bottom: 1px solid var(--row-border); }
  .type-size { font-family: monospace; color: var(--text-muted); min-width: 60px; font-size: 13px; }
  .type-meta { font-size: 12px; color: var(--text-dim); margin-left: auto; font-family: monospace; }

  /* Spacing */
  .spacing-row { display: flex; align-items: center; gap: 12px; padding: 6px 0; }
  .spacing-bar { background: linear-gradient(90deg, #3b82f6, #8b5cf6); border-radius: 4px; height: 24px; min-width: 4px; transition: width 0.3s; }
  .spacing-label { font-family: monospace; font-size: 13px; color: var(--text-sub); min-width: 60px; }

  /* Shadows */
  .shadow-card { background: var(--bg-card); border-radius: 12px; padding: 24px; text-align: center; min-height: 80px; display: flex; align-items: center; justify-content: center; border: 1px solid var(--border); }
  .shadow-label { font-size: 12px; color: var(--text); font-family: monospace; }

  /* Radii */
  .radius-item { width: 60px; height: 60px; background: linear-gradient(135deg, #3b82f6, #8b5cf6); display: flex; align-items: center; justify-content: center; font-size: 11px; color: #fff; font-weight: 600; }

  /* Accessibility */
  .a11y-score { font-size: 64px; font-weight: 800; }
  .a11y-score.good { color: #22c55e; }
  .a11y-score.warn { color: #eab308; }
  .a11y-score.bad { color: #ef4444; }
  .a11y-pair { display: flex; align-items: center; gap: 12px; padding: 10px 16px; background: var(--bg-card); border-radius: 8px; margin-bottom: 6px; border: 1px solid var(--border); flex-wrap: wrap; }
  .a11y-sample { width: 120px; padding: 6px 12px; border-radius: 6px; text-align: center; font-size: 14px; font-weight: 500; }
  .a11y-ratio { font-family: monospace; font-size: 14px; min-width: 50px; }
  .a11y-badge { font-size: 11px; font-weight: 700; padding: 2px 8px; border-radius: 4px; }
  .a11y-badge.pass { background: #22c55e20; color: #22c55e; }
  .a11y-badge.fail { background: #ef444420; color: #ef4444; }

  /* Components */
  .comp-screenshot { border-radius: 8px; border: 1px solid var(--border); max-width: 100%; }

  /* Stat cards */
  .stats { display: grid; grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); gap: 12px; margin: 24px 0; }
  .stat { background: var(--bg-card); border: 1px solid var(--border); border-radius: 12px; padding: 16px; }
  .stat-value { font-size: 28px; font-weight: 700; color: var(--text-heading); }
  .stat-label { font-size: 12px; color: var(--text-muted); margin-top: 4px; }

  .font-tag { display: inline-block; background: #1e1e2e; color: #a78bfa; padding: 4px 10px; border-radius: 6px; font-size: 13px; margin: 4px 4px 4px 0; }
  [data-theme="light"] .font-tag { background: #ede9fe; color: #6d28d9; }
</style>
</head>
<body>
<div class="container">

<div class="header-row">
  <h1>${esc(meta.title)}</h1>
  <button class="theme-toggle" onclick="toggleTheme()">Toggle Light/Dark</button>
</div>
<div class="meta">
  <span>${esc(meta.url)}</span>
  <span>${meta.elementCount} elements</span>
  <span>${new Date(meta.timestamp).toLocaleDateString()}</span>
  ${meta.pagesAnalyzed > 1 ? `<span>${meta.pagesAnalyzed} pages crawled</span>` : ''}
</div>

<div class="stats">
  <div class="stat"><div class="stat-value">${colors.all.length}</div><div class="stat-label">Colors</div></div>
  <div class="stat"><div class="stat-value">${typography.families.length}</div><div class="stat-label">Font Families</div></div>
  <div class="stat"><div class="stat-value">${spacing.scale.length}</div><div class="stat-label">Spacing Values</div></div>
  <div class="stat"><div class="stat-value">${shadows.values.length}</div><div class="stat-label">Shadows</div></div>
  <div class="stat"><div class="stat-value">${borders.radii.length}</div><div class="stat-label">Border Radii</div></div>
  <div class="stat"><div class="stat-value">${Object.keys(components).length}</div><div class="stat-label">Components</div></div>
  ${accessibility ? `<div class="stat"><div class="stat-value ${accessibility.score >= 80 ? 'good' : accessibility.score >= 50 ? 'warn' : 'bad'}" style="color: ${accessibility.score >= 80 ? '#22c55e' : accessibility.score >= 50 ? '#eab308' : '#ef4444'}">${accessibility.score}%</div><div class="stat-label">A11y Score</div></div>` : ''}
</div>

<!-- Colors -->
<h2>Color Palette</h2>

${colors.primary ? `
<h3>Brand Colors</h3>
<div class="grid grid-3">
  ${colors.primary ? swatch(colors.primary.hex, 'Primary', colors.primary.count + ' uses') : ''}
  ${colors.secondary ? swatch(colors.secondary.hex, 'Secondary', colors.secondary.count + ' uses') : ''}
  ${colors.accent ? swatch(colors.accent.hex, 'Accent', colors.accent.count + ' uses') : ''}
</div>` : ''}

${colors.neutrals.length > 0 ? `
<h3>Neutrals</h3>
<div class="grid grid-4">
  ${colors.neutrals.slice(0, 10).map(c => swatch(c.hex, '', c.count + ' uses')).join('\n  ')}
</div>` : ''}

${colors.all.length > 3 ? `
<h3>Full Palette</h3>
<div class="grid grid-4">
  ${colors.all.slice(0, 20).map(c => swatch(c.hex, c.contexts.join(', '), c.count + ' uses')).join('\n  ')}
</div>` : ''}

${colors.gradients.length > 0 ? `
<h3>Gradients</h3>
<div class="grid grid-2">
  ${colors.gradients.slice(0, 6).map(g => `<div class="swatch"><div class="swatch-color" style="background-image:${g};height:100px"></div></div>`).join('\n  ')}
</div>` : ''}

<!-- Typography -->
<h2>Typography</h2>

${typography.families.length > 0 ? `
<h3>Font Families</h3>
<div>
  ${typography.families.map(f => `<span class="font-tag">${esc(f.name)} <span style="color:#666">(${f.usage}, ${f.count}x)</span></span>`).join('')}
</div>` : ''}

${typography.scale.length > 0 ? `
<h3>Type Scale</h3>
<div>
  ${typography.scale.slice(0, 12).map(s => `
  <div class="type-row">
    <span class="type-size">${s.size}px</span>
    <span style="font-size:${Math.min(s.size, 48)}px;font-weight:${s.weight};color:var(--text-heading)">The quick brown fox</span>
    <span class="type-meta">${s.weight} / ${s.lineHeight}</span>
  </div>`).join('')}
</div>` : ''}

<!-- Spacing -->
${spacing.scale.length > 0 ? `
<h2>Spacing Scale${spacing.base ? ` (base: ${spacing.base}px)` : ''}</h2>
<div>
  ${spacing.scale.slice(0, 16).map(v => `
  <div class="spacing-row">
    <span class="spacing-label">${v}px</span>
    <div class="spacing-bar" style="width:${Math.min(v * 2, 500)}px"></div>
  </div>`).join('')}
</div>` : ''}

<!-- Shadows -->
${shadows.values.length > 0 ? `
<h2>Box Shadows</h2>
<div class="grid grid-3">
  ${shadows.values.map(s => `
  <div class="shadow-card" style="box-shadow:${s.raw}">
    <span class="shadow-label">${s.label}${s.inset ? ' (inset)' : ''}</span>
  </div>`).join('')}
</div>` : ''}

<!-- Border Radii -->
${borders.radii.length > 0 ? `
<h2>Border Radii</h2>
<div style="display:flex;gap:16px;flex-wrap:wrap;align-items:end">
  ${borders.radii.map(r => `
  <div style="text-align:center">
    <div class="radius-item" style="border-radius:${r.value}px">${r.value}px</div>
    <div style="font-size:11px;color:#666;margin-top:6px">${r.label}</div>
  </div>`).join('')}
</div>` : ''}

<!-- Accessibility -->
${accessibility ? `
<h2>Accessibility</h2>
<div style="display:flex;align-items:center;gap:24px;margin-bottom:24px">
  <div class="a11y-score ${accessibility.score >= 80 ? 'good' : accessibility.score >= 50 ? 'warn' : 'bad'}">${accessibility.score}%</div>
  <div>
    <div style="color:#fff;font-weight:600">WCAG Contrast Score</div>
    <div style="color:#666;font-size:14px">${accessibility.passCount} passing / ${accessibility.failCount} failing color pairs</div>
  </div>
</div>

<h3>Color Pair Analysis</h3>
${accessibility.pairs.slice(0, 20).map(p => `
<div class="a11y-pair">
  <div class="a11y-sample" style="background:${p.background};color:${p.foreground}">Sample</div>
  <div style="font-family:monospace;font-size:12px;color:#888">${p.foreground} on ${p.background}</div>
  <div class="a11y-ratio">${p.ratio}:1</div>
  <span class="a11y-badge ${p.level === 'FAIL' ? 'fail' : 'pass'}">${p.level}</span>
  <div style="font-size:11px;color:#555;margin-left:auto">${p.count}x</div>
</div>`).join('')}
` : ''}

<!-- Component Screenshots -->
${componentScreenshots && Object.keys(componentScreenshots).length > 0 ? `
<h2>Component Screenshots</h2>
<div class="grid grid-2">
  ${Object.entries(componentScreenshots).map(([name, info]) => `
  <div>
    <h3>${info.label}</h3>
    <img class="comp-screenshot" src="${info.path}" alt="${info.label}" />
  </div>`).join('')}
</div>` : ''}

</div>
<script>
function toggleTheme() {
  const html = document.documentElement;
  const current = html.getAttribute('data-theme');
  html.setAttribute('data-theme', current === 'light' ? 'dark' : 'light');
}
document.querySelectorAll('.swatch').forEach(el => {
  el.addEventListener('click', () => {
    const hex = el.querySelector('.swatch-hex');
    if (!hex) return;
    navigator.clipboard.writeText(hex.textContent).then(() => {
      let tip = el.querySelector('.copied-tip');
      if (!tip) { tip = document.createElement('div'); tip.className = 'copied-tip'; tip.textContent = 'Copied!'; el.appendChild(tip); }
      tip.classList.add('show');
      setTimeout(() => tip.classList.remove('show'), 1200);
    });
  });
});
</script>
</body>
</html>`;
}

function swatch(hex, label, meta) {
  const rgb = hexToRgb(hex);
  const textColor = isLight(rgb) ? '#000' : '#fff';
  return `<div class="swatch">
    <div class="swatch-color" style="background:${hex}"></div>
    <div class="swatch-info">
      <div class="swatch-hex">${hex}</div>
      ${label ? `<div class="swatch-label">${esc(label)}</div>` : ''}
      ${meta ? `<div class="swatch-label">${esc(meta)}</div>` : ''}
    </div>
  </div>`;
}

function hexToRgb(hex) {
  const m = hex.replace('#', '').match(/.{2}/g);
  return m ? { r: parseInt(m[0], 16), g: parseInt(m[1], 16), b: parseInt(m[2], 16) } : { r: 0, g: 0, b: 0 };
}

function isLight({ r, g, b }) {
  return (r * 0.299 + g * 0.587 + b * 0.114) > 150;
}

function esc(s) {
  return String(s || '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}
