/* global React, TOD, bodyXY, Celestial, ClockDial */
// ====================================================================
// Background treatments + faithful mini-port chrome.
// Directions:  Aether Wash · Celestial Accent · AETHER SKY (the lead —
// parchment floats on a living time-of-day sky, its torn deckle edges and
// corners revealing the atmosphere behind: the background-of-the-background).
// ====================================================================

// ---------- shared light layers (Aether Wash) ----------
// modes:
//   'full-dark'  — original: a temperature gradient that multiplies (darkens
//                  the page toward the cool/warm tone). Used by wash/celestial.
//   'edge'       — temperature pulled to the border; interior stays clean.
//   'full-color' — full-coverage tint toward the slot's HUE (not toward black):
//                  the whole page takes on the time colour, ink stays readable.
function WashLayers({ t, strength = 1, mode = 'full-dark' }) {
  const s = t.washStrength * strength;
  const [gx] = bodyXY(t, 100, 100);

  if (mode === 'full-color') {
    return (
      <React.Fragment>
        {/* colourise the whole page toward the time hue (preserves texture) */}
        <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none',
          background: t.tint, mixBlendMode: 'soft-light', opacity: 0.85 * s }} />
        <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none',
          background: t.tint, opacity: 0.16 * s }} />
        {/* sun / moon glow */}
        <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none',
          background: `radial-gradient(120% 90% at ${gx}% 0%, ${t.glow}, transparent 62%)`, mixBlendMode: 'soft-light', opacity: 0.8 * s }} />
        {/* faint hue-deepening toward the edges (no black) */}
        <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none',
          background: `radial-gradient(150% 130% at ${gx}% -8%, transparent 50%, ${t.tint} 100%)`, mixBlendMode: 'soft-light', opacity: 0.5 * s }} />
      </React.Fragment>
    );
  }

  const edge = mode === 'edge';
  const temp = edge
    ? { background: `radial-gradient(125% 115% at 50% 44%, transparent 52%, ${t.washBot} 100%)`, mixBlendMode: t.blend, opacity: s }
    : { background: `linear-gradient(to top, ${t.washBot}, ${t.washTop})`, mixBlendMode: t.blend, opacity: s };
  return (
    <React.Fragment>
      <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none', ...temp }} />
      <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none',
        background: `radial-gradient(120% 90% at ${gx}% 0%, ${t.glow}, transparent 58%)`, mixBlendMode: 'soft-light', opacity: (edge ? 0.6 : 0.9) * s }} />
      {/* edge lift — torn corners catch the time hue */}
      <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none',
        background: `radial-gradient(125% 120% at 50% ${edge ? 46 : 38}%, transparent ${edge ? 56 : 46}%, ${t.accent}2e 100%)`, mixBlendMode: 'screen', opacity: 0.9 * s }} />
      <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none',
        background: `radial-gradient(150% 130% at ${gx}% -10%, transparent ${edge ? 50 : 38}%, rgba(16,20,38,${(edge ? 0.14 : 0.22) * s}) 100%)` }} />
    </React.Fragment>
  );
}

// ---------- the living sky behind the sheet (Aether Sky) ----------
function SkyBacking({ t, w, h }) {
  const [bx, by] = bodyXY(t, w, h * 0.74, 20);
  return (
    <div style={{ position: 'absolute', inset: 0, overflow: 'hidden',
      background: `linear-gradient(to bottom, ${t.skyFull[0]}, ${t.skyFull[1]} 58%, ${t.skyFull[2]})` }}>
      {/* cloud / weather texture */}
      <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none', opacity: 0.5, mixBlendMode: 'soft-light',
        backgroundImage: "url('assets/textures/creases.jpeg')", backgroundSize: 'cover', backgroundPosition: 'center' }} />
      {/* stars at night */}
      {t.stars && Array.from({ length: 40 }).map((_, i) => {
        const sx = (i * 67 % 100), sy = (i * 41 % 92);
        return <span key={i} style={{ position: 'absolute', left: `${sx}%`, top: `${sy}%`,
          width: i % 6 === 0 ? 2.6 : 1.5, height: i % 6 === 0 ? 2.6 : 1.5, borderRadius: '50%',
          background: '#e2e8f6', opacity: 0.25 + (i % 4) * 0.18 }} />;
      })}
      {/* the sun / moon */}
      <div style={{ position: 'absolute', left: bx, top: by, transform: 'translate(-50%,-50%)' }}>
        <Celestial t={t} size={t.body === 'moon' ? 30 : 26} />
      </div>
      {/* horizon haze */}
      <div style={{ position: 'absolute', left: 0, right: 0, bottom: 0, height: '42%', pointerEvents: 'none',
        background: `linear-gradient(to top, ${t.glow}, transparent)`, opacity: 0.5, mixBlendMode: 'soft-light' }} />
    </div>
  );
}

