// Mobile "Maternidade" — field app shell. Mirrors mobile/src/app/maternity (real code).
// Theme tokens — mapped onto the Fazenda Guanabara DS CSS variables.
// Semantics aligned to the DS: yellow = alert, terracotta = warning.
const MC = {
  primary: 'var(--color-primary)', primaryDark: 'var(--color-primary-900)', primaryLight: 'var(--color-primary-200)',
  tint: 'var(--color-primary-30)', tintNeutral: 'var(--color-primary-50)',
  bg: 'var(--color-neutral-light-100)', bgNeutral: 'var(--color-neutral-light-300)', neutralLight: 'var(--color-neutral-light-500)',
  textLight: 'var(--color-grayish-light)', text: 'var(--color-grayish)', textDark: 'var(--color-grayish-dark)',
  border: 'var(--color-neutral-200)', disabled: 'var(--color-neutral-100)',
  female: 'var(--color-danger-light)', male: 'var(--color-info)', success: 'var(--color-success)', successDark: 'var(--color-success-dark)',
  warning: 'var(--color-alert)', warningDark: 'var(--color-alert-dark)',
  danger: 'var(--color-danger)', dangerDark: 'var(--color-danger-dark)', dangerLight: 'var(--color-danger-light-100)',
  info: 'var(--color-info)', infoDark: 'var(--color-info-dark)',
}

function Phone({ title, logo, onBack, backLabel, leadingNode, onAction, actionIcon, children, footer, modal, centerNode }) {
  const { Icon } = window.FazendaGuanabaraDesignSystem_b62f7e
  return (
    <div style={{ width: 390, height: 800, background: '#000', borderRadius: 44, padding: 12, boxShadow: '0 24px 60px rgba(0,0,0,0.35)' }}>
      <div style={{ background: MC.bg, borderRadius: 32, height: '100%', overflow: 'hidden', display: 'flex', flexDirection: 'column', position: 'relative' }}>
        <div style={{ height: 38, padding: '12px 22px 0', display: 'flex', justifyContent: 'space-between', alignItems: 'center', background: MC.primaryDark, color: '#fff', fontSize: 12, fontWeight: 600 }}>
          <span>09:24</span><span>Offline · 100%</span>
        </div>
        <div style={{ background: MC.primaryDark, color: '#fff', padding: '10px 16px 16px', display: 'flex', alignItems: 'center', minHeight: 52 }}>
          {leadingNode ? leadingNode : onBack ? (backLabel
              ? <span onClick={onBack} style={{ display: 'flex', alignItems: 'center', gap: 2, cursor: 'pointer', margin: '-4px 0' }}><Icon name="chevron-back" size={20} color="#fff" /><span style={{ fontSize: 15, fontWeight: 600, color: '#fff' }}>{backLabel}</span></span>
              : <span onClick={onBack} style={{ width: 28, cursor: 'pointer', display: 'flex' }}><Icon name="chevron-back" size={22} color="#fff" /></span>
            ) : <span style={{ width: 28 }} />}
          <span style={{ flex: 1, textAlign: centerNode ? 'left' : 'center', minWidth: 0 }}>
            {centerNode ? centerNode
              : logo
              ? <img src={(window.__resources && window.__resources.logo) || "../../assets/logo-horizontal.svg"} alt="Fazenda Guanabara" style={{ height: 26, filter: 'brightness(0) invert(1)', verticalAlign: 'middle' }} />
              : <span style={{ fontSize: 18, fontWeight: 700 }}>{title}</span>}
          </span>
          {onAction ? <span onClick={onAction} style={{ width: 28, textAlign: 'right', cursor: 'pointer', display: 'flex', justifyContent: 'flex-end' }}><Icon name={actionIcon || 'exit-outline'} size={20} color="#fff" /></span> : <span style={{ width: 28 }} />}
        </div>
        <div style={{ flex: 1, overflowY: 'auto', display: 'flex', flexDirection: 'column', padding: '20px 20px 0' }}>{children}</div>
        {footer && <div style={{ padding: '12px 20px 20px' }}>{footer}</div>}
        {modal}
      </div>
    </div>
  )
}

function StepProgress({ step, total }) {
  return (
    <div style={{ marginBottom: 16 }}>
      <div style={{ display: 'flex', gap: 4, marginBottom: 8 }}>
        {Array.from({ length: total }).map((_, i) => (
          <div key={i} style={{ flex: 1, height: 3, borderRadius: 99, background: i < step ? MC.primary : MC.disabled }} />
        ))}
      </div>
      <div style={{ fontSize: 12, color: MC.text, fontWeight: 600, textAlign: 'center', letterSpacing: '0.8px', textTransform: 'uppercase' }}>Etapa {step} de {total}</div>
    </div>
  )
}

