// Shared UI primitives — exported to window

const { useState: uiUseState } = React;

/* ── Colors ── */
const C = {
  sidebar:     '#1C416B',
  sidebarHov:  '#245485',
  sidebarAct:  '#163354',
  primary:     '#2563a8',
  primaryDark: '#1d4f8f',
  pageBg:      '#f0f2f5',
  cardBg:      '#ffffff',
  border:      '#e5e7eb',
  textPrimary: '#111827',
  textSecond:  '#6b7280',
  textMuted:   '#9ca3af',
  red:         '#dc2626',
  green:       '#16a34a',
  amber:       '#d97706',
};

/* ── Modal ── */
function Modal({ title, onClose, children, width = 380 }) {
  return (
    <div style={{ position:'fixed', inset:0, background:'rgba(0,0,0,0.45)', display:'flex', alignItems:'center', justifyContent:'center', zIndex:2000 }}
      onClick={e => e.target === e.currentTarget && onClose()}>
      <div style={{ background:'#eef3fa', borderRadius:10, width, maxWidth:'94vw', maxHeight:'90vh', overflowY:'auto', padding:'24px 28px', position:'relative', boxShadow:'0 8px 32px rgba(0,0,0,0.18)' }}>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:20 }}>
          <h2 style={{ margin:0, fontSize:17, fontWeight:600, color:'#111' }}>{title}</h2>
          <button onClick={onClose} style={{ background:'none', border:'none', cursor:'pointer', fontSize:20, color:'#6b7280', lineHeight:1, padding:'0 2px' }}>✕</button>
        </div>
        {children}
      </div>
    </div>
  );
}

/* ── Form fields ── */
function FInput({ label, placeholder, type='text', value, onChange, style, half }) {
  return (
    <div style={{ display:'flex', flexDirection:'column', gap:5, flex: half ? '1 1 45%' : '1 1 100%', ...style }}>
      {label && <label style={{ fontSize:13, fontWeight:500, color:'#374151' }}>{label}</label>}
      <input type={type} placeholder={placeholder} value={value||''} onChange={onChange}
        style={{ padding:'9px 12px', border:'1px solid #d1d5db', borderRadius:6, fontSize:14, background:'white', outline:'none', color:'#111', width:'100%' }} />
    </div>
  );
}

function FSelect({ label, children, value, onChange, style, half }) {
  return (
    <div style={{ display:'flex', flexDirection:'column', gap:5, flex: half ? '1 1 45%' : '1 1 100%', ...style }}>
      {label && <label style={{ fontSize:13, fontWeight:500, color:'#374151' }}>{label}</label>}
      <select value={value||''} onChange={onChange}
        style={{ padding:'9px 12px', border:'1px solid #d1d5db', borderRadius:6, fontSize:14, background:'white', outline:'none', color:'#111', cursor:'pointer', width:'100%' }}>
        {children}
      </select>
    </div>
  );
}

function ModalActions({ onCancel, onConfirm, cancelLabel='Cancelar', confirmLabel='Cadastrar' }) {
  return (
    <div style={{ display:'flex', justifyContent:'flex-end', gap:10, marginTop:22 }}>
      <button onClick={onCancel}
        style={{ padding:'8px 20px', borderRadius:6, border:'1px solid #d1d5db', background:'white', color:'#374151', fontSize:14, fontWeight:500, cursor:'pointer' }}>
        {cancelLabel}
      </button>
      <button onClick={onConfirm}
        style={{ padding:'8px 20px', borderRadius:6, border:'none', background:C.primary, color:'white', fontSize:14, fontWeight:500, cursor:'pointer' }}>
        {confirmLabel}
      </button>
    </div>
  );
}

/* ── Avatar ── */
function Avatar({ name='?', size=38, color='#2563a8' }) {
  const init = name.trim().split(' ').map(w=>w[0]).slice(0,1).join('').toUpperCase();
  return (
    <div style={{ width:size, height:size, borderRadius:'50%', background:color, display:'flex', alignItems:'center', justifyContent:'center', color:'white', fontWeight:700, fontSize:size*0.38, flexShrink:0 }}>
      {init}
    </div>
  );
}

