// liturgical.jsx — auto-detect season, saints, daily office, lectionary

// ─────────────────────────────────────────────────────────────
// Easter calculation — Anonymous Gregorian (Meeus/Jones/Butcher)
// Returns Date for Easter Sunday in given year
// ─────────────────────────────────────────────────────────────
function easterDate(year) {
  const a = year % 19;
  const b = Math.floor(year / 100);
  const c = year % 100;
  const d = Math.floor(b / 4);
  const e = b % 4;
  const f = Math.floor((b + 8) / 25);
  const g = Math.floor((b - f + 1) / 3);
  const h = (19 * a + b - d - g + 15) % 30;
  const i = Math.floor(c / 4);
  const k = c % 4;
  const L = (32 + 2 * e + 2 * i - h - k) % 7;
  const m = Math.floor((a + 11 * h + 22 * L) / 451);
  const month = Math.floor((h + L - 7 * m + 114) / 31); // 3=Mar, 4=Apr
  const day = ((h + L - 7 * m + 114) % 31) + 1;
  return new Date(year, month - 1, day);
}

function addDays(d, n) {
  const r = new Date(d);
  r.setDate(r.getDate() + n);
  return r;
}

// ─────────────────────────────────────────────────────────────
// Detect current liturgical season
// ─────────────────────────────────────────────────────────────
function detectSeason(date = new Date()) {
  const y = date.getFullYear();
  const easter = easterDate(y);
  const ashWed = addDays(easter, -46);
  const palmSun = addDays(easter, -7);
  const pentecost = addDays(easter, 49);
  const trinity = addDays(easter, 56);
  const epiphany = new Date(y, 0, 6);

  // First Sunday of Advent: Sunday on or before Dec 3 (4 Sundays before Dec 25)
  const xmas = new Date(y, 11, 25);
  const adventStart = (() => {
    // 4 Sundays before Christmas
    const fourth = new Date(xmas);
    fourth.setDate(xmas.getDate() - xmas.getDay() - 21);
    return fourth;
  })();
  const baptismOfLord = (() => {
    // Sunday after Jan 6
    const d = new Date(y, 0, 7);
    while (d.getDay() !== 0) d.setDate(d.getDate() + 1);
    return d;
  })();

  if (date >= adventStart && date < xmas) return 'advent';
  if ((date >= xmas && date.getMonth() === 11) || date < epiphany) return 'christmas';
  if (date.getMonth() === 0 && date.getDate() === 6) return 'epiphany';
  if (date >= epiphany && date < ashWed) return 'epiphany';
  if (date >= ashWed && date < easter) return 'lent';
  if (date >= easter && date < pentecost) return 'easter';
  if (date >= pentecost && date < trinity) return 'pentecost';
  return 'ordinary';
}

// ─────────────────────────────────────────────────────────────
// Saint of the Day — small but real list (UMC commemorates many)
// ─────────────────────────────────────────────────────────────
const SAINTS = {
  '1-1':   { name: 'The Holy Name of Jesus', kind: 'feast' },
  '1-6':   { name: 'The Epiphany of the Lord', kind: 'principal' },
  '1-17':  { name: 'St. Antony of Egypt', kind: 'memorial' },
  '1-25':  { name: 'The Conversion of St. Paul', kind: 'feast' },
  '2-2':   { name: 'The Presentation', kind: 'feast' },
  '2-14':  { name: 'Sts. Cyril and Methodius', kind: 'memorial' },
  '3-17':  { name: 'St. Patrick of Ireland', kind: 'memorial' },
  '3-25':  { name: 'The Annunciation', kind: 'principal' },
  '4-21':  { name: 'St. Anselm of Canterbury', kind: 'memorial' },
  '4-25':  { name: 'St. Mark the Evangelist', kind: 'feast' },
  '4-29':  { name: 'St. Catherine of Siena', kind: 'memorial' },
  '5-1':   { name: 'Sts. Philip and James', kind: 'feast' },
  '5-3':   { name: 'St. Athanasius', kind: 'memorial' },
  '5-24':  { name: 'John & Charles Wesley', kind: 'memorial', wesley: true },
  '5-31':  { name: 'The Visitation', kind: 'feast' },
  '6-11':  { name: 'St. Barnabas the Apostle', kind: 'feast' },
  '6-24':  { name: 'The Nativity of John the Baptist', kind: 'feast' },
  '6-29':  { name: 'Sts. Peter and Paul', kind: 'feast' },
  '7-22':  { name: 'St. Mary Magdalene', kind: 'feast' },
  '7-25':  { name: 'St. James the Apostle', kind: 'feast' },
  '8-6':   { name: 'The Transfiguration', kind: 'feast' },
  '8-15':  { name: 'St. Mary the Virgin', kind: 'feast' },
  '8-24':  { name: 'St. Bartholomew', kind: 'feast' },
  '9-14':  { name: 'Holy Cross Day', kind: 'feast' },
  '9-21':  { name: 'St. Matthew the Evangelist', kind: 'feast' },
  '9-29':  { name: 'St. Michael and All Angels', kind: 'feast' },
  '10-4':  { name: 'St. Francis of Assisi', kind: 'memorial' },
  '10-18': { name: 'St. Luke the Evangelist', kind: 'feast' },
  '10-28': { name: 'Sts. Simon and Jude', kind: 'feast' },
  '11-1':  { name: 'All Saints', kind: 'principal' },
  '11-2':  { name: 'All Souls', kind: 'memorial' },
  '11-30': { name: 'St. Andrew the Apostle', kind: 'feast' },
  '12-6':  { name: 'St. Nicholas of Myra', kind: 'memorial' },
  '12-21': { name: 'St. Thomas the Apostle', kind: 'feast' },
  '12-26': { name: 'St. Stephen, Deacon & Martyr', kind: 'feast' },
  '12-27': { name: 'St. John the Evangelist', kind: 'feast' },
  '12-28': { name: 'The Holy Innocents', kind: 'feast' },
};

function saintToday(date = new Date()) {
  const key = (date.getMonth() + 1) + '-' + date.getDate();
  return SAINTS[key] || null;
}

// ─────────────────────────────────────────────────────────────
// Daily Office — hours of prayer
// ─────────────────────────────────────────────────────────────
const OFFICES = [
  { id: 'lauds',    name: 'Morning Prayer', alt: 'Lauds',    hour: 7,  minute: 0 },
  { id: 'terce',    name: 'Mid-Morning',    alt: 'Terce',    hour: 9,  minute: 0 },
  { id: 'sext',     name: 'Midday Prayer',  alt: 'Sext',     hour: 12, minute: 0 },
  { id: 'none',     name: 'Mid-Afternoon',  alt: 'None',     hour: 15, minute: 0 },
  { id: 'vespers',  name: 'Evening Prayer', alt: 'Vespers',  hour: 18, minute: 0 },
  { id: 'compline', name: 'Night Prayer',   alt: 'Compline', hour: 21, minute: 0 },
];

function nextOffice(now = new Date()) {
  const minsNow = now.getHours() * 60 + now.getMinutes();
  for (const o of OFFICES) {
    const m = o.hour * 60 + o.minute;
    if (m > minsNow) return { ...o, when: m - minsNow, status: 'upcoming' };
  }
  // tomorrow's Lauds
  const o = OFFICES[0];
  return { ...o, when: 24 * 60 - minsNow + o.hour * 60 + o.minute, status: 'tomorrow' };
}

function currentOffice(now = new Date()) {
  const minsNow = now.getHours() * 60 + now.getMinutes();
  let prev = OFFICES[OFFICES.length - 1];
  for (const o of OFFICES) {
    const m = o.hour * 60 + o.minute;
    if (m > minsNow) break;
    prev = o;
  }
  return prev;
}

