// IVE Mobile — theme context + shared editorial atoms
const { IVE_C: U, IVEWordmark, ApertureMark, Monogram, DomainIcon, StatusIcon } = window;
const { DOMAINS, STATUS_LABEL } = window;

// ── Audience-mode themes ─────────────────────────────────────────
// One brand, three voices. Same type + axes; surface + mood swap.
const MODE_THEMES = {
  atrium: {
    name: 'Atrium', dark: false, grid: false,
    bg: U.paper, bg2: U.paper2, surface: U.card, raised: U.white,
    ink: U.ink, ink2: U.ink2, ink3: U.ink3, rule: U.rule, ruleSoft: U.ruleSoft,
    accent2: U.ochreDeep,
  },
  field: {
    name: 'Field Notes', dark: false, grid: true,
    bg: U.paper, bg2: U.paper2, surface: U.card, raised: U.white,
    ink: U.ink, ink2: U.ink2, ink3: U.ink3, rule: U.rule, ruleSoft: U.ruleSoft,
    accent2: U.field,
  },
  civic: {
    name: 'Civic', dark: true, grid: false,
    bg: '#161C12', bg2: '#1E2A1A', surface: '#222E1D', raised: '#2A3724',
    ink: '#EFEEDD', ink2: 'rgba(239,238,221,0.82)', ink3: 'rgba(239,238,221,0.55)',
    rule: 'rgba(239,238,221,0.18)', ruleSoft: 'rgba(239,238,221,0.10)',
    accent2: U.ochreSoft,
  },
};

const ThemeCtx = React.createContext(MODE_THEMES.atrium);
const useTh = () => React.useContext(ThemeCtx);
const ACC = 'var(--ive-ochre)';

// Status color resolves against a fixed semantic palette (muted, never alarmed).
const STATUS_COLOR = {
  verified: U.verified, contested: U.contested, disputed: U.disputed,
  unsupported: U.unsupported, opinion: U.opinion, unverified: U.unverified,
};

// ── Editorial primitives ─────────────────────────────────────────
function Eye({ children, style }) {
  const th = useTh();
  return (
    <div className="ive-mono" style={{
      fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase',
      color: th.ink3, ...style,
    }}>{children}</div>
  );
}

function Hair({ style, soft }) {
  const th = useTh();
  return <div style={{ height: 1, background: soft ? th.ruleSoft : th.rule, ...style }} />;
}

// ── Status badge ─────────────────────────────────────────────────
function StatusBadge({ status, size = 'md' }) {
  const th = useTh();
  const c = STATUS_COLOR[status];
  const isSm = size === 'sm';
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: isSm ? 5 : 7,
      padding: isSm ? '3px 7px' : '5px 10px', border: `1px solid ${c}`,
      color: c, background: th.dark ? 'rgba(111,125,58,0.08)' : 'transparent',
    }}>
      <StatusIcon name={status} size={isSm ? 12 : 15} color={c} />
      <span className="ive-mono" style={{
        fontSize: isSm ? 9 : 10, letterSpacing: '0.1em', textTransform: 'uppercase',
      }}>{STATUS_LABEL[status]}</span>
    </span>
  );
}

// ── Domain tag ───────────────────────────────────────────────────
function DomainTag({ domain, withIcon = true }) {
  const th = useTh();
  const d = DOMAINS[domain];
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
      {withIcon && <DomainIcon name={domain} size={16} color={th.ink2} accent={U.ochre} />}
      <span className="ive-mono" style={{
        fontSize: 9.5, letterSpacing: '0.12em', textTransform: 'uppercase', color: th.ink3,
      }}>{d.label} · {d.halfLife >= 36500 ? '∞' : d.halfLife + 'd'}</span>
    </span>
  );
}

// ── Score readout (mono numerals) ────────────────────────────────
function ScoreReadout({ eb, sc, size = 30, gap = 22, labels = true }) {
  const th = useTh();
  const Item = ({ k, v }) => (
    <div>
      {labels && <Eye style={{ fontSize: 9, letterSpacing: '0.14em' }}>{k}</Eye>}
      <div className="ive-mono" style={{
        fontSize: size, lineHeight: 1, fontWeight: 500, color: th.ink,
        marginTop: labels ? 4 : 0, fontVariantNumeric: 'tabular-nums',
      }}>{v.toFixed(2)}</div>
    </div>
  );
  return (
    <div style={{ display: 'flex', gap }}>
      <Item k="Evidence basis" v={eb} />
      <div style={{ width: 1, background: th.rule, alignSelf: 'stretch' }} />
      <Item k="Social consensus" v={sc} />
    </div>
  );
}

