/**
 * Portable Text -> HTML for the site's rich text vocabulary (see studio/schemas/richText.ts).
 * Kept dependency-free so the mapping from editor options to CSS classes stays in one place.
 */
import { imageUrl } from './image';

type Span = { _type: 'span'; text: string; marks?: string[] };
type Block = Record<string, any>;

const DECORATORS: Record<string, [string, string]> = {
  strong: ['<strong>', '</strong>'],
  em: ['<em>', '</em>'],
  underline: ['<span class="u">', '</span>'],
  sm: ['<span class="fs-sm">', '</span>'],
  lg: ['<span class="fs-lg">', '</span>'],
  xl: ['<span class="fs-xl">', '</span>'],
  xxl: ['<span class="fs-xxl">', '</span>'],
  accent: ['<span class="accent">', '</span>'],
  highlight: ['<mark>', '</mark>'],
};

const BLOCK_TAGS: Record<string, [string, string]> = {
  normal: ['p', ''],
  center: ['p', 'center'],
  lead: ['p', 'lead'],
  h2: ['h2', ''],
  h3: ['h3', ''],
  blockquote: ['blockquote', ''],
};

export function escapeHtml(s: string): string {
  return s.replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]!);
}

export function safeHref(href: string | undefined): string | null {
  if (!href) return null;
  const h = href.trim();
  if (/^(https?:|mailto:|tel:|\/|#)/i.test(h)) return h;
  return null;
}

function youtubeId(url: string): string | null {
  const m = url.match(/(?:youtu\.be\/|v=|embed\/|shorts\/|live\/)([\w-]{11})/);
  return m ? m[1] : null;
}

function renderSpans(block: Block): string {
  const defs = new Map<string, any>((block.markDefs ?? []).map((d: any) => [d._key, d]));
  return (block.children ?? [])
    .map((span: Span) => {
      let html = escapeHtml(span.text ?? '').replace(/\n/g, '<br>');
      // Wrap order: decorators inside, links outside.
      for (const mark of span.marks ?? []) {
        const deco = DECORATORS[mark];
        if (deco) {
          html = deco[0] + html + deco[1];
          continue;
        }
        const def = defs.get(mark);
        const href = def?._type === 'link' ? safeHref(def.href) : null;
        if (href) {
          const external = /^https?:/i.test(href);
          html = `<a href="${escapeHtml(href)}"${external ? ' target="_blank" rel="noopener"' : ''}>${html}</a>`;
        }
      }
      return html;
    })
    .join('');
}

function renderCustom(block: Block): string {
  switch (block._type) {
    case 'image': {
      const src = imageUrl(block, block.size === 'narrow' ? 700 : 1400);
      if (!src) return '';
      const caption = block.caption ? `<figcaption>${escapeHtml(block.caption)}</figcaption>` : '';
      return `<figure class="pt-image pt-image--${block.size ?? 'wide'}"><img src="${escapeHtml(src)}" alt="${escapeHtml(block.alt ?? '')}" loading="lazy" decoding="async">${caption}</figure>`;
    }
    case 'youtube': {
      const id = youtubeId(block.url ?? '');
      if (!id) return '';
      const title = escapeHtml(block.title || 'סרטון יוטיוב');
      return `<div class="pt-video"><iframe src="https://www.youtube-nocookie.com/embed/${id}" title="${title}" loading="lazy" allow="accelerometer; encrypted-media; gyroscope; picture-in-picture; fullscreen" referrerpolicy="strict-origin-when-cross-origin"></iframe></div>`;
    }
    case 'callout':
      return `<aside class="pt-callout pt-callout--${escapeHtml(block.tone ?? 'soft')}">${escapeHtml(block.text ?? '').replace(/\n/g, '<br>')}</aside>`;
    case 'tagCloud': {
      const tags = (block.tags ?? []).map((t: string) => `<li>${escapeHtml(t)}</li>`).join('');
      const title = block.title ? `<p class="pt-tags__title">${escapeHtml(block.title)}</p>` : '';
      return tags ? `<div class="pt-tags">${title}<ul>${tags}</ul></div>` : '';
    }
    case 'divider':
      return '<div class="pt-divider" role="separator" aria-hidden="true"><span class="ornament"></span></div>';
    case 'linkButton': {
      const href = safeHref(block.href);
      return href ? `<p class="pt-button"><a class="btn" href="${escapeHtml(href)}">${escapeHtml(block.label ?? '')}</a></p>` : '';
    }
    default:
      return '';
  }
}

export function toHTML(blocks: Block[] | undefined | null): string {
  if (!blocks?.length) return '';
  let html = '';
  let openList: string | null = null;
  let prevPara = false;
  for (const block of blocks) {
    const listTag = block._type === 'block' && block.listItem ? (block.listItem === 'number' ? 'ol' : 'ul') : null;
    if (openList && openList !== listTag) {
      html += `</${openList}>`;
      openList = null;
    }
    if (listTag) {
      if (!openList) {
        html += `<${listTag}>`;
        openList = listTag;
      }
      html += `<li>${renderSpans(block)}</li>`;
      prevPara = false;
      continue;
    }
    if (block._type !== 'block') {
      html += renderCustom(block);
      prevPara = false;
      continue;
    }
    const [tag, cls] = BLOCK_TAGS[block.style ?? 'normal'] ?? BLOCK_TAGS.normal;
    const inner = renderSpans(block);
    if (!inner.trim()) continue;
    // "sep": paragraph that follows a substantial paragraph (several lines or long) – long-form
    // layouts (.prose--flow) draw a small floral divider in the gap above it.
    const sep = tag === 'p' && prevPara;
    const classes = [cls, sep && 'sep'].filter(Boolean).join(' ');
    html += `<${tag}${classes ? ` class="${classes}"` : ''}>${inner}</${tag}>`;
    const text = (block.children ?? []).map((c: Span) => c.text ?? '').join('');
    prevPara = tag === 'p' && (text.includes('\n') || text.trim().length > 90);
    continue;
  }
  if (openList) html += `</${openList}>`;
  return html;
}

/** Plain text (for meta descriptions, search indexes). */
export function toPlainText(blocks: Block[] | undefined | null): string {
  return (blocks ?? [])
    .filter((b) => b._type === 'block')
    .map((b) => (b.children ?? []).map((c: Span) => c.text).join(''))
    .join(' ')
    .replace(/\s+/g, ' ')
    .trim();
}