// Daily office content. Each entry pairs the office with its psalm,
// canticle, and closing collect for use by the OfficeScreen.
const OFFICE_CONTENT = {
  lauds:    { versicle: 'O Lord, open thou our lips.',
              response: 'And our mouth shall show forth thy praise.',
              psalmId:  'psalm-95',
              canticleId: 'benedictus', collectKey: 'morning' },
  terce:    { versicle: 'Send forth thy Spirit and they shall be created.',
              response: 'And thou shalt renew the face of the earth.',
              psalmId:  'psalm-119-1',
              canticleId: 'teDeum',     collectKey: 'morning' },
  sext:     { versicle: 'O God, make speed to save us.',
              response: 'O Lord, make haste to help us.',
              psalmId:  'psalm-121',
              canticleId: 'teDeum',     collectKey: 'noonday' },
  none:     { versicle: 'O God, make speed to save us.',
              response: 'O Lord, make haste to help us.',
              psalmId:  'psalm-119-121',
              canticleId: 'teDeum',     collectKey: 'noonday' },
  vespers:  { versicle: 'O God, make speed to save us.',
              response: 'O Lord, make haste to help us.',
              psalmId:  'psalm-141',
              canticleId: 'magnificat', collectKey: 'evening' },
  compline: { versicle: 'The Lord almighty grant us a quiet night and a perfect end.',
              response: 'Amen.',
              psalmId:  'psalm-4',
              canticleId: 'nunc',       collectKey: 'compline' },
};

// ─────────────────────────────────────────────────────────────
// PSALTER — full text of the psalms used in the daily offices.
// Translation: King James Version (public domain).
// ─────────────────────────────────────────────────────────────
const PSALMS = {
  'psalm-4': {
    ref: 'Psalm 4',
    title: 'Cum invocarem',
    verses: [
      'Hear me when I call, O God of my righteousness: thou hast enlarged me when I was in distress; have mercy upon me, and hear my prayer.',
      'O ye sons of men, how long will ye turn my glory into shame? how long will ye love vanity, and seek after lies?',
      'But know that the Lord hath set apart him that is godly for himself: the Lord will hear when I call unto him.',
      'Stand in awe, and sin not: commune with your own heart upon your bed, and be still.',
      'Offer the sacrifices of righteousness, and put your trust in the Lord.',
      'There be many that say, Who will shew us any good? Lord, lift thou up the light of thy countenance upon us.',
      'Thou hast put gladness in my heart, more than in the time that their corn and their wine increased.',
      'I will both lay me down in peace, and sleep: for thou, Lord, only makest me dwell in safety.',
    ],
  },
  'psalm-95': {
    ref: 'Psalm 95',
    title: 'Venite, exultemus Domino',
    verses: [
      'O come, let us sing unto the Lord: let us make a joyful noise to the rock of our salvation.',
      'Let us come before his presence with thanksgiving, and make a joyful noise unto him with psalms.',
      'For the Lord is a great God, and a great King above all gods.',
      'In his hand are the deep places of the earth: the strength of the hills is his also.',
      'The sea is his, and he made it: and his hands formed the dry land.',
      'O come, let us worship and bow down: let us kneel before the Lord our maker.',
      'For he is our God; and we are the people of his pasture, and the sheep of his hand.',
    ],
  },
  'psalm-121': {
    ref: 'Psalm 121',
    title: 'Levavi oculos',
    verses: [
      'I will lift up mine eyes unto the hills, from whence cometh my help.',
      'My help cometh from the Lord, which made heaven and earth.',
      'He will not suffer thy foot to be moved: he that keepeth thee will not slumber.',
      'Behold, he that keepeth Israel shall neither slumber nor sleep.',
      'The Lord is thy keeper: the Lord is thy shade upon thy right hand.',
      'The sun shall not smite thee by day, nor the moon by night.',
      'The Lord shall preserve thee from all evil: he shall preserve thy soul.',
      'The Lord shall preserve thy going out and thy coming in from this time forth, and even for evermore.',
    ],
  },
  'psalm-141': {
    ref: 'Psalm 141 : 1—4',
    title: 'Domine, clamavi',
    verses: [
      'Lord, I cry unto thee: make haste unto me; give ear unto my voice, when I cry unto thee.',
      'Let my prayer be set forth before thee as incense; and the lifting up of my hands as the evening sacrifice.',
      'Set a watch, O Lord, before my mouth; keep the door of my lips.',
      'Incline not my heart to any evil thing, to practise wicked works with men that work iniquity.',
    ],
  },
  'psalm-119-1': {
    ref: 'Psalm 119 : 1—8',
    title: 'Beati immaculati',
    verses: [
      'Blessed are the undefiled in the way, who walk in the law of the Lord.',
      'Blessed are they that keep his testimonies, and that seek him with the whole heart.',
      'They also do no iniquity: they walk in his ways.',
      'Thou hast commanded us to keep thy precepts diligently.',
      'O that my ways were directed to keep thy statutes!',
      'Then shall I not be ashamed, when I have respect unto all thy commandments.',
      'I will praise thee with uprightness of heart, when I shall have learned thy righteous judgments.',
      'I will keep thy statutes: O forsake me not utterly.',
    ],
  },
  'psalm-119-121': {
    ref: 'Psalm 119 : 121—128',
    title: 'Feci judicium',
    verses: [
      'I have done judgment and justice: leave me not to mine oppressors.',
      'Be surety for thy servant for good: let not the proud oppress me.',
      'Mine eyes fail for thy salvation, and for the word of thy righteousness.',
      'Deal with thy servant according unto thy mercy, and teach me thy statutes.',
      'I am thy servant; give me understanding, that I may know thy testimonies.',
      'It is time for thee, Lord, to work: for they have made void thy law.',
      'Therefore I love thy commandments above gold; yea, above fine gold.',
      'Therefore I esteem all thy precepts concerning all things to be right; and I hate every false way.',
    ],
  },
};

// ─────────────────────────────────────────────────────────────
// Canticles — the great daily-office hymns
// ─────────────────────────────────────────────────────────────
const CANTICLES = {
  benedictus: {
    name: 'Benedictus',
    subtitle: 'The Song of Zechariah · Luke 1 : 68—79',
    lines: [
      'Blessed be the Lord, the God of Israel,',
      'for he hath visited and redeemed his people,',
      'and hath raised up a mighty salvation for us,',
      'in the house of his servant David.',
      'To shew mercy to our forefathers,',
      'and to remember his holy covenant.',
      'Glory be to the Father, and to the Son, and to the Holy Ghost;',
      'as it was in the beginning, is now, and ever shall be: world without end. Amen.',
    ],
  },
  magnificat: {
    name: 'Magnificat',
    subtitle: 'The Song of Mary · Luke 1 : 46—55',
    lines: [
      'My soul doth magnify the Lord,',
      'and my spirit hath rejoiced in God my Saviour.',
      'For he hath regarded the lowliness of his handmaiden;',
      'for, behold, from henceforth all generations shall call me blessed.',
      'For he that is mighty hath magnified me;',
      'and holy is his Name.',
      'And his mercy is on them that fear him,',
      'throughout all generations.',
      'Glory be to the Father, and to the Son, and to the Holy Ghost;',
      'as it was in the beginning, is now, and ever shall be: world without end. Amen.',
    ],
  },
  nunc: {
    name: 'Nunc dimittis',
    subtitle: 'The Song of Simeon · Luke 2 : 29—32',
    lines: [
      'Lord, now lettest thou thy servant depart in peace,',
      'according to thy word.',
      'For mine eyes have seen thy salvation,',
      'which thou hast prepared before the face of all people;',
      'to be a light to lighten the Gentiles,',
      'and to be the glory of thy people Israel.',
      'Glory be to the Father, and to the Son, and to the Holy Ghost;',
      'as it was in the beginning, is now, and ever shall be: world without end. Amen.',
    ],
  },
  teDeum: {
    name: 'Te Deum laudamus',
    subtitle: 'A song of the Church',
    lines: [
      'We praise thee, O God; we acknowledge thee to be the Lord.',
      'All the earth doth worship thee, the Father everlasting.',
      'To thee all angels cry aloud, the heavens, and all the powers therein.',
      'Holy, holy, holy, Lord God of Sabaoth;',
      'heaven and earth are full of the majesty of thy glory.',
    ],
  },
};

