// Gestante Companion Screen — Interative Guide for Pregnant Patients

window.GestanteScreen = function GestanteScreen({ T, onNavigate }) {
  const [trimestre, setTrimestre] = React.useState(1);
  const [activeTab, setActiveTab] = React.useState('scanner'); // scanner, alimentos, medicamentos, exames, coleta
  const [flippedCard, setFlippedCard] = React.useState(null);
  const [coletaStep, setColetaStep] = React.useState(0);
  const [showAlerts, setShowAlerts] = React.useState(false);
  const [scannerData, setScannerData] = React.useState({ febre: false, ganglios: false, fadiga: false });

  const data = GESTANTE_DATA;
  const tInfo = data.trimestres[trimestre];

  const tabs = [
    { id: 'scanner', label: 'Scanner', icon: 'scan' },
    { id: 'alimentos', label: 'Cozinha', icon: 'leaf' },
    { id: 'medicamentos', label: 'Remédios', icon: 'shield' },
    { id: 'exames', label: 'Exames', icon: 'clock' },
    { id: 'coleta', label: 'Coleta', icon: 'flask' },
  ];

  const stepsColeta = [
    { title: 'Higienização', text: 'Lave bem o recipiente e evite contaminar com urina.' },
    { title: 'Dieta', text: 'Evite carne vermelha e beterraba 3 dias antes.' },
    { title: 'Amostra', text: 'Colete pequenas partes de diferentes áreas das fezes.' },
    { title: 'Envio', text: 'Leve ao laboratório em até 2 horas ou refrigere.' },
  ];

  const toxoMatch = scannerData.febre && scannerData.ganglios;

  return (
    <div style={{ padding: '0 20px 140px', display: 'flex', flexDirection: 'column', gap: 16 }}>
      {/* Back button */}
      <div style={{ paddingTop: 14 }}>
        <button onClick={() => onNavigate('home')} style={{
          all: 'unset', cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 6,
          fontSize: 13, color: T.inkSoft, marginBottom: 12,
        }}>
          <Icon name="chevron" size={14} stroke={2} color={T.inkSoft}/> Início
        </button>
        <SectionLabel>Companion de Saúde</SectionLabel>
        <h1 style={{
          fontFamily: 'Georgia, serif', fontSize: 30, lineHeight: 1.05,
          margin: '6px 0 0', color: T.ink, fontWeight: 500, letterSpacing: -0.5,
        }}>Gestante <span style={{ fontStyle: 'italic', color: T.forest }}>Conectada.</span></h1>
      </div>

      {/* Selector de Trimestre */}
      <div style={{
        background: '#fff', borderRadius: 24, padding: 6,
        display: 'flex', border: `1px solid ${T.hair}`, gap: 4,
      }}>
        {[1, 2, 3].map(t => (
          <button key={t} onClick={() => setTrimestre(t)} style={{
            all: 'unset', cursor: 'pointer', flex: 1, textAlign: 'center',
            padding: '10px 0', borderRadius: 20, fontSize: 13, fontWeight: 600,
            background: trimestre === t ? T.forest : 'transparent',
            color: trimestre === t ? '#fff' : T.inkSoft,
            transition: 'all 0.2s cubic-bezier(0.22, 1, 0.36, 1)',
          }}>
            {t}º Tri
          </button>
        ))}
      </div>

      {/* Trimestre Context Card */}
      <div style={{
        background: tInfo.color, color: '#fff', borderRadius: 24, padding: 18,
        position: 'relative', overflow: 'hidden', minHeight: 120,
        boxShadow: `0 12px 30px -10px ${tInfo.color}66`,
      }}>
        <div style={{
          position: 'absolute', top: -40, right: -40, width: 140, height: 140, borderRadius: '50%',
          background: 'rgba(255,255,255,0.12)',
        }}/>
        <Pill color="#fff" bg="rgba(255,255,255,0.18)">{tInfo.label}</Pill>
        <div style={{ fontFamily: 'Georgia, serif', fontSize: 22, marginTop: 12 }}>{tInfo.focus}</div>
        <div style={{ fontSize: 13, marginTop: 8, opacity: 0.9, lineHeight: 1.4 }}>{tInfo.medAlert}</div>
      </div>

      {/* Main Tabs UI */}
      <div style={{ display: 'flex', gap: 4, marginTop: 8, overflowX: 'auto', margin: '0 -20px', padding: '0 20px 10px' }}>
        {tabs.map(tab => (
          <button key={tab.id} onClick={() => setActiveTab(tab.id)} style={{
            all: 'unset', cursor: 'pointer', minWidth: 74, display: 'flex', flexDirection: 'column',
            alignItems: 'center', gap: 6, padding: '12px 0', borderRadius: 20,
            background: activeTab === tab.id ? '#fff' : 'transparent',
            border: `1px solid ${activeTab === tab.id ? T.hair : 'transparent'}`,
            boxShadow: activeTab === tab.id ? '0 4px 12px rgba(0,0,0,0.05)' : 'none',
          }}>
            <Icon name={tab.icon} size={18} color={activeTab === tab.id ? T.forest : T.inkMuted} stroke={1.8}/>
            <div style={{ fontSize: 9, fontWeight: 700, color: activeTab === tab.id ? T.ink : T.inkMuted, textTransform: 'uppercase' }}>
              {tab.label}
            </div>
          </button>
        ))}
      </div>

      {/* Content Area */}
      <div style={{ minHeight: 340 }}>
        {activeTab === 'scanner' && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            <SectionLabel>Checklist de Triagem Diferenciada</SectionLabel>
            <div style={{ background: '#fff', borderRadius: 24, padding: 16, border: `1px solid ${T.hair}`, display: 'flex', flexDirection: 'column', gap: 10 }}>
              <ScannerRow label="Febre Baixa / Persistente" value={scannerData.febre} onChange={v => setScannerData({...scannerData, febre: v})} T={T}/>
              <ScannerRow label="Gânglios Inchados (Pescoço)" value={scannerData.ganglios} onChange={v => setScannerData({...scannerData, ganglios: v})} T={T}/>
              <ScannerRow label="Fadiga Extrema" value={scannerData.fadiga} onChange={v => setScannerData({...scannerData, fadiga: v})} T={T}/>
            </div>

            {toxoMatch && (
              <div style={{
                background: T.paperWarm, borderRadius: 24, padding: 18, border: `2px solid ${T.rose}`,
                display: 'flex', gap: 12, alignItems: 'flex-start',
                animation: 'toastIn 0.4s ease-out',
              }}>
                <Icon name="alert" size={20} color={T.rose} stroke={2.2}/>
                <div style={{ fontSize: 13.5, color: T.ink, lineHeight: 1.5 }}>
                  <b style={{ color: T.rose }}>Alerta de Coincidência:</b> Estes sintomas coincidem com o protocolo de <b>Toxoplasmose</b>. Verifique sua última sorologia e contate seu obstetra.
                </div>
              </div>
            )}

            <div style={{ fontSize: 12, color: T.inkSoft, textAlign: 'center', padding: '0 20px', lineHeight: 1.5 }}>
              A Toxoplasmose é frequentemente silenciosa. O scanner ajuda a identificar sinais inespecíficos citados no protocolo clínico.
            </div>
          </div>
        )}

        {activeTab === 'alimentos' && (
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            {data.alimentos.map(item => (
              <div key={item.id} onClick={() => setFlippedCard(flippedCard === item.id ? null : item.id)} style={{
                height: 160, perspective: '1000px', cursor: 'pointer',
              }}>
                <div style={{
                  position: 'relative', width: '100%', height: '100%',
                  transition: 'transform 0.6s cubic-bezier(0.22, 1, 0.36, 1)',
                  transformStyle: 'preserve-3d',
                  transform: flippedCard === item.id ? 'rotateY(180deg)' : 'rotateY(0deg)',
                }}>
                  {/* Front */}
                  <div style={{
                    position: 'absolute', inset: 0, backfaceVisibility: 'hidden',
                    background: '#fff', borderRadius: 24, border: `1px solid ${T.hair}`,
                    padding: 16, display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
                  }}>
                    <Pill color={item.level === 'danger' ? T.rose : item.level === 'warning' ? T.clay : T.moss}
                      bg={`${item.level === 'danger' ? T.rose : item.level === 'warning' ? T.clay : T.moss}12`}>
                      {item.risk}
                    </Pill>
                    <div style={{ fontFamily: 'Georgia, serif', fontSize: 16, color: T.ink }}>{item.name}</div>
                  </div>
                  {/* Back */}
                  <div style={{
                    position: 'absolute', inset: 0, backfaceVisibility: 'hidden',
                    background: T.forest, borderRadius: 24, padding: 16,
                    transform: 'rotateY(180deg)', display: 'flex', flexDirection: 'column',
                    justifyContent: 'center', alignItems: 'center', textAlign: 'center', color: '#fff',
                  }}>
                    <div style={{ fontSize: 12, fontWeight: 600, opacity: 0.8, textTransform: 'uppercase' }}>Dica</div>
                    <div style={{ fontSize: 13, marginTop: 8, lineHeight: 1.4 }}>{item.advice}</div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}

        {activeTab === 'medicamentos' && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            {data.medicamentos.map(med => {
              const isSafe = med.trimester.includes(trimestre);
              return (
                <div key={med.id} style={{
                  background: isSafe ? '#fff' : T.paperWarm, borderRadius: 24, padding: 16,
                  border: `1px solid ${isSafe ? T.hair : 'transparent'}`,
                  display: 'flex', gap: 14, alignItems: 'center', opacity: isSafe ? 1 : 0.75,
                }}>
                  <div style={{
                    width: 44, height: 44, borderRadius: 14, background: isSafe ? `${T.forest}12` : `${T.inkMuted}12`,
                    display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
                  }}>
                    <Icon name={isSafe ? 'check' : 'lock'} size={20} color={isSafe ? T.forest : T.inkMuted} stroke={2.2}/>
                  </div>
                  <div style={{ flex: 1 }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                      <div style={{ fontSize: 15, fontWeight: 600, color: T.ink }}>{med.name}</div>
                      <Pill color={isSafe ? T.moss : T.rose} bg={isSafe ? `${T.moss}12` : `${T.rose}12`} style={{ fontSize: 9 }}>
                        {isSafe ? 'Permitido' : 'Bloqueado'}
                      </Pill>
                    </div>
                    <div style={{ fontSize: 12, color: T.inkSoft, marginTop: 4 }}>{med.safety} · {med.note}</div>
                  </div>
                </div>
              );
            })}
            <div style={{ marginTop: 10, padding: 14, background: `${T.lavender}12`, borderRadius: 18, border: `1px dashed ${T.lavender}` }}>
               <div style={{ fontSize: 12, color: T.forest, lineHeight: 1.5 }}>
                 <b>Espiramicina:</b> Único fármaco considerado seguro em toda a gestação para Toxoplasmose, mas deve ser iniciado apenas sob prescrição direta do obstetra.
               </div>
            </div>
          </div>
        )}

        {activeTab === 'exames' && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            <SectionLabel>Linha do Tempo de Exames</SectionLabel>
            {data.exames.map((ex, i) => (
              <div key={ex.id} style={{
                background: '#fff', borderRadius: 24, padding: 16, border: `1px solid ${T.hair}`,
                display: 'flex', gap: 14, alignItems: 'center',
              }}>
                <div style={{
                  width: 40, height: 40, borderRadius: 12, background: `${T.forest}12`,
                  display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
                }}>
                  <div style={{ fontSize: 14, fontWeight: 700, color: T.forest }}>{i + 1}</div>
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <div style={{ fontSize: 15, fontWeight: 600, color: T.ink }}>{ex.title}</div>
                    {ex.mandatory && <Pill color={T.rose} bg={`${T.rose}12`} style={{ fontSize: 9 }}>Obrigatório</Pill>}
                  </div>
                  <div style={{ fontSize: 12, color: T.inkSoft, marginTop: 4 }}>{ex.period} · {ex.detail}</div>
                </div>
              </div>
            ))}
          </div>
        )}

        {activeTab === 'coleta' && (
          <div style={{
            background: '#fff', borderRadius: 28, padding: 24, border: `1px solid ${T.hair}`,
            display: 'flex', flexDirection: 'column', gap: 20, alignItems: 'center', textAlign: 'center',
          }}>
            <div style={{
              width: 80, height: 80, borderRadius: 99, background: `${T.forest}12`,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <Icon name="flask" size={40} color={T.forest} stroke={1.5}/>
            </div>
            <div>
              <div style={{ fontSize: 12, color: T.forest, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 1 }}>
                Passo {coletaStep + 1} de {stepsColeta.length}
              </div>
              <div style={{ fontFamily: 'Georgia, serif', fontSize: 22, color: T.ink, marginTop: 8 }}>
                {stepsColeta[coletaStep].title}
              </div>
              <div style={{ fontSize: 14, color: T.inkSoft, marginTop: 10, lineHeight: 1.5, maxWidth: 240 }}>
                {stepsColeta[coletaStep].text}
              </div>
            </div>
            <div style={{ display: 'flex', gap: 8, width: '100%', marginTop: 10 }}>
              <button onClick={() => setColetaStep(s => Math.max(0, s - 1))} style={{
                all: 'unset', cursor: 'pointer', flex: 1, padding: '12px 0', borderRadius: 16,
                background: T.paperWarm, color: T.ink, fontWeight: 600, fontSize: 14,
                opacity: coletaStep === 0 ? 0.5 : 1,
              }}>Anterior</button>
              <button onClick={() => setColetaStep(s => Math.min(stepsColeta.length - 1, s + 1))} style={{
                all: 'unset', cursor: 'pointer', flex: 2, padding: '12px 0', borderRadius: 16,
                background: T.forest, color: '#fff', fontWeight: 600, fontSize: 14,
                opacity: coletaStep === stepsColeta.length - 1 ? 0.5 : 1,
              }}>Próximo</button>
            </div>
          </div>
        )}
      </div>

      {/* Floating Alert Button */}
      <button style={{
        position: 'absolute', bottom: 100, right: 20, width: 56, height: 56,
        borderRadius: 99, background: T.rose, color: '#fff', border: 'none',
        boxShadow: '0 8px 24px rgba(185,74,93,0.4)',
        display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 40,
        cursor: 'pointer',
      }} onClick={() => setShowAlerts(true)}>
        <Icon name="alert" size={24} color="#fff" stroke={2.2}/>
      </button>

      {/* Sinais de Alerta Modal / Drawer */}
      {showAlerts && (
        <div style={{
          position: 'absolute', inset: 0, zIndex: 100,
          background: 'rgba(0,0,0,0.4)', backdropFilter: 'blur(4px)',
          display: 'flex', alignItems: 'flex-end',
        }} onClick={() => setShowAlerts(false)}>
          <div style={{
            width: '100%', background: '#fff', borderRadius: '32px 32px 0 0',
            padding: '24px 24px 48px', animation: 'sheetUp 0.4s cubic-bezier(0.22, 1, 0.36, 1)',
          }} onClick={e => e.stopPropagation()}>
            <div style={{ width: 40, height: 4, background: T.hair, borderRadius: 2, margin: '0 auto 20px' }}/>
            <h2 style={{ fontFamily: 'Georgia, serif', fontSize: 24, color: T.ink, margin: 0 }}>Sinais de Alerta</h2>
            <p style={{ color: T.inkSoft, fontSize: 14, marginTop: 8, lineHeight: 1.5 }}>
              Caso apresente qualquer um destes sintomas, procure ajuda médica ou pronto-socorro imediatamente.
            </p>
            <div style={{ marginTop: 20, display: 'flex', flexDirection: 'column', gap: 12 }}>
              <AlertItem label="Febre súbita e alta" color={T.rose}/>
              <AlertItem label="Gânglios (ínguas) doloridos" color={T.clay}/>
              <AlertItem label="Visão turva ou manchas" color={T.lavender}/>
              <AlertItem label="Dor abdominal intensa" color={T.rose}/>
            </div>
            <button onClick={() => setShowAlerts(false)} style={{
              all: 'unset', cursor: 'pointer', width: '100%', padding: '16px 0', borderRadius: 20,
              background: T.forest, color: '#fff', textAlign: 'center', fontWeight: 600, marginTop: 24,
            }}>Entendido</button>
          </div>
        </div>
      )}

    </div>
  );
};

function ScannerRow({ label, value, onChange, T }) {
  return (
    <button onClick={() => onChange(!value)} style={{
      all: 'unset', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 12, padding: '10px 0',
    }}>
      <div style={{
        width: 24, height: 24, borderRadius: 6, border: `2px solid ${value ? T.forest : T.hair}`,
        background: value ? T.forest : 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        {value && <Icon name="check" size={16} color="#fff" stroke={3}/>}
      </div>
      <div style={{ fontSize: 14.5, color: T.ink, fontWeight: 500 }}>{label}</div>
    </button>
  );
}

function AlertItem({ label, color }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px', background: `${color}10`, borderRadius: 16, borderLeft: `4px solid ${color}` }}>
      <div style={{ fontSize: 14.5, fontWeight: 600, color: '#16201f' }}>{label}</div>
    </div>
  );
}
