// ROAMR — Theme system, palette presets, logo variants, density + style tweaks.
// On every tweak change we MUTATE window.TOKENS in place (the live object that
// every screen module captured at script load) and bump a tick so Root remounts.

// ─── Palette presets ───────────────────────────────────────────────────────
// Each palette has dark + light. Accents (signal/lichen/etc.) shift slightly
// per family so the whole vibe changes — not just bg/fg.

const PALETTES = {
  // Warm travel default — clay, cream, moss. AllTrails / Airbnb energy.
  earth: {
    name: 'Earth',
    dark: {
      bg: '#1A1612', bgDeep: '#0F0C09',
      card: '#231E18', cardElev: '#2B251D',
      border: '#3A3327', borderSoft: '#52483A',
      textHi: '#F8F0DD', text: '#EFE5CD', textMid: '#CFC4A8', textLo: '#9C8F76', textMute: '#6F6553',
      signal: '#D6783A', signalDeep: '#A05418', signalGlow: '#EAA06A',
      lichen: '#9DB082', amber: '#E5B26A', rust: '#B65324', slate: '#7A8E8A',
      pageBg: '#0A0807', scrollThumb: '#3A3327',
    },
    light: {
      bg: '#F8F1E1', bgDeep: '#EDE3CD',
      card: '#FEFAEC', cardElev: '#FFFFFF',
      border: '#DCD2B9', borderSoft: '#BFB294',
      textHi: '#1A1612', text: '#2F2820', textMid: '#534736', textLo: '#7C6E55', textMute: '#9C8F76',
      signal: '#C56930', signalDeep: '#8E4416', signalGlow: '#D6783A',
      lichen: '#6A8A58', amber: '#B58936', rust: '#9D451B', slate: '#5E7572',
      pageBg: '#E5D9BE', scrollThumb: '#BFB294',
    },
  },
  // Current rugged — charcoal + signal orange. The "field instrument" mood.
  signal: {
    name: 'Signal',
    dark: {
      bg: '#0E110D', bgDeep: '#07090a',
      card: '#141812', cardElev: '#1C211A',
      border: '#2A2F27', borderSoft: '#3A4036',
      textHi: '#F2EDE2', text: '#E8E5D6', textMid: '#CDCFC1', textLo: '#A8AD9D', textMute: '#797F72',
      signal: '#E25E1F', signalDeep: '#B84812', signalGlow: '#F58A4A',
      lichen: '#7EA862', amber: '#F2B33B', rust: '#C13B1F', slate: '#6E92B0',
      pageBg: '#070908', scrollThumb: '#2A2F27',
    },
    light: {
      bg: '#F4EFE4', bgDeep: '#EAE4D5',
      card: '#FBF7ED', cardElev: '#FFFCF3',
      border: '#DAD3C1', borderSoft: '#C0B8A4',
      textHi: '#0E110D', text: '#1F2620', textMid: '#3F4538', textLo: '#5F6356', textMute: '#8A8E80',
      signal: '#D9521A', signalDeep: '#A53A10', signalGlow: '#E25E1F',
      lichen: '#5E8849', amber: '#C18A1F', rust: '#A22912', slate: '#4F758B',
      pageBg: '#E2DBC9', scrollThumb: '#BFB294',
    },
  },
  // Light, airy summer-travel palette — breeze blue + sun yellow accents.
  coastal: {
    name: 'Coastal',
    dark: {
      bg: '#0F1418', bgDeep: '#070A0C',
      card: '#161D22', cardElev: '#1E272D',
      border: '#283239', borderSoft: '#3A4651',
      textHi: '#EBF1F5', text: '#DDE5EA', textMid: '#BCC8D0', textLo: '#92A2AC', textMute: '#6A7682',
      signal: '#3FA4C2', signalDeep: '#1F7A95', signalGlow: '#5FC3DE',
      lichen: '#6FB58D', amber: '#E8C972', rust: '#C2604F', slate: '#7A9CB5',
      pageBg: '#060A0D', scrollThumb: '#283239',
    },
    light: {
      bg: '#F0F5F8', bgDeep: '#E0EAEF',
      card: '#FFFFFF', cardElev: '#FCFEFF',
      border: '#D7E0E6', borderSoft: '#B7C5CD',
      textHi: '#0F1418', text: '#1F2A30', textMid: '#42525C', textLo: '#647581', textMute: '#8B98A2',
      signal: '#1E7894', signalDeep: '#0E5670', signalGlow: '#3FA4C2',
      lichen: '#4D8A65', amber: '#A88826', rust: '#9C4434', slate: '#56768E',
      pageBg: '#D5E2EA', scrollThumb: '#B7C5CD',
    },
  },
};

