/**
 * Page sections. A page is a list of these, in any order; each has its own design on the site
 * (web/src/components/sections/*). The `title` is what Shanina sees in the "add section" menu.
 */
import { defineArrayMember, defineField, defineType } from 'sanity';
import { buttons } from './objects';

const heading = defineField({ name: 'heading', title: 'כותרת', type: 'string' });
const blocksPreview = (fallback: string) => ({
  select: { title: 'heading' },
  prepare: ({ title }: { title?: string }) => ({ title: title || fallback, subtitle: fallback }),
});

export const hero = defineType({
  name: 'hero',
  title: 'פתיח עם תמונה',
  type: 'object',
  fields: [
    defineField({ name: 'title', title: 'כותרת ראשית', type: 'string', validation: (r) => r.required() }),
    defineField({ name: 'text', title: 'טקסט', type: 'simpleText' }),
    defineField({ name: 'image', title: 'תמונה', type: 'imageWithAlt' }),
    buttons,
    defineField({ name: 'note', title: 'הערה קטנה', type: 'string' }),
  ],
  preview: { select: { title: 'title', media: 'image' }, prepare: ({ title, media }) => ({ title, subtitle: 'פתיח עם תמונה', media }) },
});

export const tilesSection = defineType({
  name: 'tilesSection',
  title: 'אריחי ניווט',
  type: 'object',
  fields: [
    heading,
    defineField({
      name: 'tiles',
      title: 'אריחים',
      type: 'array',
      of: [
        defineArrayMember({
          type: 'object',
          name: 'tile',
          fields: [
            defineField({ name: 'title', title: 'שם', type: 'string', validation: (r) => r.required() }),
            defineField({ name: 'href', title: 'קישור', type: 'string', validation: (r) => r.required() }),
            defineField({ name: 'image', title: 'תמונה', type: 'imageWithAlt' }),
          ],
          preview: { select: { title: 'title', subtitle: 'href', media: 'image' } },
        }),
      ],
    }),
  ],
  preview: blocksPreview('אריחי ניווט'),
});

export const richTextSection = defineType({
  name: 'richTextSection',
  title: 'טקסט (עם תמונה אופציונלית)',
  type: 'object',
  fields: [
    heading,
    defineField({ name: 'body', title: 'תוכן', type: 'richText' }),
    defineField({ name: 'image', title: 'תמונה בצד', type: 'imageWithAlt' }),
    defineField({
      name: 'imagePosition',
      title: 'מיקום התמונה',
      type: 'string',
      options: { list: [{ title: 'ימין', value: 'start' }, { title: 'שמאל', value: 'end' }], layout: 'radio', direction: 'horizontal' },
      initialValue: 'start',
      hidden: ({ parent }) => !parent?.image,
    }),
    defineField({
      name: 'background',
      title: 'רקע',
      type: 'string',
      options: {
        list: [{ title: 'ללא', value: 'none' }, { title: 'לילך עדין', value: 'tint' }, { title: 'זר פרחים', value: 'floral' }],
        layout: 'radio',
        direction: 'horizontal',
      },
      initialValue: 'none',
    }),
    defineField({
      name: 'width',
      title: 'רוחב',
      type: 'string',
      options: { list: [{ title: 'צר (קריאה נוחה)', value: 'narrow' }, { title: 'רחב', value: 'wide' }], layout: 'radio', direction: 'horizontal' },
      initialValue: 'narrow',
    }),
    defineField({ name: 'anchor', title: 'מזהה לקישור פנימי', type: 'string', description: 'למשל intro – ואז כפתור יכול לקשר ל-#intro' }),
  ],
  preview: { select: { title: 'heading', media: 'image' }, prepare: ({ title, media }) => ({ title: title || 'טקסט', subtitle: 'טקסט', media }) },
});

