// brand.jsx — church mark, motto, hand-tinted hero photo, easter eggs

// ─────────────────────────────────────────────────────────────
// Monogram — capital M cradling a cross, with serif terminals
// ─────────────────────────────────────────────────────────────
function ChurchMark({ size = 64, theme, monoColor, ringed = true }) {
  const c = monoColor || theme.ink;
  const accent = theme.gold;
  // viewBox 100x100 — M shape drawn with thick serif strokes;
  // a cross sits in the V of the M, vertical bar stretching slightly above.
  return (
    <svg width={size} height={size} viewBox="0 0 100 100" fill="none" style={{ display: 'block' }}>
      {ringed && (
        <>
          <circle cx="50" cy="50" r="46" stroke={accent} strokeOpacity="0.7" strokeWidth="1"/>
          <circle cx="50" cy="50" r="42" stroke={accent} strokeOpacity="0.4" strokeWidth="0.6"/>
        </>
      )}
      {/* M — left stem */}
      <path d="M22 78 L22 26 L26 22 L30 22 L30 74 Q30 76 32 76 L34 76" stroke={c} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" fill="none"/>
      {/* M — left diagonal down to the V */}
      <path d="M30 22 L48 56" stroke={c} strokeWidth="2.5" strokeLinecap="round"/>
      {/* M — right diagonal up to the right peak */}
      <path d="M52 56 L70 22" stroke={c} strokeWidth="2.5" strokeLinecap="round"/>
      {/* M — right stem */}
      <path d="M70 22 L74 22 L78 26 L78 78 L66 78 Q64 78 64 76 L64 24" stroke={c} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" fill="none"/>
      {/* Serif feet */}
      <path d="M16 78 L34 78" stroke={c} strokeWidth="2.5" strokeLinecap="round"/>
      <path d="M62 78 L84 78" stroke={c} strokeWidth="2.5" strokeLinecap="round"/>
      {/* Cross — cradled in the V of the M */}
      {/* vertical bar — extends from inside the V up above the M's peaks */}
      <path d="M50 14 L50 70" stroke={accent} strokeWidth="3.5" strokeLinecap="round"/>
      {/* horizontal crossbar */}
      <path d="M40 30 L60 30" stroke={accent} strokeWidth="3.5" strokeLinecap="round"/>
      {/* tiny gold finial at the top of the cross */}
      <circle cx="50" cy="14" r="1.6" fill={accent}/>
    </svg>
  );
}

// Smaller variant for navigation / tabs
function ChurchMarkSmall({ size = 22, color = 'currentColor', accent }) {
  return (
    <svg width={size} height={size} viewBox="0 0 100 100" fill="none">
      <path d="M22 80 L22 22 L36 22 L50 56 L64 22 L78 22 L78 80" stroke={color} strokeWidth="6" strokeLinecap="round" strokeLinejoin="round" fill="none"/>
      <path d="M50 12 L50 70" stroke={accent || color} strokeWidth="7" strokeLinecap="round"/>
      <path d="M38 30 L62 30" stroke={accent || color} strokeWidth="7" strokeLinecap="round"/>
    </svg>
  );
}

// ─────────────────────────────────────────────────────────────
// Motto — three-clause line as used on masthead and share cards
// ─────────────────────────────────────────────────────────────
const MOTTO = ['the ancient Way', 'the living Word', 'the abundant Life'];

function Motto({ theme, size = 11, color, separator = '·' }) {
  const c = color || theme.gold;
  return (
    <span style={{
      fontFamily: theme.fonts.mono, fontSize: size,
      letterSpacing: '0.22em', textTransform: 'uppercase', color: c,
      whiteSpace: 'nowrap',
    }}>
      {MOTTO.map((m, i) => (
        <React.Fragment key={i}>
          {m}
          {i < MOTTO.length - 1 && <span style={{ margin: '0 0.6em', opacity: 0.6 }}>{separator}</span>}
        </React.Fragment>
      ))}
    </span>
  );
}

