/**
 * Fill in the fields the storefront v2 design added, once, in both languages.
 *
 *     ./tk cms-tools npx payload run src/seed/storefront.ts
 *
 * Idempotent and conservative: a field is written ONLY when it is empty. Run it twice and the second
 * run changes nothing; edit any of this text in /admin afterwards and a later run will not undo it.
 * That matters because the CMS is the source of truth — this script is a first draft to make the new
 * bands appear, not a definition of them.
 *
 * The copy follows the site's established voice: Egyptian colloquial in Arabic, plain English beside
 * it. Nothing here claims anything the product does not do — the three «why» points are the lesson
 * shape the academy actually ships (an explanation in Egyptian Arabic, practice and assessments, and
 * an assistant that answers from the student's own course).
 */
import { getPayload } from 'payload'
import config from '@payload-config'

type Loc = 'ar' | 'en'
const LOCALES: Loc[] = ['ar', 'en']
type Bi = { ar: string; en: string }

const SETTINGS: Record<Loc, Record<string, unknown>> = {
  ar: {
    banner: 'الوحدة الأولى كاملة مجاناً في أي منهج — ابدأ من غير أي دفع',
    footer: {
      contactHeading: 'تواصل معانا',
      socialHeading: 'تابعنا',
    },
    ui: {
      light: 'التبديل للوضع الفاتح',
      dark: 'التبديل للوضع الداكن',
      close: 'إغلاق',
    },
    chat: {
      title: 'مساعدة Thinkera',
      greeting: 'أهلاً بيك 👋 محتاج تعرف إيه؟',
      placeholder: 'اكتب سؤالك...',
      send: 'إرسال',
      disclaimer: 'الإجابات دي مكتوبة من فريق الأكاديمية. أي سؤال تاني هيتفتح على واتساب وحد من الفريق هيرد عليك.',
      items: [
        {
          q: 'إيه المناهج المتاحة دلوقتي؟',
          a: 'تقدر تشوف كل المناهج من صفحة المناهج. اللي عليه «متاح دلوقتي» أو «متاح جزئياً» تقدر تبدأ فيه فوراً، واللي عليه «قريباً» لسه بيتجهّز وصفحته بتقول وصل لفين.',
        },
        {
          q: 'أبدأ إزاي؟',
          a: 'الوحدة الأولى كاملة مجانية في أي منهج، من غير دفع. افتح المنهج من صفحة المناهج واضغط دخول المنصة، وهتلاقي دروس الوحدة الأولى مفتوحة قدامك.',
        },
        {
          q: 'عايز أكلّم حد من الفريق',
          a: 'اكتب سؤالك في الخانة تحت واضغط إرسال، وهنفتح لك واتساب على محادثة معانا والسؤال مكتوب جاهز.',
        },
      ],
    },
  },
  en: {
    banner: 'The whole first unit is free on every course — start without paying',
    footer: {
      contactHeading: 'Get in touch',
      socialHeading: 'Follow us',
    },
    ui: {
      light: 'Switch to light',
      dark: 'Switch to dark',
      close: 'Close',
    },
    chat: {
      title: 'Thinkera help',
      greeting: 'Hello 👋 What would you like to know?',
      placeholder: 'Type your question...',
      send: 'Send',
      disclaimer: 'These answers were written by the academy team. Anything else opens WhatsApp, where a person replies.',
      items: [
        {
          q: 'Which courses are available now?',
          a: 'Every course is on the courses page. One marked “Available now” or “Partly available” can be started today; one marked “Coming soon” is still being built, and its page says how far it has got.',
        },
        {
          q: 'How do I start?',
          a: 'The whole first unit is free on every course, with no payment. Open the course from the courses page and press sign in — the first unit’s lessons are already open to you.',
        },
        {
          q: 'I want to talk to someone',
          a: 'Write your question in the box below and press send. WhatsApp opens on a chat with us, with your question already typed.',
        },
      ],
    },
  },
}