// Density presets — multiply onto layout via window.TOKENS.density
const DENSITIES = {
  cozy:    { pad: 18, padSm: 14, gap: 14, radius: 14, h1: 28, h2: 22 },
  compact: { pad: 14, padSm: 10, gap: 10, radius: 6,  h1: 22, h2: 18 },
};

// Static fonts (don't change with palette)
const FONTS = {
  fontD: 'Space Grotesk, system-ui, sans-serif',
  fontB: 'IBM Plex Sans, system-ui, sans-serif',
  fontM: 'JetBrains Mono, ui-monospace, monospace',
};

function applyTokens(t) {
  const palette = PALETTES[t.palette] || PALETTES.earth;
  const colors = palette[t.mode] || palette.dark;
  const density = DENSITIES[t.density] || DENSITIES.cozy;
  // Mutate the live shared TOKENS object — every screen has captured this ref.
  Object.assign(window.TOKENS, FONTS, colors, { density, cardStyle: t.cardStyle, mapStyle: t.mapStyle, audience: t.audience, paletteName: t.palette, modeName: t.mode });
  const root = document.documentElement;
  root.style.setProperty('--page-bg', colors.pageBg);
  root.style.setProperty('--scroll-thumb', colors.scrollThumb);
  root.style.setProperty('color-scheme', t.mode === 'light' ? 'light' : 'dark');
}

// Back-compat shim — old code may call applyPalette('dark'|'light')
function applyPalette(name) {
  applyTokens({ palette: 'signal', mode: name, density: 'cozy', cardStyle: 'photo', mapStyle: 'soft', audience: 'multi' });
}

// ─── Logos ────────────────────────────────────────────────────────────────

function LogoBlaze({ T, height = 44 }) {
  const w = height * (30 / 38);
  return (
    <svg width={w} height={height} viewBox="0 0 30 38" aria-label="ROAMR Blaze">
      <g transform="rotate(5 15 19)" opacity="0.18"><rect x="3" y="4" width="24" height="30" fill={T.signal}/></g>
      <g transform="rotate(-4 15 19)">
        <rect x="2" y="3" width="26" height="32" fill={T.textHi}/>
        <text x="15" y="27" fontFamily="Space Grotesk" fontSize="22" fontWeight="700" fill={T.bg} textAnchor="middle" letterSpacing="-0.5">R</text>
      </g>
    </svg>
  );
}
function LogoStamp({ T, height = 44 }) {
  const w = height * (30 / 38);
  return (
    <svg width={w} height={height} viewBox="0 0 30 38" aria-label="ROAMR Stamp">
      <rect x="2" y="5" width="26" height="28" rx="3" fill={T.signal}/>
      <text x="15" y="26" fontFamily="Space Grotesk" fontSize="20" fontWeight="700" fill="#FFFFFF" textAnchor="middle" letterSpacing="-0.4">R</text>
    </svg>
  );
}
function LogoContour({ T, height = 44 }) {
  const w = height * (30 / 38);
  return (
    <svg width={w} height={height} viewBox="0 0 30 38" aria-label="ROAMR Contour">
      <g transform="translate(15 19)">
        <circle r="14" stroke={T.textHi} strokeWidth="1.4" fill="none"/>
        <circle r="10" stroke={T.textHi} strokeWidth="1.4" fill="none"/>
        <circle r="6" stroke={T.textHi} strokeWidth="1.4" fill="none"/>
        <circle r="2.6" fill={T.signal}/>
      </g>
    </svg>
  );
}
function LogoTrail({ T, height = 44 }) {
  const w = height * (30 / 38);
  return (
    <svg width={w} height={height} viewBox="0 0 30 38" aria-label="ROAMR Trail">
      <g fill="none" strokeLinecap="round" strokeLinejoin="round">
        <path d="M7 32 L7 8 L18 8 Q 23 8 23 15 Q 23 22 18 22 L9 22" stroke={T.textHi} strokeWidth="3"/>
        <path d="M14 22 Q 18 26 22 30 L26 32" stroke={T.signal} strokeWidth="3"/>
      </g>
      <circle cx="26" cy="32" r="2.4" fill={T.signal}/>
    </svg>
  );
}
const LOGOS = {
  blaze:   { label: 'Blaze',   render: LogoBlaze },
  stamp:   { label: 'Stamp',   render: LogoStamp },
  contour: { label: 'Contour', render: LogoContour },
  trail:   { label: 'Trail',   render: LogoTrail },
};