// ─────────────────────────────────────────────────────────────
// Hand-tinted sanctuary photo — picks variant by theme
// ─────────────────────────────────────────────────────────────
function SanctuaryPhoto({ theme, height = 280, overlay = true, children }) {
  const variant = theme.paletteName === 'Candlelight' ? 'candlelight'
                : theme.paletteName === 'Sepia'        ? 'sepia'
                                                       : 'parchment';
  const src = `assets/sanctuary-${variant}.jpg`;
  return (
    <div style={{
      position: 'relative', width: '100%', height,
      overflow: 'hidden',
      background: theme.bgAlt,
      borderTop: `1px solid ${theme.rule}`,
      borderBottom: `1px solid ${theme.rule}`,
    }}>
      <img src={src} alt="The sanctuary of Monticello UMC"
        loading="eager" decoding="async" fetchpriority="high"
        style={{
          position: 'absolute', inset: 0, width: '100%', height: '100%',
          objectFit: 'cover', objectPosition: 'center 45%',
          display: 'block',
          filter: 'contrast(1.02)',
        }}/>
      {overlay && (
        <div style={{
          position: 'absolute', inset: 0,
          background: `linear-gradient(180deg, ${theme.paper}10 0%, transparent 28%, transparent 60%, ${theme.paper}f0 100%)`,
          pointerEvents: 'none',
        }}/>
      )}
      {/* corner key-line ornaments */}
      <CornerKey theme={theme} where="tl"/>
      <CornerKey theme={theme} where="tr"/>
      <CornerKey theme={theme} where="bl"/>
      <CornerKey theme={theme} where="br"/>
      {children}
    </div>
  );
}

function CornerKey({ theme, where }) {
  const styles = {
    tl: { top: 8, left: 8, transform: 'rotate(0deg)' },
    tr: { top: 8, right: 8, transform: 'rotate(90deg)' },
    br: { bottom: 8, right: 8, transform: 'rotate(180deg)' },
    bl: { bottom: 8, left: 8, transform: 'rotate(270deg)' },
  };
  return (
    <svg width="22" height="22" viewBox="0 0 22 22" fill="none" style={{ position: 'absolute', ...styles[where] }}>
      <path d="M2 10 L2 2 L10 2" stroke={theme.gold} strokeOpacity="0.85" strokeWidth="1.2" strokeLinecap="round"/>
      <circle cx="2" cy="2" r="1.5" fill={theme.gold} opacity="0.7"/>
    </svg>
  );
}

// ─────────────────────────────────────────────────────────────
// Feast-day Easter eggs
// Returns { feast, render } where render is a JSX layer over the page
// ─────────────────────────────────────────────────────────────
function detectFeast(date = new Date()) {
  const m = date.getMonth() + 1;
  const d = date.getDate();
  // Use easterDate from liturgical.jsx
  const easter = easterDate(date.getFullYear());
  const sameDay = (a, b) => a.getMonth() === b.getMonth() && a.getDate() === b.getDate();
  const ashWed = (() => { const x = new Date(easter); x.setDate(x.getDate() - 46); return x; })();
  const palmSun = (() => { const x = new Date(easter); x.setDate(x.getDate() - 7); return x; })();
  const maundy = (() => { const x = new Date(easter); x.setDate(x.getDate() - 3); return x; })();
  const goodFri = (() => { const x = new Date(easter); x.setDate(x.getDate() - 2); return x; })();
  const pentecost = (() => { const x = new Date(easter); x.setDate(x.getDate() + 49); return x; })();

  if (sameDay(date, easter))    return 'easter';
  if (sameDay(date, palmSun))   return 'palm';
  if (sameDay(date, maundy))    return 'maundy';
  if (sameDay(date, goodFri))   return 'goodfri';
  if (sameDay(date, ashWed))    return 'ashwed';
  if (sameDay(date, pentecost)) return 'pentecost';
  if (m === 12 && d === 24)     return 'xmaseve';
  if (m === 12 && d === 25)     return 'christmas';
  if (m === 11 && d === 1)      return 'allsaints';
  if (m === 10 && d === 31)     return 'reformation';
  if (m === 12 && d === 6)      return 'stnicholas';
  if (m === 1  && d === 6)      return 'epiphany';
  // First Sunday of Advent ~= Sunday on/before Dec 3
  const xmas = new Date(date.getFullYear(), 11, 25);
  const adventStart = (() => { const f = new Date(xmas); f.setDate(xmas.getDate() - xmas.getDay() - 21); return f; })();
  if (sameDay(date, adventStart)) return 'advent1';
  return null;
}