const HOME: Record<Loc, Record<string, unknown>> = {
  ar: {
    noteOne: 'الوحدة الأولى مجاناً',
    noteTwo: 'شرح بالعامية وتدريب عملي',
    browseCta: 'شوف المناهج',
    categoriesCta: 'اختار مجالك',
    catEyebrow: 'المجالات',
    catTitle: 'إيه المجال اللي حابب تبدأ فيه؟',
    catText: 'اختار المجال اللي يقرّب من اهتمامك، وشوف المناهج اللي تحته.',
    catLink: 'كل المجالات',
    featuredEyebrow: 'مناهج مختارة',
    featuredLink: 'كل المناهج',
    whyEyebrow: 'ليه Thinkera؟',
    whyTitle: 'كل درس مبني بنفس الطريقة',
    why: [
      { icon: 'book', title: 'شرح بالعامية المصرية', text: 'الدرس متشرح باللغة اللي بتتكلمها، خطوة ورا خطوة، من غير لف ولا تعقيد.' },
      { icon: 'target', title: 'تدريب وتقييمات', text: 'بعد كل درس تدريب وأسئلة، عشان تتأكد إنك فهمت فعلاً مش بس اتفرجت.' },
      { icon: 'ai', title: 'مساعد بيجاوب من منهجك', text: 'لو وقفت في حاجة، اسأل المساعد — بيجاوب من دروس منهجك إنت، مش من أي كلام.' },
    ],
  },
  en: {
    noteOne: 'First unit free',
    noteTwo: 'Clear teaching, real practice',
    browseCta: 'Browse courses',
    categoriesCta: 'Explore areas',
    catEyebrow: 'Learning areas',
    catTitle: 'Where would you like to start?',
    catText: 'Pick the area closest to what interests you and see the courses under it.',
    catLink: 'All areas',
    featuredEyebrow: 'Selected courses',
    featuredLink: 'All courses',
    whyEyebrow: 'Why Thinkera?',
    whyTitle: 'Every lesson is built the same way',
    why: [
      { icon: 'book', title: 'Taught in plain language', text: 'Each lesson is explained step by step, in the language you actually speak, with nothing padded out.' },
      { icon: 'target', title: 'Practice and assessments', text: 'Every lesson is followed by practice and questions, so you find out whether you understood it or only watched it.' },
      { icon: 'ai', title: 'An assistant that knows your course', text: 'Stuck on something? Ask the assistant — it answers from your own course’s lessons, not from anything it likes.' },
    ],
  },
}

const CATALOGUE: Record<Loc, Record<string, unknown>> = {
  ar: {
    filters: {
      search: 'دوّر على منهج...',
      category: 'المجال',
      level: 'المستوى',
      status: 'الإتاحة',
      all: 'الكل',
      allLevels: 'كل المستويات',
      results: 'في النتايج',
      sort: 'ترتيب حسب',
      sortDefault: 'الترتيب الافتراضي',
      sortPrice: 'الأقل سعراً',
      empty: 'مفيش مناهج مطابقة للفلاتر دي. جرّب تغيّر البحث أو تشيل فلتر.',
      page: 'صفحة',
    },
    // Arabic counts its nouns in four shapes; printing «4 منهج» is the first thing a reader notices.
    count: { one: 'منهج', two: 'منهجين', few: 'مناهج', many: 'منهجاً', other: 'منهج' },
  },
  en: {
    filters: {
      search: 'Search courses...',
      category: 'Area',
      level: 'Level',
      status: 'Availability',
      all: 'All',
      allLevels: 'All levels',
      results: 'found',
      sort: 'Sort by',
      sortDefault: 'Default order',
      sortPrice: 'Lowest price',
      empty: 'No courses match these filters. Try another search, or clear one.',
      page: 'Page',
    },
    count: { one: 'course', other: 'courses' },
  },
}

const CATEGORIES: Record<Loc, Record<string, unknown>> = {
  ar: {
    seo: { title: 'المجالات | أكاديمية Thinkera', description: 'من المناهج الدراسية للبرمجة والذكاء الاصطناعي واللغات ومهارات الشغل: اختار المجال وشوف المناهج اللي تحته.' },
    h1: 'اختار المجال اللي يناسبك',
    lead: 'المجالات دي بتتحدّث من المنصة نفسها، وعدد المناهج تحت كل مجال بيتحسب لوحده. اضغط على أي مجال عشان تشوف مناهجه.',
    featuredTitle: 'ابدأ من هنا',
    featuredLead: 'المناهج المتاحة دلوقتي، وإيه اللي جاي بعدها.',
  },
  en: {
    seo: { title: 'Learning areas | Thinkera Academy', description: 'From school curricula to programming, AI, languages and workplace skills: pick an area and see its courses.' },
    h1: 'Choose the area that suits you',
    lead: 'These areas come from the learning platform itself, and the count under each one works itself out. Open any area to see its courses.',
    featuredTitle: 'Start here',
    featuredLead: 'What is available today, and what comes next.',
  },
}

