// =============================================================
// MOTD label graphic system — the label designer's circle marks.
// Loads the real artwork from motd-sigil-paths.js (baked from the
// designer's SVG export). All 60 marks are available; helper
// components pick from a curated subset by default.
//
// All marks share a 266.66666 × 266.66666 viewBox and render with
// `stroke="currentColor"` so they pick up page text color (and
// respect the --accent variable).
//
// Public API:
//   <Sigil n={1} size={64} stroke={2} />          // n = 1..60
//   <SigilDivider ns={[1,7,12]} label="…" />      // hairline + marks + hairline
//   <SigilWatermark n={1} size={480} />           // huge, faint, decorative
//   <CornerMark n={1} lines={[…]} />              // hero cartouche
//
//   SIGIL_COUNT — 60.
//   SIGIL_PICK — small curated set used as defaults across the site.
// =============================================================

const SIGIL_PATHS = window.MOTD_SIGIL_PATHS || [];
const SIGIL_COUNT = SIGIL_PATHS.length;

// Curated subset used for sprinkled placements. Avoids visually-noisy or
// near-duplicate marks; mixes the cleaner geometric ones (rings, triangles,
// chords, phases). Updated by hand after eyeballing the source sheet.
const SIGIL_PICK = [1, 4, 7, 12, 15, 18, 23, 27, 31, 36, 42, 48, 53, 58];

// ----- Rotation -----------------------------------------------------------
// Every <Sigil n={X}/> on the site can be uniformly OFFSET into the 60-mark
// set so that the graphics quietly cycle on a schedule. Cadence is set via
// window.MOTD_SIGIL_ROTATION (driven by the Tweaks panel):
//
//   'off'      → no shift; n maps 1:1
//   'weekly'   → shifts each ISO week (default)
//   'monthly'  → shifts each calendar month
//   'visit'    → shifts each page load (random)
//
// All sprinkled placements move together, so visual relationships (e.g.
// the home and about pages using the same watermark sigil) are preserved.
// Stored once per page load in a module variable so the offset is stable
// for the duration of a session even on 'visit' mode.

const rotationVisitSeed = Math.floor(Math.random() * SIGIL_COUNT);

function isoWeek(d = new Date()) {
  // ISO 8601 week-of-year. Source: stable, no-deps formula.
  const t = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()));
  const day = t.getUTCDay() || 7;
  t.setUTCDate(t.getUTCDate() + 4 - day);
  const yearStart = new Date(Date.UTC(t.getUTCFullYear(), 0, 1));
  return Math.ceil((((t - yearStart) / 86400000) + 1) / 7);
}

function rotationOffset() {
  const mode = (typeof window !== 'undefined' && window.MOTD_SIGIL_ROTATION) || 'weekly';
  if (mode === 'off') return 0;
  if (mode === 'visit') return rotationVisitSeed;
  const now = new Date();
  if (mode === 'monthly') {
    // 12 months × year offset → stable, monotonically-increasing seed
    return ((now.getFullYear() * 12 + now.getMonth()) * 7) % SIGIL_COUNT;
  }
  // weekly (default): ISO week × year, multiplied by a prime so consecutive
  // weeks visit non-adjacent sigils.
  return ((now.getFullYear() * 53 + isoWeek(now)) * 11) % SIGIL_COUNT;
}

// Map "1..60" → inner SVG markup, applying the current rotation offset.
function sigilInner(n) {
  const off = rotationOffset();
  const idx = ((n - 1 + off) % SIGIL_COUNT + SIGIL_COUNT) % SIGIL_COUNT;
  return SIGIL_PATHS[idx] || '';
}

