// ornaments.jsx — illuminated decorative pieces, drop caps, woodcut placeholders

// ─────────────────────────────────────────────────────────────
// Decorative rule with center diamond — like a missal page break
// ─────────────────────────────────────────────────────────────
function MissalRule({ theme, color, label }) {
  const c = color || theme.gold;
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '14px 0', color: c }}>
      <div style={{ flex: 1, height: 1, background: c, opacity: 0.4 }} />
      <svg width="16" height="16" viewBox="0 0 16 16" style={{ flexShrink: 0 }}>
        <path d="M8 1 L15 8 L8 15 L1 8 Z" fill="none" stroke={c} strokeWidth="1" opacity="0.6"/>
        <circle cx="8" cy="8" r="1.6" fill={c}/>
      </svg>
      {label && <span style={{ ...smallCaps(theme, 9), color: c, opacity: 0.8 }}>{label}</span>}
      {label && <svg width="16" height="16" viewBox="0 0 16 16" style={{ flexShrink: 0 }}>
        <path d="M8 1 L15 8 L8 15 L1 8 Z" fill="none" stroke={c} strokeWidth="1" opacity="0.6"/>
        <circle cx="8" cy="8" r="1.6" fill={c}/>
      </svg>}
      <div style={{ flex: 1, height: 1, background: c, opacity: 0.4 }} />
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Illuminated drop cap. Uses a square with gold border + filigree-ish
// background using overlapping circles, holding the letter.
// ─────────────────────────────────────────────────────────────
function DropCap({ letter, theme, size = 64, color }) {
  const c = color || theme.accent;
  const id = 'dc-' + (letter || 'A') + '-' + Math.random().toString(36).slice(2, 6);
  // Stroke-dash length tuned to the corner flourish path length so it draws
  // smoothly from origin to terminal point.
  const FLOURISH_LEN = 18;
  return (
    <span style={{
      float: 'left', width: size, height: size, marginRight: 10, marginTop: 4,
      position: 'relative',
    }}>
      <svg viewBox="0 0 64 64" width={size} height={size}>
        <defs>
          <pattern id={id} x="0" y="0" width="8" height="8" patternUnits="userSpaceOnUse">
            <circle cx="4" cy="4" r="2.5" fill="none" stroke={theme.gold} strokeWidth="0.4" opacity="0.6"/>
          </pattern>
        </defs>
        {/* colored block — fades in */}
        <rect x="2" y="2" width="60" height="60" fill={c} stroke={theme.gold} strokeWidth="1.2"
              style={{ opacity: 0, animation: 'fadein 0.5s ease 0.05s both' }} />
        <rect x="2" y="2" width="60" height="60" fill={`url(#${id})`} opacity="0.6"
              style={{ animation: 'fadein 0.6s ease 0.25s both' }} />
        {/* corner flourishes — drawn in sequence with the inkDraw animation */}
        <path d="M2 12 Q 8 8 12 2" fill="none" stroke={theme.gold} strokeWidth="0.7" opacity="0.85"
              strokeDasharray={FLOURISH_LEN} strokeDashoffset={FLOURISH_LEN}
              style={{ animation: 'dropcap-ink 0.55s ease 0.4s forwards' }} />
        <path d="M62 12 Q 56 8 52 2" fill="none" stroke={theme.gold} strokeWidth="0.7" opacity="0.85"
              strokeDasharray={FLOURISH_LEN} strokeDashoffset={FLOURISH_LEN}
              style={{ animation: 'dropcap-ink 0.55s ease 0.5s forwards' }} />
        <path d="M2 52 Q 8 56 12 62" fill="none" stroke={theme.gold} strokeWidth="0.7" opacity="0.85"
              strokeDasharray={FLOURISH_LEN} strokeDashoffset={FLOURISH_LEN}
              style={{ animation: 'dropcap-ink 0.55s ease 0.6s forwards' }} />
        <path d="M62 52 Q 56 56 52 62" fill="none" stroke={theme.gold} strokeWidth="0.7" opacity="0.85"
              strokeDasharray={FLOURISH_LEN} strokeDashoffset={FLOURISH_LEN}
              style={{ animation: 'dropcap-ink 0.55s ease 0.7s forwards' }} />
      </svg>
      <span style={{
        position: 'absolute', inset: 0, display: 'flex',
        alignItems: 'center', justifyContent: 'center',
        fontFamily: theme.fonts.display,
        fontSize: size * 0.7, lineHeight: 1, color: theme.paper,
        fontWeight: 500,
        textShadow: `1px 1px 0 ${theme.gold}40`,
        animation: 'dropcap-letter 0.55s ease 0.85s both',
      }}>{letter}</span>
    </span>
  );
}