/** True when a value counts as «not filled in yet». */
const empty = (v: unknown): boolean =>
  v === null || v === undefined || (typeof v === 'string' && v.trim() === '') || (Array.isArray(v) && v.length === 0)

/**
 * Merge `add` into `current`, keeping anything already written. Walks one level into a group so
 * ui.light can be added beside an existing ui.menu instead of replacing the whole group.
 */
function fill(current: Record<string, unknown>, add: Record<string, unknown>): { out: Record<string, unknown>; wrote: string[] } {
  const out: Record<string, unknown> = { ...current }
  const wrote: string[] = []
  for (const [k, v] of Object.entries(add)) {
    const now = current?.[k]
    if (v && typeof v === 'object' && !Array.isArray(v)) {
      const sub = fill((now as Record<string, unknown>) || {}, v as Record<string, unknown>)
      if (sub.wrote.length) {
        out[k] = sub.out
        wrote.push(...sub.wrote.map((n) => `${k}.${n}`))
      }
    } else if (empty(now)) {
      out[k] = v
      wrote.push(k)
    }
  }
  return { out, wrote }
}

const NAV_CATEGORIES: Bi = { ar: 'المجالات', en: 'Learning areas' }

async function main() {
  const payload = await getPayload({ config })
  for (const locale of LOCALES) {
    for (const [slug, data] of [
      ['settings', SETTINGS[locale]],
      ['home', HOME[locale]],
      ['catalogue', CATALOGUE[locale]],
      ['categories', CATEGORIES[locale]],
    ] as const) {
      // fallbackLocale false, or Payload answers an empty English field with the Arabic one and
      // every field looks filled in already — which is exactly what happened on the first run.
      const current = (await payload.findGlobal({
        slug: slug as 'settings', locale, depth: 0, fallbackLocale: false,
      })) as unknown as Record<string, unknown>
      const { out, wrote } = fill(current, data as Record<string, unknown>)
      if (!wrote.length) {
        payload.logger.info(`${locale} · ${slug}: already filled in, nothing written`)
        continue
      }
      await payload.updateGlobal({ slug: slug as 'settings', locale, data: out as never })
      payload.logger.info(`${locale} · ${slug}: ${wrote.join(', ')}`)
    }

    // The menu gains one item, and only if it is not there already.
    const s = (await payload.findGlobal({ slug: 'settings', locale, depth: 0, fallbackLocale: false })) as { nav?: { label?: string; href?: string }[] }
    const nav = s.nav || []
    if (!nav.some((n) => (n.href || '') === '/categories')) {
      // after «المناهج», which is where a visitor looks for it
      const at = Math.max(1, nav.findIndex((n) => (n.href || '') === '/courses') + 1)
      const next = [...nav.slice(0, at), { label: NAV_CATEGORIES[locale], href: '/categories' }, ...nav.slice(at)]
      await payload.updateGlobal({ slug: 'settings', locale, data: { nav: next } as never })
      payload.logger.info(`${locale} · settings: /categories added to the menu`)
    }
  }
  // The social row, seeded only from an address the CMS already holds. The others are left empty
  // on purpose: a guessed handle is either a dead link or somebody else's account, on every page.
  const st = (await payload.findGlobal({ slug: 'settings', depth: 0 })) as unknown as {
    social?: { network?: string; url?: string }[]; contact?: { youtube?: string | null }
  }
  if (!(st.social || []).length && st.contact?.youtube) {
    await payload.updateGlobal({
      slug: 'settings',
      data: { social: [{ network: 'youtube', url: st.contact.youtube }] } as never,
    })
    payload.logger.info('settings: YouTube added to the social row (the rest are for the owner to fill)')
  }

  payload.logger.info('storefront v2: done')
}

// Top-level await, not a floating promise: `payload run` ends the process as soon as the module's
// top level finishes, so a fire-and-forget main() is abandoned at its first await and the script
// exits 0 having written nothing. That is exactly what happened the first time this was run.
await main()