const FEAST_INFO = {
  easter:      { name: 'Easter Sunday',          greet: 'Christ is risen — Alleluia!',           color: '#a87838' },
  palm:        { name: 'Palm Sunday',            greet: 'Hosanna in the highest.',                color: '#3a5a3a' },
  maundy:      { name: 'Maundy Thursday',        greet: 'A new commandment I give you: love one another.', color: '#4a2858' },
  goodfri:     { name: 'Good Friday',            greet: 'In silence we keep watch.',              color: '#1a1410' },
  ashwed:      { name: 'Ash Wednesday',          greet: 'Remember that thou art dust.',           color: '#5a4a3a' },
  pentecost:   { name: 'Pentecost',              greet: 'Come, Holy Spirit.',                     color: '#7a2e2e' },
  xmaseve:     { name: 'Christmas Eve',          greet: 'A light shines in the darkness.',       color: '#3a2858' },
  christmas:   { name: 'Christmas Day',          greet: 'Unto us a child is born.',               color: '#a83a3a' },
  allsaints:   { name: 'All Saints',             greet: 'A great cloud of witnesses.',            color: '#b8893d' },
  reformation: { name: 'Reformation Day',        greet: 'Here we stand.',                         color: '#7a2e2e' },
  stnicholas:  { name: 'St. Nicholas Day',       greet: 'Gifts of grace.',                        color: '#a83a3a' },
  epiphany:    { name: 'The Epiphany',           greet: 'We have seen his star in the east.',    color: '#3a5a7a' },
  advent1:     { name: 'First Sunday of Advent', greet: 'Watch — for the Lord is near.',          color: '#3a2858' },
};

// FeastOverlay is now a no-op. The original implementation layered
// per-feast particle animations (palm fronds, flame motes, falling ash,
// drifting coins, etc.) over the page. They read as web-1.0 JavaScript
// effects, fighting the manuscript aesthetic.
//
// On feast days the visual marker is now carried entirely by:
//   1. SeasonRibbon's high-contrast parchment strip ("Today · Easter
//      Sunday · Christ is risen — Alleluia!") rendered in page flow.
//   2. The season's marginalia ornament (illuminated wreath / star /
//      cross / flame) in the lower-right corner.
//   3. The accent color shift (when useSeasonAccent is on).
//
// Together these read like a missal whose page has turned to a feast day,
// not like confetti at a party. The legacy animation components below
// (EasterButterflies, PalmFronds, etc.) are intentionally kept defined so
// older imports don't break, but are no longer rendered.
function FeastOverlay() {
  return null;
}

// ── Individual feast effects ────────────────────────────────
function EasterButterflies({ theme }) {
  const flutters = Array.from({ length: 8 }).map((_, i) => ({
    id: i,
    delay: i * 0.6,
    x: 20 + (i * 47) % 360,
    duration: 12 + (i % 4) * 2,
    color: ['#a87838', '#b8893d', '#7a2e2e', '#3a5a3a'][i % 4],
  }));
  return (
    <>
      {flutters.map(f => (
        <svg key={f.id} width="22" height="18" viewBox="0 0 22 18" style={{
          position: 'absolute', left: f.x, bottom: -30,
          animation: `floatUp ${f.duration}s ${f.delay}s infinite ease-in-out`,
          transformOrigin: 'center',
        }}>
          <g style={{ animation: 'flap 0.4s infinite ease-in-out', transformOrigin: '11px 9px' }}>
            <ellipse cx="6" cy="9" rx="6" ry="7" fill={f.color} opacity="0.85"/>
            <ellipse cx="16" cy="9" rx="6" ry="7" fill={f.color} opacity="0.85"/>
            <line x1="11" y1="2" x2="11" y2="16" stroke={theme.ink} strokeWidth="0.8"/>
          </g>
        </svg>
      ))}
    </>
  );
}

