// fichaje.eu — Screen: Organización (admin: employees + permissions)

const ScreenOrganizacion = ({ role }) => {
  const [view, setView] = React.useState('list');
  const [createOpen, setCreateOpen] = React.useState(false);
  const [editTarget, setEditTarget] = React.useState(null);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14 }}>
        <Stat label="Empleados activos" value="24" delta="+2 este mes" tone="brand"  icon={<IUsers size={18}/>}/>
        <Stat label="Fichados ahora"    value="14" delta="58% del equipo" tone="success" icon={<IClock size={18}/>}/>
        <Stat label="Vacaciones hoy"    value="3"  tone="warning" icon={<ICalendar size={18}/>}/>
        <Stat label="Nuevas incorporaciones" value="2" delta="Este mes" tone="violet" icon={<IAward size={18}/>}/>
      </div>

      <Card padded={false}>
        <div style={{ padding: '14px 20px', borderBottom: '1px solid var(--slate-150)', display: 'flex', alignItems: 'center', gap: 12 }}>
          <Tabs tabs={[
            { value: 'list',  label: 'Directorio' },
            { value: 'org',   label: 'Organigrama' },
            { value: 'perms', label: 'Permisos y roles' },
          ]} value={view} onChange={setView}/>
          <div style={{ flex: 1 }}/>
          <Input icon={<ISearch size={14}/>} placeholder="Buscar empleado, equipo…" style={{ width: 240, background: 'var(--slate-50)' }}/>
          <Btn variant="ghost" size="sm" icon={<IFilter size={14}/>}>Equipo</Btn>
          {role === 'admin' && <Btn variant="primary" size="sm" icon={<IPlus size={14}/>} onClick={() => setCreateOpen(true)}>Nuevo empleado</Btn>}
        </div>

        {view === 'list' && <DirList role={role} onEdit={setEditTarget}/>}
        {view === 'org'  && <OrgChart/>}
        {view === 'perms' && <PermissionsMatrix/>}
      </Card>

      {createOpen && <CreateEmployeeModal onClose={() => setCreateOpen(false)}/>}
      {editTarget && <EditEmployeeModal employee={editTarget} onClose={() => setEditTarget(null)}/>}
    </div>
  );
};

const DirList = ({ role, onEdit }) => (
  <div>
    <div style={{ display: 'grid', gridTemplateColumns: '2fr 1.2fr 1fr 1fr 1fr 100px 32px', padding: '12px 20px', fontSize: 11.5, fontWeight: 700, color: 'var(--slate-500)', textTransform: 'uppercase', letterSpacing: '.06em', borderBottom: '1px solid var(--slate-150)' }}>
      <div>Nombre</div><div>Puesto</div><div>Equipo</div><div>Antigüedad</div><div>Permisos</div><div>Estado</div><div></div>
    </div>
    {TEAM.map((p, i) => {
      const status = {
        fichado:    { tone: 'success', label: 'Fichado' },
        pausa:      { tone: 'warning', label: 'En pausa' },
        vacaciones: { tone: 'brand',   label: 'Vacaciones' },
        fuera:      { tone: 'slate',   label: 'Fuera' },
      }[p.status];
      const isAdmin = ['CTO', 'People Ops'].includes(p.role);
      const isManager = ['CTO', 'Lead Engineer', 'Marketing Lead', 'People Ops'].includes(p.role);
      return (
        <div key={p.name} style={{ display: 'grid', gridTemplateColumns: '2fr 1.2fr 1fr 1fr 1fr 100px 32px', padding: '14px 20px', borderBottom: '1px solid var(--slate-100)', alignItems: 'center', fontSize: 13.5 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <Avatar name={p.name} size={36}/>
            <div>
              <div style={{ fontWeight: 600, color: 'var(--ink)' }}>{p.name}</div>
              <div style={{ fontSize: 12, color: 'var(--slate-500)' }}>{p.email}</div>
            </div>
          </div>
          <div style={{ color: 'var(--slate-700)' }}>{p.role}</div>
          <div><Badge tone="slate">{p.team}</Badge></div>
          <div className="tnum" style={{ color: 'var(--slate-600)' }}>{p.tenure}</div>
          <div style={{ display: 'flex', gap: 4 }}>
            {isAdmin && <Badge tone="brand">Admin</Badge>}
            {isManager && !isAdmin && <Badge tone="violet">Manager</Badge>}
            {!isAdmin && !isManager && <Badge tone="slate">Empleado</Badge>}
          </div>
          <Badge tone={status.tone} dot>{status.label}</Badge>
          {role === 'admin' ? (
            <RowMenu onEdit={() => onEdit(p)} employee={p}/>
          ) : <div/>}
        </div>
      );
    })}
  </div>
);

const RowMenu = ({ onEdit, employee }) => {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  const onDelete = async () => {
    if (!employee || !employee.id || !window.api) return;
    if (!window.confirm(`¿Dar de baja a ${employee.name}? Esta acción no se puede deshacer.`)) return;
    await window.api.deleteEmployee(employee.id);
    await window.api.reloadBootstrap();
    window.location.reload();
  };
  React.useEffect(() => {
    if (!open) return;
    const handle = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', handle);
    return () => document.removeEventListener('mousedown', handle);
  }, [open]);
  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <button onClick={() => setOpen(!open)} style={{ width: 28, height: 28, borderRadius: 'var(--r-sm)', color: 'var(--slate-500)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', background: open ? 'var(--slate-100)' : 'transparent' }}><IMoreH size={16}/></button>
      {open && (
        <div style={{
          position: 'absolute', right: 0, top: '100%', marginTop: 4,
          background: '#fff', border: '1px solid var(--slate-150)',
          borderRadius: 'var(--r-md)', boxShadow: 'var(--shadow-md)',
          padding: 4, zIndex: 20, minWidth: 200,
        }}>
          {[
            { i: <IEdit size={14}/>, l: 'Editar empleado', a: () => { setOpen(false); onEdit(); } },
            { i: <IShield size={14}/>, l: 'Cambiar permisos' },
            { i: <ICalendar size={14}/>, l: 'Ajustar vacaciones', a: () => { setOpen(false); onEdit(); } },
            { i: <IFile size={14}/>, l: 'Subir documento' },
            { i: <IMail size={14}/>, l: 'Reenviar invitación' },
            { divider: true },
            { i: <ITrash size={14}/>, l: 'Dar de baja', danger: true, a: () => { setOpen(false); onDelete(); } },
          ].map((it, i) => it.divider ? (
            <div key={i} style={{ height: 1, background: 'var(--slate-100)', margin: '4px 0' }}/>
          ) : (
            <button key={i} onClick={it.a} style={{
              display: 'flex', alignItems: 'center', gap: 10, width: '100%',
              padding: '7px 10px', borderRadius: 'var(--r-sm)',
              fontSize: 13, fontWeight: 500,
              color: it.danger ? 'var(--danger-600)' : 'var(--slate-700)',
              textAlign: 'left',
            }}
            onMouseEnter={(e) => e.currentTarget.style.background = it.danger ? 'var(--danger-50)' : 'var(--slate-50)'}
            onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
            >
              <span style={{ color: it.danger ? 'var(--danger-500)' : 'var(--slate-500)' }}>{it.i}</span>
              {it.l}
            </button>
          ))}
        </div>
      )}
    </div>
  );
};

const OrgChart = () => (
  <div style={{ padding: '32px 20px', overflow: 'auto' }}>
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 32 }}>
      <OrgNode person={{ name: 'Lucía Ferrer', role: 'CEO & Founder', team: 'Dirección' }} level="ceo"/>
      <div style={{ width: 1, height: 24, background: 'var(--slate-200)' }}/>
      <div style={{ display: 'flex', gap: 28, position: 'relative' }}>
        <div style={{ position: 'absolute', top: -24, left: '12.5%', right: '12.5%', height: 1, background: 'var(--slate-200)' }}/>
        {[
          { name: 'Núria Castells', role: 'CTO', team: 'Dirección' },
          { name: 'Berta Folch', role: 'Marketing Lead', team: 'Marketing' },
          { name: 'Helena Prats', role: 'People Ops', team: 'RRHH' },
          { name: 'Joel Vidal', role: 'Sales Engineer', team: 'Comercial' },
        ].map(p => (
          <div key={p.name} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 16 }}>
            <div style={{ width: 1, height: 24, background: 'var(--slate-200)', marginTop: -32 }}/>
            <OrgNode person={p} level="lead"/>
          </div>
        ))}
      </div>
      <div style={{ fontSize: 13, color: 'var(--slate-500)', marginTop: 8 }}>+ 19 personas en niveles inferiores</div>
    </div>
  </div>
);

