/* Zona B — Drawer "O meu Digi" (slide-in lateral 420px da direita).
   KPIs pessoais + empresas que sirvo + marcas/mercados + RGPD.
   Aviso "manager vê tudo + não apagável" sempre visível.
   NÃO incluir botão "Eliminar histórico" (decisão fechada).

   Aberto via Zona A ou ⌘, (handler no shell). */

const UserDrawer = ({ open, onClose, user, onNavigate, onOpenChat }) => {
  const u = user || {};
  const [activeCompanyId] = useActiveCompany(u.empresaId);
  const userCompanies = u.empresas || [u.empresaId || 'FBS'];
  const accessibleCompanies = (window.FARBEN_COMPANIES || []).filter(c => userCompanies.includes(c.id));

  const [consents, setConsents] = React.useState({
    process: true,
    training: true,
    newsletter: false,
  });
  const toggleConsent = (k) => setConsents(c => ({ ...c, [k]: !c[k] }));

  if (!open) return null;

  return (
    <>
      {/* Backdrop */}
      <div onClick={onClose} style={{
        position: 'fixed', inset: 0, zIndex: 1300,
        background: 'rgba(0,0,0,0.4)',
        animation: 'fadeIn 0.2s ease',
      }} />
      {/* Drawer */}
      <aside style={{
        position: 'fixed', top: 0, right: 0, bottom: 0, zIndex: 1301,
        width: 420, maxWidth: '92vw',
        background: 'var(--bg-elev)',
        borderLeft: '1px solid var(--border)',
        boxShadow: 'var(--shadow-lg)',
        display: 'flex', flexDirection: 'column',
        animation: 'fadeIn 0.18s ease-out',
      }}>
        {/* Header */}
        <div style={{ padding: '18px 20px 14px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', gap: 12 }}>
          <div style={{ width: 36, height: 36, borderRadius: 8, background: 'var(--ai-500)', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
            <Icon name="sparkle" size={18} style={{ color: '#fff' }} />
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="font-display" style={{ fontSize: 15, fontWeight: 600, letterSpacing: '0.02em' }}>O MEU DIGI</div>
            <div style={{ fontSize: 11, color: 'var(--text-muted)', fontFamily: 'var(--font-mono)' }}>{u.nome} · {u.role?.toUpperCase()}</div>
          </div>
          <button onClick={onClose} className="btn btn-sm btn-ghost" title="Fechar (Esc)">
            <Icon name="close" size={14} />
          </button>
        </div>

        {/* Body */}
        <div className="scrollbar" style={{ flex: 1, overflowY: 'auto', padding: '16px 20px' }}>
          {/* Primary CTA */}
          <button
            onClick={() => { onClose && onClose(); onOpenChat && onOpenChat(); }}
            className="btn btn-ai"
            style={{ width: '100%', justifyContent: 'center', padding: '12px 16px', fontSize: 13, marginBottom: 18 }}
          >
            <Icon name="sparkle" size={15} />
            Falar com o Digi
          </button>

          {/* KPIs pessoais */}
          <DrawerSection title="KPIs PESSOAIS">
            <DrawerKPI icon="chat" label="Conversas hoje" value="3" />
            <DrawerKPI icon="check" label="Tarefas abertas" value="7" meta="ClickUp" />
            <DrawerKPI icon="bell" label="Alertas activos" value="2" valueTone="danger" />
            <DrawerKPI icon="history" label="Histórico Digi" value="142" meta="trocas" />
            <DrawerKPI icon="circle" label="Última sessão" value="há 4h 12m" valueSize="small" />
          </DrawerSection>

          {/* Empresas */}
          <DrawerSection title="EMPRESAS QUE SIRVO">
            {accessibleCompanies.map(c => (
              <div key={c.id} style={{
                display: 'flex', alignItems: 'center', gap: 10,
                padding: '8px 10px',
                borderRadius: 'var(--r-3)',
                background: c.id === activeCompanyId ? 'color-mix(in oklch, var(--ai-500) 10%, transparent)' : 'transparent',
                marginBottom: 2,
              }}>
                <span style={{
                  width: 8, height: 8, borderRadius: '50%',
                  background: c.id === activeCompanyId ? 'var(--ai-500)' : 'var(--text-dim)',
                  flexShrink: 0,
                }} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 12.5, fontWeight: c.id === activeCompanyId ? 600 : 500 }}>{c.name}</div>
                  <div style={{ fontSize: 10, color: 'var(--text-dim)' }}>{c.country} · {c.tipo}</div>
                </div>
                {c.id === activeCompanyId && (
                  <span style={{ fontSize: 9.5, fontFamily: 'var(--font-mono)', color: 'var(--ai-500)', fontWeight: 600, letterSpacing: '0.06em' }}>ACTIVA</span>
                )}
              </div>
            ))}
          </DrawerSection>

          {/* Marcas + Mercados */}
          <DrawerSection title="MARCAS QUE COBRO">
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 10 }}>
              {(u.marcas || []).map(m => (
                <span key={m} style={{
                  fontSize: 11, padding: '4px 9px', borderRadius: 999,
                  background: 'var(--surface-muted)',
                  border: '1px solid var(--border)',
                  fontFamily: 'var(--font-display)', fontWeight: 600, letterSpacing: '0.04em',
                }}>{m}</span>
              ))}
            </div>
            <div style={{ fontSize: 11.5, color: 'var(--text-muted)', display: 'flex', alignItems: 'center', gap: 6 }}>
              <Icon name="globe" size={12} style={{ color: 'var(--text-dim)' }} />
              Mercados: <span style={{ color: 'var(--text)', fontFamily: 'var(--font-mono)' }}>{(u.mercados || []).join(' · ')}</span>
            </div>
          </DrawerSection>

          {/* RGPD */}
          <DrawerSection title="CONSENTIMENTOS RGPD">
            <DrawerCheckbox label="Digi pode processar conversas" checked={consents.process} onChange={() => toggleConsent('process')} />
            <DrawerCheckbox label="Histórico para training Digi" checked={consents.training} onChange={() => toggleConsent('training')} />
            <DrawerCheckbox label="Receber novidades do produto" checked={consents.newsletter} onChange={() => toggleConsent('newsletter')} />
            <div style={{ display: 'flex', gap: 6, marginTop: 10 }}>
              <button className="btn btn-xs" style={{ flex: 1, justifyContent: 'center' }}>
                <Icon name="doc" size={11} /> Ler T&C
              </button>
              <button className="btn btn-xs" style={{ flex: 1, justifyContent: 'center' }}>
                <Icon name="download" size={11} /> Exportar dados
              </button>
            </div>
          </DrawerSection>

          {/* Aviso transparência */}
          <div style={{
            padding: '11px 12px',
            borderRadius: 'var(--r-3)',
            background: 'color-mix(in oklch, var(--warning) 10%, transparent)',
            border: '1px solid color-mix(in oklch, var(--warning) 30%, transparent)',
            display: 'flex', gap: 10, marginTop: 4, marginBottom: 16,
          }}>
            <Icon name="alert" size={14} style={{ color: 'var(--warning)', flexShrink: 0, marginTop: 1 }} />
            <div style={{ fontSize: 11.5, lineHeight: 1.45, color: 'var(--text)' }}>
              <strong style={{ fontWeight: 600 }}>Importante:</strong> as conversas com o Digi ficam disponíveis ao manager e não podem ser apagadas pelo utilizador.
            </div>
          </div>

          <button
            onClick={() => { onClose && onClose(); onNavigate && onNavigate('settings'); }}
            className="btn"
            style={{ width: '100%', justifyContent: 'center', padding: '10px' }}
          >
            <Icon name="history" size={13} />
            Histórico completo de conversas
          </button>
        </div>

        <style>{`
          @keyframes slideInRight {
            from { transform: translateX(100%); }
            to { transform: translateX(0); }
          }
          @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
          }
        `}</style>
      </aside>
    </>
  );
};