// Office-level closing collects (different from the day's RCL collect).
const OFFICE_COLLECTS = {
  morning:  'O Lord, our heavenly Father, almighty and everlasting God, who hast safely brought us to the beginning of this day: Defend us in the same with thy mighty power; and grant that this day we fall into no sin, neither run into any kind of danger; but that all our doings, being ordered by thy governance, may be righteous in thy sight; through Jesus Christ our Lord. Amen.',
  noonday:  'Blessed Saviour, at this hour thou didst hang upon the cross, stretching out thy loving arms: Grant that all the peoples of the earth may look unto thee and be saved; for thy tender mercies\' sake. Amen.',
  evening:  'Lighten our darkness, we beseech thee, O Lord; and by thy great mercy defend us from all perils and dangers of this night; for the love of thy only Son, our Saviour Jesus Christ. Amen.',
  compline: 'Visit, we beseech thee, O Lord, this dwelling, and drive far from it all the snares of the enemy; let thy holy angels dwell herein to preserve us in peace; and may thy blessing be upon us evermore; through Jesus Christ our Lord. Amen.',
};

// ─────────────────────────────────────────────────────────────
// Lectionary — sample Year B Proper readings (full text excerpts)
// ─────────────────────────────────────────────────────────────
const LECTIONARY_FULL = {
  first: {
    citation: '2 Kings 5 : 1—14',
    title: 'The healing of Naaman',
    body: [
      'Now Naaman, commander of the army of the king of Aram, was a great man and in high favor with his master, because by him the Lord had given victory to Aram. The man, though a mighty warrior, suffered from leprosy.',
      'Meanwhile the Arameans on one of their raids had taken a young girl captive from the land of Israel, and she served Naaman’s wife. She said to her mistress, “If only my lord were with the prophet who is in Samaria! He would cure him of his leprosy.”',
      'So Naaman went with his horses and chariots, and halted at the entrance of Elisha’s house. Elisha sent a messenger to him, saying, “Go, wash in the Jordan seven times, and your flesh shall be restored and you shall be clean.”',
      'So he went down and immersed himself seven times in the Jordan, according to the word of the man of God; his flesh was restored like the flesh of a young boy, and he was clean.',
    ],
  },
  psalm: {
    citation: 'Psalm 30',
    title: 'Exaltabo te, Domine',
    body: [
      'I will exalt you, O Lord, for you have lifted me up · and have not let my enemies triumph over me.',
      'O Lord my God, I cried out to you, · and you restored me to health.',
      'You brought me up, O Lord, from the dead; · you restored my life as I was going down to the grave.',
      'Sing to the Lord, you servants of his; · give thanks for the remembrance of his holiness.',
      'Weeping may spend the night, · but joy comes in the morning.',
    ],
  },
  epistle: {
    citation: 'Galatians 6 : 7—16',
    title: 'Bear one another’s burdens',
    body: [
      'Do not be deceived; God is not mocked, for you reap whatever you sow. Those who sow to their own flesh will from the flesh reap corruption; but those who sow to the Spirit will from the Spirit reap eternal life.',
      'So let us not grow weary in doing what is right, for we will reap at harvest time, if we do not give up. So then, whenever we have an opportunity, let us work for the good of all, and especially for those of the family of faith.',
      'May I never boast of anything except the cross of our Lord Jesus Christ, by which the world has been crucified to me, and I to the world. Peace be upon all who follow this rule.',
    ],
  },
  gospel: {
    citation: 'St. Luke 10 : 1—11',
    title: 'The sending of the seventy',
    body: [
      'After this the Lord appointed seventy others and sent them on ahead of him in pairs to every town and place where he himself intended to go.',
      'He said to them, “The harvest is plentiful, but the laborers are few; therefore ask the Lord of the harvest to send out laborers into his harvest. Go on your way. See, I am sending you out like lambs into the midst of wolves.”',
      '“Carry no purse, no bag, no sandals; and greet no one on the road. Whatever house you enter, first say, ‘Peace to this house!’”',
      '“Whenever you enter a town and its people welcome you, eat what is set before you; cure the sick who are there, and say to them, ‘The kingdom of God has come near to you.’”',
    ],
  },
};

Object.assign(window, {
  easterDate, detectSeason, saintToday, OFFICES, nextOffice, currentOffice, OFFICE_CONTENT, LECTIONARY_FULL,
  rclYear, sundaysAfterPentecost, getRCLToday, RCL_SUNDAYS, getNextSundayDate,
  COLLECTS, getCollect,
});

// ─────────────────────────────────────────────────────────────
// Revised Common Lectionary — Sunday-by-Sunday feed
// ─────────────────────────────────────────────────────────────

// Returns 'A', 'B', or 'C' for the lectionary year.
// New cycle starts on the First Sunday of Advent.
// Year A = years where (year+2) % 3 === 0  (e.g. 2025-26 is C; 2026-27 is A)
function rclYear(date = new Date()) {
  let y = date.getFullYear();
  // First Sunday of Advent for THIS calendar year
  const adv = firstSundayAdvent(y);
  // If we're past Advent 1, we're in the cycle that BEGINS this year (next civil year's Year)
  const civilYear = date >= adv ? y + 1 : y;
  const r = civilYear % 3;
  return r === 1 ? 'A' : r === 2 ? 'B' : 'C';
}

function firstSundayAdvent(year) {
  // Sunday on or before Dec 3 (i.e. closest Sunday that is ≥ Nov 27 and ≤ Dec 3)
  const xmas = new Date(year, 11, 25); // Dec 25
  const f = new Date(xmas);
  f.setDate(xmas.getDate() - xmas.getDay() - 21);
  return f;
}

// Returns the boundaries of every liturgical season in the current liturgical
// year, each expressed as a fraction (0-1) of the year that starts at Advent 1.
// Used by the YearWheel diagram so arcs reflect actual season dates instead of
// fixed calendar guesses.
function getLiturgicalSeasons(date = new Date()) {
  const yY = date.getFullYear();
  const advThis = firstSundayAdvent(yY);
  const startCal = (date >= advThis) ? advThis : firstSundayAdvent(yY - 1);
  const startYear = startCal.getFullYear();
  const nextStart = firstSundayAdvent(startYear + 1);
  const totalDays = (nextStart - startCal) / 86400000;
  const frac = (d) => Math.max(0, Math.min(1, (d - startCal) / 86400000 / totalDays));

  const christmas = new Date(startYear, 11, 25);     // Dec 25
  const epiphany  = new Date(startYear + 1, 0, 6);   // Jan 6
  const easter    = easterDate(startYear + 1);
  const ashWed    = addDays(easter, -46);
  const pentecost = addDays(easter, 49);
  const trinity   = addDays(pentecost, 7);
  const reignSun  = addDays(nextStart, -7);

  return {
    advent:    { from: 0,                to: frac(christmas) },
    christmas: { from: frac(christmas),  to: frac(epiphany) },
    epiphany:  { from: frac(epiphany),   to: frac(ashWed) },
    lent:      { from: frac(ashWed),     to: frac(easter) },
    // Easter Day through Pentecost Eve
    easter:    { from: frac(easter),     to: frac(pentecost) },
    // Pentecost Day itself — a 7-day wedge so it's visible on the wheel.
    // Liturgically red, the only red day in the year apart from feasts of martyrs.
    pentecostDay: { from: frac(pentecost), to: frac(addDays(pentecost, 7)) },
    // Long Season after Pentecost — from the week after Pentecost to Reign of Christ Eve.
    pentecost: { from: frac(addDays(pentecost, 7)), to: frac(reignSun) },
    reign:     { from: frac(reignSun),   to: 1 },
    today:     frac(date),
    startYear: startYear,
    endYear:   startYear + 1,
  };
}

// Given a Sunday date, return the next Sunday Date
function getNextSundayDate(from = new Date()) {
  const d = new Date(from);
  const day = d.getDay();
  const add = day === 0 ? 7 : 7 - day;
  d.setDate(d.getDate() + add);
  return d;
}

// Approximate "Proper N" (Sundays after Pentecost / Ordinary Time)
// Used for the long stretch from Trinity Sunday to Christ the King.
function sundaysAfterPentecost(date) {
  const easter = easterDate(date.getFullYear());
  const pentecost = addDays(easter, 49);
  const trinity = addDays(pentecost, 7);
  if (date < trinity) return 0;
  const diff = Math.floor((date - trinity) / (7 * 86400000));
  return diff + 1;
}