const OrgNode = ({ person, level }) => {
  const isCeo = level === 'ceo';
  return (
    <div style={{
      background: isCeo ? 'linear-gradient(135deg, var(--brand-700), var(--brand-500))' : 'var(--white)',
      border: `1px solid ${isCeo ? 'var(--brand-700)' : 'var(--slate-150)'}`,
      borderRadius: 'var(--r-lg)',
      padding: 14,
      width: 200,
      textAlign: 'center',
      boxShadow: 'var(--shadow-sm)',
      color: isCeo ? '#fff' : 'var(--ink)',
    }}>
      <Avatar name={person.name} size={44}/>
      <div style={{ fontSize: 14, fontWeight: 700, marginTop: 8 }}>{person.name}</div>
      <div style={{ fontSize: 12, opacity: 0.85, marginTop: 2 }}>{person.role}</div>
    </div>
  );
};

const PermissionsMatrix = () => {
  const roles = ['Empleado', 'Manager', 'RRHH', 'Admin'];
  const perms = [
    { area: 'Fichaje',     perms: ['Fichar propio', 'Ver registros propios', 'Ver registros del equipo', 'Editar registros'] },
    { area: 'Ausencias',   perms: ['Solicitar ausencia', 'Aprobar del equipo', 'Aprobar de todos', 'Configurar políticas'] },
    { area: 'Documentos',  perms: ['Ver propios', 'Subir a su perfil', 'Subir a otros', 'Gestionar plantillas'] },
    { area: 'Organización',perms: ['Ver directorio', 'Editar su equipo', 'Editar cualquier persona', 'Crear usuarios'] },
  ];
  const matrix = {
    'Empleado': [true, false, false, false],
    'Manager':  [true, true, false, false],
    'RRHH':     [true, true, true, false],
    'Admin':    [true, true, true, true],
  };
  return (
    <div style={{ padding: 20 }}>
      <div style={{ display: 'grid', gridTemplateColumns: '180px repeat(4, 1fr)', gap: 0 }}>
        <div></div>
        {roles.map(r => (
          <div key={r} style={{ padding: '10px 8px', textAlign: 'center' }}>
            <Badge tone={r === 'Admin' ? 'brand' : r === 'RRHH' ? 'violet' : r === 'Manager' ? 'success' : 'slate'}>{r}</Badge>
            <div style={{ fontSize: 11, color: 'var(--slate-500)', marginTop: 4 }}>
              {r === 'Empleado' ? '21 personas' : r === 'Manager' ? '5 personas' : r === 'RRHH' ? '1 persona' : '2 personas'}
            </div>
          </div>
        ))}
        {perms.map((g, gi) => (
          <React.Fragment key={gi}>
            <div style={{ gridColumn: '1 / -1', marginTop: 16, marginBottom: 8, fontSize: 12, fontWeight: 700, color: 'var(--slate-500)', textTransform: 'uppercase', letterSpacing: '.06em' }}>{g.area}</div>
            {g.perms.map((p, pi) => (
              <React.Fragment key={pi}>
                <div style={{ padding: '10px 12px', fontSize: 13, color: 'var(--slate-700)', borderTop: '1px solid var(--slate-100)' }}>{p}</div>
                {roles.map(r => (
                  <div key={r} style={{ padding: '10px 12px', textAlign: 'center', borderTop: '1px solid var(--slate-100)' }}>
                    {matrix[r][pi] ? (
                      <span style={{ display: 'inline-flex', width: 22, height: 22, borderRadius: 999, background: 'var(--success-100)', color: 'var(--success-600)', alignItems: 'center', justifyContent: 'center' }}><ICheck size={13}/></span>
                    ) : (
                      <span style={{ display: 'inline-block', width: 14, height: 2, background: 'var(--slate-200)', borderRadius: 999 }}/>
                    )}
                  </div>
                ))}
              </React.Fragment>
            ))}
          </React.Fragment>
        ))}
      </div>
    </div>
  );
};

