// Shared atoms for ROAMR mobile prototype
const TOKENS = {
  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',
  fontD: 'Space Grotesk, system-ui, sans-serif',
  fontB: 'IBM Plex Sans, system-ui, sans-serif',
  fontM: 'JetBrains Mono, ui-monospace, monospace',
};

// ─── Chip (activity / filter) ───────────────────────────────
function Chip({ children, active, onClick, signal, danger, icon, sm }) {
  const base = {
    display: 'inline-flex', alignItems: 'center', gap: 5,
    fontFamily: TOKENS.fontB, fontWeight: 500,
    fontSize: sm ? 11 : 12,
    padding: sm ? '4px 8px' : '6px 11px',
    border: `1px solid ${TOKENS.borderSoft}`,
    color: TOKENS.text, background: 'transparent',
    borderRadius: 2, cursor: 'pointer',
    letterSpacing: 0.1,
    whiteSpace: 'nowrap',
  };
  const styles = active ? { ...base, background: TOKENS.textHi, color: TOKENS.bg, borderColor: TOKENS.textHi }
    : signal ? { ...base, background: 'rgba(226,94,31,0.14)', color: TOKENS.signalGlow, borderColor: TOKENS.signalDeep }
    : danger ? { ...base, color: TOKENS.rust, borderColor: TOKENS.rust }
    : base;
  return <button style={styles} onClick={onClick}>{icon}{children}</button>;
}

// ─── Confidence pip indicator ───────────────────────────────
function ConfBadge({ level = 'high', days, compact }) {
  const fill = level === 'high' ? TOKENS.lichen : level === 'med' ? TOKENS.amber : TOKENS.rust;
  const filled = level === 'high' ? 4 : level === 'med' ? 3 : 1;
  const label = level === 'high' ? 'HIGH' : level === 'med' ? 'MED' : 'LOW';
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center', gap: 7,
      padding: compact ? '3px 7px 3px 5px' : '5px 9px 5px 7px',
      background: TOKENS.cardElev, border: `1px solid ${TOKENS.border}`,
      fontFamily: TOKENS.fontM, fontSize: compact ? 9 : 10,
      letterSpacing: 0.6, borderRadius: 2,
    }}>
      <span style={{ display: 'inline-flex', gap: 1.5 }}>
        {[0,1,2,3].map(i => (
          <span key={i} style={{
            width: 3, height: compact ? 8 : 10,
            background: i < filled ? fill : '#3A4036',
          }} />
        ))}
      </span>
      <span style={{ color: TOKENS.textHi, fontWeight: 600 }}>{label}</span>
      {days != null && <span style={{ color: TOKENS.textMute }}>· {days}d</span>}
    </div>
  );
}

// ─── Stat (number + unit) ───────────────────────────────────
function Stat({ value, unit, size = 'm', color, sub }) {
  const sz = size === 'xl' ? 32 : size === 'l' ? 24 : size === 'm' ? 18 : 14;
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
      <span style={{
        fontFamily: TOKENS.fontM, fontSize: sz, fontWeight: 500,
        color: color || TOKENS.textHi, letterSpacing: -0.3, lineHeight: 1,
      }}>{value}</span>
      <span style={{
        fontFamily: TOKENS.fontM, fontSize: 9, color: TOKENS.textMute,
        letterSpacing: 1, textTransform: 'uppercase', marginTop: 4,
      }}>{unit}</span>
      {sub && <span style={{ fontFamily: TOKENS.fontM, fontSize: 9, color: TOKENS.textLo, marginTop: 2 }}>{sub}</span>}
    </div>
  );
}

// ─── Surface bar ────────────────────────────────────────────
function SurfaceBar({ parts, showLegend }) {
  // parts: [{label, pct, color}]
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 8, width: '100%' }}>
      <div style={{ display: 'flex', height: 8, width: '100%', overflow: 'hidden' }}>
        {parts.map((p, i) => (
          <div key={i} style={{ flex: p.pct, background: p.color }} />
        ))}
      </div>
      {showLegend && (
        <div style={{ display: 'flex', gap: 14, flexWrap: 'wrap',
          fontFamily: TOKENS.fontM, fontSize: 10, color: TOKENS.textMute, letterSpacing: 0.5 }}>
          {parts.map((p, i) => (
            <span key={i}><b style={{ color: p.color, fontWeight: 600 }}>{p.pct}%</b> {p.label.toUpperCase()}</span>
          ))}
        </div>
      )}
    </div>
  );
}