// Mobile button — single source of truth is the DS Button; this thin wrapper
// keeps the field-footer API (variant/rightIcon) used across the app screens.
function MButton({ children, onClick, variant = 'primary', disabled, rightIcon, style }) {
  const { Button } = window.FazendaGuanabaraDesignSystem_b62f7e
  const type = { primary: 'primary', outline: 'outline', ghost: 'ghost' }[variant] || 'primary'
  const base = { height: 54, maxHeight: 'none', width: '100%', justifyContent: 'center', padding: '0 1.1em' }
  // Estado desabilitado desenhado aqui: em campo o operador precisa VER que o botão
  // não está disponível (fundo neutro + texto apagado), não só o cursor.
  if (disabled) return (
    <button type="button" disabled style={{ ...base, display: 'inline-flex', alignItems: 'center', border: '1px solid ' + MC.border, borderRadius: 'var(--border-radius-default)',
      background: MC.disabled, color: MC.textLight, cursor: 'not-allowed', fontFamily: 'var(--font-family)', fontSize: 'var(--font-size-lg)', fontWeight: 'var(--font-weight-semibold)',
      textTransform: 'uppercase', ...style }}>{children}</button>
  )
  return (
    <Button type={type} size="field" onClick={onClick}
      icon={rightIcon} iconPosition="right"
      style={{ ...base, ...style }}>{children}</Button>
  )
}

const MHeading = ({ children }) => <div style={{ fontSize: 22, fontWeight: 700, color: MC.primary, textAlign: 'center', marginBottom: 8, lineHeight: 1.3 }}>{children}</div>
const MSub = ({ children }) => <div style={{ color: MC.text, fontSize: 16, textAlign: 'center', marginBottom: 24, lineHeight: 1.5 }}>{children}</div>

// Big tappable choice card — used for Sexo da cria (Fêmea/Macho) and "É animal de associação?" (Sim/Não).
function ChoiceCard({ icon, iconColor, label, selected, onClick }) {
  const { Icon } = window.FazendaGuanabaraDesignSystem_b62f7e
  return (
    <div onClick={onClick} style={{ flex: 1, background: selected ? MC.tint : '#fff', border: '1.8px solid ' + (selected ? MC.primary : MC.border),
      borderRadius: 15, padding: '28px 16px', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 12, cursor: 'pointer', minHeight: 132, justifyContent: 'center' }}>
      <Icon name={icon} size={40} color={iconColor || MC.primary} />
      <span style={{ fontSize: 16, fontWeight: 700, color: MC.textDark, textTransform: 'uppercase', letterSpacing: '0.5px' }}>{label}</span>
    </div>
  )
}

// ---- Maternidade — dados reais do dia (Fazenda Paranapanema, operador Siogo Pereira) ----
// Séries reais (lista completa, ignora-se a quantidade): GGUA, WCC, CMNP, SMM, GGUM, DQSD, ISPK, GTR, CEA, DQSC, LJVG
const SERIES_ASSOC = ['GGUA', 'WCC', 'CMNP', 'SMM', 'GGUM', 'DQSD', 'ISPK', 'GTR', 'CEA', 'DQSC', 'LJVG']

// 14 registros no dia: 7 fêmeas + 5 machos vivos + 2 perdas (natimorto/aborto).
const DAY_BASE = [
  { serie: 'GGUA', plantel: '1543', calf: '2032', sex: 'female', hora: '06:12' },
  { serie: 'WCC',  plantel: '0871', calf: '2033', sex: 'male',   hora: '06:48' },
  { serie: 'CMNP', plantel: '1190', calf: '2034', sex: 'female', hora: '07:05' },
  { serie: 'SMM',  plantel: '2210', calf: '2035', sex: 'female', hora: '07:31' },
  { serie: 'GGUM', plantel: '0345', calf: null,   sex: 'female', loss: true, tipo: 'Natimorto', hora: '07:52' },
  { serie: 'DQSD', plantel: '1822', calf: '2036', sex: 'male',   hora: '08:18' },
  { serie: 'GGUA', plantel: '0996', calf: '2037', sex: 'female', hora: '08:44' },
  { serie: 'ISPK', plantel: '1457', calf: '2038', sex: 'male',   hora: '09:10' },
  { serie: 'GTR',  plantel: '0612', calf: '2039', sex: 'female', hora: '09:39' },
  { serie: 'CEA',  plantel: '1303', calf: null,   sex: 'male',   loss: true, tipo: 'Aborto', hora: '10:02' },
  { serie: 'DQSC', plantel: '0788', calf: '2040', sex: 'male',   hora: '10:27' },
  { serie: 'LJVG', plantel: '1675', calf: '2041', sex: 'female', hora: '10:55' },
  { serie: 'WCC',  plantel: '2104', calf: '2042', sex: 'female', hora: '11:20' },
  { serie: 'SMM',  plantel: '0459', calf: '2043', sex: 'male',   hora: '11:48' },
]