// drifting accent motes
function Motes({ t }) {
  return (
    <React.Fragment>
      <style>{`@keyframes todMote{0%{transform:translateY(8px);opacity:0}30%{opacity:.7}100%{transform:translateY(-30px);opacity:0}}`}</style>
      {[14, 30, 47, 63, 80, 91].map((x, i) => (
        <span key={i} style={{ position: 'absolute', bottom: 30, left: `${x}%`, width: 4, height: 4, borderRadius: '50%',
          background: i % 2 ? t.accent2 : t.accent, boxShadow: `0 0 7px ${t.accent}`,
          animation: `todMote ${4 + (i % 3)}s ease-in ${i * 0.6}s infinite`, pointerEvents: 'none' }} />
      ))}
    </React.Fragment>
  );
}

// corner stamped celestial sigil
function Sigil({ t, size = 72 }) {
  const r = size / 2, cx = r, cy = r;
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}
      style={{ position: 'absolute', top: 12, right: 12, opacity: 0.5, pointerEvents: 'none', zIndex: 6 }}>
      <circle cx={cx} cy={cy} r={r - 3} fill="none" stroke={t.accent} strokeWidth="1" strokeDasharray="2 3" />
      <circle cx={cx} cy={cy} r={r - 9} fill="none" stroke={t.accent} strokeWidth="0.7" />
      {t.body === 'moon'
        ? <path d={`M ${cx} ${cy - 10} A 10 10 0 1 0 ${cx} ${cy + 10} A 7 10 0 1 1 ${cx} ${cy - 10} Z`} fill={t.accent} opacity="0.8" />
        : <g stroke={t.accent} strokeWidth="1.1" strokeLinecap="round">
            {Array.from({ length: 12 }).map((_, i) => { const a = i / 12 * Math.PI * 2; return <line key={i} x1={cx + Math.cos(a) * 7} y1={cy + Math.sin(a) * 7} x2={cx + Math.cos(a) * 13} y2={cy + Math.sin(a) * 13} />; })}
            <circle cx={cx} cy={cy} r="6" fill={t.accent} opacity="0.7" />
          </g>}
    </svg>
  );
}

// ====================================================================
// Chrome — the recognizable Sky Hearth port UI (shared by every treatment).
// ====================================================================
const ELEM_GLYPH = { Fire: '△', Earth: '□', Ice: '◊', Holy: '✦', Lightning: '╱', Wind: '≋', Water: '~', Nature: '✿' };