function PentecostFire({ theme }) {
  return (
    <div style={{ position: 'absolute', top: 60, left: 0, right: 0, height: 60, display: 'flex', justifyContent: 'space-around', pointerEvents: 'none' }}>
      {Array.from({ length: 7 }).map((_, i) => (
        <svg key={i} width="22" height="36" viewBox="0 0 22 36" style={{ animation: `flicker 0.${4 + i % 5}s infinite alternate`, transformOrigin: '11px 36px' }}>
          <path d="M11 2 Q 18 12 16 22 Q 18 30 11 34 Q 4 30 6 22 Q 4 12 11 2 Z" fill="#d4452f" opacity="0.85"/>
          <path d="M11 8 Q 15 16 14 24 Q 15 30 11 32 Q 7 30 8 24 Q 7 16 11 8 Z" fill="#f4a83d" opacity="0.9"/>
          <path d="M11 14 Q 13 20 12 26 Q 11 30 11 30 Q 11 30 10 26 Q 9 20 11 14 Z" fill="#fff5d8" opacity="0.95"/>
        </svg>
      ))}
    </div>
  );
}

function SoftSnow({ theme }) {
  const flakes = Array.from({ length: 30 }).map((_, i) => ({
    id: i,
    left: (i * 37) % 100 + '%',
    delay: -((i * 1.3) % 14),
    duration: 12 + (i % 6) * 2,
    size: 2 + (i % 4),
  }));
  return (
    <>
      {flakes.map(f => (
        <div key={f.id} style={{
          position: 'absolute', top: -20, left: f.left,
          width: f.size, height: f.size, borderRadius: '50%',
          background: '#fff', opacity: 0.7,
          animation: `snowFall ${f.duration}s ${f.delay}s infinite linear`,
          boxShadow: '0 0 4px rgba(255,255,255,0.6)',
        }}/>
      ))}
    </>
  );
}

function FlickeringStars({ theme }) {
  return Array.from({ length: 20 }).map((_, i) => (
    <div key={i} style={{
      position: 'absolute',
      top: ((i * 67) % 320) + 'px',
      left: ((i * 113) % 96) + '%',
      width: 2 + (i % 3), height: 2 + (i % 3), borderRadius: '50%',
      background: '#fff5d8',
      animation: `twinkle ${2 + (i % 5) * 0.5}s ${i * 0.2}s infinite alternate ease-in-out`,
      boxShadow: '0 0 6px #fff5d8',
    }}/>
  ));
}

function FrostFringe({ theme }) {
  return (
    <svg width="100%" height="60" viewBox="0 0 400 60" preserveAspectRatio="none" style={{ position: 'absolute', top: 0, left: 0, right: 0 }}>
      <path d="M0 0 L0 30 Q 10 18 20 28 Q 30 14 40 26 Q 50 16 60 30 Q 70 12 80 26 Q 90 18 100 30 Q 110 14 120 28 Q 130 16 140 26 Q 150 18 160 30 Q 170 14 180 28 Q 190 16 200 26 Q 210 18 220 30 Q 230 14 240 28 Q 250 16 260 26 Q 270 18 280 30 Q 290 14 300 28 Q 310 16 320 26 Q 330 18 340 30 Q 350 14 360 28 Q 370 16 380 26 Q 390 18 400 30 L400 0 Z"
            fill="#cfd8e8" opacity="0.55"/>
    </svg>
  );
}

function FallingAsh({ theme }) {
  return Array.from({ length: 18 }).map((_, i) => (
    <div key={i} style={{
      position: 'absolute', top: -10, left: ((i * 53) % 100) + '%',
      width: 1 + (i % 3), height: 1 + (i % 3),
      background: '#5a4a3a', borderRadius: '50%', opacity: 0.5,
      animation: `ashFall ${10 + (i % 6) * 2}s ${-((i * 0.7) % 10)}s infinite linear`,
    }}/>
  ));
}

function DimVeil({ theme }) {
  return <div style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.25)', pointerEvents: 'none' }}/>;
}

function PalmFronds({ theme }) {
  return (
    <svg width="100%" height="40" style={{ position: 'absolute', top: 50, left: 0, right: 0 }}>
      {Array.from({ length: 6 }).map((_, i) => (
        <g key={i} transform={`translate(${20 + i * 60} 20) rotate(${(i % 2 ? 1 : -1) * 14})`}>
          <path d="M0 0 L30 -8 M0 0 L25 -14 M0 0 L20 -18 M0 0 L15 -20 M0 0 L30 0" stroke="#3a5a3a" strokeWidth="2" strokeLinecap="round"/>
        </g>
      ))}
    </svg>
  );
}