// scenario: 'parcial' | 'sincronizado' | 'offline' | 'vazio'  — o total SEMPRE inclui pendentes (offline-first).
// Os últimos 7 dias. Hoje (offset 0) segue o cenário de sincronização; dias anteriores já estão sincronizados.
const WEEK = [
  { date: '11/05/2026', wd: 'Hoje' },
  { date: '10/05/2026', wd: 'Ontem' },
  { date: '09/05/2026', wd: 'Sábado' },
  { date: '08/05/2026', wd: 'Sexta-feira' },
  { date: '07/05/2026', wd: 'Quinta-feira' },
  { date: '06/05/2026', wd: 'Quarta-feira' },
  { date: '05/05/2026', wd: 'Terça-feira' },
]

function totalsOf(records) {
  return {
    records,
    total: records.length,
    femeas: records.filter(r => r.sex === 'female' && !r.loss).length,
    machos: records.filter(r => r.sex === 'male' && !r.loss).length,
    perdas: records.filter(r => r.loss).length,
    enviados: records.filter(r => r.status === 'enviado').length,
    aguardando: records.filter(r => r.status === 'aguardando').length,
  }
}

// Dia de hoje (offset 0) — segue o cenário.
function buildToday(scenario) {
  if (scenario === 'vazio') return { ...totalsOf([]), ...WEEK[0], offset: 0 }
  const records = DAY_BASE.map((r, i) => ({
    ...r, id: i,
    status: scenario === 'sincronizado' ? 'enviado'
      : scenario === 'offline' ? 'aguardando'
      : (i >= 11 ? 'aguardando' : 'enviado'), // parcial: 11 enviados, 3 aguardando
  }))
  return { ...totalsOf(records), ...WEEK[0], offset: 0 }
}

// Dias anteriores — gerados de forma determinística, todos já sincronizados.
function buildPastDay(offset) {
  let seed = offset * 7 + 3
  const rnd = () => { seed = (seed * 9301 + 49297) % 233280; return seed / 233280 }
  const counts = [0, 9, 12, 0, 11, 6, 0]
  const n = counts[offset]
  const horas = ['05:50', '06:20', '06:55', '07:30', '08:05', '08:40', '09:15', '09:50', '10:25', '11:00', '11:35', '12:10']
  const calfBase = 2000 - offset * 40
  const records = []
  for (let i = 0; i < n; i++) {
    const loss = (i === 3 || i === 8) && rnd() < 0.85
    const sex = i % 2 === 0 ? 'female' : 'male'
    records.push({
      id: i,
      serie: SERIES_ASSOC[Math.floor(rnd() * SERIES_ASSOC.length)],
      plantel: String(Math.floor(rnd() * 2400)).padStart(4, '0'),
      calf: loss ? null : String(calfBase + i),
      sex, loss, tipo: loss ? (rnd() < 0.5 ? 'Natimorto' : 'Aborto') : undefined,
      hora: horas[i % horas.length], status: 'enviado',
    })
  }
  return { ...totalsOf(records), ...WEEK[offset], offset }
}

// Semana inteira (índice = offset; 0 = hoje).
function buildWeek(scenario) {
  return WEEK.map((_, o) => o === 0 ? buildToday(scenario) : buildPastDay(o))
}

// Compat: resumo de hoje para o card da Home.
function buildDay(scenario) { return buildToday(scenario) }

// Linha de composição: "7 fêmeas · 5 machos · 2 perdas" com pontos coloridos.
function Composition({ d, size }) {
  const seg = (n, lbl, color, plural) => (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, whiteSpace: 'nowrap' }}>
      <span style={{ width: 9, height: 9, borderRadius: '50%', background: color, flexShrink: 0 }} />
      <span style={{ fontSize: size || 14, color: MC.text }}><b style={{ color: MC.textDark, fontWeight: 700 }}>{n}</b> {n === 1 ? lbl : plural}</span>
    </span>
  )
  return (
    <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px 16px', alignItems: 'center' }}>
      {seg(d.femeas, 'fêmea', MC.female, 'fêmeas')}
      {seg(d.machos, 'macho', MC.male, 'machos')}
      {seg(d.perdas, 'natimorto/aborto', MC.warningDark, 'natimortos/abortos')}
    </div>
  )
}

