// NotificationsMenu — dropdown anchored under the bell icon in the topbar.
// Shows the user's active "notify-me" subscriptions + recent updates.
// For the v3 mockup, we surface ONE entry: the user has asked to be
// notified when Matthew becomes available in French.
//
// Open state is managed locally by NotificationsBell (the wrapper). The
// menu closes on outside-click and Escape.
//
// audit rank 10: this component was 100% hardcoded Spanish inside an
// English-default app. It now localizes to the UI language (en/ca/es, with an
// English fallback for other UI languages) via a self-contained string table —
// the same pattern already used for `bookNameLocal` — and the topbar unread
// dot is now clearable instead of permanently lit.

// UI-language string table for the notifications surface. Keyed by UI language
// ONLY; the notified *content* language (French, here) is a separate axis and
// is shown literally regardless of UI language.
function notifStrings(lang) {
  const TABLE = {
    en: {
      title:'Notifications', markRead:'Mark all read',
      subs:'Subscriptions', activity:'Activity', commissions:'Commissions',
      waiting:'Awaiting availability', requested:'Requested 3 days ago',
      availTag:'Availability alert', gospelNT:'Gospel · New Testament',
      french:'French',
      titlePre:'We’ll tell you when ', titleMid:' is available in ',
      body:(bn)=>'Today, 12 of '+bn+'’s 28 passages have a French reading (Mode C · courtesy of Biblica). We’ll notify you as soon as the first linguist-reviewed version is complete.',
      passages:' / 28 passages', eta:'ETA ~4–6 weeks',
      adjust:'Adjust alert', viewMap:'View coverage map', cancelSub:'Cancel subscription',
      channel:'Channel: email to ', freq:' · Frequency: one alert per milestone · ', changePrefs:'change preferences',
      recent:'Recent activity',
      readyPre:'Your commission ', readyPost:' is ready.',
      sealedPost:' sealed 3 new passages in Romans.',
      yesterday:'yesterday', days2:'2 days ago',
      viewAll:'View all notifications', prefs:'Notification preferences',
    },
    ca: {
      title:'Notificacions', markRead:'Marca-les com llegides',
      subs:'Subscripcions', activity:'Activitat', commissions:'Encàrrecs',
      waiting:'Esperant disponibilitat', requested:'Sol·licitat fa 3 dies',
      availTag:'Avís de disponibilitat', gospelNT:'Evangeli · Nou Testament',
      french:'francès',
      titlePre:'T’avisarem quan ', titleMid:' estigui disponible en ',
      body:(bn)=>'Avui, 12 dels 28 passatges de '+bn+' tenen una lectura en francès (Mode C · cortesia de Biblica). T’enviarem un avís tan aviat com es completi la primera versió revisada per un lingüista acreditat.',
      passages:' / 28 passatges', eta:'ETA aprox. 4–6 setmanes',
      adjust:'Ajusta l’avís', viewMap:'Mostra el mapa de cobertura', cancelSub:'Cancel·la la subscripció',
      channel:'Canal: correu a ', freq:' · Freqüència: un sol avís per fita · ', changePrefs:'canvia les preferències',
      recent:'Activitat recent',
      readyPre:'El teu encàrrec ', readyPost:' està llest.',
      sealedPost:' ha segellat 3 passatges nous a Romans.',
      yesterday:'ahir', days2:'fa 2 dies',
      viewAll:'Mostra totes les notificacions', prefs:'Preferències de notificació',
    },
    es: {
      title:'Notificaciones', markRead:'Marcar como leídas',
      subs:'Suscripciones', activity:'Actividad', commissions:'Encargos',
      waiting:'Esperando disponibilidad', requested:'Solicitado hace 3 días',
      availTag:'Aviso de disponibilidad', gospelNT:'Evangelio · Nuevo Testamento',
      french:'francés',
      titlePre:'Te avisaremos cuando ', titleMid:' esté disponible en ',
      body:(bn)=>'Hoy, 12 de los 28 pasajes de '+bn+' tienen una lectura en francés (Mode C · cortesía de Biblica). Te enviaremos un aviso en cuanto se complete la primera versión revisada por un lingüista acreditado.',
      passages:' / 28 pasajes', eta:'ETA aprox. 4–6 semanas',
      adjust:'Ajustar aviso', viewMap:'Ver mapa de cobertura', cancelSub:'Cancelar suscripción',
      channel:'Canal: correo a ', freq:' · Frecuencia: un solo aviso por hito · ', changePrefs:'cambiar preferencias',
      recent:'Actividad reciente',
      readyPre:'Tu encargo ', readyPost:' está listo.',
      sealedPost:' ha sellado 3 pasajes nuevos en Romanos.',
      yesterday:'ayer', days2:'hace 2 días',
      viewAll:'Ver todas las notificaciones', prefs:'Preferencias de notificación',
    },
  };
  return TABLE[lang] || TABLE.en;
}