// ─────────────────────────────────────────────────────────────
// Chalice countdown — fills based on % of week elapsed
// ─────────────────────────────────────────────────────────────
function Chalice({ theme, fillPct = 0.6, width = 80 }) {
  const h = width * 1.4;
  const fillY = 28 + (40 - fillPct * 40); // wine surface
  return (
    <svg viewBox="0 0 80 112" width={width} height={h} style={{ display: 'block' }}>
      <defs>
        <clipPath id="cup-clip">
          <path d="M14 28 Q 40 30 66 28 L 60 64 Q 40 72 20 64 Z" />
        </clipPath>
        <linearGradient id="wine" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={theme.accent} stopOpacity="0.9"/>
          <stop offset="100%" stopColor={theme.accent} stopOpacity="1"/>
        </linearGradient>
      </defs>
      {/* cup outline */}
      <path d="M14 28 Q 40 30 66 28 L 60 64 Q 40 72 20 64 Z"
            fill={theme.bgAlt} stroke={theme.gold} strokeWidth="1.5"/>
      {/* wine */}
      <g clipPath="url(#cup-clip)">
        <rect x="10" y={fillY} width="60" height="50" fill="url(#wine)"/>
        {/* meniscus */}
        <ellipse cx="40" cy={fillY} rx="26" ry="2.5" fill={theme.accent} opacity="0.6"/>
      </g>
      {/* rim highlight */}
      <ellipse cx="40" cy="28.5" rx="26" ry="3" fill="none" stroke={theme.gold} strokeWidth="1"/>
      {/* stem */}
      <rect x="37" y="68" width="6" height="22" fill={theme.gold}/>
      {/* knob */}
      <circle cx="40" cy="80" r="5" fill={theme.bgAlt} stroke={theme.gold} strokeWidth="1"/>
      {/* base */}
      <ellipse cx="40" cy="98" rx="22" ry="4" fill={theme.gold}/>
      <ellipse cx="40" cy="96" rx="22" ry="3" fill={theme.bgAlt} stroke={theme.gold} strokeWidth="1"/>
    </svg>
  );
}

