// Gradients emitter — surface the gradients the colour extractor already
// captured as a ready-to-paste CSS file with utility classes.
//
// Outputs two files:
//   <host>-gradients.css   — :root vars + .grad-N utility classes
//   <host>-gradients.json  — structured list (type, direction, stops)
//
// Designers like gradients. Most sites have 3–20 unique ones. Surfacing
// them as utility classes lets engineers replicate hero / card / button
// backgrounds without eye-balling rgba stops out of devtools.

function cleanRaw(raw) {
  if (!raw || typeof raw !== 'string') return null;
  // Drop browser duplicates, collapse whitespace, trim quotes.
  return raw.replace(/\s+/g, ' ').trim().replace(/^"|"$/g, '');
}

function uniqGradients(design) {
  const list = design?.gradients?.gradients
            || (Array.isArray(design?.gradients) ? design.gradients : [])
            || (design?.colors?.gradients || []);
  const out = [];
  const seen = new Set();
  for (const g of list) {
    const raw = cleanRaw(g?.raw || g?.value || g);
    if (!raw || !raw.includes('gradient')) continue;
    if (seen.has(raw)) continue;
    seen.add(raw);
    out.push({
      raw,
      type: g?.type || (raw.match(/^(linear|radial|conic)-gradient/i)?.[1] || 'linear').toLowerCase(),
      direction: g?.direction || null,
      stops: Array.isArray(g?.stops) ? g.stops : [],
      classification: g?.classification || null,
    });
  }
  return out;
}

export function formatGradientsCss(design) {
  const grads = uniqGradients(design);
  if (grads.length === 0) {
    return [
      '/* designlang — no gradients detected on the source page. */',
      '/* Run with --interactions to capture hover backgrounds. */',
      '',
    ].join('\n');
  }

  const lines = [
    '/* ──────────────────────────────────────────────────────────────',
    `   ${grads.length} gradients — generated by designlang`,
    `   ${design?.meta?.url || ''}`,
    `   ${new Date().toISOString()}`,
    '   ────────────────────────────────────────────────────────────── */',
    '',
    ':root {',
  ];
  grads.forEach((g, i) => { lines.push(`  --grad-${i + 1}: ${g.raw};`); });
  lines.push('}', '');

  grads.forEach((g, i) => {
    lines.push(
      `/* ${g.type}${g.classification ? ` · ${g.classification}` : ''} */`,
      `.grad-${i + 1}    { background-image: var(--grad-${i + 1}); }`,
      `.grad-text-${i + 1} {`,
      `  background-image: var(--grad-${i + 1});`,
      `  -webkit-background-clip: text;`,
      `          background-clip: text;`,
      `  color: transparent;`,
      `}`,
      ''
    );
  });

  return lines.join('\n');
}

export function formatGradientsJson(design) {
  const grads = uniqGradients(design);
  return JSON.stringify({
    $schema: 'https://designlang.app/schemas/gradients.json',
    source: design?.meta?.url || null,
    generated: new Date().toISOString(),
    count: grads.length,
    gradients: grads,
  }, null, 2);
}