// ─── Mini stylized map (SVG) ────────────────────────────────
function MapMock({ height = 200, routePath, pins = [], showLabels, dense, hero }) {
  const defaultPath = "M40 170 Q 80 140 110 110 Q 150 80 200 100 Q 260 130 310 95 Q 360 60 380 90";
  return (
    <svg viewBox="0 0 400 200" preserveAspectRatio="xMidYMid slice"
      style={{ width: '100%', height, display: 'block', background: hero ? '#0a0d0a' : '#0E110D' }}>
      <defs>
        <pattern id="grid-roamr" width="40" height="40" patternUnits="userSpaceOnUse">
          <path d="M40 0 L0 0 L0 40" fill="none" stroke="#1c211a" strokeWidth="0.5"/>
        </pattern>
      </defs>
      <rect width="400" height="200" fill="url(#grid-roamr)" />
      {/* contour lines */}
      <g stroke="#2a2f27" strokeWidth="0.7" fill="none">
        <path d="M0 60 Q 80 40 160 50 T 320 55 T 400 70" />
        <path d="M0 80 Q 80 60 160 70 T 320 75 T 400 90" />
        <path d="M0 100 Q 80 80 160 90 T 320 95 T 400 110" />
        <path d="M0 120 Q 80 100 160 110 T 320 115 T 400 130" />
        <path d="M0 140 Q 80 120 160 130 T 320 135 T 400 150" />
        {dense && <>
          <path d="M0 70 Q 80 50 160 60 T 320 65 T 400 80" stroke="#3A4036" opacity="0.4"/>
          <path d="M0 90 Q 80 70 160 80 T 320 85 T 400 100" stroke="#3A4036" opacity="0.4"/>
          <path d="M0 110 Q 80 90 160 100 T 320 105 T 400 120" stroke="#3A4036" opacity="0.4"/>
        </>}
      </g>
      {/* water */}
      <path d="M0 165 Q 100 175 200 168 T 400 165" stroke="#6E92B0" strokeWidth="1.2" fill="none" opacity="0.6" />
      {/* route */}
      <path d={routePath || defaultPath}
        stroke="#E25E1F" strokeWidth="3" fill="none" strokeLinecap="round" strokeLinejoin="round" />
      {/* pins */}
      {pins.map((p, i) => (
        <g key={i} transform={`translate(${p.x},${p.y})`}>
          <circle r={p.size || 7} fill={p.color || '#E25E1F'} stroke="#F2EDE2" strokeWidth="1.8" />
          {p.label && <text y="3" textAnchor="middle" fontFamily="JetBrains Mono" fontSize="8" fontWeight="700"
            fill={p.color === '#F2B33B' ? '#0E110D' : '#fff'}>{p.label}</text>}
        </g>
      ))}
      {showLabels && (
        <>
          <text x="10" y="16" fontFamily="JetBrains Mono" fontSize="8" fill="#797F72" letterSpacing="1.5">53.1424°N · 1.9789°W</text>
          <text x="390" y="16" textAnchor="end" fontFamily="JetBrains Mono" fontSize="8" fill="#797F72" letterSpacing="1.5">PEAK DISTRICT</text>
        </>
      )}
    </svg>
  );
}

// ─── Elevation graph ────────────────────────────────────────
function ElevationGraph({ height = 80 }) {
  return (
    <svg viewBox="0 0 400 100" preserveAspectRatio="none" style={{ width: '100%', height, display: 'block' }}>
      <defs>
        <linearGradient id="elev-fill" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#E25E1F" stopOpacity="0.25" />
          <stop offset="100%" stopColor="#E25E1F" stopOpacity="0" />
        </linearGradient>
      </defs>
      <g stroke="#2A2F27" strokeWidth="0.5">
        <line x1="0" y1="25" x2="400" y2="25" />
        <line x1="0" y1="50" x2="400" y2="50" />
        <line x1="0" y1="75" x2="400" y2="75" />
      </g>
      <path d="M0 80 L20 70 L50 55 L80 60 L120 35 L160 40 L200 25 L240 30 L280 50 L320 45 L360 65 L400 70 L400 100 L0 100 Z"
        fill="url(#elev-fill)" />
      <path d="M0 80 L20 70 L50 55 L80 60 L120 35 L160 40 L200 25 L240 30 L280 50 L320 45 L360 65 L400 70"
        stroke="#E25E1F" strokeWidth="1.5" fill="none" />
      <text x="6" y="14" fontFamily="JetBrains Mono" fontSize="8" fill="#797F72" letterSpacing="1">+612M GAIN · −598M LOSS</text>
    </svg>
  );
}