// ─────────────────────────────────────────────────────────────
// Votive candle — flickering flame
// ─────────────────────────────────────────────────────────────
function Candle({ theme, lit = true, size = 1, name, prayer }) {
  const w = 56 * size, h = 90 * size;
  return (
    <div style={{
      display: 'flex', flexDirection: 'column', alignItems: 'center',
      filter: lit ? 'none' : 'grayscale(0.8) opacity(0.5)',
    }}>
      <div style={{ position: 'relative', width: w, height: h * 0.5 }}>
        {lit && (
          <>
            {/* glow halo */}
            <div style={{
              position: 'absolute', left: '50%', top: 0, transform: 'translate(-50%, -50%)',
              width: w * 1.4, height: w * 1.4, borderRadius: '50%',
              background: `radial-gradient(circle, ${theme.gold}66, transparent 70%)`,
              animation: 'breathe 2.4s ease-in-out infinite',
            }} />
            {/* flame */}
            <svg viewBox="0 0 20 30" width={w * 0.4} height={w * 0.6}
                 style={{
                   position: 'absolute', left: '50%', top: 4,
                   transform: 'translateX(-50%)',
                   transformOrigin: '50% 100%',
                   animation: 'flicker 1.2s ease-in-out infinite',
                 }}>
              <path d="M10 2 C 14 8, 16 14, 14 22 C 13 26, 10 28, 10 28 C 10 28, 7 26, 6 22 C 4 14, 6 8, 10 2 Z"
                    fill={theme.gold}/>
              <path d="M10 8 C 12 12, 13 16, 12 22 C 11 25, 10 26, 10 26 C 10 26, 9 25, 8 22 C 7 16, 8 12, 10 8 Z"
                    fill="#fff5d8"/>
            </svg>
          </>
        )}
        {/* wick */}
        <div style={{
          position: 'absolute', left: '50%', bottom: 0,
          transform: 'translateX(-50%)', width: 1.5, height: 6,
          background: '#2a1a10',
        }} />
      </div>
      {/* candle body */}
      <div style={{
        width: w * 0.5, height: h * 0.5,
        background: lit ? `linear-gradient(180deg, ${theme.paper}, ${theme.bgAlt})` : theme.bgAlt,
        borderRadius: '2px 2px 0 0',
        boxShadow: lit ? `inset 0 0 12px ${theme.gold}30` : 'none',
        position: 'relative',
      }}>
        {/* drips */}
        <div style={{
          position: 'absolute', top: 6, left: 4, width: 2, height: 12,
          background: theme.bgAlt, opacity: 0.6, borderRadius: '0 0 50% 50%',
        }} />
      </div>
      {/* glass holder */}
      <div style={{
        width: w * 0.7, height: 4,
        background: theme.gold, opacity: 0.7,
        marginTop: -2,
      }} />
      {name && <div style={{
        ...smallCaps(theme, 10), color: theme.inkMute, marginTop: 6, textAlign: 'center', maxWidth: w * 1.5,
      }}>{name}</div>}
      {prayer && <div style={{
        fontFamily: theme.fonts.body, fontStyle: 'italic',
        fontSize: 13, color: theme.inkSoft, marginTop: 2, textAlign: 'center', maxWidth: w * 1.6,
        lineHeight: 1.35,
      }}>{prayer}</div>}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Liturgical season ribbon — top of screen accent
// ─────────────────────────────────────────────────────────────
// Compress a long RCL Sunday name for places where horizontal room is tight
// (iPhone-width ribbon, etc.). "Fifth Sunday of Easter" → "Easter 5";
// "Reign of Christ · Christ the King" → "Christ the King"; preserves short
// names ("Trinity Sunday", "The Day of Pentecost") as-is.
function shortSundayName(name) {
  if (!name) return '';
  const m = name.match(/^(First|Second|Third|Fourth|Fifth|Sixth|Seventh) Sunday (?:in|of|after) (.+)$/);
  if (m) {
    const ord = { First: 1, Second: 2, Third: 3, Fourth: 4, Fifth: 5, Sixth: 6, Seventh: 7 }[m[1]];
    return `${m[2].split(' ')[0]} ${ord}`;
  }
  return name.split(' · ')[0].replace(/^The /, '');
}

function SeasonRibbon({ theme }) {
  const s = theme.season;
  // Dynamic Year + Sunday name from the RCL helper. Falls back to season name
  // if the helper isn't loaded yet (defensive — should always be available).
  let tagline = '';
  try {
    if (typeof getRCLToday === 'function') {
      const rcl = getRCLToday();
      if (rcl && rcl.year && rcl.name) tagline = `Year ${rcl.year} · ${shortSundayName(rcl.name)}`;
    }
  } catch (e) { /* ignore — leave tagline empty */ }

  return (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      gap: 10, flexWrap: 'wrap',
      padding: '6px 18px',
      background: s.accent, color: '#f4e8d2',
      ...smallCaps(theme, 9),
    }}>
      <span style={{ whiteSpace: 'nowrap' }}>† {s.name}</span>
      {tagline && <span style={{ opacity: 0.8, whiteSpace: 'nowrap' }}>{tagline}</span>}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Woodcut-style placeholder — a "stained-glass" composition
// uses simple repeating geometry, no figural recreation
// ─────────────────────────────────────────────────────────────
function StainedGlass({ theme, height = 200, seed = 1 }) {
  const palette = [theme.accent, theme.gold, '#3a5a7a', '#3a2858', '#3a5a3a'];
  // Tall Gothic lancet with an abstract Celtic cross within
  const stoneStroke = theme.ink;
  // Lancet path (pointed arch). Apex at top, springs from y=110.
  const arch = "M40 240 L40 110 Q40 28 100 14 Q160 28 160 110 L160 240 Z";
  return (
    <div style={{
      width: '100%', height, position: 'relative', overflow: 'hidden',
      background: theme.bgAlt,
      borderTop: `1px solid ${theme.rule}`,
      borderBottom: `1px solid ${theme.rule}`,
    }}>
      <svg viewBox="0 0 200 240" preserveAspectRatio="xMidYMid meet"
           width="100%" height="100%" style={{ display: 'block' }}>
        <defs>
          <clipPath id={`lancet-${seed}`}>
            <path d={arch}/>
          </clipPath>
          <radialGradient id={`bg-${seed}`} cx="0.5" cy="0.55" r="0.65">
            <stop offset="0%" stopColor={palette[(seed + 1) % palette.length]} stopOpacity="0.85"/>
            <stop offset="100%" stopColor={palette[(seed + 3) % palette.length]} stopOpacity="0.95"/>
          </radialGradient>
        </defs>

        {/* Stone outer arch */}
        <path d={arch} fill={theme.bgAlt} stroke={stoneStroke} strokeOpacity="0.55" strokeWidth="3"/>

        {/* Glass field within the lancet */}
        <g clipPath={`url(#lancet-${seed})`}>
          {/* Background glass (deep colored field) */}
          <rect x="0" y="0" width="200" height="240" fill={`url(#bg-${seed})`}/>

          {/* Diamond lattice (lead came) across the whole field */}
          {(() => {
            const lines = [];
            for (let y = 30; y <= 240; y += 22) {
              lines.push(<line key={`h${y}`} x1="20" y1={y} x2="180" y2={y} stroke={stoneStroke} strokeOpacity="0.18" strokeWidth="0.6"/>);
            }
            for (let x = 50; x <= 150; x += 22) {
              lines.push(<line key={`v${x}`} x1={x} y1="20" x2={x} y2="240" stroke={stoneStroke} strokeOpacity="0.18" strokeWidth="0.6"/>);
            }
            return lines;
          })()}

          {/* Celtic cross — abstract */}
          {/* Nimbus / halo ring (the circle) */}
          <circle cx="100" cy="118" r="34" fill={theme.gold} opacity="0.42"/>
          <circle cx="100" cy="118" r="34" fill="none" stroke={stoneStroke} strokeOpacity="0.55" strokeWidth="3"/>
          <circle cx="100" cy="118" r="27" fill="none" stroke={stoneStroke} strokeOpacity="0.4" strokeWidth="1.2"/>

          {/* Vertical bar of the cross */}
          <rect x="92" y="58" width="16" height="158" fill={palette[(seed) % palette.length]} opacity="0.92"
                stroke={stoneStroke} strokeOpacity="0.6" strokeWidth="2"/>
          {/* Horizontal crossbar */}
          <rect x="56" y="110" width="88" height="16" fill={palette[(seed) % palette.length]} opacity="0.92"
                stroke={stoneStroke} strokeOpacity="0.6" strokeWidth="2"/>

          {/* Center jewel where the bars cross */}
          <circle cx="100" cy="118" r="6" fill={theme.gold}
                  stroke={stoneStroke} strokeOpacity="0.6" strokeWidth="1.2"/>

          {/* Small jewels along the cross arms */}
          <circle cx="100" cy="78" r="3" fill={theme.gold} stroke={stoneStroke} strokeOpacity="0.5" strokeWidth="0.8"/>
          <circle cx="100" cy="200" r="3" fill={theme.gold} stroke={stoneStroke} strokeOpacity="0.5" strokeWidth="0.8"/>
          <circle cx="68" cy="118" r="3" fill={theme.gold} stroke={stoneStroke} strokeOpacity="0.5" strokeWidth="0.8"/>
          <circle cx="132" cy="118" r="3" fill={theme.gold} stroke={stoneStroke} strokeOpacity="0.5" strokeWidth="0.8"/>
        </g>

        {/* Inner stone arch outline */}
        <path d={arch} fill="none" stroke={stoneStroke} strokeOpacity="0.55" strokeWidth="2"/>
      </svg>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Manuscript-style placeholder card with monospace label
// ─────────────────────────────────────────────────────────────
function PlaceholderImg({ theme, height = 120, label = 'photograph' }) {
  return (
    <div style={{
      width: '100%', height, position: 'relative',
      background: `repeating-linear-gradient(135deg, ${theme.bgAlt}, ${theme.bgAlt} 8px, ${theme.paper} 8px, ${theme.paper} 16px)`,
      border: `1px solid ${theme.rule}`,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
    }}>
      <span style={{ ...smallCaps(theme, 9), color: theme.inkMute }}>[ {label} ]</span>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Cross / chi-rho / fleur small icons (monoline)
// ─────────────────────────────────────────────────────────────
const Icons = {
  cross: (size = 14, c = 'currentColor') => (
    <svg width={size} height={size} viewBox="0 0 14 14" fill="none">
      <path d="M7 1 V13 M2 5 H12" stroke={c} strokeWidth="1.4" strokeLinecap="round"/>
    </svg>
  ),
  chalice: (size = 14, c = 'currentColor') => (
    <svg width={size} height={size} viewBox="0 0 14 14" fill="none">
      <path d="M3 3 H11 L9.5 8 Q7 9.5 4.5 8 Z M7 8 V11 M4 12 H10" stroke={c} strokeWidth="1.2" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  ),
  candle: (size = 14, c = 'currentColor') => (
    <svg width={size} height={size} viewBox="0 0 14 14" fill="none">
      <path d="M7 1 Q 8.5 3 7 5 Q 5.5 3 7 1 Z" fill={c}/>
      <rect x="5" y="6" width="4" height="6" stroke={c} strokeWidth="1.2" fill="none"/>
    </svg>
  ),
  alms: (size = 14, c = 'currentColor') => (
    <svg width={size} height={size} viewBox="0 0 14 14" fill="none">
      <path d="M2 6 Q 7 2 12 6 V11 Q 7 13 2 11 Z" stroke={c} strokeWidth="1.2" fill="none" strokeLinejoin="round"/>
      <circle cx="7" cy="8" r="1.5" stroke={c} strokeWidth="1.2" fill="none"/>
    </svg>
  ),
  scroll: (size = 14, c = 'currentColor') => (
    <svg width={size} height={size} viewBox="0 0 14 14" fill="none">
      <path d="M3 2 H11 V12 H3 Z M5 5 H9 M5 7 H9 M5 9 H8" stroke={c} strokeWidth="1.2" strokeLinecap="round"/>
    </svg>
  ),
  door: (size = 14, c = 'currentColor') => (
    <svg width={size} height={size} viewBox="0 0 14 14" fill="none">
      <path d="M3 13 V4 Q 7 1 11 4 V13 Z M9 8 V9" stroke={c} strokeWidth="1.2" strokeLinejoin="round" fill="none"/>
    </svg>
  ),
  star: (size = 14, c = 'currentColor') => (
    <svg width={size} height={size} viewBox="0 0 14 14" fill="none">
      <path d="M7 2 L8 6 L12 6 L9 8.5 L10 12.5 L7 10 L4 12.5 L5 8.5 L2 6 L6 6 Z" stroke={c} strokeWidth="1.1" strokeLinejoin="round" fill="none"/>
    </svg>
  ),
  pin: (size = 14, c = 'currentColor') => (
    <svg width={size} height={size} viewBox="0 0 14 14" fill="none">
      <path d="M7 1 Q 12 1 12 6 Q 12 9 7 13 Q 2 9 2 6 Q 2 1 7 1 Z" stroke={c} strokeWidth="1.2" fill="none"/>
      <circle cx="7" cy="6" r="1.5" stroke={c} strokeWidth="1.2" fill="none"/>
    </svg>
  ),
  bell: (size = 14, c = 'currentColor') => (
    <svg width={size} height={size} viewBox="0 0 14 14" fill="none">
      <path d="M7 2 Q 11 3 11 8 L 12 10 H 2 L 3 8 Q 3 3 7 2 Z M 6 11 Q 7 12.5 8 11" stroke={c} strokeWidth="1.2" fill="none" strokeLinejoin="round"/>
    </svg>
  ),
  book: (size = 14, c = 'currentColor') => (
    <svg width={size} height={size} viewBox="0 0 14 14" fill="none">
      <path d="M2 3 H6 Q 7 4 7 5 V13 Q 7 12 6 12 H2 Z M12 3 H8 Q 7 4 7 5 V13 Q 7 12 8 12 H12 Z" stroke={c} strokeWidth="1.1" fill="none" strokeLinejoin="round"/>
    </svg>
  ),
};

Object.assign(window, { MissalRule, DropCap, Chalice, Candle, SeasonRibbon, StainedGlass, PlaceholderImg, Icons });