const DrawerSection = ({ title, children }) => (
  <section style={{ marginBottom: 18 }}>
    <div style={{ fontSize: 9.5, color: 'var(--text-dim)', fontFamily: 'var(--font-display)', fontWeight: 600, letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 8 }}>
      {title}
    </div>
    {children}
  </section>
);

const DrawerKPI = ({ icon, label, value, valueTone, valueSize, meta }) => (
  <div style={{
    display: 'flex', alignItems: 'center', gap: 10,
    padding: '7px 10px', marginBottom: 2,
    borderRadius: 'var(--r-2)',
  }}>
    <Icon name={icon} size={13} style={{ color: 'var(--text-muted)', flexShrink: 0 }} />
    <span style={{ flex: 1, fontSize: 12.5, color: 'var(--text)' }}>{label}</span>
    {meta && <span style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)' }}>{meta}</span>}
    <span style={{
      fontSize: valueSize === 'small' ? 11.5 : 13,
      fontFamily: 'var(--font-display)', fontWeight: 600,
      color: valueTone === 'danger' ? 'var(--danger)' : 'var(--text)',
      letterSpacing: '0.01em',
    }}>{value}</span>
  </div>
);

const DrawerCheckbox = ({ label, checked, onChange }) => (
  <label style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '6px 0', cursor: 'pointer', fontSize: 12.5 }}>
    <span style={{
      width: 16, height: 16, borderRadius: 4, flexShrink: 0,
      border: `1.5px solid ${checked ? 'var(--ai-500)' : 'var(--border-strong)'}`,
      background: checked ? 'var(--ai-500)' : 'transparent',
      display: 'grid', placeItems: 'center',
      transition: 'all 0.12s',
    }}>
      {checked && <Icon name="check" size={11} style={{ color: '#fff' }} />}
    </span>
    <span style={{ flex: 1, color: 'var(--text)' }}>{label}</span>
    <input type="checkbox" checked={checked} onChange={onChange} style={{ display: 'none' }} />
  </label>
);

window.UserDrawer = UserDrawer;