function FloatingCandles({ theme }) {
  return Array.from({ length: 10 }).map((_, i) => (
    <div key={i} style={{
      position: 'absolute', bottom: -10, left: ((i * 41) % 100) + '%',
      width: 4, height: 4, borderRadius: '50%', background: '#f4a83d',
      boxShadow: '0 0 12px #f4a83d, 0 0 20px #f4a83d',
      animation: `floatUp ${14 + (i % 4)}s ${-((i * 0.9) % 14)}s infinite linear`,
    }}/>
  ));
}

function DriftingCoins({ theme }) {
  return Array.from({ length: 8 }).map((_, i) => (
    <div key={i} style={{
      position: 'absolute', top: -10, left: ((i * 41) % 100) + '%',
      width: 8, height: 8, borderRadius: '50%',
      background: 'radial-gradient(#f4d878, #b8893d)',
      animation: `ashFall ${12 + (i % 5)}s ${-((i * 0.5) % 10)}s infinite linear`,
    }}/>
  ));
}

function StarOfBethlehem({ theme }) {
  return (
    <svg width="60" height="60" style={{ position: 'absolute', top: 30, right: '20%', animation: 'twinkle 2.4s infinite alternate' }}>
      <path d="M30 4 L34 26 L56 30 L34 34 L30 56 L26 34 L4 30 L26 26 Z" fill="#fff5d8" opacity="0.9"/>
      <path d="M30 14 L32 28 L46 30 L32 32 L30 46 L28 32 L14 30 L28 28 Z" fill="#f4d878" opacity="0.9"/>
    </svg>
  );
}

// MAUNDY THURSDAY — soft candlelit upper-room glow + 12 candle motes around a long table
function MaundyTable({ theme }) {
  return (
    <>
      {/* Warm glow from below — the upper room */}
      <div style={{
        position: 'absolute', inset: 0,
        background: 'radial-gradient(ellipse at 50% 90%, rgba(244,168,61,0.18) 0%, transparent 55%)',
        pointerEvents: 'none',
      }}/>
      {Array.from({ length: 12 }).map((_, i) => (
        <div key={i} style={{
          position: 'absolute', bottom: 60 + (i % 2) * 4,
          left: `${8 + i * 7}%`,
          width: 3, height: 3, borderRadius: '50%', background: '#f4a83d',
          boxShadow: '0 0 8px #f4a83d, 0 0 14px #f4a83d',
          animation: `flicker ${1.6 + (i % 5) * 0.3}s ${-(i * 0.2)}s infinite alternate`,
        }}/>
      ))}
      <style>{`@keyframes flicker { 0%,100%{opacity:0.55;transform:translateY(0)} 50%{opacity:1;transform:translateY(-1px)} }`}</style>
    </>
  );
}

// REFORMATION DAY — wax-seal monograms drift slowly
function ReformationSeals({ theme }) {
  return Array.from({ length: 6 }).map((_, i) => (
    <div key={i} style={{
      position: 'absolute', top: -20, left: ((i * 53) % 100) + '%',
      width: 22, height: 22, borderRadius: '50%',
      background: 'radial-gradient(circle at 35% 35%, #d4554a, #7a2e2e 70%, #4a1a1a)',
      boxShadow: 'inset -2px -2px 4px rgba(0,0,0,0.4), 0 1px 3px rgba(0,0,0,0.3)',
      animation: `ashFall ${18 + (i % 4)}s ${-((i * 1.4) % 18)}s infinite linear`,
      opacity: 0.85,
    }}>
      <div style={{
        position: 'absolute', inset: 4,
        border: '1px solid #f4d878', borderRadius: '50%',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontFamily: 'serif', fontSize: 9, color: '#f4d878', fontWeight: 700, fontStyle: 'italic',
      }}>M</div>
    </div>
  ));
}