// ── A condensed RCL — the Sundays we expect to surface in-app ─
// Each key is a liturgical-Sunday id. Values give Year A/B/C tracks.
// Citations are real RCL appointments. (We supply Track 2 / Continuous in the
// few places RCL forks; this is appropriate for a parish app.)
const RCL_SUNDAYS = {
  // ── Advent ─────────────────────────────────────────
  advent1:   { name: 'First Sunday of Advent',        season: 'Advent',
    A: { first: 'Isaiah 2 : 1—5',     psalm: 'Psalm 122',     epistle: 'Romans 13 : 11—14',         gospel: 'Matthew 24 : 36—44' },
    B: { first: 'Isaiah 64 : 1—9',    psalm: 'Psalm 80 : 1—7, 17—19', epistle: '1 Corinthians 1 : 3—9', gospel: 'Mark 13 : 24—37' },
    C: { first: 'Jeremiah 33 : 14—16', psalm: 'Psalm 25 : 1—10', epistle: '1 Thessalonians 3 : 9—13', gospel: 'Luke 21 : 25—36' },
  },
  advent2:   { name: 'Second Sunday of Advent',       season: 'Advent',
    A: { first: 'Isaiah 11 : 1—10',   psalm: 'Psalm 72 : 1—7, 18—19', epistle: 'Romans 15 : 4—13',  gospel: 'Matthew 3 : 1—12' },
    B: { first: 'Isaiah 40 : 1—11',   psalm: 'Psalm 85 : 1—2, 8—13',  epistle: '2 Peter 3 : 8—15a', gospel: 'Mark 1 : 1—8' },
    C: { first: 'Malachi 3 : 1—4',    psalm: 'Luke 1 : 68—79',         epistle: 'Philippians 1 : 3—11', gospel: 'Luke 3 : 1—6' },
  },
  advent3:   { name: 'Third Sunday of Advent · Gaudete', season: 'Advent',
    A: { first: 'Isaiah 35 : 1—10',   psalm: 'Psalm 146 : 5—10',      epistle: 'James 5 : 7—10',     gospel: 'Matthew 11 : 2—11' },
    B: { first: 'Isaiah 61 : 1—4, 8—11', psalm: 'Psalm 126',           epistle: '1 Thessalonians 5 : 16—24', gospel: 'John 1 : 6—8, 19—28' },
    C: { first: 'Zephaniah 3 : 14—20', psalm: 'Isaiah 12 : 2—6',       epistle: 'Philippians 4 : 4—7', gospel: 'Luke 3 : 7—18' },
  },
  advent4:   { name: 'Fourth Sunday of Advent',       season: 'Advent',
    A: { first: 'Isaiah 7 : 10—16',   psalm: 'Psalm 80 : 1—7, 17—19', epistle: 'Romans 1 : 1—7',     gospel: 'Matthew 1 : 18—25' },
    B: { first: '2 Samuel 7 : 1—11, 16', psalm: 'Luke 1 : 47—55',     epistle: 'Romans 16 : 25—27',  gospel: 'Luke 1 : 26—38' },
    C: { first: 'Micah 5 : 2—5a',     psalm: 'Luke 1 : 47—55',         epistle: 'Hebrews 10 : 5—10',  gospel: 'Luke 1 : 39—45' },
  },
  // ── Christmas / Epiphany ───────────────────────────
  christmas: { name: 'The Nativity of Our Lord',      season: 'Christmas',
    A: { first: 'Isaiah 9 : 2—7', psalm: 'Psalm 96',  epistle: 'Titus 2 : 11—14', gospel: 'Luke 2 : 1—20' },
    B: { first: 'Isaiah 9 : 2—7', psalm: 'Psalm 96',  epistle: 'Titus 2 : 11—14', gospel: 'Luke 2 : 1—20' },
    C: { first: 'Isaiah 9 : 2—7', psalm: 'Psalm 96',  epistle: 'Titus 2 : 11—14', gospel: 'Luke 2 : 1—20' },
  },
  epiphany:  { name: 'The Epiphany of Our Lord',      season: 'Epiphany',
    A: { first: 'Isaiah 60 : 1—6', psalm: 'Psalm 72 : 1—7, 10—14', epistle: 'Ephesians 3 : 1—12', gospel: 'Matthew 2 : 1—12' },
    B: { first: 'Isaiah 60 : 1—6', psalm: 'Psalm 72 : 1—7, 10—14', epistle: 'Ephesians 3 : 1—12', gospel: 'Matthew 2 : 1—12' },
    C: { first: 'Isaiah 60 : 1—6', psalm: 'Psalm 72 : 1—7, 10—14', epistle: 'Ephesians 3 : 1—12', gospel: 'Matthew 2 : 1—12' },
  },
  baptism:   { name: 'The Baptism of Our Lord',       season: 'Epiphany',
    A: { first: 'Isaiah 42 : 1—9',   psalm: 'Psalm 29', epistle: 'Acts 10 : 34—43', gospel: 'Matthew 3 : 13—17' },
    B: { first: 'Genesis 1 : 1—5',   psalm: 'Psalm 29', epistle: 'Acts 19 : 1—7',   gospel: 'Mark 1 : 4—11' },
    C: { first: 'Isaiah 43 : 1—7',   psalm: 'Psalm 29', epistle: 'Acts 8 : 14—17',  gospel: 'Luke 3 : 15—17, 21—22' },
  },
  transfig:  { name: 'The Transfiguration of Our Lord', season: 'Epiphany',
    A: { first: 'Exodus 24 : 12—18', psalm: 'Psalm 2',  epistle: '2 Peter 1 : 16—21', gospel: 'Matthew 17 : 1—9' },
    B: { first: '2 Kings 2 : 1—12',  psalm: 'Psalm 50 : 1—6', epistle: '2 Corinthians 4 : 3—6', gospel: 'Mark 9 : 2—9' },
    C: { first: 'Exodus 34 : 29—35', psalm: 'Psalm 99', epistle: '2 Corinthians 3 : 12 — 4 : 2', gospel: 'Luke 9 : 28—43a' },
  },
  // ── Lent ───────────────────────────────────────────
  ashwed:    { name: 'Ash Wednesday',                 season: 'Lent',
    A: { first: 'Joel 2 : 1—2, 12—17', psalm: 'Psalm 51 : 1—17', epistle: '2 Corinthians 5 : 20b — 6 : 10', gospel: 'Matthew 6 : 1—6, 16—21' },
    B: { first: 'Joel 2 : 1—2, 12—17', psalm: 'Psalm 51 : 1—17', epistle: '2 Corinthians 5 : 20b — 6 : 10', gospel: 'Matthew 6 : 1—6, 16—21' },
    C: { first: 'Joel 2 : 1—2, 12—17', psalm: 'Psalm 51 : 1—17', epistle: '2 Corinthians 5 : 20b — 6 : 10', gospel: 'Matthew 6 : 1—6, 16—21' },
  },
  lent1:     { name: 'First Sunday in Lent',          season: 'Lent',
    A: { first: 'Genesis 2 : 15—17, 3 : 1—7', psalm: 'Psalm 32', epistle: 'Romans 5 : 12—19', gospel: 'Matthew 4 : 1—11' },
    B: { first: 'Genesis 9 : 8—17', psalm: 'Psalm 25 : 1—10', epistle: '1 Peter 3 : 18—22', gospel: 'Mark 1 : 9—15' },
    C: { first: 'Deuteronomy 26 : 1—11', psalm: 'Psalm 91 : 1—2, 9—16', epistle: 'Romans 10 : 8b—13', gospel: 'Luke 4 : 1—13' },
  },
  lent2:     { name: 'Second Sunday in Lent',         season: 'Lent',
    A: { first: 'Genesis 12 : 1—4a', psalm: 'Psalm 121',     epistle: 'Romans 4 : 1—5, 13—17', gospel: 'John 3 : 1—17' },
    B: { first: 'Genesis 17 : 1—7, 15—16', psalm: 'Psalm 22 : 23—31', epistle: 'Romans 4 : 13—25', gospel: 'Mark 8 : 31—38' },
    C: { first: 'Genesis 15 : 1—12, 17—18', psalm: 'Psalm 27', epistle: 'Philippians 3 : 17 — 4 : 1', gospel: 'Luke 13 : 31—35' },
  },
  lent3:     { name: 'Third Sunday in Lent',          season: 'Lent',
    A: { first: 'Exodus 17 : 1—7',  psalm: 'Psalm 95',  epistle: 'Romans 5 : 1—11',     gospel: 'John 4 : 5—42' },
    B: { first: 'Exodus 20 : 1—17', psalm: 'Psalm 19',  epistle: '1 Corinthians 1 : 18—25', gospel: 'John 2 : 13—22' },
    C: { first: 'Isaiah 55 : 1—9',  psalm: 'Psalm 63 : 1—8', epistle: '1 Corinthians 10 : 1—13', gospel: 'Luke 13 : 1—9' },
  },
  lent4:     { name: 'Fourth Sunday in Lent · Laetare', season: 'Lent',
    A: { first: '1 Samuel 16 : 1—13', psalm: 'Psalm 23', epistle: 'Ephesians 5 : 8—14', gospel: 'John 9 : 1—41' },
    B: { first: 'Numbers 21 : 4—9',   psalm: 'Psalm 107 : 1—3, 17—22', epistle: 'Ephesians 2 : 1—10', gospel: 'John 3 : 14—21' },
    C: { first: 'Joshua 5 : 9—12',    psalm: 'Psalm 32', epistle: '2 Corinthians 5 : 16—21', gospel: 'Luke 15 : 1—3, 11b—32' },
  },
  lent5:     { name: 'Fifth Sunday in Lent',          season: 'Lent',
    A: { first: 'Ezekiel 37 : 1—14',  psalm: 'Psalm 130', epistle: 'Romans 8 : 6—11', gospel: 'John 11 : 1—45' },
    B: { first: 'Jeremiah 31 : 31—34', psalm: 'Psalm 51 : 1—12', epistle: 'Hebrews 5 : 5—10', gospel: 'John 12 : 20—33' },
    C: { first: 'Isaiah 43 : 16—21',  psalm: 'Psalm 126', epistle: 'Philippians 3 : 4b—14', gospel: 'John 12 : 1—8' },
  },
  palm:      { name: 'Palm Sunday',                   season: 'Lent',
    A: { first: 'Isaiah 50 : 4—9a', psalm: 'Psalm 31 : 9—16', epistle: 'Philippians 2 : 5—11', gospel: 'Matthew 26 : 14 — 27 : 66' },
    B: { first: 'Isaiah 50 : 4—9a', psalm: 'Psalm 31 : 9—16', epistle: 'Philippians 2 : 5—11', gospel: 'Mark 14 : 1 — 15 : 47' },
    C: { first: 'Isaiah 50 : 4—9a', psalm: 'Psalm 31 : 9—16', epistle: 'Philippians 2 : 5—11', gospel: 'Luke 22 : 14 — 23 : 56' },
  },
  goodfri:   { name: 'Good Friday',                   season: 'Holy Week',
    A: { first: 'Isaiah 52 : 13 — 53 : 12', psalm: 'Psalm 22', epistle: 'Hebrews 10 : 16—25', gospel: 'John 18 : 1 — 19 : 42' },
    B: { first: 'Isaiah 52 : 13 — 53 : 12', psalm: 'Psalm 22', epistle: 'Hebrews 10 : 16—25', gospel: 'John 18 : 1 — 19 : 42' },
    C: { first: 'Isaiah 52 : 13 — 53 : 12', psalm: 'Psalm 22', epistle: 'Hebrews 10 : 16—25', gospel: 'John 18 : 1 — 19 : 42' },
  },
  easter:    { name: 'Easter Sunday',                 season: 'Easter',
    A: { first: 'Acts 10 : 34—43',   psalm: 'Psalm 118 : 1—2, 14—24', epistle: 'Colossians 3 : 1—4', gospel: 'John 20 : 1—18' },
    B: { first: 'Acts 10 : 34—43',   psalm: 'Psalm 118 : 1—2, 14—24', epistle: '1 Corinthians 15 : 1—11', gospel: 'Mark 16 : 1—8' },
    C: { first: 'Acts 10 : 34—43',   psalm: 'Psalm 118 : 1—2, 14—24', epistle: '1 Corinthians 15 : 19—26', gospel: 'John 20 : 1—18' },
  },
  easter2:   { name: 'Second Sunday of Easter',       season: 'Easter',
    A: { first: 'Acts 2 : 14a, 22—32', psalm: 'Psalm 16', epistle: '1 Peter 1 : 3—9', gospel: 'John 20 : 19—31' },
    B: { first: 'Acts 4 : 32—35',     psalm: 'Psalm 133', epistle: '1 John 1 : 1 — 2 : 2', gospel: 'John 20 : 19—31' },
    C: { first: 'Acts 5 : 27—32',     psalm: 'Psalm 118 : 14—29', epistle: 'Revelation 1 : 4—8', gospel: 'John 20 : 19—31' },
  },
  easter3:   { name: 'Third Sunday of Easter',        season: 'Easter',
    A: { first: 'Acts 2 : 14a, 36—41', psalm: 'Psalm 116 : 1—4, 12—19', epistle: '1 Peter 1 : 17—23', gospel: 'Luke 24 : 13—35' },
    B: { first: 'Acts 3 : 12—19',      psalm: 'Psalm 4',                epistle: '1 John 3 : 1—7',     gospel: 'Luke 24 : 36b—48' },
    C: { first: 'Acts 9 : 1—6 (7—20)', psalm: 'Psalm 30',               epistle: 'Revelation 5 : 11—14', gospel: 'John 21 : 1—19' },
  },
  easter4:   { name: 'Fourth Sunday of Easter · Good Shepherd', season: 'Easter',
    A: { first: 'Acts 2 : 42—47',  psalm: 'Psalm 23', epistle: '1 Peter 2 : 19—25',  gospel: 'John 10 : 1—10' },
    B: { first: 'Acts 4 : 5—12',   psalm: 'Psalm 23', epistle: '1 John 3 : 16—24',   gospel: 'John 10 : 11—18' },
    C: { first: 'Acts 9 : 36—43',  psalm: 'Psalm 23', epistle: 'Revelation 7 : 9—17', gospel: 'John 10 : 22—30' },
  },
  easter5:   { name: 'Fifth Sunday of Easter',        season: 'Easter',
    A: { first: 'Acts 7 : 55—60',  psalm: 'Psalm 31 : 1—5, 15—16', epistle: '1 Peter 2 : 2—10', gospel: 'John 14 : 1—14',
         keyVerse: { text: 'I am the way, the truth, and the life.', cite: 'John 14 : 6' } },
    B: { first: 'Acts 8 : 26—40',  psalm: 'Psalm 22 : 25—31',       epistle: '1 John 4 : 7—21',  gospel: 'John 15 : 1—8',
         keyVerse: { text: 'I am the vine, you are the branches.', cite: 'John 15 : 5' } },
    C: { first: 'Acts 11 : 1—18',  psalm: 'Psalm 148',              epistle: 'Revelation 21 : 1—6', gospel: 'John 13 : 31—35',
         keyVerse: { text: 'By this everyone will know that you are my disciples, if you have love for one another.', cite: 'John 13 : 35' } },
  },
  easter6:   { name: 'Sixth Sunday of Easter',        season: 'Easter',
    A: { first: 'Acts 17 : 22—31', psalm: 'Psalm 66 : 8—20', epistle: '1 Peter 3 : 13—22', gospel: 'John 14 : 15—21',
         keyVerse: { text: 'I will not leave you orphaned; I am coming to you.', cite: 'John 14 : 18' } },
    B: { first: 'Acts 10 : 44—48', psalm: 'Psalm 98',         epistle: '1 John 5 : 1—6',    gospel: 'John 15 : 9—17',
         keyVerse: { text: 'You did not choose me, but I chose you.', cite: 'John 15 : 16' } },
    C: { first: 'Acts 16 : 9—15',  psalm: 'Psalm 67',         epistle: 'Revelation 21 : 10, 22 — 22 : 5', gospel: 'John 14 : 23—29',
         keyVerse: { text: 'Peace I leave with you; my peace I give to you.', cite: 'John 14 : 27' } },
  },
  easter7:   { name: 'Seventh Sunday of Easter',      season: 'Easter',
    A: { first: 'Acts 1 : 6—14',           psalm: 'Psalm 68 : 1—10, 32—35', epistle: '1 Peter 4 : 12—14, 5 : 6—11', gospel: 'John 17 : 1—11',
         keyVerse: { text: 'May they all be one, as you, Father, are in me and I am in you.', cite: 'John 17 : 21' } },
    B: { first: 'Acts 1 : 15—17, 21—26',   psalm: 'Psalm 1',                 epistle: '1 John 5 : 9—13',              gospel: 'John 17 : 6—19',
         keyVerse: { text: 'Sanctify them in the truth; your word is truth.', cite: 'John 17 : 17' } },
    C: { first: 'Acts 16 : 16—34',         psalm: 'Psalm 97',                epistle: 'Revelation 22 : 12—14, 16—17, 20—21', gospel: 'John 17 : 20—26',
         keyVerse: { text: 'I am the Alpha and the Omega, the first and the last, the beginning and the end.', cite: 'Revelation 22 : 13' } },
  },
  pentecost: { name: 'The Day of Pentecost',          season: 'Pentecost',
    A: { first: 'Acts 2 : 1—21',     psalm: 'Psalm 104 : 24—34, 35b', epistle: '1 Corinthians 12 : 3b—13', gospel: 'John 20 : 19—23' },
    B: { first: 'Acts 2 : 1—21',     psalm: 'Psalm 104 : 24—34, 35b', epistle: 'Romans 8 : 22—27',         gospel: 'John 15 : 26—27, 16 : 4b—15' },
    C: { first: 'Acts 2 : 1—21',     psalm: 'Psalm 104 : 24—34, 35b', epistle: 'Romans 8 : 14—17',         gospel: 'John 14 : 8—17, 25—27' },
  },
  trinity:   { name: 'Trinity Sunday',                season: 'Ordinary',
    A: { first: 'Genesis 1 : 1 — 2 : 4a', psalm: 'Psalm 8', epistle: '2 Corinthians 13 : 11—13', gospel: 'Matthew 28 : 16—20' },
    B: { first: 'Isaiah 6 : 1—8',         psalm: 'Psalm 29', epistle: 'Romans 8 : 12—17',        gospel: 'John 3 : 1—17' },
    C: { first: 'Proverbs 8 : 1—4, 22—31', psalm: 'Psalm 8', epistle: 'Romans 5 : 1—5',          gospel: 'John 16 : 12—15' },
  },
  reign:     { name: 'Reign of Christ · Christ the King', season: 'Ordinary',
    A: { first: 'Ezekiel 34 : 11—16, 20—24', psalm: 'Psalm 100', epistle: 'Ephesians 1 : 15—23', gospel: 'Matthew 25 : 31—46' },
    B: { first: '2 Samuel 23 : 1—7',          psalm: 'Psalm 132 : 1—12', epistle: 'Revelation 1 : 4b—8', gospel: 'John 18 : 33—37' },
    C: { first: 'Jeremiah 23 : 1—6',          psalm: 'Luke 1 : 68—79',   epistle: 'Colossians 1 : 11—20', gospel: 'Luke 23 : 33—43' },
  },
  // Generic Ordinary Time fallback
  ordinary:  { name: 'Sunday after Pentecost',         season: 'Ordinary',
    A: { first: '1 Kings 19 : 9—18',  psalm: 'Psalm 85 : 8—13',  epistle: 'Romans 10 : 5—15',  gospel: 'Matthew 14 : 22—33' },
    B: { first: '2 Kings 5 : 1—14',   psalm: 'Psalm 30',         epistle: 'Galatians 6 : 7—16', gospel: 'Luke 10 : 1—11' },
    C: { first: 'Isaiah 1 : 1, 10—20', psalm: 'Psalm 50 : 1—8, 22—23', epistle: 'Hebrews 11 : 1—3, 8—16', gospel: 'Luke 12 : 32—40' },
  },
};