export const principlesSection = defineType({
  name: 'principlesSection',
  title: 'הנחות היסוד',
  type: 'object',
  description: 'מציג את הנחות היסוד מתוך "הגדרות האתר" – עורכים אותן במקום אחד והן מתעדכנות בכל העמודים.',
  fields: [heading, defineField({ name: 'intro', title: 'פתיח', type: 'richText' })],
  preview: blocksPreview('הנחות היסוד'),
});

export const latestSection = defineType({
  name: 'latestSection',
  title: 'פרסומים אחרונים',
  type: 'object',
  fields: [
    heading,
    defineField({
      name: 'kind',
      title: 'מה להציג',
      type: 'string',
      options: { list: [{ title: 'מאמרים', value: 'article' }, { title: 'מתכונים', value: 'recipe' }, { title: 'אירועים קרובים', value: 'event' }], layout: 'radio' },
      initialValue: 'article',
      validation: (r) => r.required(),
    }),
    defineField({ name: 'count', title: 'כמה להציג', type: 'number', initialValue: 3, validation: (r) => r.min(1).max(12) }),
    defineField({ name: 'intro', title: 'פתיח', type: 'simpleText' }),
    defineField({ name: 'linkLabel', title: 'טקסט כפתור "לכל..."', type: 'string' }),
  ],
  preview: { select: { title: 'heading', kind: 'kind' }, prepare: ({ title, kind }) => ({ title: title || 'פרסומים אחרונים', subtitle: { article: 'מאמרים אחרונים', recipe: 'מתכונים אחרונים', event: 'אירועים קרובים' }[kind as string] }) },
});

export const instagramSection = defineType({
  name: 'instagramSection',
  title: 'פיד אינסטגרם',
  type: 'object',
  fields: [heading, defineField({ name: 'handle', title: 'שם המשתמש', type: 'string', initialValue: 'shaninaway' })],
  preview: blocksPreview('פיד אינסטגרם'),
});

export const ctaSection = defineType({
  name: 'ctaSection',
  title: 'הזמנה לפעולה',
  type: 'object',
  fields: [heading, defineField({ name: 'text', title: 'טקסט', type: 'richText' }), buttons],
  preview: blocksPreview('הזמנה לפעולה'),
});

export const acronymSection = defineType({
  name: 'acronymSection',
  title: 'ראשי תיבות (אי"ך)',
  type: 'object',
  fields: [
    defineField({
      name: 'letters',
      title: 'אותיות',
      type: 'array',
      of: [
        defineArrayMember({
          type: 'object',
          name: 'letter',
          fields: [
            defineField({ name: 'letter', title: 'אות', type: 'string', validation: (r) => r.required().max(2) }),
            defineField({ name: 'word', title: 'מילה', type: 'string', validation: (r) => r.required() }),
          ],
          preview: { select: { title: 'letter', subtitle: 'word' } },
        }),
      ],
    }),
    defineField({ name: 'body', title: 'טקסט', type: 'richText' }),
  ],
  preview: { prepare: () => ({ title: 'א · י · כ', subtitle: 'ראשי תיבות' }) },
});

export const listSection = defineType({
  name: 'listSection',
  title: 'רשימה מעוצבת',
  type: 'object',
  fields: [
    heading,
    defineField({ name: 'intro', title: 'פתיח', type: 'richText' }),
    defineField({ name: 'items', title: 'פריטים', type: 'simpleText', description: 'כל פסקה היא פריט ברשימה' }),
    defineField({
      name: 'marker',
      title: 'סימן',
      type: 'string',
      options: { list: [{ title: 'פרח', value: 'flower' }, { title: 'וי', value: 'check' }], layout: 'radio', direction: 'horizontal' },
      initialValue: 'flower',
    }),
  ],
  preview: blocksPreview('רשימה'),
});