function NotificationsMenu({ open, onClose, anchorRef, onMarkRead }) {
  const I = window.useI18n();
  const ref = React.useRef(null);
  const S = notifStrings(I.getLang && I.getLang());

  React.useEffect(() => {
    if (!open) return;
    const onDoc = (e) => {
      if (ref.current && ref.current.contains(e.target)) return;
      if (anchorRef && anchorRef.current && anchorRef.current.contains(e.target)) return;
      onClose();
    };
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    const id = setTimeout(() => document.addEventListener('mousedown', onDoc), 0);
    window.addEventListener('keydown', onKey);
    return () => {
      clearTimeout(id);
      document.removeEventListener('mousedown', onDoc);
      window.removeEventListener('keydown', onKey);
    };
  }, [open, onClose, anchorRef]);

  if (!open) return null;

  // Small French flag glyph (tricolor bars) — pure SVG, no deps.
  const FrFlag = React.createElement('svg', {
    width: 18, height: 13, viewBox: '0 0 18 13',
    style: { borderRadius: 2, boxShadow: '0 0 0 1px rgba(6,31,39,.14)' }
  },
    React.createElement('rect', { x: 0,  y: 0, width: 6, height: 13, fill: '#0055A4' }),
    React.createElement('rect', { x: 6,  y: 0, width: 6, height: 13, fill: '#FFFFFF' }),
    React.createElement('rect', { x: 12, y: 0, width: 6, height: 13, fill: '#EF4135' })
  );

  // "Matthew" localization — show the book name in the user's current UI language.
  const bookNameLocal = (() => {
    const lang = I.getLang && I.getLang();
    const map = {
      en: 'Matthew', es: 'Mateo', ca: 'Mateu',
      fr: 'Matthieu', pt: 'Mateus', de: 'Matthäus',
      it: 'Matteo', nl: 'Matteüs', sw: 'Mathayo'
    };
    return map[lang] || 'Matthew';
  })();

  return React.createElement('div', { className: 'amos-notif-menu', ref, role: 'dialog', 'aria-label': S.title },
    // ── Header
    React.createElement('div', { className: 'wnm-head' },
      React.createElement('div', { className: 'wnm-title' }, S.title),
      React.createElement('button', {
        className: 'wnm-mark-read',
        onClick: (e) => { e.stopPropagation(); onMarkRead && onMarkRead(); }
      }, S.markRead)
    ),

    // ── Tabs (decorative, 1 active)
    React.createElement('div', { className: 'wnm-tabs' },
      React.createElement('button', { className: 'wnm-tab on' }, S.subs + ' ', React.createElement('span', { className: 'wnm-count' }, '1')),
      React.createElement('button', { className: 'wnm-tab' }, S.activity),
      React.createElement('button', { className: 'wnm-tab' }, S.commissions)
    ),

    // ── Pending subscription entry ──
    React.createElement('div', { className: 'wnm-section' },
      React.createElement('div', { className: 'wnm-section-head' },
        React.createElement('span', { className: 'wnm-dot pending' }),
        S.waiting,
        React.createElement('span', { className: 'wnm-when' }, S.requested)
      ),

      React.createElement('article', { className: 'wnm-card pending' },
        // left rail — flag + icon badge
        React.createElement('div', { className: 'wnm-card-left' },
          React.createElement('div', { className: 'wnm-flag-stack' },
            FrFlag,
            React.createElement('div', { className: 'wnm-lang-code' }, 'FR')
          )
        ),

        // body
        React.createElement('div', { className: 'wnm-card-body' },
          React.createElement('div', { className: 'wnm-kicker' },
            React.createElement('span', { className: 'wnm-kicker-tag' }, S.availTag),
            React.createElement('span', { className: 'wnm-kicker-sep' }, '·'),
            React.createElement('span', null, S.gospelNT)
          ),
          React.createElement('h4', { className: 'wnm-card-title' },
            S.titlePre, React.createElement('em', null, bookNameLocal), S.titleMid,
            React.createElement('strong', null, S.french), '.'
          ),
          React.createElement('p', { className: 'wnm-card-body-text' }, S.body(bookNameLocal)),

          // Progress strip — 12/28
          React.createElement('div', { className: 'wnm-progress' },
            React.createElement('div', { className: 'wnm-progress-bar' },
              React.createElement('span', { style: { width: '43%' } })
            ),
            React.createElement('div', { className: 'wnm-progress-meta' },
              React.createElement('span', null, React.createElement('b', null, '12'), S.passages),
              React.createElement('span', { className: 'wnm-progress-eta' }, S.eta)
            )
          ),

          // Actions
          React.createElement('div', { className: 'wnm-actions' },
            React.createElement('button', { className: 'wnm-btn wnm-btn-primary' },
              window.I.bell(13), S.adjust
            ),
            React.createElement('button', { className: 'wnm-btn wnm-btn-ghost' }, S.viewMap),
            React.createElement('button', { className: 'wnm-btn wnm-btn-ghost wnm-btn-danger' }, S.cancelSub)
          ),

          // fine print
          React.createElement('div', { className: 'wnm-fineprint' },
            S.channel, React.createElement('strong', null, 'jordan@readsonthetrain.org'),
            S.freq,
            React.createElement('a', { className: 'wnm-link' }, S.changePrefs)
          )
        )
      )
    ),

    // ── Recent updates (lighter) ──
    React.createElement('div', { className: 'wnm-section muted' },
      React.createElement('div', { className: 'wnm-section-head' },
        React.createElement('span', { className: 'wnm-dot' }),
        S.recent
      ),
      React.createElement('div', { className: 'wnm-mini-row' },
        React.createElement('span', { className: 'wnm-mini-ico' }, window.I.check(12)),
        React.createElement('span', { className: 'wnm-mini-text' },
          S.readyPre, React.createElement('strong', null, 'Rom 8:28–30 · Analytical (ca)'), S.readyPost
        ),
        React.createElement('span', { className: 'wnm-mini-time' }, S.yesterday)
      ),
      React.createElement('div', { className: 'wnm-mini-row' },
        React.createElement('span', { className: 'wnm-mini-ico seal' }, '✍'),
        React.createElement('span', { className: 'wnm-mini-text' },
          React.createElement('strong', null, 'Martí Cardona'), S.sealedPost
        ),
        React.createElement('span', { className: 'wnm-mini-time' }, S.days2)
      )
    ),

    // ── Footer
    React.createElement('div', { className: 'wnm-foot' },
      React.createElement('a', { className: 'wnm-link' }, S.viewAll),
      React.createElement('a', { className: 'wnm-link subtle' }, S.prefs)
    )
  );
}