// Today's lectionary id (for arbitrary date) — what Sunday's readings apply?
function rclSundayId(date = new Date()) {
  const y = date.getFullYear();
  const easter = easterDate(y);
  const ashWed = addDays(easter, -46);
  const palmSun = addDays(easter, -7);
  const goodFri = addDays(easter, -2);
  const pentecost = addDays(easter, 49);
  const trinity = addDays(pentecost, 7);
  const adv = firstSundayAdvent(y);
  const sameDay = (a, b) => a.toDateString() === b.toDateString();
  const between = (start, end) => date >= start && date < end;

  // Specific feast days first
  if (sameDay(date, ashWed))    return 'ashwed';
  if (sameDay(date, palmSun))   return 'palm';
  if (sameDay(date, goodFri))   return 'goodfri';
  if (sameDay(date, easter))    return 'easter';
  if (sameDay(date, pentecost)) return 'pentecost';
  if (sameDay(date, trinity))   return 'trinity';
  if (date.getMonth() === 11 && date.getDate() === 25) return 'christmas';
  if (date.getMonth() === 0  && date.getDate() === 6)  return 'epiphany';

  // Lent — Sundays after Ash Wed
  if (between(addDays(ashWed, 1), palmSun)) {
    const w = Math.floor((date - addDays(ashWed, 4)) / (7 * 86400000));
    return ['lent1','lent2','lent3','lent4','lent5'][Math.min(4, Math.max(0, w))];
  }
  // Eastertide — distinguish Easter 2 through Easter 7
  if (between(addDays(easter, 1), pentecost)) {
    const w = Math.floor((date - easter) / (7 * 86400000));
    return ['easter','easter2','easter3','easter4','easter5','easter6','easter7'][Math.min(6, Math.max(0, w))];
  }
  // Advent
  const adventEnd = new Date(y, 11, 25);
  if (between(adv, adventEnd)) {
    const w = Math.floor((date - adv) / (7 * 86400000));
    return ['advent1','advent2','advent3','advent4'][Math.min(3, Math.max(0, w))];
  }
  // Last Sunday before Advent — Reign of Christ
  if (between(addDays(adv, -7), adv)) return 'reign';
  // Default
  return 'ordinary';
}