/* ── Badge ── */
function Badge({ children, variant='primary' }) {
  const map = {
    primary:    { bg:'#dbeafe', color:'#1e40af' },
    amber:      { bg:'#fef3c7', color:'#92400e' },
    green:      { bg:'#d1fae5', color:'#065f46' },
    red:        { bg:'#fee2e2', color:'#991b1b' },
    blue:       { bg:'#dbeafe', color:'#1e40af' },
    teal:       { bg:'#ccfbf1', color:'#0f766e' },
    slate:      { bg:'#f1f5f9', color:'#475569' },
    pendente:   { bg:'#d97706', color:'white' },
    confirmado: { bg:'#16a34a', color:'white' },
    menor:      { bg:'#f59e0b', color:'white' },
    admin:      { bg:'#16a34a', color:'white' },
    secretaria: { bg:'#d97706', color:'white' },
    terapeuta:  { bg:'#2563a8', color:'white' },
    ativo:      { bg:'#2563a8', color:'white' },
    unit:       { bg:'#e0e7ff', color:'#3730a3' },
  };
  const s = map[variant] || map.primary;
  return (
    <span style={{ display:'inline-block', padding:'2px 10px', borderRadius:20, fontSize:12, fontWeight:600, background:s.bg, color:s.color, whiteSpace:'nowrap' }}>
      {children}
    </span>
  );
}

/* ── Card ── */
function Card({ children, style }) {
  return (
    <div style={{ background:'white', borderRadius:8, boxShadow:'0 1px 4px rgba(0,0,0,0.07)', ...style }}>
      {children}
    </div>
  );
}

/* ── Topbar ── */
/* ── Topbar ── */
const NOTIFS_INIT = [
  { id:1, tipo:'consulta', titulo:'Nova consulta agendada', desc:'Ana Silva — hoje às 14h00 • Sala 201', time:'5 min', lida:false },
  { id:2, tipo:'pagamento', titulo:'Pagamento recebido', desc:'Jorge Ribeiro — R$ 120,00 via PIX', time:'32 min', lida:false },
  { id:3, tipo:'alerta', titulo:'Consulta em 1 hora', desc:'Amanda Viana • Unidade Jardins • Sala 202', time:'1h', lida:false },
  { id:4, tipo:'sistema', titulo:'Novo usuário cadastrado', desc:'Carlos Mendes foi adicionado como Terapeuta', time:'2h', lida:true },
  { id:5, tipo:'consulta', titulo:'Consulta cancelada', desc:'Carmem Lúcia cancelou a sessão de amanhã', time:'3h', lida:true },
];

const NOTIF_ICON = tipo => (
  tipo === 'consulta'  ? { bg:'#eff6ff', color:'#2563a8', path:'M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z' } :
  tipo === 'pagamento' ? { bg:'#f0fdf4', color:'#16a34a', path:'M12 1v22M17 5H9.5a3.5 3.5 0 000 7h5a3.5 3.5 0 010 7H6' } :
  tipo === 'alerta'    ? { bg:'#fffbeb', color:'#d97706', path:'M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0zM12 9v4M12 17h.01' } :
                         { bg:'#f5f3ff', color:'#7c3aed', path:'M12 15a3 3 0 100-6 3 3 0 000 6z M19.4 15a1.65 1.65 0 00.33 1.82l.06.06a2 2 0 01-2.83 2.83l-.06-.06A1.65 1.65 0 0015 19.4a1.65 1.65 0 00-1 1.51V21a2 2 0 01-4 0v-.09A1.65 1.65 0 009 19.4a1.65 1.65 0 00-1.82.33l-.06.06a2 2 0 01-2.83-2.83l.06-.06A1.65 1.65 0 004.68 15a1.65 1.65 0 00-1.51-1H3a2 2 0 010-4h.09A1.65 1.65 0 004.6 9a1.65 1.65 0 00-.33-1.82l-.06-.06a2 2 0 012.83-2.83l.06.06A1.65 1.65 0 009 4.68a1.65 1.65 0 001-1.51V3a2 2 0 014 0v.09a1.65 1.65 0 001 1.51 1.65 1.65 0 001.82-.33l.06-.06a2 2 0 012.83 2.83l-.06.06A1.65 1.65 0 0019.4 9a1.65 1.65 0 001.51 1H21a2 2 0 010 4h-.09a1.65 1.65 0 00-1.51 1z' }
);