function Chrome({ t, acc, tinted, inset = 0 }) {
  return (
    <div style={{ position: 'absolute', inset, zIndex: 5, display: 'flex', flexDirection: 'column',
      padding: '15px 19px', fontFamily: "'Special Elite', monospace" }}>
      {/* header */}
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12 }}>
        <div>
          <div style={{ font: "10px 'Special Elite',monospace", letterSpacing: '0.18em', color: 'var(--sepia)', textTransform: 'uppercase' }}>Hearth Census</div>
          <div style={{ display: 'flex', gap: 8, alignItems: 'baseline', marginTop: 2 }}>
            <span style={{ fontFamily: "'IM Fell English SC',serif", fontSize: 19, color: 'var(--ink)' }}>SKYHEARTH PORT</span>
            <span style={{ border: `1.5px solid ${acc}`, color: acc, font: "10px 'IM Fell English SC',serif", padding: '1px 6px', letterSpacing: '0.08em', transform: 'rotate(-3deg)' }}>TIER III</span>
          </div>
          <div style={{ font: "11px 'JetBrains Mono',monospace", color: 'var(--sepia)', marginTop: 5, letterSpacing: '0.04em' }}>
            Day 04 · <span style={{ color: acc, fontWeight: 600 }}>{t.label}</span>
          </div>
        </div>
        <div style={{ flexShrink: 0 }}><ClockDial t={t} size={84} /></div>
      </div>

      {/* slot caption */}
      <div style={{ marginTop: 10, font: "10px 'JetBrains Mono',monospace", letterSpacing: '0.14em', color: tinted ? t.accent : 'var(--sepia)' }}>
        {t.label.toUpperCase()} SLOT · ON-TIME {t.pair[0].toUpperCase()} · {t.pair[1].toUpperCase()}
      </div>
      <div style={{ height: 1, background: 'var(--ink-faded)', margin: '8px 0 12px' }} />

      {/* element chips */}
      <div style={{ display: 'flex', gap: 9, flexWrap: 'wrap' }}>
        {['Fire', 'Ice', 'Lightning', 'Water', 'Earth', 'Holy', 'Wind', 'Nature'].map(name => {
          const lit = t.pair.includes(name);
          return (
            <div key={name} style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '5px 9px',
              border: `1.2px solid ${lit ? t.accent : 'var(--ink-ghost)'}`,
              background: lit ? `${t.accent}1f` : 'transparent', opacity: lit ? 1 : 0.5 }}>
              <span style={{ fontFamily: "'IM Fell English SC',serif", fontSize: 14, color: lit ? t.accent : 'var(--ink-faded)' }}>{ELEM_GLYPH[name]}</span>
              <span style={{ font: "10px 'JetBrains Mono',monospace", color: lit ? 'var(--ink)' : 'var(--ink-faded)', letterSpacing: '0.04em' }}>{name}</span>
            </div>
          );
        })}
      </div>

      <div style={{ flex: 1 }} />

      {/* footer */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10,
        borderTop: '1px solid var(--ink-faded)', paddingTop: 11 }}>
        <span style={{ fontFamily: "'IM Fell English SC',serif", fontStyle: 'italic', fontSize: 13, color: 'var(--sepia)' }}>{t.poem}</span>
        <span style={{ background: 'var(--ink)', color: 'var(--paper-light)', font: "12px 'IM Fell English SC',serif", letterSpacing: '0.16em', padding: '8px 18px' }}>LAUNCH ▸</span>
      </div>
    </div>
  );
}

// the torn parchment sheet, masked so its deckle edges reveal the sky behind
function TornSheet({ children, inset = 8, washChild }) {
  return (
    <div style={{ position: 'absolute', inset,
      backgroundColor: 'var(--paper)', backgroundImage: "url('assets/textures/parchment-base.jpeg')",
      backgroundSize: 'cover', backgroundPosition: 'center',
      WebkitMaskImage: "url('assets/textures/torn-alpha.png')", maskImage: "url('assets/textures/torn-alpha.png')",
      WebkitMaskSize: '100% 100%', maskSize: '100% 100%', WebkitMaskRepeat: 'no-repeat', maskRepeat: 'no-repeat',
      filter: 'drop-shadow(0 6px 15px rgba(8,10,22,0.6))',
      boxShadow: 'inset 0 0 60px rgba(110,80,40,0.22)' }}>
      {washChild}
      {/* age splotches, clipped to the sheet */}
      <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none',
        background: 'radial-gradient(ellipse 180px 130px at 96% 94%, rgba(110,70,30,0.16), transparent 70%), radial-gradient(ellipse 140px 110px at 4% 92%, rgba(110,70,30,0.12), transparent 70%)' }} />
      {children}
    </div>
  );
}

// Which corner lifts to show more sky — aligned to where each slot's sun/moon
// sits, so the open corner nestles the celestial body (intentional + cute).
const REVEAL_CORNER = { night: 'tl', morning: 'bl', afternoon: 'tr', evening: 'br' };
function insetFor(corner) {
  const B = 30, S = 11; // big gap / small gap, in px  (top right bottom left)
  return {
    tl: `${B}px ${S}px ${S}px ${B}px`,
    tr: `${B}px ${B}px ${S}px ${S}px`,
    bl: `${S}px ${S}px ${B}px ${B}px`,
    br: `${S}px ${B}px ${B}px ${S}px`,
  }[corner];
}