// ─────────────────────────────────────────────────────────────
// COLLECTS — one for each liturgical Sunday + ordinary Propers
// Drawn from the BCP / UMC Book of Worship tradition.
// ─────────────────────────────────────────────────────────────
const COLLECTS = {
  advent1:    'Almighty God, give us grace to cast away the works of darkness and to put on the armour of light, now in the time of this mortal life in which thy Son Jesus Christ came to visit us in great humility; that in the last day, when he shall come again in his glorious majesty to judge both the quick and the dead, we may rise to the life immortal; through him who liveth and reigneth with thee and the Holy Spirit, one God, now and ever.',
  advent2:    'Merciful God, who sent thy messengers the prophets to preach repentance and prepare the way for our salvation: Give us grace to heed their warnings and forsake our sins, that we may greet with joy the coming of Jesus Christ our Redeemer; who liveth and reigneth with thee and the Holy Spirit, one God, now and for ever.',
  advent3:    'Stir up thy power, O Lord, and with great might come among us; and, because we are sorely hindered by our sins, let thy bountiful grace and mercy speedily help and deliver us; through Jesus Christ our Lord, to whom, with thee and the Holy Spirit, be honour and glory, world without end.',
  advent4:    'Purify our conscience, Almighty God, by thy daily visitation, that thy Son Jesus Christ, at his coming, may find in us a mansion prepared for himself; who liveth and reigneth with thee and the Holy Spirit, one God, now and for ever.',
  christmas:  'O God, who hast caused this holy night to shine with the brightness of the true Light: Grant that we, who have known the mystery of that Light on earth, may also enjoy him perfectly in heaven; through Jesus Christ our Lord, who liveth and reigneth with thee in the unity of the Holy Spirit, one God, now and for ever.',
  epiphany:   'O God, who by the leading of a star didst manifest thy only-begotten Son to the peoples of the earth: Lead us, who know thee now by faith, to thy presence, where we may behold thy glory face to face; through Jesus Christ our Lord, who liveth and reigneth with thee and the Holy Spirit, one God, now and for ever.',
  baptism:    'Father in heaven, who at the baptism of Jesus in the river Jordan didst proclaim him thy beloved Son and anoint him with the Holy Spirit: Grant that all who are baptized into his name may keep the covenant they have made, and boldly confess him as Lord and Saviour; who liveth and reigneth with thee and the Holy Spirit, one God, in glory everlasting.',
  transfig:   'O God, who before the passion of thy only-begotten Son didst reveal his glory upon the holy mount: Grant unto us that, beholding by faith the light of his countenance, we may be strengthened to bear our cross and be changed into his likeness from glory to glory; through the same Jesus Christ our Lord.',
  ashwed:     'Almighty and everlasting God, who hatest nothing that thou hast made and dost forgive the sins of all those who are penitent: Create and make in us new and contrite hearts, that we, worthily lamenting our sins and acknowledging our wretchedness, may obtain of thee, the God of all mercy, perfect remission and forgiveness; through Jesus Christ our Lord.',
  lent1:      'Almighty God, whose blessed Son was led by the Spirit to be tempted of Satan: Come quickly to help us who are assaulted by many temptations; and, as thou knowest the weakness of every one of us, let each one find thee mighty to save; through Jesus Christ thy Son our Lord.',
  lent2:      'O God, whose glory it is always to have mercy: Be gracious to all who have gone astray from thy ways, and bring them again with penitent hearts and steadfast faith to embrace and hold fast the unchangeable truth of thy Word, Jesus Christ thy Son.',
  lent3:      'Almighty God, you know that we have no power in ourselves to help ourselves: Keep us both outwardly in our bodies and inwardly in our souls, that we may be defended from all adversities which may happen to the body, and from all evil thoughts which may assault and hurt the soul; through Jesus Christ our Lord.',
  lent4:      'Gracious Father, whose blessed Son Jesus Christ came down from heaven to be the true bread which giveth life to the world: Evermore give us this bread, that he may live in us, and we in him; who liveth and reigneth with thee and the Holy Spirit, one God, now and for ever.',
  lent5:      'Almighty God, you alone can bring into order the unruly wills and affections of sinners: Grant your people grace to love what you command and desire what you promise; that, among the swift and varied changes of the world, our hearts may surely there be fixed where true joys are to be found; through Jesus Christ our Lord.',
  palm:       'Almighty and everliving God, in tender love towards the human race thou didst send thy Son our Saviour Jesus Christ to take upon him our flesh, and to suffer death upon the cross: Grant that we may walk in the way of his suffering, and also share in his resurrection; who liveth and reigneth with thee and the Holy Spirit, one God, for ever and ever.',
  goodfri:    'Almighty God, we beseech thee graciously to behold this thy family, for which our Lord Jesus Christ was contented to be betrayed, and given up into the hands of sinners, and to suffer death upon the cross; who now liveth and reigneth with thee and the Holy Spirit, one God, for ever and ever.',
  easter:     'Almighty God, who through thine only-begotten Son Jesus Christ hast overcome death and opened unto us the gate of everlasting life: Grant that we, who celebrate with joy the day of the Lord\'s resurrection, may be raised from the death of sin by thy life-giving Spirit; through Jesus Christ our Lord, who liveth and reigneth with thee and the Holy Spirit, one God, now and for ever.',
  easter2:    'Almighty and everlasting God, who in the Paschal mystery hast established the new covenant of reconciliation: Grant that all who have been reborn into the fellowship of Christ\'s Body may show forth in their lives what they profess by their faith; through Jesus Christ our Lord.',
  easter3:    'O God, whose blessed Son did manifest himself to his disciples in the breaking of bread: Open the eyes of our faith, that we may behold him in all his redeeming work; who liveth and reigneth with thee and the Holy Spirit, one God, now and for ever.',
  easter4:    'O God, whose Son Jesus is the good shepherd of thy people: Grant that, when we hear his voice, we may know him who calleth us each by name, and follow where he doth lead; who liveth and reigneth with thee and the Holy Spirit, one God, for ever and ever.',
  easter5:    'Almighty God, whom truly to know is everlasting life: Grant us so perfectly to know thy Son Jesus Christ to be the way, the truth, and the life, that we may steadfastly follow his steps in the way that leadeth to eternal life; through the same Jesus Christ our Lord.',
  easter6:    'O God, who hast prepared for those who love thee such good things as pass our understanding: Pour into our hearts such love toward thee, that we, loving thee in all things and above all things, may obtain thy promises, which exceed all that we can desire; through Jesus Christ our Lord.',
  ascension:  'Almighty God, whose blessed Son our Saviour Jesus Christ ascended far above all heavens that he might fill all things: Mercifully give us faith to perceive that, according to his promise, he abideth with his Church on earth, even to the end of the ages; who liveth and reigneth with thee and the Holy Spirit, one God, in glory everlasting.',
  easter7:    'O God, the King of glory, who hast exalted thine only Son Jesus Christ with great triumph unto thy kingdom in heaven: We beseech thee, leave us not comfortless, but send to us thine Holy Spirit to strengthen us, and exalt us unto the same place whither our Saviour Christ is gone before; who liveth and reigneth with thee and the Holy Spirit, one God, world without end.',
  pentecost:  'Almighty God, on this day thou didst open the way of eternal life to every race and nation by the promised gift of thy Holy Spirit: Shed abroad this gift throughout the world by the preaching of the Gospel, that it may reach to the ends of the earth; through Jesus Christ our Lord, who liveth and reigneth with thee, in the unity of the same Spirit, one God, for ever and ever.',
  trinity:    'Almighty and everlasting God, who hast given unto us thy servants grace, by the confession of a true faith, to acknowledge the glory of the eternal Trinity, and in the power of the divine Majesty to worship the Unity: We beseech thee that thou wouldest keep us steadfast in this faith and worship, and bring us at last to see thee in thy one and eternal glory, O Father; who with the Son and the Holy Spirit livest and reignest, one God, for ever and ever.',
  reign:      'Almighty and everlasting God, whose will it is to restore all things in thy well-beloved Son, the King of kings and Lord of lords: Mercifully grant that the peoples of the earth, divided and enslaved by sin, may be freed and brought together under his most gracious rule; who liveth and reigneth with thee and the Holy Spirit, one God, now and for ever.',

  // Ordinary Time Propers — rotated by week-of-year as a fallback
  proper4:    'O God, from whom all good doth come: Grant that by thy holy inspiration we may think those things that are right, and by thy merciful guiding may perform the same; through Jesus Christ our Lord.',
  proper5:    'O Lord, from whom no secrets are hid: Cleanse the thoughts of our hearts by the inspiration of thy Holy Spirit, that we may perfectly love thee, and worthily magnify thy holy name; through Christ our Lord.',
  proper6:    'Keep, O Lord, thy household the Church in thy steadfast faith and love, that, through thy grace, we may proclaim thy truth with boldness and minister thy justice with compassion; for the sake of our Saviour Jesus Christ, who liveth and reigneth with thee and the Holy Spirit, one God, now and for ever.',
  proper7:    'O Lord, make us to have a perpetual fear and love of thy holy name, for thou never failest to help and govern those whom thou hast set upon the sure foundation of thy loving-kindness; through Jesus Christ our Lord.',
  proper8:    'Almighty God, thou hast built thy Church upon the foundation of the apostles and prophets, Jesus Christ himself being the head corner-stone: Grant us so to be joined together in unity of spirit by their teaching, that we may be made an holy temple acceptable unto thee; through Jesus Christ our Lord.',
  proper9:    'O God, who hast taught us to keep all thy commandments by loving thee and our neighbour: Grant us the grace of thy Holy Spirit, that we may be devoted to thee with our whole heart, and united to one another with pure affection; through Jesus Christ our Lord.',
  proper10:   'O Lord, mercifully receive the prayers of thy people who call upon thee, and grant that they may both perceive and know what things they ought to do, and also may have grace and power faithfully to fulfil them; through Jesus Christ our Lord.',
  proper11:   'Almighty God, the fountain of all wisdom, who knowest our necessities before we ask and our ignorance in asking: Have compassion on our weakness, and mercifully give us those things which for our unworthiness we dare not, and for our blindness we cannot ask; through the worthiness of thy Son Jesus Christ our Lord.',
  proper12:   'O God, the protector of all that trust in thee, without whom nothing is strong, nothing is holy: Increase and multiply upon us thy mercy; that, thou being our ruler and guide, we may so pass through things temporal that we finally lose not the things eternal; through Jesus Christ our Lord.',
  proper13:   'Let thy continual mercy, O Lord, cleanse and defend thy Church; and, because it cannot continue in safety without thy succour, preserve it evermore by thy help and goodness; through Jesus Christ our Lord.',
  proper14:   'Grant to us, O Lord, we beseech thee, the spirit to think and do always those things that are right, that we, who cannot exist without thee, may by thee be enabled to live according to thy will; through Jesus Christ our Lord.',
  proper15:   'Almighty God, who hast given thy only Son to be unto us both a sacrifice for sin and also an example of godly life: Give us grace that we may always most thankfully receive that his inestimable benefit, and also daily endeavour ourselves to follow the blessed steps of his most holy life; through the same Jesus Christ thy Son our Lord.',
  proper16:   'Grant, O merciful God, that thy Church, being gathered together in unity by thy Holy Spirit, may shew forth thy power among all peoples, to the glory of thy name; through Jesus Christ our Lord.',
  proper17:   'Lord of all power and might, the author and giver of all good things: Graft in our hearts the love of thy name, increase in us true religion, nourish us with all goodness, and bring forth in us the fruit of good works; through Jesus Christ our Lord.',
  proper18:   'Grant us, O Lord, we pray thee, to trust in thee with all our heart; seeing that, as thou dost alway resist the proud who confide in their own strength, so thou never dost forsake those who make their boast of thy mercy; through Jesus Christ our Lord.',
  proper19:   'O God, because without thee we are not able to please thee, mercifully grant that thy Holy Spirit may in all things direct and rule our hearts; through Jesus Christ our Lord.',
  proper20:   'Grant us, Lord, not to be anxious about earthly things, but to love things heavenly; and even now, while we are placed among things that are passing away, to hold fast to those that shall endure; through Jesus Christ our Lord.',
  proper21:   'O God, thou declarest thy almighty power chiefly in showing mercy and pity: Grant us the fullness of thy grace, that we, running to obtain thy promises, may be made partakers of thy heavenly treasure; through Jesus Christ our Lord.',
  proper22:   'Almighty and everlasting God, who art always more ready to hear than we to pray, and to give more than either we desire or deserve: Pour down upon us the abundance of thy mercy, forgiving us those things whereof our conscience is afraid, and giving us those good things for which we are not worthy to ask; through Jesus Christ our Lord.',
  proper23:   'Lord, we pray that thy grace may always precede and follow us, that we may continually be given to good works; through Jesus Christ our Lord.',
  proper24:   'Almighty and everlasting God, in Christ thou hast revealed thy glory among the nations: Preserve the works of thy mercy, that thy Church throughout the world may persevere with steadfast faith in the confession of thy name; through Jesus Christ our Lord.',
  proper25:   'Almighty and everlasting God, increase in us the gifts of faith, hope, and charity; and, that we may obtain that which thou dost promise, make us to love that which thou dost command; through Jesus Christ our Lord.',
  proper26:   'Almighty and merciful God, of whose only gift it cometh that thy faithful people do unto thee true and laudable service: Grant, we beseech thee, that we may so faithfully serve thee in this life, that we fail not finally to attain thy heavenly promises; through the merits of Jesus Christ our Lord.',
  proper27:   'O God, whose blessed Son came into the world that he might destroy the works of the devil and make us children of God and heirs of eternal life: Grant that, having this hope, we may purify ourselves even as he is pure; that, when he shall appear again with power and great glory, we may be made like unto him in his eternal and glorious kingdom; through the same Jesus Christ our Lord.',
  proper28:   'Blessed Lord, who hast caused all holy Scriptures to be written for our learning: Grant us so to hear them, read, mark, learn, and inwardly digest them, that, by patience and the comfort of thy holy Word, we may embrace and ever hold fast the blessed hope of everlasting life; through Jesus Christ our Lord.',
  proper29:   'Almighty and everlasting God, whose will it is to restore all things in thy well-beloved Son, the King of kings and Lord of lords: Mercifully grant that the peoples of the earth, divided and enslaved by sin, may be freed and brought together under his most gracious rule; who liveth and reigneth with thee and the Holy Spirit, one God, now and for ever.',
};