// NotificationsBell — the topbar button + menu wrapper.
// Shows a red dot while there is unread activity; clears when the user opens
// the menu and chooses "mark all read" (audit rank 10 — was permanently lit).
function NotificationsBell() {
  const I = window.useI18n();
  const [open, setOpen] = React.useState(false);
  const [unread, setUnread] = React.useState(1);   // 1 pending subscription in the mock
  const anchorRef = React.useRef(null);
  const S = notifStrings(I.getLang && I.getLang());

  const label = unread > 0 ? (S.title + ' (' + unread + ')') : S.title;

  return React.createElement('div', { className: 'amos-notif-wrap' },
    React.createElement('button', {
      ref: anchorRef,
      className: 'amos-icon-btn amos-notif-btn' + (open ? ' on' : ''),
      title: label,
      'aria-label': label,
      onClick: (e) => { e.stopPropagation(); setOpen(o => !o); }
    },
      window.I.bell(16),
      // unread indicator — only while there is unread activity
      unread > 0 && React.createElement('span', { className: 'amos-notif-badge', 'aria-hidden': 'true' })
    ),
    React.createElement(NotificationsMenu, {
      open,
      onClose: () => setOpen(false),
      onMarkRead: () => setUnread(0),
      anchorRef
    })
  );
}

Object.assign(window, { NotificationsMenu, NotificationsBell });