// ====================================================================
// MiniPort
// ====================================================================
function MiniPort({ todKey, treatment, w = 560, h = 360, offset = 14, tilt = 0, wash = 0.78, washMode = 'edge' }) {
  const t = TOD[todKey];
  const tinted = treatment === 'celestial' || treatment === 'aethersky';
  const acc = tinted ? t.accent : 'var(--stamp-amber)';

  // ---- AETHER SKY: sheet floats on the living time-of-day sky ----
  if (treatment === 'aethersky') {
    const ins = (offset && typeof offset === 'object')
      ? `${offset.top}px ${offset.right}px ${offset.bottom}px ${offset.left}px`
      : offset;
    const inner = (
      <React.Fragment>
        <TornSheet inset={ins} washChild={<WashLayers t={t} strength={wash} mode={washMode} />} />
        <Chrome t={t} acc={acc} tinted={tinted} inset={ins} />
      </React.Fragment>
    );
    return (
      <div style={{ position: 'relative', width: w, height: h, overflow: 'hidden', background: '#0c0a12' }}>
        <SkyBacking t={t} w={w} h={h} />
        {tilt
          ? <div style={{ position: 'absolute', inset: 0, transform: `rotate(${tilt}deg)`, transformOrigin: '50% 52%' }}>{inner}</div>
          : inner}
      </div>
    );
  }

  // ---- WASH / CELESTIAL: light & accents on a full-bleed sheet ----
  const showWash = treatment === 'wash' || treatment === 'celestial';
  const washStrength = treatment === 'celestial' ? 0.34 : 1;
  return (
    <div style={{ position: 'relative', width: w, height: h, overflow: 'hidden',
      background: 'var(--paper)', backgroundImage: "url('assets/textures/parchment-base.jpeg')",
      backgroundSize: 'cover', backgroundPosition: 'center', boxShadow: 'inset 0 0 60px rgba(110,80,40,0.22)' }}>
      {showWash && <WashLayers t={t} strength={washStrength} />}
      {treatment === 'celestial' && <Sigil t={t} />}
      <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none',
        background: 'radial-gradient(ellipse 180px 130px at 96% 94%, rgba(110,70,30,0.16), transparent 70%), radial-gradient(ellipse 140px 110px at 4% 92%, rgba(110,70,30,0.12), transparent 70%)' }} />
      <Chrome t={t} acc={acc} tinted={tinted} />
    </div>
  );
}

Object.assign(window, { MiniPort });

// ====================================================================
// AetherSky — LIVE background for the real #canvas. Crossfades the four
// day-slots (sky backing + torn-masked parchment + full-colour wash) as
// the day ticks. Rendered behind the UI (zIndex 0, pointer-events none).
// Baked from the v4 study: margin 14/14/2/2, full-colour wash @ 0.78.
// ====================================================================
function AetherSky({ slotIdx, offset, wash = 0.78, washMode = 'full-color', w = 1440, h = 900 }) {
  const off = offset || { top: 14, right: 14, bottom: 2, left: 2 };
  const ins = `${off.top}px ${off.right}px ${off.bottom}px ${off.left}px`;
  // Per-slot wash scale — Night's cool wash reads heaviest, so soften it ~40%.
  const WASH_SCALE = { night: 0.6, morning: 1, afternoon: 1, evening: 1 };
  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 0, overflow: 'hidden', pointerEvents: 'none' }}>
      {TOD_ORDER.map((k, i) => {
        const t = TOD[k];
        const on = i === slotIdx;
        return (
          <div key={k} style={{ position: 'absolute', inset: 0, opacity: on ? 1 : 0, transition: 'opacity 900ms ease' }}>
            <SkyBacking t={t} w={w} h={h} />
            <TornSheet inset={ins} washChild={<WashLayers t={t} strength={wash * (WASH_SCALE[k] ?? 1)} mode={washMode} />} />
          </div>
        );
      })}
    </div>
  );
}

Object.assign(window, { AetherSky });