// Selo de sincronização (pill verde "Tudo sincronizado" ou âmbar com nº aguardando).
function SyncPill({ d, block }) {
  const { Icon } = window.FazendaGuanabaraDesignSystem_b62f7e
  const synced = d.aguardando === 0
  const bg = synced ? 'rgba(88,177,73,0.14)' : 'rgba(243,212,48,0.22)'
  const fg = synced ? MC.successDark : MC.warningDark
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 8, background: bg, color: fg,
      padding: '8px 13px', borderRadius: 99, fontSize: 13, fontWeight: 700, whiteSpace: 'nowrap',
      alignSelf: block ? 'stretch' : 'flex-start', justifyContent: block ? 'center' : 'flex-start' }}>
      <Icon name={synced ? 'checkmark-circle-outline' : 'file-tray-full-outline'} size={15} color={fg} />
      {synced ? 'Tudo sincronizado' : d.enviados + ' enviados · ' + d.aguardando + ' aguardando envio'}
    </div>
  )
}

// Card de status do leitor (bastão de chip/brinco eletrônico) — Home.
function ReaderCard({ connected }) {
  return (
    <div style={{ background: MC.bg, borderRadius: 15, padding: '18px 18px', boxShadow: '0 1px 2px rgba(0,0,0,0.12)', display: 'flex', alignItems: 'center', gap: 14 }}>
      <span style={{ width: 14, height: 14, borderRadius: '50%', flexShrink: 0, background: connected ? MC.success : MC.border,
        boxShadow: connected ? '0 0 0 4px rgba(88,177,73,0.18)' : 'none' }} />
      <div>
        <div style={{ fontSize: 16, fontWeight: 700, color: connected ? MC.primary : MC.text }}>{connected ? 'Leitor conectado' : 'Leitor desconectado'}</div>
        <div style={{ fontSize: 13, color: MC.textLight, marginTop: 1 }}>{connected ? 'Pronto para leitura' : 'Conecte o bastão para ler o brinco'}</div>
      </div>
    </div>
  )
}

// Card "Resumo do dia" — Home. Tocável → abre o detalhe (com seletor de dias).
function DaySummaryCard({ d, onOpen }) {
  const { Icon } = window.FazendaGuanabaraDesignSystem_b62f7e
  const hint = (
    <div onClick={onOpen} style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6, marginTop: 14, paddingTop: 13, borderTop: '1px solid ' + MC.neutralLight, cursor: 'pointer', color: MC.primary, fontSize: 12.5, fontWeight: 700 }}>
      Ver lançamentos de outros dias <Icon name="chevron-forward" size={14} color={MC.primary} />
    </div>
  )
  if (d.total === 0) {
    return (
      <div style={{ background: MC.bg, borderRadius: 15, padding: '20px 18px', boxShadow: '0 1px 2px rgba(0,0,0,0.12)' }}>
        <div style={{ fontSize: 11, textTransform: 'uppercase', fontWeight: 700, color: MC.textLight, letterSpacing: '0.8px', marginBottom: 10 }}>Resumo do dia</div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, color: MC.textLight }}>
          <Icon name="file-tray-full-outline" size={20} color={MC.textLight} />
          <span style={{ fontSize: 14 }}>Nenhum registro hoje ainda</span>
        </div>
        {hint}
      </div>
    )
  }
  return (
    <div style={{ background: MC.bg, borderRadius: 15, padding: '18px 18px', boxShadow: '0 1px 2px rgba(0,0,0,0.12)' }}>
      <div onClick={onOpen} style={{ cursor: 'pointer' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
          <span style={{ fontSize: 11, textTransform: 'uppercase', fontWeight: 700, color: MC.textLight, letterSpacing: '0.8px' }}>Resumo do dia</span>
          <Icon name="chevron-forward" size={18} color={MC.textLight} />
        </div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 12 }}>
          <span style={{ fontSize: 46, fontWeight: 700, color: MC.primary, lineHeight: 1 }}>{d.total}</span>
          <span style={{ fontSize: 14, color: MC.textLight, fontWeight: 600, whiteSpace: 'nowrap' }}>registros hoje</span>
        </div>
        <div style={{ marginBottom: 14 }}><Composition d={d} /></div>
        <SyncPill d={d} />
      </div>
      {hint}
    </div>
  )
}