// ─── Activity icon ──────────────────────────────────────────
function ActIcon({ kind, size = 18, color }) {
  const c = color || 'currentColor';
  const s = { stroke: c, strokeWidth: 1.6, fill: 'none', strokeLinecap: 'round', strokeLinejoin: 'round' };
  switch (kind) {
    case 'moto': return (
      <svg width={size} height={size} viewBox="0 0 24 24" style={s}>
        <circle cx="5" cy="17" r="3"/><circle cx="19" cy="17" r="3"/>
        <path d="M5 17 L11 9 L15 9 L19 17 M11 9 L9 6 L7 6 M15 9 L18 7"/>
      </svg>
    );
    case 'hike': return (
      <svg width={size} height={size} viewBox="0 0 24 24" style={s}>
        <path d="M9 4 L12 9 L9 14 L13 20 M12 9 L17 8 M9 14 L6 13"/>
        <circle cx="9" cy="3.5" r="1.2" fill={c} stroke="none"/>
      </svg>
    );
    case 'gravel': return (
      <svg width={size} height={size} viewBox="0 0 24 24" style={s}>
        <circle cx="5" cy="17" r="3"/><circle cx="19" cy="17" r="3"/>
        <path d="M5 17 L10 9 L14 13 L17 8 L19 17 M10 9 L14 9 M14 8 L18 8"/>
      </svg>
    );
    case 'mtb': return (
      <svg width={size} height={size} viewBox="0 0 24 24" style={s}>
        <circle cx="5" cy="17" r="3"/><circle cx="19" cy="17" r="3"/>
        <path d="M5 17 L9 7 L15 14 L19 17 M9 7 L13 9 M15 14 L18 9"/>
      </svg>
    );
    case '4x4': return (
      <svg width={size} height={size} viewBox="0 0 24 24" style={s}>
        <path d="M3 16 L3 12 L6 8 L18 8 L21 12 L21 16 L19 16 M3 16 L5 16 M11 16 L13 16"/>
        <circle cx="7" cy="17" r="2"/><circle cx="17" cy="17" r="2"/>
      </svg>
    );
    case 'run': return (
      <svg width={size} height={size} viewBox="0 0 24 24" style={s}>
        <circle cx="14" cy="4" r="1.5" fill={c} stroke="none"/>
        <path d="M9 20 L11 15 L8 12 L12 8 L15 11 L18 11 M11 15 L14 16 L16 20"/>
      </svg>
    );
    case 'dog': return (
      <svg width={size} height={size} viewBox="0 0 24 24" style={s}>
        <path d="M5 14 L5 11 L7 9 L9 9 L11 11 L15 11 L17 9 L19 11 L19 17 L17 17 L17 14 L11 14 L11 17 L9 17 L9 14 L7 14 M7 9 L5 7 M17 9 L19 7"/>
      </svg>
    );
    case 'camp': return (
      <svg width={size} height={size} viewBox="0 0 24 24" style={s}>
        <path d="M12 4 L4 20 L20 20 Z M12 4 L8 20 M12 4 L16 20"/>
      </svg>
    );
    default: return null;
  }
}

// ─── Section header in screens ──────────────────────────────
function SectionHead({ kicker, title, action, onAction }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', padding: '0 18px', marginBottom: 12 }}>
      <div>
        {kicker && <div style={{ fontFamily: TOKENS.fontM, fontSize: 10, color: TOKENS.signal, letterSpacing: 2, marginBottom: 4 }}>{kicker}</div>}
        <div style={{ fontFamily: TOKENS.fontD, fontSize: 18, fontWeight: 600, color: TOKENS.textHi, letterSpacing: -0.2 }}>{title}</div>
      </div>
      {action && (
        <button onClick={onAction} style={{
          background: 'transparent', border: 'none', cursor: 'pointer',
          fontFamily: TOKENS.fontM, fontSize: 10, color: TOKENS.textLo, letterSpacing: 1.2,
        }}>{action} →</button>
      )}
    </div>
  );
}

// ─── Icon-only button (for nav, header) ─────────────────────
function IconBtn({ children, onClick, active, size = 38, label }) {
  return (
    <button onClick={onClick} aria-label={label} style={{
      width: size, height: size, display: 'flex', alignItems: 'center', justifyContent: 'center',
      background: active ? TOKENS.textHi : TOKENS.card,
      color: active ? TOKENS.bg : TOKENS.textHi,
      border: `1px solid ${active ? TOKENS.textHi : TOKENS.border}`,
      cursor: 'pointer', borderRadius: 2,
    }}>{children}</button>
  );
}

Object.assign(window, { TOKENS, Chip, ConfBadge, Stat, SurfaceBar, MapMock, ElevationGraph, ActIcon, SectionHead, IconBtn });