export const stepsSection = defineType({
  name: 'stepsSection',
  title: 'שלבים',
  type: 'object',
  fields: [
    heading,
    defineField({ name: 'intro', title: 'פתיח', type: 'richText' }),
    defineField({
      name: 'steps',
      title: 'שלבים',
      type: 'array',
      of: [
        defineArrayMember({
          type: 'object',
          name: 'step',
          fields: [
            defineField({ name: 'title', title: 'שם השלב', type: 'string', validation: (r) => r.required() }),
            defineField({ name: 'body', title: 'תיאור', type: 'richText' }),
          ],
          preview: { select: { title: 'title' } },
        }),
      ],
    }),
  ],
  preview: blocksPreview('שלבים'),
});

export const cardsSection = defineType({
  name: 'cardsSection',
  title: 'כרטיסים',
  type: 'object',
  fields: [
    heading,
    defineField({ name: 'intro', title: 'פתיח', type: 'richText' }),
    defineField({
      name: 'layout',
      title: 'עיצוב',
      type: 'string',
      options: {
        list: [
          { title: 'רשת', value: 'grid' }, { title: 'ממוספר', value: 'numbered' },
          { title: 'ארגז כלים (תאים עם סמל)', value: 'toolbox' }, { title: 'כרטיסים עם מחיר וסטטוס (קורסים)', value: 'programs' },
        ],
        layout: 'radio',
      },
      initialValue: 'grid',
    }),
    defineField({
      name: 'cards',
      title: 'כרטיסים',
      type: 'array',
      of: [
        defineArrayMember({
          type: 'object',
          name: 'card',
          fields: [
            defineField({ name: 'title', title: 'כותרת', type: 'string', validation: (r) => r.required() }),
            defineField({ name: 'body', title: 'טקסט', type: 'richText' }),
            defineField({ name: 'image', title: 'תמונה', type: 'imageWithAlt' }),
            defineField({ name: 'href', title: 'קישור', type: 'string' }),
            defineField({ name: 'linkLabel', title: 'טקסט הקישור', type: 'string', description: 'בלי קישור – יוצג כתווית (למשל "בקרוב")' }),
            defineField({
              name: 'icon', title: 'סמל (בעיצוב ארגז כלים)', type: 'string',
              options: { list: [
                { title: 'ספירלה', value: 'spiral' }, { title: 'עלה', value: 'leaf' }, { title: 'כף רגל', value: 'foot' },
                { title: 'טיפה', value: 'drop' }, { title: 'לוח שנה', value: 'calendar' }, { title: 'מיקרופון', value: 'podcast' },
              ] },
            }),
            defineField({
              name: 'status', title: 'סטטוס (בעיצוב קורסים)', type: 'string',
              options: { list: [{ title: 'זמין עכשיו', value: 'available' }, { title: 'בקרוב', value: 'soon' }, { title: 'הסתיים', value: 'ended' }], layout: 'radio', direction: 'horizontal' },
            }),
            defineField({ name: 'price', title: 'מחיר (בעיצוב קורסים)', type: 'string', description: 'למשל: 75 ש"ח למפגש' }),
          ],
          preview: { select: { title: 'title', media: 'image' } },
        }),
      ],
    }),
  ],
  preview: blocksPreview('כרטיסים'),
});

export const tagsSection = defineType({
  name: 'tagsSection',
  title: 'ענן תגיות',
  type: 'object',
  fields: [
    heading,
    defineField({
      name: 'groups',
      title: 'קבוצות',
      type: 'array',
      of: [
        defineArrayMember({
          type: 'object',
          name: 'tagGroup',
          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, 6).join(', ') }) },
        }),
      ],
    }),
    defineField({ name: 'note', title: 'הערה', type: 'string' }),
  ],
  preview: blocksPreview('ענן תגיות'),
});

export const quoteSection = defineType({
  name: 'quoteSection',
  title: 'ציטוט',
  type: 'object',
  fields: [defineField({ name: 'body', title: 'ציטוט', type: 'simpleText' })],
  preview: { prepare: () => ({ title: '❝ ציטוט' }) },
});