// Seletor de dia — dia atual bem visível, < dia anterior · > dia mais recente (limitado a hoje).
function DayNavigator({ d, onPrev, onNext, canPrev, canNext }) {
  const { Icon } = window.FazendaGuanabaraDesignSystem_b62f7e
  const Arrow = ({ dir, on, onClick }) => (
    <button onClick={on ? onClick : undefined} disabled={!on} style={{ width: 44, height: 44, borderRadius: 12, flexShrink: 0, border: '1.5px solid ' + (on ? MC.border : MC.neutralLight),
      background: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: on ? 'pointer' : 'default', opacity: on ? 1 : 0.4 }}>
      <Icon name={dir === 'prev' ? 'chevron-back' : 'chevron-forward'} size={20} color={on ? MC.primary : MC.textLight} />
    </button>
  )
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 16 }}>
      <Arrow dir="prev" on={canPrev} onClick={onPrev} />
      <div style={{ flex: 1, textAlign: 'center' }}>
        <div style={{ fontSize: 18, fontWeight: 700, color: MC.primary, lineHeight: 1.1 }}>{d.wd}</div>
        <div style={{ fontSize: 12.5, color: MC.textLight, marginTop: 2 }}>{d.date}</div>
      </div>
      <Arrow dir="next" on={canNext} onClick={onNext} />
    </div>
  )
}

// Conteúdo da tela de lançamentos (seletor de dia + cabeçalho repete total + composição; lista em leitura).
function DaySummaryDetail({ d, nav }) {
  const { Icon } = window.FazendaGuanabaraDesignSystem_b62f7e
  return (
    <>
      {nav && <DayNavigator d={d} onPrev={nav.onPrev} onNext={nav.onNext} canPrev={nav.canPrev} canNext={nav.canNext} />}
      {d.total === 0 ? (
        <div style={{ background: '#fff', borderRadius: 15, padding: '40px 18px', boxShadow: '0 1px 2px rgba(0,0,0,0.1)', textAlign: 'center', marginBottom: 20 }}>
          <Icon name="file-tray-full-outline" size={30} color={MC.textLight} />
          <div style={{ fontSize: 16, fontWeight: 700, color: MC.text, marginTop: 12 }}>Nenhum lançamento neste dia</div>
          <div style={{ fontSize: 13, color: MC.textLight, marginTop: 4 }}>{d.offset === 0 ? 'Toque em Registrar nascimento para começar' : 'Não houve registros em ' + d.date}</div>
        </div>
      ) : (<>
        <div style={{ background: '#fff', borderRadius: 15, padding: '18px', boxShadow: '0 1px 2px rgba(0,0,0,0.1)', marginBottom: 16 }}>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 12 }}>
            <span style={{ fontSize: 40, fontWeight: 700, color: MC.primary, lineHeight: 1 }}>{d.total}</span>
            <span style={{ fontSize: 13.5, color: MC.textLight, fontWeight: 600, whiteSpace: 'nowrap' }}>{d.total === 1 ? 'registro' : 'registros'}{d.offset === 0 ? ' hoje' : ''}</span>
          </div>
          <div style={{ marginBottom: 14 }}><Composition d={d} /></div>
          <SyncPill d={d} block />
        </div>
        <div style={{ background: '#fff', borderRadius: 15, padding: '4px 16px', boxShadow: '0 1px 2px rgba(0,0,0,0.1)', marginBottom: 20 }}>
          {d.records.map((r, i) => <DayRow key={r.id} r={r} last={i === d.records.length - 1} />)}
        </div>
      </>)}
    </>
  )
}

// Linha de um registro na lista do dia (leitura).
function DayRow({ r, last }) {
  const { Icon } = window.FazendaGuanabaraDesignSystem_b62f7e
  const sent = r.status === 'enviado'
  const accent = r.loss ? MC.warningDark : (r.sex === 'female' ? MC.female : MC.male)
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 0', borderBottom: last ? 'none' : '1px solid ' + MC.neutralLight }}>
      <span style={{ width: 38, height: 38, borderRadius: '50%', flexShrink: 0, background: r.loss ? 'rgba(100,84,0,0.10)' : (r.sex === 'female' ? 'rgba(244,125,125,0.14)' : 'rgba(70,167,208,0.14)'),
        display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <Icon name={r.loss ? 'warning-outline' : r.sex} size={20} color={accent} />
      </span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 14.5, fontWeight: 700, color: MC.textDark }}>{r.serie} {r.plantel}</div>
        <div style={{ fontSize: 12.5, color: MC.textLight, marginTop: 2 }}>
          {r.loss ? r.tipo : 'Cria ' + r.calf + ' · ' + (r.sex === 'female' ? 'Fêmea' : 'Macho')}
        </div>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 5, flexShrink: 0 }}>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, whiteSpace: 'nowrap',
          background: sent ? 'rgba(88,177,73,0.14)' : 'rgba(243,212,48,0.22)',
          color: sent ? MC.successDark : MC.warningDark, fontSize: 11, fontWeight: 700, padding: '5px 9px', borderRadius: 99 }}>
          <Icon name={sent ? 'checkmark-circle-outline' : 'file-tray-full-outline'} size={13} color={sent ? MC.successDark : MC.warningDark} />
          {sent ? 'Enviado' : 'Aguardando'}
        </span>
        <span style={{ fontSize: 11.5, color: MC.textLight, fontWeight: 600 }}>{r.hora}</span>
      </div>
    </div>
  )
}