// ─────────────────────────────────────────────────────────────
// SeasonalAmbience — subtle, season-wide atmosphere
// ─────────────────────────────────────────────────────────────
// Distinct from FeastOverlay (which fires on a single liturgical day):
// this one runs throughout the season, but turned WAY down so it reads as
// atmosphere rather than celebration. A 6-flake snow drift in Advent
// instead of the 30-flake Christmas-morning blizzard. Three butterflies
// in Eastertide instead of eight at Easter Sunday. The season's color is
// already shifting via theme.accent (when useSeasonAccent is on); these
// particles add the gentle visual companion.
//
// "ordinary" intentionally returns null — Ordinary Time should look
// quiet. The forest-green accent does enough work on its own.
// Per-season SVG ornaments. All sized to a 100x100 viewBox and rendered as
// gold-line drawings ("illumination") rather than literal symbols. They sit
// in the bottom-right of the viewport like a wax-seal stamp on the margin
// of a manuscript page. Static — opacity breathes very slowly (8s) so they
// register as living without becoming distracting.
const SEASON_ORNAMENTS = {
  // Advent — viewed from the side: a horizontal evergreen wreath at the
  // bottom with four candles standing vertically out of it. Three violet
  // candles for Advent 1, 2, and 4 plus one rose candle for Gaudete
  // Sunday (Advent 3). All four flames lit, as the wreath is shown in its
  // completed Advent-4 state.
  advent: ({ ink, accent, gold }) => (
    <g>
      {/* Evergreen wreath base — flattened ellipse seen at a slight angle */}
      <ellipse cx="50" cy="82" rx="42" ry="9" fill="#2e4a2e" opacity="0.65"/>
      <ellipse cx="50" cy="80" rx="34" ry="5" fill="none" stroke={ink} strokeWidth="0.5" opacity="0.3"/>
      {/* Greenery sprigs along the front edge */}
      {[12, 22, 32, 42, 52, 62, 72, 82].map((x, i) => (
        <g key={i} opacity="0.7">
          <line x1={x} y1="83" x2={x - 3} y2="77" stroke="#2e4a2e" strokeWidth="0.9"/>
          <line x1={x} y1="83" x2={x + 3} y2="77" stroke="#2e4a2e" strokeWidth="0.9"/>
        </g>
      ))}
      {/* Holly berries scattered on the wreath */}
      <circle cx="22" cy="84" r="1.4" fill="#8a2828" opacity="0.8"/>
      <circle cx="42" cy="86" r="1.4" fill="#8a2828" opacity="0.8"/>
      <circle cx="65" cy="84" r="1.4" fill="#8a2828" opacity="0.8"/>
      <circle cx="80" cy="86" r="1.4" fill="#8a2828" opacity="0.8"/>

      {/* Four candles standing vertically. Order left → right:
          violet, violet, rose (Gaudete, Advent 3), violet. */}
      {[
        { x: 18, color: accent },
        { x: 38, color: accent },
        { x: 58, color: '#d97aa3' },
        { x: 78, color: accent },
      ].map((c, i) => (
        <g key={i}>
          {/* candle body */}
          <rect x={c.x - 2.5} y="40" width="5" height="38" fill={c.color} opacity="0.92"/>
          <rect x={c.x - 2.5} y="40" width="5" height="38" fill="none"
                stroke={ink} strokeWidth="0.4" opacity="0.55"/>
          {/* tiny wick */}
          <line x1={c.x} y1="38" x2={c.x} y2="40" stroke={ink} strokeWidth="0.6"/>
          {/* flame */}
          <path d={`M ${c.x} 30 Q ${c.x + 2.6} 34 ${c.x} 38 Q ${c.x - 2.6} 34 ${c.x} 30 Z`}
                fill={gold} opacity="0.95"/>
          <ellipse cx={c.x} cy="35.5" rx="0.9" ry="2.2" fill="#fff5d8" opacity="0.85"/>
        </g>
      ))}
    </g>
  ),

  // Christmastide — Star of Bethlehem with rays (illuminated)
  christmas: ({ ink, gold }) => (
    <g>
      <g stroke={gold} strokeWidth="0.5" opacity="0.55">
        {Array.from({ length: 16 }).map((_, i) => {
          const a = (i * 22.5 - 90) * Math.PI / 180;
          const r1 = 14, r2 = 42;
          return <line key={i}
            x1={50 + r1 * Math.cos(a)} y1={50 + r1 * Math.sin(a)}
            x2={50 + r2 * Math.cos(a)} y2={50 + r2 * Math.sin(a)}/>;
        })}
      </g>
      <path d="M50 18 L54 46 L82 50 L54 54 L50 82 L46 54 L18 50 L46 46 Z"
            fill={gold} opacity="0.35"/>
      <path d="M50 28 L52 48 L72 50 L52 52 L50 72 L48 52 L28 50 L48 48 Z"
            fill="#fff5d8" opacity="0.7"/>
      <circle cx="50" cy="50" r="2.4" fill={ink}/>
    </g>
  ),

  // Epiphany — gold-leaf 8-pointed star (the magi's sign)
  epiphany: ({ ink, gold, accent }) => (
    <g>
      <path d="M50 14 L56 44 L86 50 L56 56 L50 86 L44 56 L14 50 L44 44 Z"
            fill={gold} opacity="0.45" stroke={accent} strokeWidth="0.6"/>
      <path d="M50 26 L54 46 L74 50 L54 54 L50 74 L46 54 L26 50 L46 46 Z"
            fill="#fff5d8" opacity="0.7"/>
      <circle cx="50" cy="50" r="2.6" fill={accent}/>
      {/* outer ring of dots */}
      {[0, 90, 180, 270].map((deg, i) => {
        const r = 40, rad = (deg - 45) * Math.PI / 180;
        return <circle key={i} cx={50 + r * Math.cos(rad)} cy={50 + r * Math.sin(rad)}
                       r="1.2" fill={ink} opacity="0.5"/>;
      })}
    </g>
  ),

  // Lent — Latin cross marked with ash, plain and grave
  lent: ({ ink, accent }) => (
    <g>
      {/* ash dust around the cross */}
      <g opacity="0.4" fill={ink}>
        <circle cx="34" cy="40" r="0.7"/><circle cx="68" cy="38" r="0.6"/>
        <circle cx="28" cy="58" r="0.5"/><circle cx="72" cy="62" r="0.7"/>
        <circle cx="40" cy="76" r="0.5"/><circle cx="62" cy="80" r="0.6"/>
      </g>
      <rect x="46" y="18" width="8" height="64" fill={accent} opacity="0.7"/>
      <rect x="30" y="36" width="40" height="8" fill={accent} opacity="0.7"/>
      <rect x="46" y="18" width="8" height="64" fill="none" stroke={ink} strokeWidth="0.5" opacity="0.6"/>
      <rect x="30" y="36" width="40" height="8" fill="none" stroke={ink} strokeWidth="0.5" opacity="0.6"/>
    </g>
  ),

  // Eastertide — risen cross with rays of light
  easter: ({ ink, gold, accent }) => (
    <g>
      <g stroke={gold} strokeWidth="0.5" opacity="0.55">
        {Array.from({ length: 12 }).map((_, i) => {
          const a = (i * 30 - 90) * Math.PI / 180;
          return <line key={i}
            x1={50} y1={50}
            x2={50 + 42 * Math.cos(a)} y2={50 + 42 * Math.sin(a)}/>;
        })}
      </g>
      <rect x="46" y="22" width="8" height="56" fill={gold} opacity="0.85"/>
      <rect x="30" y="40" width="40" height="8" fill={gold} opacity="0.85"/>
      <rect x="46" y="22" width="8" height="56" fill="none" stroke={accent} strokeWidth="0.5"/>
      <rect x="30" y="40" width="40" height="8" fill="none" stroke={accent} strokeWidth="0.5"/>
      <circle cx="50" cy="44" r="2.4" fill={ink}/>
    </g>
  ),

  // Pentecost — single illuminated tongue of fire over a dove silhouette
  pentecost: ({ ink, gold, accent }) => (
    <g>
      {/* dove suggestion (very abstract, descending) */}
      <path d="M30 76 Q 50 56 70 76" fill="none" stroke={ink} strokeWidth="0.6" opacity="0.4"/>
      <ellipse cx="50" cy="68" rx="8" ry="3" fill="#fff5d8" opacity="0.5"/>
      {/* central tongue of fire */}
      <path d="M50 14 Q 60 30 56 46 Q 62 60 50 70 Q 38 60 44 46 Q 40 30 50 14 Z"
            fill={accent} opacity="0.8"/>
      <path d="M50 24 Q 56 34 54 44 Q 58 54 50 62 Q 42 54 46 44 Q 44 34 50 24 Z"
            fill="#d4554a" opacity="0.85"/>
      <path d="M50 34 Q 52 42 51 48 Q 53 54 50 58 Q 47 54 49 48 Q 48 42 50 34 Z"
            fill={gold} opacity="0.9"/>
    </g>
  ),
};