export const contactSection = defineType({
  name: 'contactSection',
  title: 'יצירת קשר',
  type: 'object',
  description: 'פרטי הקשר נלקחים מ"הגדרות האתר".',
  fields: [
    heading,
    defineField({ name: 'image', title: 'תמונה', type: 'imageWithAlt' }),
    defineField({ name: 'caption', title: 'כיתוב לתמונה', type: 'string' }),
    defineField({ name: 'showForm', title: 'להציג טופס פנייה', type: 'boolean', initialValue: true }),
    defineField({ name: 'body', title: 'טקסט', type: 'richText' }),
  ],
  preview: blocksPreview('יצירת קשר'),
});

export const videoPlaylistSection = defineType({
  name: 'videoPlaylistSection',
  title: 'פלייליסט יוטיוב',
  type: 'object',
  description: 'שורת סרטונים נגללת. סרטונים חדשים בפלייליסט נוספים לבד בכל בנייה של האתר (עד 15 האחרונים) – אין צורך להוסיף ידנית.',
  fields: [
    heading,
    defineField({ name: 'intro', title: 'טקסט קצר', type: 'text', rows: 2 }),
    defineField({
      name: 'playlistUrl', title: 'קישור לפלייליסט', type: 'url',
      description: 'הקישור מיוטיוב, למשל https://www.youtube.com/playlist?list=…',
      validation: (r) => r.required(),
    }),
    defineField({ name: 'linkLabel', title: 'טקסט הקישור לפלייליסט המלא', type: 'string', initialValue: 'לכל הפלייליסט ביוטיוב' }),
    defineField({
      name: 'videos', title: 'סרטונים', type: 'array',
      description: 'מסודרים לפי המספר. אפשר לתקן כותרת או אורך. סרטון חדש שעולה לפלייליסט נוסף לאתר לבד.',
      of: [
        defineArrayMember({
          name: 'video', type: 'object', title: 'סרטון',
          fields: [
            defineField({ name: 'number', title: 'מספר', type: 'number' }),
            defineField({ name: 'title', title: 'כותרת', type: 'string' }),
            defineField({ name: 'videoId', title: 'מזהה הסרטון ביוטיוב', type: 'string', description: 'החלק שאחרי watch?v= בכתובת הסרטון' }),
            defineField({ name: 'duration', title: 'אורך', type: 'string' }),
          ],
          preview: { select: { n: 'number', title: 'title', videoId: 'videoId' }, prepare: ({ n, title, videoId }) => ({ title: `${n ?? ''}. ${title ?? ''}`, media: undefined, subtitle: videoId }) },
        }),
      ],
    }),
  ],
  preview: blocksPreview('פלייליסט יוטיוב'),
});

export const productsSection = defineType({
  name: 'productsSection',
  title: 'גלריית המרקחות',
  type: 'object',
  description: 'מציגה את כל המרקחות המסומנות "להציג באתר", לפי המיקום שנקבע להן.',
  fields: [
    heading,
    defineField({ name: 'intro', title: 'פתיח', type: 'richText' }),
    defineField({ name: 'notice', title: 'אזהרות כלליות', type: 'text', rows: 4, description: 'מופיעות בתיבה מעל הגלריה' }),
    defineField({ name: 'pickHint', title: 'הסבר על סימון מוצרים', type: 'string', description: 'מעל הגלריה. ברירת מחדל: סמני את המרקחות שמעניינות אותך – ושלחי לי את כולן בהודעת וואטסאפ אחת.' }),
    defineField({ name: 'ctaText', title: 'טקסט ההזמנה בתחתית', type: 'string', initialValue: 'להזמנה או להתאמה אישית – כתבי לי' }),
  ],
  preview: blocksPreview('גלריית המרקחות'),
});

export const sectionTypes = [
  hero, tilesSection, richTextSection, principlesSection, latestSection, instagramSection, ctaSection,
  acronymSection, listSection, stepsSection, cardsSection, tagsSection, quoteSection, contactSection,
  videoPlaylistSection, productsSection,
];