const CreateEmployeeModal = ({ onClose }) => {
  const [step, setStep] = React.useState(1);
  const [form, setForm] = React.useState({
    first_name: '', last_name: '', email: '', dni: '', phone: '', address: '', birth: '',
    role_title: '', team: 'Implementación', manager: '', center: 'Oficina Valencia',
    contract: 'Indefinido · Jornada completa', start: '2026-06-01',
    weekly_hours: 40, schedule: 'L–V · 09:00–18:00 (40h)',
    vacation_days: 23, personal_days: 2,
    permission_role: 'Empleado',
  });
  const set = (k, v) => setForm(s => ({ ...s, [k]: v }));
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState('');

  const submit = async () => {
    if (!window.api) return;
    if (!form.first_name || !form.last_name || !form.email) {
      setErr('Nombre, apellidos y email son obligatorios.');
      setStep(1);
      return;
    }
    setBusy(true); setErr('');
    try {
      const payload = {
        full_name: `${form.first_name} ${form.last_name}`.trim(),
        email: form.email,
        role: form.role_title || 'Empleado',
        team: form.team,
        manager: form.manager,
        location: form.center,
        contract: form.contract,
        start_date: form.start,
        schedule: form.schedule,
        vacation_total: Number(form.vacation_days) || 23,
        permission: form.permission_role,
        phone: form.phone,
        birthday: form.birth,
      };
      const r = await window.api.createEmployee(payload);
      if (r && r.error) { setErr(r.error); setBusy(false); return; }
      await window.api.reloadBootstrap();
      window.location.reload();
    } catch (e) { setErr(String(e)); setBusy(false); }
  };

  return (
    <div style={{ position: 'fixed', inset: 0, background: 'rgba(15,23,42,0.5)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 50 }} onClick={onClose}>
      <div onClick={e => e.stopPropagation()} style={{ background: '#fff', borderRadius: 'var(--r-xl)', width: 760, maxHeight: '92vh', display: 'flex', flexDirection: 'column', boxShadow: 'var(--shadow-lg)' }}>
        <div style={{ padding: '20px 28px 16px', borderBottom: '1px solid var(--slate-150)' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
            <div>
              <div style={{ fontSize: 19, fontWeight: 700 }}>Crear nuevo empleado</div>
              <div style={{ fontSize: 13, color: 'var(--slate-500)', marginTop: 2 }}>Se enviará un email de bienvenida con sus accesos cuando termines.</div>
            </div>
            <button onClick={onClose} style={{ color: 'var(--slate-500)', padding: 6 }}><IX size={18}/></button>
          </div>
          <div style={{ display: 'flex', gap: 4, marginTop: 16 }}>
            {[
              { n: 1, l: 'Datos básicos' },
              { n: 2, l: 'Contrato y horario' },
              { n: 3, l: 'Vacaciones' },
              { n: 4, l: 'Permisos' },
            ].map((s, i, arr) => (
              <React.Fragment key={s.n}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <div style={{
                    width: 22, height: 22, borderRadius: 999,
                    background: step >= s.n ? 'var(--brand-600)' : 'var(--slate-150)',
                    color: step >= s.n ? '#fff' : 'var(--slate-500)',
                    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                    fontSize: 11, fontWeight: 700,
                  }}>{step > s.n ? <ICheck size={12}/> : s.n}</div>
                  <div style={{ fontSize: 12.5, fontWeight: step === s.n ? 700 : 500, color: step === s.n ? 'var(--ink)' : 'var(--slate-500)' }}>{s.l}</div>
                </div>
                {i < arr.length - 1 && <div style={{ flex: 1, height: 1, background: step > s.n ? 'var(--brand-300)' : 'var(--slate-150)', alignSelf: 'center' }}/>}
              </React.Fragment>
            ))}
          </div>
        </div>

        <div style={{ flex: 1, overflow: 'auto', padding: 28 }}>
          {step === 1 && <Step1Basics form={form} set={set}/>}
          {step === 2 && <Step2Contract form={form} set={set}/>}
          {step === 3 && <Step3Vacation form={form} set={set}/>}
          {step === 4 && <Step4Permissions form={form} set={set}/>}
        </div>

        <div style={{ padding: '16px 28px', borderTop: '1px solid var(--slate-150)', display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12 }}>
          <div style={{ fontSize: 12, color: 'var(--slate-500)' }}>Paso {step} de 4</div>
          {err && <div style={{ fontSize: 12, color: '#991B1B', background: '#FEE2E2', padding: '6px 10px', borderRadius: 6 }}>{err}</div>}
          <div style={{ display: 'flex', gap: 10 }}>
            <Btn variant="ghost" onClick={onClose} disabled={busy}>Cancelar</Btn>
            {step > 1 && <Btn variant="secondary" onClick={() => setStep(step - 1)} icon={<IChevronLeft size={14}/>} disabled={busy}>Atrás</Btn>}
            {step < 4 ? (
              <Btn variant="primary" iconRight={<IChevronRight size={14}/>} onClick={() => setStep(step + 1)}>Siguiente</Btn>
            ) : (
              <Btn variant="primary" icon={<ICheck size={14}/>} onClick={submit} disabled={busy}>{busy ? 'Creando…' : 'Crear empleado'}</Btn>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

const Step1Basics = ({ form, set }) => (
  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
    <Field label="Nombre" required><Input placeholder="Anna" value={form.first_name} onChange={e => set('first_name', e.target.value)}/></Field>
    <Field label="Apellidos" required><Input placeholder="Boixader Casals" value={form.last_name} onChange={e => set('last_name', e.target.value)}/></Field>
    <Field label="Email corporativo" required hint="@iabusiness.es"><Input placeholder="anna@iabusiness.es" icon={<IMail size={14}/>} value={form.email} onChange={e => set('email', e.target.value)}/></Field>
    <Field label="Teléfono"><Input placeholder="+34 6XX XX XX XX" icon={<IPhone size={14}/>} value={form.phone} onChange={e => set('phone', e.target.value)}/></Field>
    <Field label="DNI / NIE"><Input placeholder="47892331-K" value={form.dni} onChange={e => set('dni', e.target.value)}/></Field>
    <Field label="Fecha de nacimiento"><Input type="date" value={form.birth} onChange={e => set('birth', e.target.value)}/></Field>
    <Field label="Dirección"><Input placeholder="C/ ... · Ciudad" value={form.address} onChange={e => set('address', e.target.value)}/></Field>
    <div/>
  </div>
);

const Step2Contract = ({ form, set }) => (
  <div>
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
      <Field label="Puesto" required><Input placeholder="AI Solutions Engineer" value={form.role_title} onChange={e => set('role_title', e.target.value)}/></Field>
      <Field label="Equipo" required>
        <select style={selectStyle} value={form.team} onChange={e => set('team', e.target.value)}>
          <option>Implementación</option><option>Plataforma</option><option>Comercial</option><option>Marketing</option><option>RRHH</option><option>Dirección</option>
        </select>
      </Field>
      <Field label="Manager directo"><Input placeholder="Núria Castells" value={form.manager} onChange={e => set('manager', e.target.value)}/></Field>
      <Field label="Centro de trabajo">
        <select style={selectStyle} value={form.center} onChange={e => set('center', e.target.value)}>
          <option>Oficina Valencia</option><option>Remoto · España</option><option>Híbrido</option>
        </select>
      </Field>
      <Field label="Tipo de contrato" required>
        <select style={selectStyle} value={form.contract} onChange={e => set('contract', e.target.value)}>
          <option>Indefinido · Jornada completa</option><option>Indefinido · Media jornada</option><option>Temporal · Jornada completa</option><option>Prácticas / Becario</option>
        </select>
      </Field>
      <Field label="Inicio del contrato" required><Input type="date" value={form.start} onChange={e => set('start', e.target.value)}/></Field>
      <Field label="Convenio colectivo">
        <select style={selectStyle}>
          <option>Consultoría TIC</option><option>Comercio</option><option>Oficinas y despachos</option><option>Sin convenio</option>
        </select>
      </Field>
      <Field label="Categoría profesional">
        <select style={selectStyle}>
          <option>Grupo 1 · Dirección</option><option>Grupo 2 · Senior</option><option>Grupo 3 · Mid-level</option><option>Grupo 4 · Junior</option>
        </select>
      </Field>
    </div>

    <div style={{ marginTop: 22, padding: 18, background: 'var(--slate-50)', borderRadius: 'var(--r-md)', border: '1px solid var(--slate-150)' }}>
      <div style={{ fontSize: 13, fontWeight: 700, marginBottom: 12 }}>Horario y jornada</div>
      <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr 1fr', gap: 14 }}>
        <Field label="Plantilla horaria">
          <select style={selectStyle} value={form.schedule} onChange={e => set('schedule', e.target.value)}>
            <option>L–V · 09:00–18:00 (40h)</option>
            <option>L–J · 09:00–18:30 · V · 09:00–15:00 (40h)</option>
            <option>L–V · 08:00–15:00 (35h)</option>
            <option>Turno rotativo</option>
            <option>Personalizado</option>
          </select>
        </Field>
        <Field label="Horas semanales"><Input type="number" value={form.weekly_hours} onChange={e => set('weekly_hours', e.target.value)} style={{ fontFamily: 'var(--font-mono)' }}/></Field>
        <Field label="Flexibilidad ±">
          <select style={selectStyle}>
            <option>Sin flexibilidad</option><option>±15 min</option><option>±30 min</option><option>±60 min</option>
          </select>
        </Field>
      </div>
    </div>
  </div>
);

const Step3Vacation = ({ form, set }) => {
  const vacationDays = form.vacation_days;
  const personalDays = form.personal_days;
  const setVacationDays = (v) => set('vacation_days', v);
  const setPersonalDays = (v) => set('personal_days', v);
  const [proRata, setProRata] = React.useState(true);
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10, padding: 14, background: 'var(--brand-50)', border: '1px solid var(--brand-100)', borderRadius: 'var(--r-md)', marginBottom: 22 }}>
        <ISparkle size={16} style={{ color: 'var(--brand-600)', marginTop: 1, flexShrink: 0 }}/>
        <div style={{ fontSize: 13, color: 'var(--slate-700)', lineHeight: 1.55 }}>
          Por convenio <strong>Consultoría TIC</strong>, lo habitual son <strong>23 días laborables de vacaciones</strong> + <strong>2 días de asuntos propios</strong> al año. Aplicaremos el prorrateo según fecha de inicio.
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18 }}>
        <PolicyCounter
          icon={<ICalendar size={18}/>}
          tone="brand"
          title="Vacaciones anuales"
          subtitle="Días laborables que le pertenecen al año natural"
          value={vacationDays}
          onChange={setVacationDays}
          unit="días"
          presets={[22, 23, 25, 30]}
        />
        <PolicyCounter
          icon={<IFlag size={18}/>}
          tone="violet"
          title="Asuntos propios"
          subtitle="Días retribuidos para gestiones personales"
          value={personalDays}
          onChange={setPersonalDays}
          unit="días"
          presets={[0, 1, 2, 4]}
        />
      </div>

      <div style={{ marginTop: 18, padding: 18, background: 'var(--slate-50)', borderRadius: 'var(--r-md)', border: '1px solid var(--slate-150)' }}>
        <div style={{ fontSize: 13, fontWeight: 700, marginBottom: 14 }}>Otros permisos retribuidos (configurables)</div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 14 }}>
          <MiniField label="Mudanza"        unit="días" defaultValue="1"/>
          <MiniField label="Matrimonio"     unit="días" defaultValue="15"/>
          <MiniField label="Fallecimiento familiar" unit="días" defaultValue="2"/>
          <MiniField label="Nacimiento hijo/a"      unit="semanas" defaultValue="16"/>
          <MiniField label="Examen / formación"     unit="horas" defaultValue="40"/>
          <MiniField label="Médico (con justif.)"   unit="ilimitado" defaultValue="—" disabled/>
        </div>
      </div>

      <div style={{ marginTop: 18, padding: '12px 16px', background: 'var(--white)', border: '1px solid var(--slate-200)', borderRadius: 'var(--r-md)', display: 'flex', alignItems: 'center', gap: 12 }}>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 13, fontWeight: 600 }}>Prorratear si entra a mitad de año</div>
          <div style={{ fontSize: 12, color: 'var(--slate-500)' }}>Empieza el 1 jun → recibe <strong>{Math.round(vacationDays * 7 / 12)} días</strong> de vacaciones y <strong>{Math.round(personalDays * 7 / 12)} de asuntos propios</strong> para 2026.</div>
        </div>
        <Toggle defaultOn={proRata}/>
      </div>

      <div style={{ marginTop: 14, padding: '12px 16px', background: 'var(--white)', border: '1px solid var(--slate-200)', borderRadius: 'var(--r-md)', display: 'flex', alignItems: 'center', gap: 12 }}>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 13, fontWeight: 600 }}>Permitir arrastrar días al año siguiente</div>
          <div style={{ fontSize: 12, color: 'var(--slate-500)' }}>Hasta 5 días no consumidos pueden usarse antes del 31 marzo.</div>
        </div>
        <Toggle/>
      </div>
    </div>
  );
};