// ---- PARTO GEMELAR ----
// Cenário da mãe buscada (controlado por Tweak): normal / já pariu hoje (alerta vermelho) /
// 1ª cria de gêmeos já registrada e faltando a 2ª (gêmeo pendente). Substitui a heurística por marcação.
function maeCenarioFlag(cenario, serie, plantel) {
  if (cenario === 'jaPariu') return { kind: 'jaPariu', first: { serie, plantel, calf: '2032', sex: 'female' } }
  if (cenario === 'gemeoPendente') return { kind: 'gemeoPendente', first: { serie, plantel, calf: '2035', sex: 'female' } }
  return null
}

// Alerta na busca da mãe. 'jaPariu' = vermelho (2º parto hoje) → oferece registrar como gemelar.
// 'gemeoPendente' = azul (1ª cria já registrada) → oferece registrar a 2ª cria do mesmo parto.
function BirthAlert({ flag, onAction }) {
  const { Icon } = window.FazendaGuanabaraDesignSystem_b62f7e
  const danger = flag.kind === 'jaPariu'
  const bar = danger ? MC.danger : MC.info
  const bg = danger ? MC.dangerLight : 'rgba(70,167,208,0.12)'
  const fg = danger ? MC.dangerDark : MC.infoDark
  const title = danger ? 'Esta vaca já teve um parto hoje' : 'Parto gemelar em aberto'
  const body = danger
    ? 'Se nasceram dois bezerros, registre como parto gemelar para não duplicar a mãe.'
    : 'A 1ª cria deste parto gemelar já foi registrada. Falta registrar a 2ª cria.'
  const btn = danger ? 'Registrar como parto gemelar' : 'Registrar 2ª cria'
  return (
    <div style={{ marginTop: 16, background: bg, borderLeft: '4px solid ' + bar, borderRadius: 12, padding: '14px 16px' }}>
      <div style={{ display: 'flex', gap: 10 }}>
        <Icon name={danger ? 'warning-outline' : 'information-circle-outline'} size={20} color={fg} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 14.5, fontWeight: 700, color: fg }}>{title}</div>
          <div style={{ fontSize: 13, color: MC.text, marginTop: 3, lineHeight: 1.45 }}>{body}</div>
        </div>
      </div>
      <window.MButton onClick={onAction} rightIcon="people-outline" style={{ marginTop: 14, background: danger ? MC.danger : MC.primary }}>{btn}</window.MButton>
    </div>
  )
}

