'use client';

import React from 'react';
import { hasRichMarkers, parseRich } from './richText';

/**
 * "How it prints" — renders **bold**, *italic*, __underline__ and • bullets the same way the
 * Word / PDF report does, so the auditor sees the formatting instead of the markers.
 * Shown only when the text actually uses a marker (or always=true).
 */
export default function RichPreview({ text, always = false }: { text: string; always?: boolean }) {
  if (!text || (!always && !hasRichMarkers(text))) return null;
  const blocks = parseRich(text);
  if (!blocks.length) return null;
  return (
    <div
      style={{ marginTop: 6, padding: '6px 10px', border: '1px dashed #d6d3e0', borderRadius: 8, background: '#fafafc', fontSize: 12, lineHeight: 1.45, color: '#1f2937' }}
      title="Preview — this is how the text prints in the report"
    >
      <div style={{ fontSize: 10, fontWeight: 700, color: '#6b7280', textTransform: 'uppercase', letterSpacing: '.04em', marginBottom: 2 }}>Prints as</div>
      {blocks.map((b, i) => (
        <div key={i} style={{ display: 'flex', gap: 6, margin: b.heading ? '2px 0 0' : '2px 0', paddingLeft: b.bullet ? 4 : 0 }}>
          {b.bullet && <span>•</span>}
          <span>
            {b.runs.map((r, j) => (
              <span key={j} style={{ fontWeight: r.b ? 700 : undefined, fontStyle: r.i ? 'italic' : undefined, textDecoration: r.u ? 'underline' : undefined }}>{r.t}</span>
            ))}
          </span>
        </div>
      ))}
    </div>
  );
}

/** Ctrl/⌘ + B / I / U → which formatting button the key stands for (null = not a shortcut). */
export function shortcutOf(e: React.KeyboardEvent): 'bold' | 'italic' | 'underline' | null {
  if (!(e.ctrlKey || e.metaKey) || e.altKey || e.shiftKey) return null;
  const k = e.key.toLowerCase();
  return k === 'b' ? 'bold' : k === 'i' ? 'italic' : k === 'u' ? 'underline' : null;
}