const Step4Permissions = ({ form, set }) => (
  <div>
    <Field label="Rol del empleado" required hint="Define qué áreas y datos podrá ver y modificar.">
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8, marginTop: 4 }}>
        {[
          { r: 'Empleado', d: 'Acceso a sus propios datos y fichaje.', i: <IUsers size={16}/> },
          { r: 'Manager',  d: 'Aprueba ausencias del equipo y ve registros.', i: <IUsers size={16}/> },
          { r: 'RRHH',     d: 'Gestiona personal, documentos y políticas.', i: <IShield size={16}/> },
          { r: 'Admin',    d: 'Control total del workspace.', i: <IShield size={16}/> },
        ].map(o => {
          const active = form.permission_role === o.r;
          return (
          <button key={o.r} onClick={() => set('permission_role', o.r)} style={{
            padding: 14, textAlign: 'left',
            border: `1px solid ${active ? 'var(--brand-500)' : 'var(--slate-200)'}`,
            background: active ? 'var(--brand-50)' : '#fff',
            borderRadius: 'var(--r-md)',
            boxShadow: active ? 'var(--ring-brand)' : 'none',
            display: 'flex', flexDirection: 'column', gap: 6, cursor: 'pointer',
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, color: active ? 'var(--brand-700)' : 'var(--slate-600)' }}>
              {o.i}
              <span style={{ fontSize: 13, fontWeight: 700 }}>{o.r}</span>
            </div>
            <div style={{ fontSize: 11.5, color: 'var(--slate-500)', lineHeight: 1.4 }}>{o.d}</div>
          </button>
        );})}
      </div>
    </Field>

    <div style={{ marginTop: 22 }}>
      <div style={{ fontSize: 13, fontWeight: 700, marginBottom: 10 }}>Onboarding automático</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {[
          { l: 'Crear cuenta corporativa', s: 'anna.boixader@iabusiness.es', on: true },
          { l: 'Firmar contrato base de Consultoría TIC', s: 'Plantilla "Indefinido · Jornada completa"', on: true },
          { l: 'Asignar equipo informático', s: 'Solicitud automática a IT', on: true },
          { l: 'Añadir a Slack: #general, #implementacion', s: '', on: true },
          { l: 'Notificar incorporación al equipo', s: 'Email al equipo de Implementación y tablón', on: false },
        ].map((x, i) => (
          <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 14px', border: '1px solid var(--slate-150)', borderRadius: 'var(--r-md)' }}>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 600 }}>{x.l}</div>
              {x.s && <div style={{ fontSize: 12, color: 'var(--slate-500)' }}>{x.s}</div>}
            </div>
            <Toggle defaultOn={x.on}/>
          </div>
        ))}
      </div>
    </div>
  </div>
);