// Map season key → ornament function. Ordinary returns no ornament — the
// quiet green accent does its own work.
function getSeasonOrnament(theme) {
  const s = theme.season;
  if (!s) return null;
  if (s.color === 'green') return null;
  if (s.color === 'purple') return SEASON_ORNAMENTS.advent;
  if (s.color === 'blue') return SEASON_ORNAMENTS.epiphany;
  if (s.color === 'violet') return SEASON_ORNAMENTS.lent;
  if (s.color === 'red') return SEASON_ORNAMENTS.pentecost;
  if (s.color === 'gold' && s.label === 'Christmastide') return SEASON_ORNAMENTS.christmas;
  if (s.color === 'gold' && s.label === 'Eastertide')    return SEASON_ORNAMENTS.easter;
  return null;
}

function SeasonalAmbience({ theme, mode = 'auto', enabled = true }) {
  if (!enabled || mode === 'off') return null;

  // Honor the user's reduce-motion accessibility preference. If they've
  // asked for no animation, the ornament still appears but with a fixed
  // opacity (no breathing).
  const reduceMotion = typeof document !== 'undefined' &&
    document.body && document.body.classList.contains('reduce-motion');

  const Ornament = getSeasonOrnament(theme);
  if (!Ornament) return null;

  // The colors used by every ornament. Most are `theme.ink` / `theme.gold`
  // so they harmonize with the parchment shell automatically; a few use
  // `theme.accent` (which itself shifts per season).
  const colors = { ink: theme.ink, gold: theme.gold, accent: theme.accent };

  // Lent and Pentecost get a faint additional treatment in the page edge.
  // Lent: a vignette darkening the corners (mortification).
  // Pentecost: a slow warm-glow band along the very top edge (the Spirit
  // descending). Both are CSS gradients, no DOM animation cost.
  const isLent      = theme.season.color === 'violet';
  const isPentecost = theme.season.color === 'red';

  return (
    <div aria-hidden="true" style={{
      position: 'fixed', inset: 0, pointerEvents: 'none',
      overflow: 'hidden', zIndex: 1,
    }}>
      {isPentecost && (
        <div style={{
          position: 'absolute', top: 0, left: 0, right: 0, height: 140,
          background: 'linear-gradient(to bottom, rgba(244,168,61,0.18) 0%, rgba(122,46,46,0.05) 60%, transparent 100%)',
          animation: reduceMotion ? 'none' : 'pentecostGlow 9s ease-in-out infinite alternate',
        }}/>
      )}
      {isLent && (
        <div style={{
          position: 'absolute', inset: 0,
          background: 'radial-gradient(ellipse at center, transparent 50%, rgba(0,0,0,0.18) 100%)',
        }}/>
      )}

      {/* Corner watermark — illuminated ornament in the bottom-right of
          every page, sized like a wax seal in a marginal note. Sits above
          any safe-area inset on iPhone notch/home-bar devices. */}
      <div style={{
        position: 'absolute',
        right:  'calc(18px + env(safe-area-inset-right))',
        bottom: 'calc(80px + env(safe-area-inset-bottom))',
        width: 88, height: 88,
        animation: reduceMotion ? 'none' : 'ornamentBreathe 8s ease-in-out infinite',
      }}>
        <svg viewBox="0 0 100 100" width="100%" height="100%">
          <Ornament {...colors}/>
        </svg>
      </div>

      <style>{`
        @keyframes ornamentBreathe {
          0%, 100% { opacity: 0.42; }
          50%      { opacity: 0.62; }
        }
        @keyframes pentecostGlow {
          0%   { opacity: 0.7; }
          100% { opacity: 1.0; }
        }
      `}</style>
    </div>
  );
}

Object.assign(window, {
  ChurchMark, ChurchMarkSmall, Motto, MOTTO,
  SanctuaryPhoto, detectFeast, FEAST_INFO, FeastOverlay,
  SeasonalAmbience,
});