// Get the collect for a given date — same Sunday id as the readings,
// falling back to a Proper-N rotation through Ordinary Time.
function getCollect(date = new Date()) {
  const id = rclSundayId(date);
  if (COLLECTS[id]) return { id, text: COLLECTS[id], name: (RCL_SUNDAYS[id] && RCL_SUNDAYS[id].name) || '' };
  // Ordinary Time → use week-of-year mod 26 as a Proper rotation
  const start = new Date(date.getFullYear(), 0, 1);
  const week = Math.floor((date - start) / (7 * 24 * 3600 * 1000));
  const propers = ['proper4','proper5','proper6','proper7','proper8','proper9','proper10','proper11','proper12','proper13','proper14','proper15','proper16','proper17','proper18','proper19','proper20','proper21','proper22','proper23','proper24','proper25','proper26','proper27','proper28','proper29'];
  const pid = propers[week % propers.length];
  return { id: pid, text: COLLECTS[pid], name: 'Ordinary Time' };
}

// Public API: returns full readings for today (or any date) in the current RCL year.
function getRCLToday(date = new Date()) {
  const id = rclSundayId(date);
  const yr = rclYear(date);
  const entry = RCL_SUNDAYS[id] || RCL_SUNDAYS.ordinary;
  const readings = entry[yr] || entry.A;
  // Find next Sunday for the date these readings will be used
  const targetDate = (id === 'goodfri' || id === 'ashwed' || id === 'christmas' || id === 'epiphany')
    ? date
    : (date.getDay() === 0 ? date : getNextSundayDate(date));
  return {
    id,
    name: entry.name,
    season: entry.season,
    year: yr,
    date: targetDate,
    readings,
  };
}