// Leitura do brinco eletrônico — 3 métodos: bastão Bluetooth, câmera/código de barras e manual.
// value = brinco já lido (finalizado). onChange(tag) finaliza a leitura.
function BrincoReader({ leitor, value, onChange }) {
  const { Icon, Input } = window.FazendaGuanabaraDesignSystem_b62f7e
  const [method, setMethod] = React.useState(null)
  const [scanning, setScanning] = React.useState(false)
  const [manual, setManual] = React.useState('')
  const fakeTag = () => '9820004387' + String(Math.floor(10000 + Math.random() * 89999))

  // Leitura concluída.
  if (value) return (
    <div style={{ background: MC.tint, border: '1.5px solid ' + MC.primary, borderRadius: 15, padding: '18px 16px' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <span style={{ width: 40, height: 40, borderRadius: '50%', background: 'rgba(88,177,73,0.18)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
          <Icon name="checkmark-circle-outline" size={22} color={MC.successDark} /></span>
        <div style={{ minWidth: 0 }}>
          <div style={{ fontSize: 11, color: MC.textLight, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.6px' }}>Brinco lido</div>
          <div style={{ fontSize: 18, fontWeight: 700, color: MC.primary, wordBreak: 'break-all' }}>{value}</div>
        </div>
      </div>
      <window.MButton variant="ghost" onClick={() => { onChange(''); setMethod(null); setManual('') }} style={{ marginTop: 6 }}>Ler novamente</window.MButton>
    </div>
  )

  // Escolha do método.
  if (!method) {
    const methods = [
      { id: 'bastao', icon: 'radio-button-on', title: 'Bastão Bluetooth', desc: leitor ? 'Leitor conectado · aproxime do brinco' : 'Leitor desconectado' },
      { id: 'camera', icon: 'bar-chart-outline', title: 'Câmera / código de barras', desc: 'Escaneie o código do brinco' },
      { id: 'manual', icon: 'pencil', title: 'Manual', desc: 'Digite o número do brinco' },
    ]
    return (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {methods.map(m => (
          <div key={m.id} onClick={() => setMethod(m.id)} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '16px', border: '1.5px solid ' + MC.border, borderRadius: 15, background: '#fff', cursor: 'pointer', minHeight: 64 }}>
            <span style={{ width: 44, height: 44, borderRadius: 12, flexShrink: 0, background: MC.tint, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Icon name={m.icon} size={22} color={MC.primary} /></span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 15, fontWeight: 700, color: MC.textDark }}>{m.title}</div>
              <div style={{ fontSize: 12.5, color: MC.textLight, marginTop: 2 }}>{m.desc}</div>
            </div>
            <Icon name="chevron-forward" size={18} color={MC.textLight} />
          </div>
        ))}
      </div>
    )
  }

  const backRow = <window.MButton variant="ghost" onClick={() => { setMethod(null); setManual('') }} style={{ marginTop: 14 }}>Trocar método</window.MButton>
  const scan = () => { setScanning(true); setTimeout(() => { setScanning(false); onChange(fakeTag()) }, 900) }

  if (method === 'manual') return (
    <div>
      <Input label="Número do brinco eletrônico" placeholder="Ex: 982000438721603" value={manual} onChange={e => setManual(e.target.value)} />
      <window.MButton disabled={!manual.trim()} onClick={() => onChange(manual.trim())} style={{ marginTop: 16 }}>Confirmar brinco</window.MButton>
      {backRow}
    </div>
  )

  if (method === 'bastao') return (
    <div>
      <div style={{ border: '1.5px dashed ' + (leitor ? MC.primary : MC.border), borderRadius: 15, padding: '28px 16px', textAlign: 'center', background: leitor ? MC.tint : MC.bgNeutral }}>
        <span style={{ width: 56, height: 56, borderRadius: '50%', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', background: '#fff', boxShadow: leitor ? '0 0 0 6px rgba(88,177,73,0.15)' : 'none' }}>
          <Icon name="radio-button-on" size={28} color={leitor ? MC.primary : MC.textLight} /></span>
        <div style={{ fontSize: 15, fontWeight: 700, color: MC.textDark, marginTop: 14 }}>{leitor ? (scanning ? 'Lendo…' : 'Aproxime o bastão do brinco') : 'Leitor desconectado'}</div>
        <div style={{ fontSize: 13, color: MC.textLight, marginTop: 4 }}>{leitor ? 'A leitura é automática' : 'Conecte o bastão na Home ou use outro método'}</div>
      </div>
      <window.MButton disabled={!leitor || scanning} onClick={scan} style={{ marginTop: 16 }}>{scanning ? 'Lendo…' : 'Simular leitura'}</window.MButton>
      {backRow}
    </div>
  )

  // Câmera / código de barras.
  return (
    <div>
      <div style={{ position: 'relative', border: '1.5px solid ' + MC.border, borderRadius: 15, height: 180, background: '#1a1a1a', overflow: 'hidden', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <div style={{ width: '70%', height: 76, border: '2px solid rgba(255,255,255,0.85)', borderRadius: 10 }} />
        <div style={{ position: 'absolute', left: '15%', right: '15%', height: 2, background: MC.female, boxShadow: '0 0 8px ' + MC.female, animation: 'scanline 1.6s ease-in-out infinite' }} />
        <div style={{ position: 'absolute', bottom: 10, left: 0, right: 0, textAlign: 'center', color: 'rgba(255,255,255,0.85)', fontSize: 12 }}>Aponte para o código de barras do brinco</div>
      </div>
      <window.MButton disabled={scanning} onClick={scan} style={{ marginTop: 16 }}>{scanning ? 'Capturando…' : 'Capturar código'}</window.MButton>
      {backRow}
    </div>
  )
}

// ---- Menu de módulos do app (compartilhado entre Maternidade e Manejo de Pasto) ----
// Um só cadastro de módulos: usado no lançador pós-login e no drawer de troca de módulo.
const APP_MODULOS = [
  { id: 'servicos', title: 'Boletins', sub: 'Horas trabalhadas e serviços realizados', icon: 'briefcase-outline' },
  { id: 'maternidade', title: 'Maternidade', sub: 'Registro de nascimentos', icon: 'cow', href: '../mobile-maternidade/index.html' },
  { id: 'pasto', title: 'Manejo de Pastagem', sub: 'Movimentações, rodízio e consulta de módulos', icon: 'list-outline', href: '../pastagem-app/index.html?m=1', iconNode: (
    <svg width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="var(--color-primary)" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round">
      <path d="M12 21c0-5 0-9 0-12" /><path d="M12 12c0-4 3-7 7-7 0 4-3 7-7 7z" /><path d="M12 15c0-3.5-2.5-6-6-6 0 3.5 2.5 6 6 6z" />
    </svg>
  ) },
]

// Botão hambúrguer do cabeçalho.
function MModulesButton({ onClick }) {
  return (
    <span onClick={onClick} style={{ width: 28, cursor: 'pointer', display: 'flex', alignItems: 'center' }}>
      <span style={{ display: 'flex', flexDirection: 'column', justifyContent: 'space-between', width: 19, height: 14 }}>
        {[0, 1, 2].map((i) => <span key={i} style={{ height: 2.5, borderRadius: 2, background: '#fff' }} />)}
      </span>
    </span>
  )
}

// Drawer lateral: troca de módulo depois do login.
function MModulosSheet({ mods, atual, onPick, onClose }) {
  const { Icon } = window.FazendaGuanabaraDesignSystem_b62f7e
  const list = mods || APP_MODULOS
  return (
    <div onClick={onClose} style={{ position: 'absolute', inset: 0, zIndex: 60, background: 'rgba(0,0,0,0.4)', display: 'flex' }}>
      <div onClick={(e) => e.stopPropagation()} style={{ width: '82%', maxWidth: 320, height: '100%', display: 'flex', flexDirection: 'column', background: '#fff', boxShadow: '4px 0 20px rgba(24,40,22,0.22)', animation: 'fgDrawer .22s ease-out', overflowY: 'auto' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, padding: '16px 16px 12px', background: MC.primaryDark }}>
          <span style={{ fontSize: 12, fontWeight: 700, color: 'rgba(255,255,255,0.75)', textTransform: 'uppercase', letterSpacing: '0.8px' }}>Ir para</span>
          <button onClick={onClose} style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', width: 36, height: 36, border: 'none', background: 'transparent', cursor: 'pointer' }}>
            <Icon name="close" size={20} color="#fff" />
          </button>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', padding: '4px 0' }}>
          {list.map((m, i) => {
            const on = m.id === atual
            return (
              <div key={m.id} onClick={() => onPick(m.id)} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px', minHeight: 44, cursor: 'pointer', background: on ? MC.tint : 'transparent', borderBottom: i < list.length - 1 ? '1px solid ' + MC.neutralLight : 'none' }}>
                <span style={{ width: 40, height: 40, borderRadius: 10, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', background: on ? '#fff' : MC.tint }}>
                  {m.iconNode ? m.iconNode : <Icon name={m.icon} size={21} color={MC.primary} />}
                </span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 16, fontWeight: 700, color: on ? MC.primary : MC.textDark, lineHeight: 1.2 }}>{m.title}</div>
                  <div style={{ fontSize: 12, color: MC.text, marginTop: 2, lineHeight: 1.3 }}>{m.sub}</div>
                </div>
                {on
                  ? <span style={{ flexShrink: 0, fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.6px', padding: '2px 7px', borderRadius: 99, background: '#fff', color: MC.successDark }}>Atual</span>
                  : <Icon name="chevron-forward" size={18} color={MC.border} />}
              </div>
            )
          })}
        </div>
        <div style={{ marginTop: 'auto', display: 'flex', alignItems: 'center', gap: 8, padding: '14px 16px', borderTop: '1px solid ' + MC.neutralLight, fontSize: 12, color: MC.text }}>
          <Icon name="person-circle-outline" size={15} color={MC.text} />
          <span>Siogo Pereira</span><span style={{ color: MC.border }}>·</span><span>v2.4.0</span>
        </div>
      </div>
    </div>
  )
}

// Conteúdo da tela de detalhe do dia (cabeçalho repete total + composição; lista em leitura).
window.APP_MODULOS = APP_MODULOS
window.MModulesButton = MModulesButton
window.MModulosSheet = MModulosSheet
window.MC = MC
window.BirthAlert = BirthAlert
window.BrincoReader = BrincoReader
window.maeCenarioFlag = maeCenarioFlag
window.MPhone = Phone
window.MStepProgress = StepProgress
window.MButton = MButton
window.MHeading = MHeading
window.MSub = MSub
window.MChoiceCard = ChoiceCard
window.SERIES_ASSOC = SERIES_ASSOC
window.buildDay = buildDay
window.buildWeek = buildWeek
window.ReaderCard = ReaderCard
window.DaySummaryCard = DaySummaryCard
window.DaySummaryDetail = DaySummaryDetail