// Core component. `size` is the rendered pixel box; `stroke` is the
// viewBox-relative stroke width (designer drew at 2 — bump to 2.8–3.5
// for small renders so the lines don't disappear at 24–40 px).
const Sigil = ({
  n = 1,
  size = 56,
  stroke = 2.6,
  title,
  style,
  className = '',
}) => {
  const inner = sigilInner(n);
  return (
    <svg
      className={`motd-sigil motd-sigil-${n} ${className}`}
      viewBox="0 0 266.66666 266.66666"
      width={size}
      height={size}
      fill="none"
      stroke="currentColor"
      strokeWidth={stroke}
      strokeLinecap="butt"
      strokeLinejoin="round"
      strokeMiterlimit="10"
      role={title ? 'img' : 'presentation'}
      aria-label={title || undefined}
      style={{ display: 'block', overflow: 'visible', flex: '0 0 auto', ...style }}
      dangerouslySetInnerHTML={{ __html: inner }}
    />
  );
};

// Section divider — hairline · sigil(s) · hairline. Use anywhere a quiet
// section break is wanted (instead of a bare <div className="rule" />).
// `ns` is an array of 1-indexed sigil numbers (1..60); falls back to the
// first three picks.
const SigilDivider = ({
  ns = SIGIL_PICK.slice(0, 3),
  size = 40,
  stroke = 2.6,
  label,
  margin = '60px 0',
  faint = false,
}) => (
  <div
    className="sigil-divider"
    style={{
      display: 'flex', flexDirection: 'column', alignItems: 'center',
      gap: 14,
      margin,
      color: faint ? 'var(--fg-faint)' : 'var(--fg-soft)',
    }}
  >
    <div style={{
      display: 'flex', alignItems: 'center', gap: 26,
      width: '100%',
    }}>
      <div style={{ flex: 1, height: 1, background: 'var(--rule)' }} />
      <div style={{ display: 'flex', gap: 22, alignItems: 'center' }}>
        {ns.map((n, i) => (
          <Sigil key={n + ':' + i} n={n} size={size} stroke={stroke} />
        ))}
      </div>
      <div style={{ flex: 1, height: 1, background: 'var(--rule)' }} />
    </div>
    {label && (
      <div className="mono" style={{ color: 'var(--fg-faint)' }}>{label}</div>
    )}
  </div>
);

// Huge, faint, decorative — sits behind a section as a watermark.
// Caller is responsible for positioning (absolute + inset) and z-index.
const SigilWatermark = ({
  n = 1,
  size = 480,
  opacity = 0.08,
  stroke = 1.4,
  style,
}) => (
  <div
    aria-hidden="true"
    style={{
      position: 'absolute',
      pointerEvents: 'none',
      color: 'var(--fg)',
      opacity,
      ...style,
    }}
  >
    <Sigil n={n} size={size} stroke={stroke} />
  </div>
);

// Hero cartouche — a sigil with up to three short mono lines stacked
// next to it. Used in the corner of the hero like an old map's title
// block ("MOTD · est. 2009 · Bristol").
const CornerMark = ({
  n = 1,
  lines = [],
  size = 40,
  stroke = 2.6,
  align = 'right',  // 'left' | 'right'
  style,
}) => (
  <div
    style={{
      display: 'inline-flex',
      flexDirection: align === 'right' ? 'row' : 'row-reverse',
      alignItems: 'center',
      gap: 14,
      color: 'var(--fg-soft)',
      ...style,
    }}
  >
    <Sigil n={n} size={size} stroke={stroke} />
    <div style={{
      display: 'flex', flexDirection: 'column',
      gap: 3,
      textAlign: align === 'right' ? 'left' : 'right',
      fontFamily: 'var(--motd-mono)',
      fontSize: 10,
      letterSpacing: 'var(--motd-mono-track)',
      textTransform: 'uppercase',
      lineHeight: 1.4,
    }}>
      {lines.map((l, i) => (
        <span key={i} style={{ color: i === 0 ? 'var(--fg)' : 'var(--fg-faint)' }}>{l}</span>
      ))}
    </div>
  </div>
);

window.MOTD_SIGILS = {
  Sigil, SigilDivider, SigilWatermark, CornerMark,
  SIGIL_COUNT, SIGIL_PICK,
};
