// AGENTFORGE-IA — barra lateral + barra superior
const { useState, useEffect, useMemo, useRef } = React;

function Topbar({ theme, onTheme, onCmdK, currentUser, onLoginClick, onLogout, goBack, canGoBack, sessionExpired }) {
  const { t, lang, setLang } = useI18n();
  const [open, setOpen] = useState(false);
  const [userOpen, setUserOpen] = useState(false);
  const langTimer = useRef(null);
  const userTimer = useRef(null);

  const initials = currentUser
    ? (currentUser.full_name || currentUser.email || '?').split(' ').map(w => w[0]).join('').slice(0, 2).toUpperCase()
    : null;
  const roleLabels = {
    propietario: 'Propietario',
    administrador: 'Administrador',
    constructor: 'Builder',
    revisor: 'Revisor',
    lector: 'Lector',
    operador_sensible: 'Operador sensible',
  };
  const sectionLabels = {
    playground: 'Pruebas',
    integrations: 'Integraciones',
    deployment: 'Despliegue',
    library: 'Biblioteca',
    crm: 'CRM',
    scheduling: 'Agenda',
    billing: 'Facturación',
    settings: 'Ajustes',
    runs: 'Ejecuciones',
    analytics: 'Analítica',
    admin: 'Admin usuarios',
    ops_finance: 'Ops Finanzas',
    ops_sales: 'Ops Ventas',
    ops_marketing: 'Ops Marketing',
    ops_operations: 'Ops Operaciones',
    ops_hr: 'Ops RRHH',
    ops_support: 'Ops Soporte',
  };
  const roles = Array.isArray(currentUser?.roles) ? currentUser.roles : [];
  const sections = currentUser?.sections && typeof currentUser.sections === 'object' ? currentUser.sections : {};
  const sectionEntries = Object.entries(sections).filter(([, level]) => level === 'view' || level === 'edit');

  return (
    <div className="topbar">
      <div className="tb-brand">
        {canGoBack && (
          <button
            className="tb-icon-btn"
            onClick={goBack}
            data-tip="Volver"
            style={{ marginRight: 8, flexShrink: 0, width: 32, height: 32, borderRadius: 8, background: 'var(--bg-2)', border: '1px solid var(--border)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}
          >
            <Icon name="arrow-left" size={20} />
          </button>
        )}
        <img src="agentforge-logo.png?v=4" alt="AgentForge" className="tb-logo-img" />
        <span className="tag" style={{ marginLeft: 4 }}>v2.4</span>
      </div>
      <div className="tb-mid">
        <button className="tb-cmd" onClick={onCmdK}>
          <Icon name="search" size={13} />
          <span>{t('tb.search')}</span>
          <kbd>⌘K</kbd>
        </button>
      </div>
      <div className="tb-right">
        <div
          className="lang-switch"
          onMouseEnter={() => clearTimeout(langTimer.current)}
          onMouseLeave={() => { langTimer.current = setTimeout(() => setOpen(false), 250); }}
        >
          <button className="lang-btn" onClick={() => setOpen(o => !o)} data-tip={t('lang.label')}>
            <Icon name="globe" size={14} />
            <span className="mono">{lang.toUpperCase()}</span>
            <Icon name="chevron-down" size={11} />
          </button>
          {open && (
            <div className="lang-menu">
              <div className="lang-h">{t('lang.label')}</div>
              {[['es','Español','🇪🇸'],['en','English','🇬🇧']].map(([code, name, flag]) => (
                <button key={code} className={'lang-opt' + (lang === code ? ' active' : '')} onClick={() => { setLang(code); setOpen(false); }}>
                  <span style={{ fontSize: 14 }}>{flag}</span>
                  <span style={{ flex: 1 }}>{name}</span>
                  {lang === code && <Icon name="check" size={12} />}
                </button>
              ))}
            </div>
          )}
        </div>
        <button className="tb-icon-btn" data-tip={t('tb.theme')} onClick={onTheme}>
          <Icon name={theme === 'dark' ? 'sun' : 'moon'} size={15} />
        </button>
        <button className="tb-icon-btn" data-tip={t('tb.notifications')} onClick={() => window.afNotify && window.afNotify('No hay notificaciones nuevas')}>
          <Icon name="bell" size={15} />
        </button>
        <button className="tb-icon-btn" data-tip={t('tb.help')} onClick={() => window.afNotify && window.afNotify('Centro de ayuda próximamente')}><Icon name="help" size={15} /></button>

        {currentUser ? (
          <div
            style={{ position: 'relative' }}
            onMouseEnter={() => clearTimeout(userTimer.current)}
            onMouseLeave={() => { userTimer.current = setTimeout(() => setUserOpen(false), 250); }}
          >
            <div
              className="tb-pill"
              style={{ cursor: 'pointer', userSelect: 'none' }}
              onClick={() => setUserOpen(o => !o)}
            >
              <div className="av" style={{ background: '#ff5b1f', color: '#fff' }}>{initials}</div>
              <div className="org" style={{ maxWidth: 120, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                {currentUser.full_name || currentUser.email}
                {(() => {
                  const ROLE_LABELS = { propietario: 'Propietario', administrador: 'Admin', constructor: 'Builder', revisor: 'Revisor', lector: 'Lector', operador_sensible: 'Op. sensible' };
                  const ROLE_COLORS = { propietario: '#7c3aed', administrador: '#f472b6', constructor: '#34d399', revisor: '#60a5fa', lector: '#fbbf24', operador_sensible: '#ef4444' };
                  const topRole = currentUser.is_admin ? 'propietario' : (currentUser.roles && currentUser.roles[0]);
                  if (!topRole) return null;
                  return <span style={{ marginLeft: 5, fontSize: 10, color: ROLE_COLORS[topRole] || '#ff5b1f', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.05em' }}>{ROLE_LABELS[topRole] || topRole}</span>;
                })()}
              </div>
              <Icon name="chevron-down" size={12} />
            </div>
            {userOpen && (
              <div style={{
                position: 'absolute', top: 'calc(100% + 6px)', right: 0,
                background: '#1a1a1a', border: '1px solid #2a2a2a', borderRadius: 8,
                minWidth: 180, zIndex: 200, boxShadow: '0 8px 24px rgba(0,0,0,0.4)',
                padding: '4px 0',
              }}>
                <div style={{ padding: '8px 14px 6px', borderBottom: '1px solid #222' }}>
                  <div style={{ fontSize: 12.5, fontWeight: 600, color: '#e5e5e5' }}>{currentUser.full_name || '—'}</div>
                  <div style={{ fontSize: 11.5, color: '#888', marginTop: 1 }}>{currentUser.email}</div>
                </div>
                <div style={{ padding: '8px 14px', borderBottom: '1px solid #222' }}>
                  <div style={{ fontSize: 10.5, color: '#9ca3af', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 6 }}>
                    Permisos efectivos
                  </div>
                  <div style={{ fontSize: 11.5, color: '#cfcfcf', marginBottom: 6 }}>
                    <b>Roles:</b>{' '}
                    {currentUser.is_admin
                      ? 'Admin global'
                      : (roles.length > 0 ? roles.map((r) => roleLabels[r] || r).join(', ') : 'Sin roles')}
                  </div>
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                    {sectionEntries.length > 0 ? (
                      sectionEntries.map(([section, level]) => (
                        <span
                          key={section}
                          style={{
                            fontSize: 10.5,
                            color: '#d1d5db',
                            background: '#111827',
                            border: '1px solid #374151',
                            borderRadius: 999,
                            padding: '2px 7px',
                          }}
                          title={`Nivel: ${level}`}
                        >
                          {(sectionLabels[section] || section)} · {level}
                        </span>
                      ))
                    ) : (
                      <span style={{ fontSize: 11, color: '#9ca3af' }}>Sin secciones RBAC asignadas</span>
                    )}
                  </div>
                </div>
                <button
                  onClick={() => { setUserOpen(false); onLogout && onLogout(); }}
                  style={{
                    display: 'flex', alignItems: 'center', gap: 8,
                    width: '100%', padding: '8px 14px', background: 'none', border: 'none',
                    color: '#ff6b6b', cursor: 'pointer', fontSize: 13, fontFamily: 'inherit',
                    textAlign: 'left',
                  }}
                >
                  <Icon name="logout" size={13} /> Cerrar sesión
                </button>
              </div>
            )}
          </div>
        ) : (
          <button
            onClick={onLoginClick}
            style={{
              background: '#ff5b1f', color: '#fff', border: 'none',
              borderRadius: 7, padding: '6px 14px', fontSize: 13, fontWeight: 700,
              cursor: 'pointer', fontFamily: 'inherit', whiteSpace: 'nowrap',
            }}
          >
            Iniciar sesión
          </button>
        )}
      </div>
    </div>
  );
}

// Rutas que requieren solo login (cualquier usuario registrado)
const SIDEBAR_USER = new Set(['library', 'builder', 'playground', 'integrations', 'deployment']);
// Rutas que requieren perfil admin/trabajador
const SIDEBAR_ADMIN = new Set([
  'crm', 'scheduling',
  'plans', 'billing', 'settings',
  'runs', 'analytics', 'admin',
]);
const SIDEBAR_SENSITIVE = new Set([
  'ops_finance', 'ops_sales', 'ops_marketing', 'ops_operations', 'ops_hr', 'ops_support',
]);
const STRICT_ADMIN_ONLY = new Set(['crm', 'scheduling']);
const USER_RBAC_ROUTES = new Set(['playground', 'integrations']);

function Sidebar({ route, setRoute, currentUser }) {
  const { t } = useI18n();
  const canAccessUserRbacRoute = (section) => {
    if (!USER_RBAC_ROUTES.has(section)) return true;
    if (!currentUser) return false;
    if (currentUser.is_admin) return true;
    return !!(currentUser.sections && currentUser.sections[section]);
  };

  const openContactForm = () => {
    window.dispatchEvent(new CustomEvent('af:contact:open', { detail: { public: true } }));
  };

  const adminChildren = [
    { id: 'plans', label: t('sb.plans'), icon: 'layers' },
    { id: 'billing', label: t('sb.billing'), icon: 'wallet' },
  ];
  if (currentUser && (currentUser.is_admin || (currentUser.sections && Object.keys(currentUser.sections).length > 0))) {
    adminChildren.push({ id: 'admin', label: 'Admin usuarios', icon: 'shield' });
  }

  const sensitiveChildren = [
    { id: 'ops_finance', label: t('sb.ops_finance'), icon: 'wallet' },
    { id: 'ops_sales', label: t('sb.ops_sales'), icon: 'megaphone' },
    { id: 'ops_marketing', label: t('sb.ops_marketing'), icon: 'sparkles' },
    { id: 'ops_operations', label: t('sb.ops_operations'), icon: 'grid' },
    { id: 'ops_hr', label: t('sb.ops_hr'), icon: 'users' },
    { id: 'ops_support', label: t('sb.ops_support'), icon: 'headset' },
  ];

  const items = [
    { group: t('sb.group.space'), children: [
      { id: 'home', label: t('sb.home'), icon: 'home' },
      { id: 'marketplace', label: t('sb.marketplace'), icon: 'store', count: '1.085' },
      { id: 'library', label: t('sb.library'), icon: 'grid', count: 6 },
      { id: 'builder', label: t('sb.builder'), icon: 'flow' },
      { id: 'playground', label: t('sb.playground'), icon: 'chat' },
      { id: 'integrations', label: t('sb.integrations'), icon: 'plug', count: 18 },
      { id: 'deployment', label: t('sb.deployment'), icon: 'cloud' },
    ]},
    { group: t('sb.group.observe'), children: [
      { id: 'crm', label: t('sb.crm'), icon: 'users', count: 60 },
      { id: 'scheduling', label: t('sb.scheduling'), icon: 'calendar' },
      { id: 'runs', label: t('sb.runs'), icon: 'logs', count: 412 },
      { id: 'analytics', label: t('sb.analytics'), icon: 'chart' },
    ]},
    { group: t('sb.group.admin'), children: adminChildren },
    { group: t('sb.group.ops'), children: sensitiveChildren },
  ];

  return (
    <aside className="sidebar">
      <button className="btn btn-primary" style={{ margin: '4px 6px 12px', justifyContent: 'flex-start' }} onClick={() => setRoute('onboarding')}>
        <Icon name="plus" size={13} stroke={2.2} /> {t('sb.new_agent')}
        <span className="mono" style={{ marginLeft: 'auto', opacity: 0.55, fontSize: 10.5 }}>⌘N</span>
      </button>
      <button
        className="btn btn-contact"
        style={{ margin: '0 6px 4px', justifyContent: 'flex-start' }}
        onClick={openContactForm}
      >
        <Icon name="mail" size={13} stroke={2.2} /> {t('btn.contact_us')}
      </button>
      {items.map((g, i) => (
        <React.Fragment key={i}>
          <div className="nav-group"><span>{g.group}</span></div>
          {g.children.map(it => {
            const needsAdmin = SIDEBAR_ADMIN.has(it.id);
            const needsSensitive = SIDEBAR_SENSITIVE.has(it.id);
            const needsUser = SIDEBAR_USER.has(it.id);
            const needsUserRbac = USER_RBAC_ROUTES.has(it.id);
            const strictAdmin = STRICT_ADMIN_ONLY.has(it.id);
            const canAccessSection = !needsAdmin || (
              currentUser && (
                (strictAdmin && currentUser.is_admin) ||
                (!strictAdmin && (currentUser.is_admin || (currentUser.sections && currentUser.sections[it.id])))
              )
            );
            const locked = !canAccessSection || (needsUser && !currentUser) || (needsUserRbac && !canAccessUserRbacRoute(it.id));
            const canAccessSensitive = !needsSensitive || (
              currentUser && (
                currentUser.is_admin ||
                (currentUser.sections && currentUser.sections[it.id])
              )
            );
            if (needsUserRbac && !canAccessUserRbacRoute(it.id)) {
              return null;
            }
            if (needsSensitive && !canAccessSensitive) {
              return null;
            }
            if (needsAdmin && !canAccessSection) {
              return null;
            }
            return (
              <div key={it.id}
                className={'nav-item' + (route === it.id ? ' active' : '') + (locked ? ' nav-locked' : '')}
                onClick={() => setRoute(it.id)}
                style={locked ? { opacity: 0.55 } : undefined}
              >
                <Icon name={it.icon} size={15} />
                <span>{it.label}</span>
                {locked
                  ? <Icon name="lock" size={11} style={{ opacity: 0.5, marginLeft: 'auto' }} />
                  : it.count != null && <span className="count">{it.count}</span>
                }
              </div>
            );
          })}
        </React.Fragment>
      ))}
      <div className="sb-foot">
        <div className="sb-meter">
          <div className="row"><span>{t('sb.usage')}</span><b>62,4 k <span style={{ color: 'var(--ink-4)' }}>/ 100 k</span></b></div>
          <div className="bar"><div style={{ width: '62%' }} /></div>
          <div className="lbl">{t('sb.usage.runs')}</div>
        </div>
      </div>
    </aside>
  );
}

// ── Booking Modal global ───────────────────────────────────────────────────────
function BookingModal({ onClose, prefill = {}, currentUser }) {
  const { lang } = useI18n();
  const token = sessionStorage.getItem('af_token') || '';
  const [googleOk, setGoogleOk] = React.useState(null);
  const [loading, setLoading]   = React.useState(false);
  const [done, setDone]         = React.useState(null);
  const [error, setError]       = React.useState('');

  const today = new Date().toISOString().slice(0, 10);
  const durByType = { demo: 30, discovery: 20, support: 15, consulting: 45, qbr: 60 };
  const localDateTime = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}T${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}:00`;

  const [form, setForm] = React.useState({
    title:    prefill.title || '',
    email:    prefill.email || '',
    type:     prefill.type  || 'demo',
    date:     prefill.date  || today,
    start:    prefill.start || '10:00',
    duration: prefill.duration || durByType[prefill.type] || 30,
  });

  React.useEffect(() => {
    if (!token) { setGoogleOk(false); return; }
    fetch('/api/v1/scheduling/google/status', { headers: { Authorization: 'Bearer ' + token } })
      .then(r => r.json()).then(d => setGoogleOk(!!d?.connected)).catch(() => setGoogleOk(false));
  }, [token]);

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const types = [
    { id: 'demo',       label: lang === 'en' ? 'Sales demo (30 min)'         : 'Demo comercial (30 min)',            dur: 30 },
    { id: 'discovery',  label: lang === 'en' ? 'Discovery call (20 min)'     : 'Llamada de descubrimiento (20 min)', dur: 20 },
    { id: 'support',    label: lang === 'en' ? 'Support session (15 min)'    : 'Sesión de soporte (15 min)',          dur: 15 },
    { id: 'consulting', label: lang === 'en' ? 'Consulting (45 min)'         : 'Consultoría (45 min)',                dur: 45 },
    { id: 'qbr',        label: lang === 'en' ? 'Quarterly review (60 min)'   : 'Revisión trimestral (60 min)',        dur: 60 },
  ];

  const submit = async () => {
    if (!form.title.trim()) { setError(lang === 'en' ? 'Name required' : 'Nombre requerido'); return; }
    setLoading(true); setError('');
    try {
      const endDate = new Date(`${form.date}T${form.start}:00`);
      endDate.setMinutes(endDate.getMinutes() + Number(form.duration));
      const res = await fetch('/api/v1/scheduling/events', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + token },
        body: JSON.stringify({
          title: form.title,
          start: `${form.date}T${form.start}:00`,
          end:   localDateTime(endDate),
          description: `Tipo: ${form.type}${form.email ? '\nContacto: ' + form.email : ''}`,
          attendee_email: form.email || null,
          event_type: form.type,
        }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.detail || 'Error');
      setDone(data.html_link || true);
    } catch (e) { setError(e.message); }
    finally { setLoading(false); }
  };

  return (
    <div className="modal-overlay" onClick={e => e.target === e.currentTarget && onClose()}>
      <div className="modal-box" style={{ maxWidth: 420 }}>
        <div className="modal-head">
          <span>{lang === 'en' ? 'Book appointment' : 'Agendar cita'}</span>
          <button className="modal-close" onClick={onClose}><Icon name="x" size={14} /></button>
        </div>

        {done ? (
          <div style={{ padding: '32px 24px', textAlign: 'center' }}>
            <div style={{ fontSize: 32, marginBottom: 12 }}>✓</div>
            <p style={{ marginBottom: 16, fontWeight: 600 }}>
              {lang === 'en' ? 'Appointment created in Google Calendar' : 'Cita creada en Google Calendar'}
            </p>
            {done !== true && (
              <a href={done} target="_blank" rel="noreferrer" className="btn btn-primary" style={{ display: 'inline-block' }}>
                {lang === 'en' ? 'Open in Google Calendar' : 'Abrir en Google Calendar'} →
              </a>
            )}
            <br />
            <button className="btn" style={{ marginTop: 12 }} onClick={onClose}>
              {lang === 'en' ? 'Close' : 'Cerrar'}
            </button>
          </div>
        ) : (
          <div className="modal-body" style={{ display: 'flex', flexDirection: 'column', gap: 14, padding: '20px 24px 24px' }}>
            {googleOk === false && (
              <div style={{ border: '1px solid var(--line)', borderRadius: 10, padding: 10, color: 'var(--ink-3)', fontSize: 12, lineHeight: 1.45 }}>
                {lang === 'en'
                  ? 'Google Workspace is not connected. The appointment will be saved in AgentForge and can be synced after connecting Google.'
                  : 'Google Workspace no está conectado. La cita se guardará en AgentForge y podrá sincronizarse al conectar Google.'}
              </div>
            )}
            <label className="field-label">
              {lang === 'en' ? 'Contact name *' : 'Nombre del contacto *'}
              <input className="field-input" value={form.title} onChange={e => set('title', e.target.value)} placeholder={lang === 'en' ? 'e.g. María García' : 'ej. María García'} />
            </label>
            <label className="field-label">
              {lang === 'en' ? 'Contact email' : 'Email del contacto'}
              <input className="field-input" type="email" value={form.email} onChange={e => set('email', e.target.value)} placeholder="email@empresa.com" />
            </label>
            <label className="field-label">
              {lang === 'en' ? 'Type' : 'Tipo de cita'}
              <select className="field-input" value={form.type} onChange={e => { const t = types.find(x => x.id === e.target.value); set('type', e.target.value); if (t) set('duration', t.dur); }}>
                {types.map(t => <option key={t.id} value={t.id}>{t.label}</option>)}
              </select>
            </label>
            <div style={{ display: 'flex', gap: 12 }}>
              <label className="field-label" style={{ flex: 1 }}>
                {lang === 'en' ? 'Date' : 'Fecha'}
                <input className="field-input" type="date" value={form.date} min={today} onChange={e => set('date', e.target.value)} />
              </label>
              <label className="field-label" style={{ flex: 1 }}>
                {lang === 'en' ? 'Time' : 'Hora'}
                <input className="field-input" type="time" value={form.start} onChange={e => set('start', e.target.value)} />
              </label>
            </div>
            {error && <p style={{ color: 'var(--error, #ef4444)', fontSize: 13, margin: 0 }}>{error}</p>}
            <button className="btn btn-primary" onClick={submit} disabled={loading} style={{ marginTop: 4 }}>
              {loading ? (lang === 'en' ? 'Saving…' : 'Guardando…') : (lang === 'en' ? 'Create appointment' : 'Crear cita')}
            </button>
          </div>
        )}
      </div>
    </div>
  );
}

window.BookingModal = BookingModal;
window.Topbar = Topbar;
window.Sidebar = Sidebar;