// ── Screen header — editorial, clears the status bar ─────────────
function ScreenHeader({ eyebrow, title, onBack, right, sticky = true, big = true }) {
  const th = useTh();
  return (
    <div style={{
      position: 'relative', zIndex: 20, flexShrink: 0,
      background: th.bg, paddingTop: 'calc(env(safe-area-inset-top, 0px) + 18px)',
    }}>
      <div style={{ padding: '0 22px 14px' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', minHeight: 24 }}>
          {onBack ? (
            <button onClick={onBack} style={{
              all: 'unset', cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 6,
              color: th.ink2,
            }}>
              <svg width="9" height="15" viewBox="0 0 9 15"><path d="M8 1L1.5 7.5 8 14" stroke={th.ink2} strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
              <span className="ive-mono" style={{ fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase' }}>Back</span>
            </button>
          ) : <Eye>{eyebrow}</Eye>}
          {right || <span />}
        </div>
        {title && (
          <div className="ive-serif" style={{
            fontSize: big ? 34 : 26, fontWeight: 300, letterSpacing: '-0.02em',
            color: th.ink, lineHeight: 1.04, marginTop: onBack ? 14 : 10,
          }}>{title}</div>
        )}
      </div>
      <Hair />
    </div>
  );
}

// ── Pill button ──────────────────────────────────────────────────
function Pill({ children, onClick, solid, disabled, style }) {
  const th = useTh();
  return (
    <button onClick={onClick} disabled={disabled} style={{
      all: 'unset', cursor: disabled ? 'default' : 'pointer', textAlign: 'center',
      fontFamily: 'var(--ive-mono)', fontSize: 11, letterSpacing: '0.12em', textTransform: 'uppercase',
      padding: '12px 18px', opacity: disabled ? 0.4 : 1,
      background: solid ? U.ink : 'transparent',
      color: solid ? U.paper : th.ink,
      border: `1px solid ${solid ? U.ink : th.rule}`,
      ...style,
    }}>{children}</button>
  );
}

// ── Bottom tab bar ───────────────────────────────────────────────
const TAB_ICONS = {
  today: (c) => <g><line x1="4" y1="7" x2="20" y2="7" stroke={c} strokeWidth="1.5"/><line x1="4" y1="12" x2="20" y2="12" stroke={c} strokeWidth="1.5"/><line x1="4" y1="17" x2="14" y2="17" stroke={c} strokeWidth="1.5"/></g>,
  submit: (c) => <g><line x1="12" y1="5" x2="12" y2="19" stroke={c} strokeWidth="1.5"/><line x1="5" y1="12" x2="19" y2="12" stroke={c} strokeWidth="1.5"/></g>,
  saved: (c) => <path d="M6 4h12v16l-6-4-6 4V4z" fill="none" stroke={c} strokeWidth="1.5" strokeLinejoin="round"/>,
  verify: (c) => <g><rect x="4" y="4" width="16" height="16" fill="none" stroke={c} strokeWidth="1.5"/><path d="M8 12l3 3 5-6" fill="none" stroke={c} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></g>,
  you: (c) => <g><circle cx="12" cy="9" r="4" fill="none" stroke={c} strokeWidth="1.5"/><path d="M5 20c1.2-3.5 4-5 7-5s5.8 1.5 7 5" fill="none" stroke={c} strokeWidth="1.5" strokeLinecap="round"/></g>,
};

function TabBar({ active, onChange, role }) {
  const th = useTh();
  const tabs = role === 'verifier'
    ? [['today', 'Today'], ['submit', 'Submit'], ['verify', 'Verify'], ['you', 'You']]
    : [['today', 'Today'], ['submit', 'Submit'], ['saved', 'Saved'], ['you', 'You']];
  return (
    <div style={{
      flexShrink: 0, borderTop: `1px solid ${th.rule}`, background: th.bg,
      paddingBottom: 'calc(env(safe-area-inset-bottom, 0px) + 10px)', paddingTop: 8,
      display: 'grid', gridTemplateColumns: `repeat(${tabs.length}, 1fr)`,
    }}>
      {tabs.map(([k, label]) => {
        const on = active === k;
        const c = on ? U.ochre : th.ink3;
        return (
          <button key={k} onClick={() => onChange(k)} style={{
            all: 'unset', cursor: 'pointer', display: 'flex', flexDirection: 'column',
            alignItems: 'center', gap: 5, padding: '4px 0',
          }}>
            <svg width="22" height="22" viewBox="0 0 24 24">{TAB_ICONS[k](c)}</svg>
            <span className="ive-mono" style={{
              fontSize: 8.5, letterSpacing: '0.1em', textTransform: 'uppercase', color: c,
            }}>{label}</span>
            <span style={{ width: 4, height: 4, background: on ? U.ochre : 'transparent', marginTop: -1 }} />
          </button>
        );
      })}
    </div>
  );
}

Object.assign(window, {
  MODE_THEMES, ThemeCtx, useTh, ACC, STATUS_COLOR,
  Eye, Hair, StatusBadge, DomainTag, ScoreReadout, ScreenHeader, Pill, TabBar,
});
