import type { Course, Setting } from '@/payload-types'
import { Support } from '@/components/Support'
import { SiteHeader, type NavItem } from '@/components/SiteHeader'
import type { PublicConfig } from '@/lib/config'
import { Icon, SOCIAL_NAME, SocialIcon, type SocialName } from '@/components/icons'
import { type Locale, isExternal, localHref, other, whatsapp } from '@/lib/site'

type Props = {
  locale: Locale
  /** this page's path without the language prefix ("/", "/courses", "/courses/bacc-en") */
  path: string
  settings: Setting
  courses: Course[]
  config: PublicConfig
  children: React.ReactNode
}

/**
 * Header, page, footer and the help bubble: the frame every page shares.
 *
 * A server component. It reads the CMS once, resolves every label and address, and hands the two
 * interactive pieces — the header's menu and the chat — exactly the strings they print. Neither of
 * them knows what a locale or a global is, so nothing about the CMS reaches the browser.
 *
 * Text an editor has not filled in is left out rather than replaced with a built-in English default:
 * an empty heading is a thing someone notices and fills, and an English one on an Arabic page looks
 * deliberate and survives for months.
 */
export function Shell({ locale, path, settings: s, courses, config, children }: Props) {
  const brand = s.brandName || 'Thinkera'
  const alt = other(locale)
  const current = (href: string) => (href === '/' ? path === '/' : path === href || path.startsWith(`${href}/`))

  const nav: NavItem[] = (s.nav || []).map((n) => ({
    label: n.label || '',
    href: localHref(locale, n.href),
    current: current(n.href || ''),
  }))

  // The ways to reach us, straight from the settings. A missing one is simply not printed.
  const wa = whatsapp(s.contact?.whatsapp, s.contact?.waText || undefined)
  const email = s.contact?.email || config.email
  const social = (s.social || []).filter((x) => x.network && (x.url || '').trim())

  // Live support: on only when the academy switched it on and gave it somewhere to talk to. The old help
  // bubble (s.chat) is retired — its text is kept in the CMS but nothing renders it.
  const support = s.support
  const showSupport = Boolean(support?.enabled && support?.baseUrl && support?.websiteToken)

  return (
    <>
      <a className="skip" href="#main">
        {s.ui?.skip}
      </a>

      <SiteHeader
        brand={brand}
        logo="/brand/thinkera-logo.svg"
        banner={s.banner}
        nav={nav}
        altHref={localHref(alt, path)}
        altLang={alt}
        altLabel={alt === 'en' ? 'EN' : 'ع'}
        signIn={s.platformUrl ? { href: s.platformUrl, label: s.ui?.signIn || '' } : null}
        labels={{
          menu: s.ui?.menu || '',
          light: s.ui?.light || '',
          dark: s.ui?.dark || '',
          langSwitch: s.ui?.langSwitch || '',
        }}
        defaultTheme={config.defaultTheme}
      />

      <main id="main">{children}</main>

      <footer className="footer">
        <div className="container">
          <div className="footergrid">
            <div>
              <a className="brand-link" href={localHref(locale, '/')} aria-label={brand}>
                <img className="logo" src="/brand/thinkera-logo.svg" alt={brand} width={150} height={42} />
              </a>
              <p>{s.footer?.tagline}</p>
            </div>
            <div>
              <h4>{s.footer?.coursesHeading}</h4>
              {courses.map((c) => (
                <a key={c.id} href={localHref(locale, `/courses/${c.slug}`)}>
                  {c.titleShort || c.title}
                </a>
              ))}
            </div>
            <div>
              <h4>{s.footer?.academyHeading}</h4>
              {/* The brand guidelines are not for visitors: the page was taken down on the owner's
                  instruction (27 September 2026), so its link is dropped here whether or not the
                  setting behind it has been deleted in the admin yet. */}
              {(s.footer?.links || [])
                .filter((l) => !(l.href || '').startsWith('/brand/'))
                .map((l) => (
                  <a key={l.id || l.href} href={localHref(locale, l.href)}
                     rel={isExternal(l.href) ? 'noopener' : undefined}>
                    {l.label}
                  </a>
                ))}
            </div>
            <div>
              <h4>{s.footer?.contactHeading}</h4>
              {/* The address and the number are Latin runs in an Arabic column: `.ltr` isolates each
                  one so the bidi algorithm cannot carry its dots and plus sign to the wrong end. */}
              {email ? (
                <a className="foot-contact" href={`mailto:${email}`}>
                  <Icon name="mail" />
                  <span className="ltr">{email}</span>
                </a>
              ) : null}
              {wa ? (
                <a className="foot-contact" href={wa.href} target="_blank" rel="noopener noreferrer">
                  <SocialIcon name="whatsapp" />
                  <span className="ltr">{wa.label}</span>
                </a>
              ) : null}
              {s.contact?.phone ? (
                <a className="foot-contact" href={`tel:${s.contact.phone.replace(/[^\d+]/g, '')}`}>
                  <Icon name="phone" />
                  <span className="ltr">{s.contact.phone}</span>
                </a>
              ) : null}
            </div>
          </div>

          {social.length ? (
            <div className="social">
              {s.footer?.socialHeading ? <h4>{s.footer.socialHeading}</h4> : null}
              <ul>
                {social.map((x) => {
                  const net = x.network as SocialName
                  return (
                    <li key={x.id || x.url}>
                      {/* The link carries the network's name; the icon is decoration inside it, so a
                          screen reader reads «Facebook», not «graphic». */}
                      <a href={x.url as string} target="_blank" rel="noopener noreferrer"
                         aria-label={SOCIAL_NAME[net] || net} title={SOCIAL_NAME[net] || net}>
                        <SocialIcon name={net} />
                      </a>
                    </li>
                  )
                })}
              </ul>
            </div>
          ) : null}
          <div className="copyright">
            <span>
              © <span className="num">{new Date().getFullYear()}</span> {brand}. {s.footer?.rights}
            </span>
          </div>
        </div>
      </footer>

      {showSupport ? (
        <Support baseUrl={support?.baseUrl} websiteToken={support?.websiteToken} locale={locale} />
      ) : null}
    </>
  )
}