const selectStyle = { width: '100%', padding: '10px 12px', fontSize: 14, border: '1px solid var(--slate-200)', borderRadius: 'var(--r-md)', background: '#fff' };

const PolicyCounter = ({ icon, tone, title, subtitle, value, onChange, unit, presets }) => {
  const tones = {
    brand:  ['var(--brand-50)',  'var(--brand-600)',  'var(--brand-100)'],
    violet: ['var(--violet-100)', '#6D28D9',          'var(--violet-100)'],
  }[tone];
  return (
    <div style={{ padding: 18, background: '#fff', border: '1px solid var(--slate-150)', borderRadius: 'var(--r-md)' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 4 }}>
        <div style={{ width: 32, height: 32, borderRadius: 'var(--r-sm)', background: tones[0], color: tones[1], display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>{icon}</div>
        <div>
          <div style={{ fontSize: 14, fontWeight: 700 }}>{title}</div>
          <div style={{ fontSize: 12, color: 'var(--slate-500)' }}>{subtitle}</div>
        </div>
      </div>

      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 14 }}>
        <button onClick={() => onChange(Math.max(0, value - 1))} style={{ width: 32, height: 32, borderRadius: 'var(--r-md)', border: '1px solid var(--slate-200)', background: '#fff', color: 'var(--slate-700)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: 18, fontWeight: 700 }}>−</button>
        <div className="tnum" style={{ flex: 1, padding: '6px 12px', background: tones[0], border: `1px solid ${tones[2]}`, borderRadius: 'var(--r-md)', textAlign: 'center', fontSize: 22, fontWeight: 700, color: tones[1], fontFamily: 'var(--font-sans)', display: 'flex', alignItems: 'baseline', justifyContent: 'center', gap: 6 }}>
          {value}<span style={{ fontSize: 13, fontWeight: 600, opacity: 0.7 }}>{unit}</span>
        </div>
        <button onClick={() => onChange(value + 1)} style={{ width: 32, height: 32, borderRadius: 'var(--r-md)', border: '1px solid var(--slate-200)', background: '#fff', color: 'var(--slate-700)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: 18, fontWeight: 700 }}>+</button>
      </div>

      <div style={{ display: 'flex', gap: 6, marginTop: 12 }}>
        {presets.map(p => (
          <button key={p} onClick={() => onChange(p)} style={{
            flex: 1, padding: '6px 4px',
            fontSize: 12, fontWeight: 600,
            border: `1px solid ${value === p ? tones[1] : 'var(--slate-200)'}`,
            background: value === p ? tones[0] : '#fff',
            color: value === p ? tones[1] : 'var(--slate-600)',
            borderRadius: 'var(--r-sm)',
          }}>{p}</button>
        ))}
      </div>
    </div>
  );
};

const MiniField = ({ label, unit, defaultValue, disabled }) => (
  <div>
    <div style={{ fontSize: 11.5, fontWeight: 600, color: 'var(--slate-600)', marginBottom: 4 }}>{label}</div>
    <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
      <input defaultValue={defaultValue} disabled={disabled} className="mono" style={{
        flex: 1, padding: '6px 10px', fontSize: 13, fontWeight: 600,
        border: '1px solid var(--slate-200)', borderRadius: 'var(--r-sm)',
        background: disabled ? 'var(--slate-50)' : '#fff',
        color: disabled ? 'var(--slate-400)' : 'var(--ink)',
      }}/>
      <span style={{ fontSize: 11, color: 'var(--slate-500)', minWidth: 50 }}>{unit}</span>
    </div>
  </div>
);

const EditEmployeeModal = ({ employee, onClose }) => {
  const [tab, setTab] = React.useState('datos');
  const initialFirst = (employee.name || '').split(' ')[0] || '';
  const initialLast  = (employee.name || '').split(' ').slice(1).join(' ');
  const [form, setForm] = React.useState({
    first_name: initialFirst, last_name: initialLast,
    email: employee.email || '', phone: '', location: 'Valencia, ES', birth: '',
    role_title: employee.role || '', team: employee.team || 'Implementación',
    contract: 'Indefinido · Jornada completa', start: '2024-03-04', manager: 'Núria Castells',
    schedule: 'L–V · 09:00–18:00 (40h)',
  });
  const set = (k, v) => setForm(s => ({ ...s, [k]: v }));
  const [busy, setBusy] = React.useState(false);

  const save = async () => {
    if (!employee.id || !window.api) return;
    setBusy(true);
    await window.api.updateEmployee(employee.id, {
      full_name: `${form.first_name} ${form.last_name}`.trim(),
      email: form.email, phone: form.phone, location: form.location, birthday: form.birth,
      role: form.role_title, team: form.team, manager: form.manager,
      contract: form.contract, start_date: form.start, schedule: form.schedule,
    });
    await window.api.reloadBootstrap();
    window.location.reload();
  };

  const remove = async () => {
    if (!employee.id || !window.api) return;
    if (!window.confirm(`¿Dar de baja a ${employee.name}? Esta acción no se puede deshacer.`)) return;
    setBusy(true);
    await window.api.deleteEmployee(employee.id);
    await window.api.reloadBootstrap();
    window.location.reload();
  };

  return (
    <div style={{ position: 'fixed', inset: 0, background: 'rgba(15,23,42,0.5)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 50 }} onClick={onClose}>
      <div onClick={e => e.stopPropagation()} style={{ background: '#fff', borderRadius: 'var(--r-xl)', width: 780, maxHeight: '92vh', display: 'flex', flexDirection: 'column', boxShadow: 'var(--shadow-lg)' }}>
        <div style={{ padding: '20px 28px', borderBottom: '1px solid var(--slate-150)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <Avatar name={employee.name} size={48}/>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 17, fontWeight: 700 }}>Editar {employee.name}</div>
              <div style={{ fontSize: 13, color: 'var(--slate-500)' }}>{employee.role} · {employee.team} · {employee.email}</div>
            </div>
            <Btn variant="secondary" size="sm" icon={<IExternal size={13}/>}>Ver perfil</Btn>
            <button onClick={onClose} style={{ color: 'var(--slate-500)', padding: 6 }}><IX size={18}/></button>
          </div>
        </div>

        <div style={{ padding: '12px 28px 0', borderBottom: '1px solid var(--slate-150)' }}>
          <div style={{ display: 'flex', gap: 4 }}>
            {[
              { v: 'datos',      l: 'Datos' },
              { v: 'contrato',   l: 'Contrato' },
              { v: 'vacaciones', l: 'Vacaciones y permisos' },
              { v: 'permisos',   l: 'Rol y accesos' },
            ].map(t => (
              <button key={t.v} onClick={() => setTab(t.v)} style={{
                padding: '10px 14px',
                fontSize: 13.5, fontWeight: 600,
                color: tab === t.v ? 'var(--brand-600)' : 'var(--slate-600)',
                borderBottom: `2px solid ${tab === t.v ? 'var(--brand-600)' : 'transparent'}`,
                marginBottom: -1,
              }}>{t.l}</button>
            ))}
          </div>
        </div>

        <div style={{ flex: 1, overflow: 'auto', padding: 28 }}>
          {tab === 'vacaciones' && <EditVacationTab employee={employee}/>}
          {tab === 'datos' && (
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
              <Field label="Nombre"><Input value={form.first_name} onChange={e => set('first_name', e.target.value)}/></Field>
              <Field label="Apellidos"><Input value={form.last_name} onChange={e => set('last_name', e.target.value)}/></Field>
              <Field label="Email corporativo"><Input value={form.email} onChange={e => set('email', e.target.value)} icon={<IMail size={14}/>}/></Field>
              <Field label="Teléfono"><Input placeholder="+34 6XX XX XX XX" value={form.phone} onChange={e => set('phone', e.target.value)}/></Field>
              <Field label="Cumpleaños"><Input type="date" value={form.birth} onChange={e => set('birth', e.target.value)}/></Field>
              <Field label="Localización"><Input value={form.location} onChange={e => set('location', e.target.value)}/></Field>
            </div>
          )}
          {tab === 'contrato' && (
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
              <Field label="Puesto"><Input value={form.role_title} onChange={e => set('role_title', e.target.value)}/></Field>
              <Field label="Equipo">
                <select style={selectStyle} value={form.team} onChange={e => set('team', e.target.value)}>
                  <option>Implementación</option><option>Plataforma</option><option>Comercial</option><option>Marketing</option><option>RRHH</option><option>Dirección</option>
                </select>
              </Field>
              <Field label="Tipo de contrato">
                <select style={selectStyle} value={form.contract} onChange={e => set('contract', e.target.value)}>
                  <option>Indefinido · Jornada completa</option><option>Indefinido · Media jornada</option><option>Temporal · Jornada completa</option>
                </select>
              </Field>
              <Field label="Inicio del contrato"><Input type="date" value={form.start} onChange={e => set('start', e.target.value)}/></Field>
              <Field label="Manager directo"><Input value={form.manager} onChange={e => set('manager', e.target.value)}/></Field>
              <Field label="Horario">
                <select style={selectStyle} value={form.schedule} onChange={e => set('schedule', e.target.value)}>
                  <option>L–V · 09:00–18:00 (40h)</option><option>L–V · 08:00–15:00 (35h)</option>
                </select>
              </Field>
            </div>
          )}
          {tab === 'permisos' && (
            <EmployeeAccessPanel employee={employee}/>
          )}
        </div>

        <div style={{ padding: '14px 28px', borderTop: '1px solid var(--slate-150)', display: 'flex', justifyContent: 'space-between' }}>
          <Btn variant="ghost" size="sm" icon={<ITrash size={13}/>} style={{ color: 'var(--danger-600)' }} onClick={remove} disabled={busy}>Dar de baja</Btn>
          <div style={{ display: 'flex', gap: 10 }}>
            <Btn variant="ghost" onClick={onClose} disabled={busy}>Cancelar</Btn>
            <Btn variant="primary" icon={<ICheck size={14}/>} onClick={save} disabled={busy}>{busy ? 'Guardando…' : 'Guardar cambios'}</Btn>
          </div>
        </div>
      </div>
    </div>
  );
};

const EditVacationTab = ({ employee }) => {
  const [vacationTotal, setVacationTotal] = React.useState(23);
  const [personalTotal, setPersonalTotal] = React.useState(2);
  const used = 7, usedPersonal = 1;
  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginBottom: 22 }}>
        <div style={{ padding: 18, background: 'var(--brand-50)', borderRadius: 'var(--r-md)', border: '1px solid var(--brand-100)' }}>
          <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--brand-600)', textTransform: 'uppercase', letterSpacing: '.06em' }}>Vacaciones — saldo actual 2026</div>
          <div className="tnum" style={{ fontSize: 28, fontWeight: 700, marginTop: 6, color: 'var(--ink)' }}>
            {vacationTotal - used} <span style={{ fontSize: 14, fontWeight: 500, color: 'var(--slate-500)' }}>/ {vacationTotal} días</span>
          </div>
          <ProgressBar value={used} max={vacationTotal} color="var(--brand-600)" track="var(--brand-200)" height={6}/>
          <div style={{ fontSize: 12, color: 'var(--slate-600)', marginTop: 6 }}>{used} usados · {vacationTotal - used} disponibles</div>
        </div>
        <div style={{ padding: 18, background: 'var(--violet-100)', borderRadius: 'var(--r-md)', border: '1px solid var(--violet-100)' }}>
          <div style={{ fontSize: 12, fontWeight: 600, color: '#6D28D9', textTransform: 'uppercase', letterSpacing: '.06em' }}>Asuntos propios — saldo actual</div>
          <div className="tnum" style={{ fontSize: 28, fontWeight: 700, marginTop: 6, color: 'var(--ink)' }}>
            {personalTotal - usedPersonal} <span style={{ fontSize: 14, fontWeight: 500, color: 'var(--slate-500)' }}>/ {personalTotal} días</span>
          </div>
          <ProgressBar value={usedPersonal} max={Math.max(1, personalTotal)} color="#6D28D9" track="rgba(139,92,246,0.25)" height={6}/>
          <div style={{ fontSize: 12, color: 'var(--slate-600)', marginTop: 6 }}>{usedPersonal} usado · {personalTotal - usedPersonal} disponible</div>
        </div>
      </div>

      <div style={{ fontSize: 13, fontWeight: 700, marginBottom: 12 }}>Asignación anual</div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
        <PolicyCounter icon={<ICalendar size={18}/>} tone="brand" title="Vacaciones anuales"
          subtitle="Días laborables por año natural"
          value={vacationTotal} onChange={setVacationTotal} unit="días" presets={[22, 23, 25, 30]}/>
        <PolicyCounter icon={<IFlag size={18}/>} tone="violet" title="Asuntos propios"
          subtitle="Días retribuidos según convenio"
          value={personalTotal} onChange={setPersonalTotal} unit="días" presets={[0, 1, 2, 4]}/>
      </div>

      <div style={{ marginTop: 18, padding: 14, background: 'var(--warning-50)', border: '1px solid var(--warning-100)', borderRadius: 'var(--r-md)', display: 'flex', gap: 10 }}>
        <IFlag size={16} style={{ color: 'var(--warning-600)', marginTop: 1, flexShrink: 0 }}/>
        <div style={{ fontSize: 13, color: 'var(--slate-700)', lineHeight: 1.55 }}>
          Si cambias la asignación a mitad de año, el saldo actual se recalculará. Si reduces por debajo de los días ya consumidos ({used} usados), aparecerá saldo negativo y deberás justificar el ajuste.
        </div>
      </div>

      <Divider style={{ margin: '22px 0' }}/>

      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
        <div style={{ fontSize: 13, fontWeight: 700 }}>Ajuste manual del saldo</div>
        <Btn variant="ghost" size="sm" icon={<IPlus size={13}/>}>Añadir ajuste</Btn>
      </div>
      <div style={{ border: '1px solid var(--slate-150)', borderRadius: 'var(--r-md)', overflow: 'hidden' }}>
        {[
          { d: '01 ene 2026', t: 'Saldo inicial 2026',          v: '+23 días', by: 'Automático', tone: 'slate' },
          { d: '12 feb 2026', t: 'Arrastre días 2025',          v: '+3 días',  by: 'Helena Prats', tone: 'success' },
          { d: '20 abr 2026', t: 'Día compensación trabajo finde', v: '+1 día', by: 'Helena Prats', tone: 'success' },
          { d: 'mar–may',     t: 'Vacaciones consumidas',       v: '−7 días',  by: 'Solicitudes aprobadas', tone: 'danger' },
        ].map((r, i, arr) => (
          <div key={i} style={{ display: 'grid', gridTemplateColumns: '110px 1fr 100px 1fr', alignItems: 'center', gap: 12, padding: '10px 14px', borderBottom: i < arr.length - 1 ? '1px solid var(--slate-100)' : 'none', fontSize: 13 }}>
            <div className="mono" style={{ color: 'var(--slate-500)' }}>{r.d}</div>
            <div style={{ color: 'var(--slate-700)' }}>{r.t}</div>
            <div className="mono tnum" style={{ fontWeight: 700, color: r.tone === 'danger' ? 'var(--danger-600)' : r.tone === 'success' ? 'var(--success-600)' : 'var(--ink)' }}>{r.v}</div>
            <div style={{ fontSize: 12, color: 'var(--slate-500)' }}>{r.by}</div>
          </div>
        ))}
      </div>
    </div>
  );
};

const EmployeeAccessPanel = ({ employee }) => {
  const [loading, setLoading] = React.useState(true);
  const [hasUser, setHasUser] = React.useState(false);
  const [username, setUsername] = React.useState('');
  const [role, setRole] = React.useState('empleado');
  const [password, setPassword] = React.useState('');
  const [confirm, setConfirm] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [msg, setMsg] = React.useState(null);

  React.useEffect(() => {
    let cancel = false;
    (async () => {
      if (!employee || !employee.id || !window.api) { setLoading(false); return; }
      const r = await window.api.getEmployeeAccess(employee.id);
      if (cancel) return;
      if (r && !r.error) {
        setHasUser(!!r.has_user);
        setUsername(r.username || r.suggested_username || '');
        setRole(r.role || 'empleado');
      }
      setLoading(false);
    })();
    return () => { cancel = true; };
  }, [employee && employee.id]);

  const save = async () => {
    setMsg(null);
    if (!password || password.length < 6) {
      setMsg({ type: 'error', text: 'La contraseña debe tener al menos 6 caracteres.' });
      return;
    }
    if (password !== confirm) {
      setMsg({ type: 'error', text: 'Las contraseñas no coinciden.' });
      return;
    }
    setBusy(true);
    const r = await window.api.setEmployeeAccess(employee.id, { username, password, role });
    setBusy(false);
    if (r && r.error) {
      setMsg({ type: 'error', text: r.error });
    } else {
      setHasUser(true);
      setUsername(r.username || username);
      setPassword(''); setConfirm('');
      setMsg({ type: 'ok', text: r.created
        ? `Acceso creado. Login: empresa + «${r.username}» + nueva contraseña.`
        : `Contraseña actualizada para «${r.username}».` });
    }
  };

  if (loading) return <div style={{ padding: 20, color: 'var(--slate-500)' }}>Cargando acceso…</div>;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
      <div style={{
        padding: 14, borderRadius: 'var(--r-md)',
        background: hasUser ? 'var(--success-50)' : 'var(--warning-50)',
        border: `1px solid ${hasUser ? 'var(--success-100)' : 'var(--warning-100)'}`,
        fontSize: 13, color: 'var(--slate-700)',
      }}>
        {hasUser
          ? <>Este empleado <strong>ya tiene acceso</strong>. Usuario actual: <code style={{ background: '#fff', padding: '2px 6px', borderRadius: 4 }}>{username}</code>. Puedes cambiar su contraseña o rol abajo.</>
          : <>Este empleado <strong>todavía no tiene usuario</strong>. Al guardar se le creará uno y podrá entrar al sistema.</>}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
        <Field label="Nombre de usuario" required hint="Lo usará para iniciar sesión junto al slug de la empresa.">
          <Input value={username} onChange={e => setUsername(e.target.value.toLowerCase())} placeholder="ej. marc.vives" autoComplete="off"/>
        </Field>
        <Field label="Rol" required>
          <select style={selectStyle} value={role} onChange={e => setRole(e.target.value)}>
            <option value="empleado">Empleado</option>
            <option value="admin">Administrador</option>
          </select>
        </Field>
        <Field label={hasUser ? 'Nueva contraseña' : 'Contraseña'} required hint="Mínimo 6 caracteres.">
          <Input type="password" value={password} onChange={e => setPassword(e.target.value)} placeholder="••••••••" autoComplete="new-password"/>
        </Field>
        <Field label="Confirmar contraseña" required>
          <Input type="password" value={confirm} onChange={e => setConfirm(e.target.value)} placeholder="••••••••" autoComplete="new-password"/>
        </Field>
      </div>

      {msg && (
        <div style={{
          padding: 12, borderRadius: 'var(--r-md)', fontSize: 13,
          background: msg.type === 'ok' ? 'var(--success-50)' : '#FEE2E2',
          color:      msg.type === 'ok' ? 'var(--success-700)' : '#991B1B',
          border: `1px solid ${msg.type === 'ok' ? 'var(--success-100)' : '#FCA5A5'}`,
        }}>{msg.text}</div>
      )}

      <div>
        <Btn variant="primary" icon={<IShield size={14}/>} onClick={save} disabled={busy}>
          {busy ? 'Guardando…' : (hasUser ? 'Actualizar acceso' : 'Crear acceso')}
        </Btn>
      </div>
    </div>
  );
};

Object.assign(window, { ScreenOrganizacion });
