// 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 = ['Ancient Faith', 'Open Doors', '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' },
};

function FeastOverlay({ feast, theme }) {
  if (!feast) return null;
  const info = FEAST_INFO[feast];

  // Layered animations per feast
  return (
    <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none', zIndex: 80, overflow: 'hidden' }}>
      {feast === 'easter'     && <EasterButterflies theme={theme} />}
      {feast === 'palm'       && <PalmFronds theme={theme} />}
      {feast === 'maundy'     && <MaundyTable theme={theme} />}
      {feast === 'pentecost'  && <PentecostFire theme={theme} />}
      {feast === 'xmaseve'    && <FlickeringStars theme={theme} />}
      {feast === 'christmas'  && <SoftSnow theme={theme} />}
      {feast === 'advent1'    && <FrostFringe theme={theme} />}
      {feast === 'ashwed'     && <FallingAsh theme={theme} />}
      {feast === 'goodfri'    && <DimVeil theme={theme} />}
      {feast === 'allsaints'  && <FloatingCandles theme={theme} />}
      {feast === 'reformation'&& <ReformationSeals theme={theme} />}
      {feast === 'stnicholas' && <DriftingCoins theme={theme} />}
      {feast === 'epiphany'   && <StarOfBethlehem theme={theme} />}

      {/* Feast banner */}
      <div style={{
        position: 'absolute', top: 100, left: 0, right: 0,
        textAlign: 'center', pointerEvents: 'none',
        animation: 'feastReveal 1.4s 0.4s both',
      }}>
        <div style={{ ...smallCaps(theme, 9), color: info.color, marginBottom: 4 }}>Today</div>
        <div style={{ fontFamily: theme.fonts.display, fontSize: 22, fontStyle: 'italic', color: theme.ink }}>{info.name}</div>
        <div style={{ fontFamily: theme.fonts.display, fontSize: 14, fontStyle: 'italic', color: theme.inkMute, marginTop: 2 }}>{info.greet}</div>
      </div>
    </div>
  );
}

// ── 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>
  ));
}

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