/**
 * The rich text vocabulary shared by every text field on the site.
 * Each option here maps 1:1 to a CSS class in web/src/lib/portable-text.ts,
 * so whatever Shanina picks in the editor is exactly what the site renders.
 */
import { defineArrayMember, defineField, defineType } from 'sanity';
import type { ReactNode } from 'react';

type Children = { children?: ReactNode };

// How each word-level option looks inside the editor (close to the site).
const Size = (em: number, serif = false) =>
  function SizeMark({ children }: Children) {
    return (
      <span style={{ fontSize: `${em}em`, color: em > 1.2 ? '#2a4f93' : undefined }}>
        {children}
      </span>
    );
  };
const Accent = ({ children }: Children) => <span style={{ color: '#6b51b2' }}>{children}</span>;
const Highlight = ({ children }: Children) => (
  <span style={{ background: 'linear-gradient(transparent 55%, #e7defc 55%)' }}>{children}</span>
);
const Center = ({ children }: Children) => <div style={{ textAlign: 'center' }}>{children}</div>;
const Lead = ({ children }: Children) => <div style={{ fontSize: '1.15em', color: '#4b5582' }}>{children}</div>;

const icon = (label: string, style: Record<string, string | number> = {}) =>
  function ToolbarIcon() {
    return <span style={{ fontWeight: 700, fontSize: 13, ...style }}>{label}</span>;
  };

const decorators = [
  { title: 'מודגש', value: 'strong' },
  { title: 'נטוי', value: 'em' },
  { title: 'קו תחתון', value: 'underline' },
  { title: 'טקסט קטן', value: 'sm', icon: icon('א', { fontSize: 10 }), component: Size(0.86) },
  { title: 'גדול', value: 'lg', icon: icon('א', { fontSize: 14 }), component: Size(1.16) },
  { title: 'גדול מאוד', value: 'xl', icon: icon('א', { fontSize: 17 }), component: Size(1.34, true) },
  { title: 'ענק', value: 'xxl', icon: icon('א', { fontSize: 21 }), component: Size(1.75, true) },
  { title: 'סגול', value: 'accent', icon: icon('●', { color: '#6b51b2' }), component: Accent },
  { title: 'מרקר', value: 'highlight', icon: icon('ab', { background: '#e7defc', padding: '0 2px' }), component: Highlight },
];

const styles = [
  { title: 'רגיל', value: 'normal' },
  { title: 'ממורכז (שורות שיריות)', value: 'center', component: Center },
  { title: 'פסקת פתיחה', value: 'lead', component: Lead },
  { title: 'כותרת', value: 'h2' },
  { title: 'כותרת משנה', value: 'h3' },
  { title: 'ציטוט מודגש', value: 'blockquote' },
];

const linkAnnotation = defineArrayMember({
  name: 'link',
  type: 'object',
  title: 'קישור',
  fields: [
    defineField({
      name: 'href',
      title: 'כתובת',
      type: 'string',
      description: 'כתובת מלאה (https://...) או עמוד באתר, למשל /method',
      validation: (r) => r.required(),
    }),
  ],
});

const textBlock = (withStyles: boolean) =>
  defineArrayMember({
    type: 'block',
    styles: withStyles ? styles : [{ title: 'רגיל', value: 'normal' }],
    lists: withStyles ? [{ title: 'רשימה', value: 'bullet' }, { title: 'רשימה ממוספרת', value: 'number' }] : [],
    marks: { decorators: decorators as any, annotations: [linkAnnotation] },
  });

/** Full rich text: styles, word sizes, images, video, callouts and buttons. */
export const richText = defineType({
  name: 'richText',
  title: 'טקסט עשיר',
  type: 'array',
  of: [
    textBlock(true),
    defineArrayMember({
      name: 'image',
      type: 'image',
      title: 'תמונה',
      options: { hotspot: true },
      fields: [
        defineField({ name: 'alt', title: 'תיאור התמונה (לנגישות)', type: 'string' }),
        defineField({ name: 'caption', title: 'כיתוב', type: 'string' }),
        defineField({
          name: 'size',
          title: 'גודל',
          type: 'string',
          options: { list: [{ title: 'צר', value: 'narrow' }, { title: 'רחב', value: 'wide' }], layout: 'radio', direction: 'horizontal' },
          initialValue: 'wide',
        }),
      ],
    }),
    defineArrayMember({
      name: 'youtube',
      type: 'object',
      title: 'סרטון יוטיוב',
      fields: [
        defineField({ name: 'url', title: 'קישור לסרטון', type: 'url', validation: (r) => r.required() }),
        defineField({ name: 'title', title: 'שם הסרטון', type: 'string' }),
      ],
      preview: { select: { title: 'title', subtitle: 'url' }, prepare: ({ title, subtitle }) => ({ title: `▶ ${title || 'סרטון יוטיוב'}`, subtitle }) },
    }),
    defineArrayMember({
      name: 'callout',
      type: 'object',
      title: 'תיבת הדגשה',
      fields: [
        defineField({ name: 'text', title: 'טקסט', type: 'text', rows: 3, validation: (r) => r.required() }),
        defineField({
          name: 'tone',
          title: 'צבע',
          type: 'string',
          options: { list: [{ title: 'סגול רך', value: 'soft' }, { title: 'תכלת', value: 'info' }], layout: 'radio', direction: 'horizontal' },
          initialValue: 'soft',
        }),
      ],
      preview: { select: { title: 'text' }, prepare: ({ title }) => ({ title: `❀ ${title ?? ''}` }) },
    }),
    defineArrayMember({
      name: 'linkButton',
      type: 'object',
      title: 'כפתור',
      fields: [
        defineField({ name: 'label', title: 'טקסט הכפתור', type: 'string', validation: (r) => r.required() }),
        defineField({ name: 'href', title: 'קישור', type: 'string', validation: (r) => r.required() }),
      ],
      preview: { select: { title: 'label', subtitle: 'href' }, prepare: ({ title, subtitle }) => ({ title: `[ ${title} ]`, subtitle }) },
    }),
    defineArrayMember({
      name: 'tagCloud',
      type: 'object',
      title: 'ענן מילים (רשימה קצרה)',
      fields: [
        defineField({ name: 'title', title: 'כותרת (לא חובה)', type: 'string' }),
        defineField({ name: 'tags', title: 'מילים', type: 'array', of: [{ type: 'string' }], options: { layout: 'tags' } }),
      ],
      preview: { select: { title: 'title', tags: 'tags' }, prepare: ({ title, tags }) => ({ title: title || 'ענן מילים', subtitle: (tags ?? []).slice(0, 8).join(' · ') }) },
    }),
    defineArrayMember({
      name: 'divider',
      type: 'object',
      title: 'קישוט מפריד (פרח)',
      fields: [defineField({ name: 'style', type: 'string', hidden: true, initialValue: 'flower' })],
      preview: { prepare: () => ({ title: '— ❀ —' }) },
    }),
  ],
});

/** Inline-only rich text: word sizes and emphasis, no headings or embeds. Each paragraph = one item. */
export const simpleText = defineType({
  name: 'simpleText',
  title: 'טקסט',
  type: 'array',
  of: [textBlock(false)],
});