function Topbar({ title }) {
  const now = new Date(2026, 4, 13);
  const days = ['domingo','segunda-feira','terça-feira','quarta-feira','quinta-feira','sexta-feira','sábado'];
  const months = ['janeiro','fevereiro','março','abril','maio','junho','julho','agosto','setembro','outubro','novembro','dezembro'];
  const label = `${days[now.getDay()]}, ${now.getDate()} de ${months[now.getMonth()]} de ${now.getFullYear()}`;

  const [notifs, setNotifs] = uiUseState(NOTIFS_INIT);
  const [open, setOpen]     = uiUseState(false);
  const unread = notifs.filter(n => !n.lida).length;
  const prontuPend = (typeof window !== 'undefined' && window.__prontuariosPendentes) || 0;
  const totalBadge = unread + prontuPend;

  const marcarTodas = () => setNotifs(ns => ns.map(n => ({ ...n, lida:true })));
  const marcarUma   = id  => setNotifs(ns => ns.map(n => n.id === id ? { ...n, lida:true } : n));

  return (
    <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', padding:'0 28px', height:56, background:'white', borderBottom:'1px solid #e5e7eb', flexShrink:0, position:'relative', zIndex:100 }}>
      <h1 style={{ fontSize:18, fontWeight:600, color:'#111827', margin:0 }}>{title}</h1>
      <div style={{ display:'flex', alignItems:'center', gap:16 }}>
        <span style={{ fontSize:13, color:'#6b7280' }}>{label}</span>

        {/* Sino */}
        <div style={{ position:'relative' }}>
          <button onClick={() => setOpen(o => !o)}
            style={{ background: open ? '#f3f4f6' : 'none', border:'none', cursor:'pointer', padding:'6px', borderRadius:8, lineHeight:1, display:'flex', alignItems:'center', justifyContent:'center', transition:'background .15s' }}>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#374151" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M18 8A6 6 0 006 8c0 7-3 9-3 9h18s-3-2-3-9M13.73 21a2 2 0 01-3.46 0"/>
            </svg>
            {totalBadge > 0 && (
              <span style={{
                position:'absolute', top:-3, right:-3,
                background:'#ef4444', color:'white', borderRadius:'50%',
                width:16, height:16, fontSize:10, fontWeight:700,
                display:'flex', alignItems:'center', justifyContent:'center',
                border:'2px solid white',
              }}>{totalBadge}</span>
            )}
          </button>

          {/* Painel de notificações */}
          {open && (
            <>
              <div style={{ position:'fixed', inset:0, zIndex:200 }} onClick={() => setOpen(false)} />
              <div style={{
                position:'absolute', top:'calc(100% + 8px)', right:0,
                width:340, background:'white', borderRadius:10,
                boxShadow:'0 8px 32px rgba(0,0,0,0.14)', border:'1px solid #e5e7eb',
                zIndex:300, overflow:'hidden',
              }}>
                {/* Header */}
                <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', padding:'14px 16px', borderBottom:'1px solid #f0f2f5' }}>
                  <span style={{ fontSize:14, fontWeight:700, color:'#111' }}>
                    Notificações {unread > 0 && <span style={{ fontSize:12, color:'white', background:'#ef4444', borderRadius:10, padding:'1px 7px', marginLeft:6 }}>{unread}</span>}
                  </span>
                  {unread > 0 && (
                    <button onClick={marcarTodas}
                      style={{ fontSize:12, color:C.primary, background:'none', border:'none', cursor:'pointer', fontWeight:500 }}>
                      Marcar todas como lidas
                    </button>
                  )}
                </div>

                {/* Prontúrios pendentes */}
                {prontuPend > 0 && (
                  <div style={{ display:'flex', gap:12, padding:'12px 16px', background:'#fff7ed', borderBottom:'1px solid #f3f4f6', cursor:'default' }}>
                    <div style={{ width:36, height:36, borderRadius:8, background:'#ffedd5', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
                      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#f97316" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></svg>
                    </div>
                    <div style={{ flex:1 }}>
                      <div style={{ fontSize:13, fontWeight:600, color:'#9a3412' }}>Prontúrios pendentes: {prontuPend}</div>
                      <div style={{ fontSize:12, color:'#6b7280' }}>Preencha todos os prontúrios antes do check-out.</div>
                    </div>
                  </div>
                )}
                {/* Notificações gerais */}
                <div style={{ maxHeight:360, overflowY:'auto' }}>
                  {notifs.map((n, i) => {
                    const ic = NOTIF_ICON(n.tipo);
                    return (
                      <div key={n.id} onClick={() => marcarUma(n.id)}
                        style={{
                          display:'flex', gap:12, padding:'12px 16px', cursor:'pointer',
                          background: n.lida ? 'white' : '#f8faff',
                          borderBottom: i < notifs.length-1 ? '1px solid #f3f4f6' : 'none',
                          transition:'background .1s',
                        }}
                        onMouseEnter={e => e.currentTarget.style.background='#f9fafb'}
                        onMouseLeave={e => e.currentTarget.style.background= n.lida ? 'white' : '#f8faff'}>
                        {/* Ícone */}
                        <div style={{ width:36, height:36, borderRadius:8, background:ic.bg, display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
                          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke={ic.color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                            <path d={ic.path} />
                          </svg>
                        </div>
                        {/* Texto */}
                        <div style={{ flex:1, minWidth:0 }}>
                          <div style={{ fontSize:13, fontWeight: n.lida ? 400 : 600, color:'#111', marginBottom:2 }}>{n.titulo}</div>
                          <div style={{ fontSize:12, color:'#6b7280', lineHeight:1.4, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{n.desc}</div>
                          <div style={{ fontSize:11, color:'#9ca3af', marginTop:3 }}>{n.time} atrás</div>
                        </div>
                        {/* Ponto não lida */}
                        {!n.lida && <div style={{ width:8, height:8, borderRadius:'50%', background:'#3b82f6', flexShrink:0, marginTop:4 }} />}
                      </div>
                    );
                  })}
                </div>

                {/* Footer */}
                <div style={{ padding:'10px 16px', borderTop:'1px solid #f0f2f5', textAlign:'center' }}>
                  <button style={{ fontSize:13, color:C.primary, background:'none', border:'none', cursor:'pointer', fontWeight:500 }}>
                    Ver todas as notificações
                  </button>
                </div>
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

/* ── Icon helpers (inline SVG) ── */
function Icon({ name, size=16, color='currentColor' }) {
  const paths = {
    dashboard: 'M3 9l9-7 9 7v11a2 2 0 01-2 2H5a2 2 0 01-2-2z M9 22V12h6v10',
    agenda:    'M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z',
    pacientes: 'M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2 M9 7a4 4 0 100 8 4 4 0 000-8z M23 21v-2a4 4 0 00-3-3.87 M16 3.13a4 4 0 010 7.75',
    usuarios:  'M20 21v-2a4 4 0 00-4-4H8a4 4 0 00-4 4v2 M12 7a4 4 0 100 8 4 4 0 000-8z',
    financeiro:'M12 1v22M17 5H9.5a3.5 3.5 0 000 7h5a3.5 3.5 0 010 7H6',
    unidades:  'M3 9l9-7 9 7v11a2 2 0 01-2 2H5a2 2 0 01-2-2z',
    search:    'M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z',
    plus:      'M12 5v14M5 12h14',
    edit:      'M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7 M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z',
    trash:     'M3 6h18M8 6V4h8v2M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6',
    lock:      'M19 11H5a2 2 0 00-2 2v7a2 2 0 002 2h14a2 2 0 002-2v-7a2 2 0 00-2-2z M7 11V7a5 5 0 0110 0v4',
    chevLeft:  'M15 18l-6-6 6-6',
    chevRight: 'M9 18l6-6-6-6',
    chevDown:  'M6 9l6 6 6-6',
    upload:    'M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4M17 8l-5-5-5 5M12 3v12',
    file:      'M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z M14 2v6h6',
    building:  'M6 22V4a2 2 0 012-2h8a2 2 0 012 2v18z M6 12H4a2 2 0 00-2 2v6a2 2 0 002 2h2 M18 9h2a2 2 0 012 2v9a2 2 0 01-2 2h-2 M10 6h4 M10 10h4 M10 14h4 M10 18h4',
    filter:    'M22 3H2l8 9.46V19l4 2v-8.54L22 3z',
    list:      'M8 6h13M8 12h13M8 18h13M3 6h.01M3 12h.01M3 18h.01',
    grid:      'M3 3h7v7H3z M14 3h7v7h-7z M3 14h7v7H3z M14 14h7v7h-7z',
    download:  'M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4M7 10l5 5 5-5M12 15V3',
    back:      'M19 12H5M12 5l-7 7 7 7',
    pin:       'M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0118 0z M12 10a1 1 0 100 2 1 1 0 000-2z',
    calendar:  'M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z',
    phone:     'M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07A19.5 19.5 0 013.07 8.81a19.79 19.79 0 01-3.07-8.63A2 2 0 012 0h3a2 2 0 012 1.72 12.84 12.84 0 00.7 2.81 2 2 0 01-.45 2.11L6.09 7.91a16 16 0 006 6l1.27-1.27a2 2 0 012.11-.45 12.84 12.84 0 002.81.7A2 2 0 0122 14.92v2z',
    mail:      'M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z M22 6l-10 7L2 6',
    eye:       'M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z M12 9a3 3 0 100 6 3 3 0 000-6z',
    eyeOff:    'M17.94 17.94A10.07 10.07 0 0112 20c-7 0-11-8-11-8a18.45 18.45 0 015.06-5.94M9.9 4.24A9.12 9.12 0 0112 4c7 0 11 8 11 8a18.5 18.5 0 01-2.16 3.19m-6.72-1.07a3 3 0 11-4.24-4.24 M1 1l22 22',
    arrowUp:   'M12 19V5M5 12l7-7 7 7',
    settings:  'M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z',
    clipboard:  'M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9h6m-6 4h6m-6-8h.01',
    idcard:     'M20 7H4a2 2 0 00-2 2v6a2 2 0 002 2h16a2 2 0 002-2V9a2 2 0 00-2-2z M12 12a2 2 0 100-4 2 2 0 000 4z M8 17v-1a4 4 0 018 0v1',
    chart:      'M18 20V10M12 20V4M6 20v-6',
  };
  const d = paths[name] || '';
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d={d} />
    </svg>
  );
}

Object.assign(window, { C, Modal, FInput, FSelect, ModalActions, Avatar, Badge, Card, Topbar, Icon });