// Returns the "key verse" of the upcoming Sunday — the line we surface in the
// hero and on the share-card, tied to that Sunday's lectionary. Falls back to
// a small generic-verse pool when the Sunday entry doesn't have one curated.
function getKeyVerse(date = new Date()) {
  const id = rclSundayId(date);
  const yr = rclYear(date);
  const entry = RCL_SUNDAYS[id];
  if (entry && entry[yr] && entry[yr].keyVerse) {
    return { ...entry[yr].keyVerse, sundayName: entry.name, year: yr };
  }
  // Generic seasonal fallbacks
  const SEASONAL_VERSES = {
    Advent:    { text: 'Comfort, comfort my people, says your God.', cite: 'Isaiah 40 : 1' },
    Christmas: { text: 'For unto us a child is born, unto us a son is given.', cite: 'Isaiah 9 : 6' },
    Epiphany:  { text: 'In the beginning was the Word, and the Word was with God, and the Word was God.', cite: 'John 1 : 1' },
    Lent:      { text: 'Create in me a clean heart, O God, and renew a right spirit within me.', cite: 'Psalm 51 : 10' },
    Easter:    { text: 'I am the resurrection and the life.', cite: 'John 11 : 25' },
    Pentecost: { text: 'The fruit of the Spirit is love, joy, peace, patience, kindness.', cite: 'Galatians 5 : 22' },
    Ordinary:  { text: 'Be still, and know that I am God.', cite: 'Psalm 46 : 10' },
    'Holy Week': { text: 'Father, into your hands I commend my spirit.', cite: 'Luke 23 : 46' },
  };
  const season = (entry && entry.season) || 'Ordinary';
  const fallback = SEASONAL_VERSES[season] || SEASONAL_VERSES.Ordinary;
  return { ...fallback, sundayName: (entry && entry.name) || 'This Sunday', year: yr };
}

// Re-export the items declared after the earlier Object.assign call so they
// are actually accessible on `window` from other script tags.
Object.assign(window, { RCL_SUNDAYS, COLLECTS, getCollect, getRCLToday, rclSundayId, getLiturgicalSeasons, getKeyVerse, CANTICLES, OFFICE_COLLECTS, PSALMS });