Object.assign(window, {
  PALETTES, DENSITIES, FONTS, applyTokens, applyPalette, LOGOS,
  LogoBlaze, LogoStamp, LogoContour, LogoTrail,
});

// ─── Roamr Tweaks panel ───────────────────────────────────────────────────

function PaletteSwatch({ palette, mode, active, onClick }) {
  const c = (PALETTES[palette] || PALETTES.earth)[mode] || (PALETTES[palette] || PALETTES.earth).dark;
  return (
    <button type="button" onClick={onClick}
      title={PALETTES[palette].name}
      style={{
        padding: 4, borderRadius: 10, cursor: 'pointer',
        background: active ? 'rgba(0,0,0,0.05)' : 'transparent',
        border: active ? '1.5px solid rgba(0,0,0,0.35)' : '1px solid rgba(0,0,0,0.10)',
        display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
      }}>
      <div style={{
        width: 56, height: 36, borderRadius: 6, overflow: 'hidden',
        display: 'grid', gridTemplateColumns: '2fr 1fr 1fr',
        border: '1px solid rgba(0,0,0,0.08)',
      }}>
        <div style={{ background: c.bg }} />
        <div style={{ background: c.signal }} />
        <div style={{ background: c.textHi }} />
      </div>
      <div style={{ fontFamily: 'JetBrains Mono', fontSize: 9, letterSpacing: 0.6,
        color: active ? c.signal : 'rgba(41,38,27,0.72)' }}>{PALETTES[palette].name.toUpperCase()}</div>
    </button>
  );
}

function LogoSwatch({ kind, T, active, onClick }) {
  const L = LOGOS[kind];
  return (
    <button type="button" onClick={onClick} title={L.label} style={{
      padding: '8px 4px 6px', borderRadius: 8, cursor: 'pointer',
      display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 5,
      background: active ? 'rgba(214,120,58,0.12)' : 'rgba(0,0,0,0.04)',
      border: active ? `1.5px solid ${T.signal}` : '1px solid rgba(0,0,0,0.10)',
      fontFamily: 'JetBrains Mono', fontSize: 8.5, letterSpacing: 0.6,
      color: active ? T.signal : 'rgba(41,38,27,0.72)',
    }}>
      <div style={{
        width: 30, height: 32, display: 'flex', alignItems: 'center', justifyContent: 'center',
        background: T.bg, borderRadius: 4, border: '1px solid rgba(0,0,0,0.08)',
      }}>
        <L.render T={T} height={22} />
      </div>
      {L.label.toUpperCase()}
    </button>
  );
}

function RoamrTweaksPanel({ t, setTweak, T }) {
  return (
    <window.TweaksPanel title="ROAMR · Tweaks">
      <window.TweakSection label="Palette" />
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 6 }}>
        {['earth', 'signal', 'coastal'].map(p => (
          <PaletteSwatch key={p} palette={p} mode={t.mode}
            active={t.palette === p} onClick={() => setTweak('palette', p)} />
        ))}
      </div>
      <window.TweakRadio label="Mode" value={t.mode} options={['dark', 'light']}
        onChange={(v) => setTweak('mode', v)} />

      <window.TweakSection label="Logo direction" />
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 5 }}>
        {Object.keys(LOGOS).map(k => (
          <LogoSwatch key={k} kind={k} T={T} active={t.logo === k}
            onClick={() => setTweak('logo', k)} />
        ))}
      </div>

      <window.TweakSection label="Layout" />
      <window.TweakRadio label="Density" value={t.density}
        options={['cozy', 'compact']} onChange={(v) => setTweak('density', v)} />
      <window.TweakRadio label="Cards" value={t.cardStyle}
        options={['photo', 'map', 'minimal']} onChange={(v) => setTweak('cardStyle', v)} />
      <window.TweakRadio label="Map" value={t.mapStyle}
        options={['soft', 'contour', 'satellite']} onChange={(v) => setTweak('mapStyle', v)} />

      <window.TweakSection label="Audience" />
      <window.TweakRadio label="Lead with" value={t.audience}
        options={['multi', 'green-lane']} onChange={(v) => setTweak('audience', v)} />
    </window.TweaksPanel>
  );
}

Object.assign(window, { RoamrTweaksPanel, PaletteSwatch, LogoSwatch });
